allwright 1.55.0 → 1.56.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/bin/allwright.js +226 -177
  2. package/package.json +1 -1
package/bin/allwright.js CHANGED
@@ -1,31 +1,31 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var jp=Object.create;var _o=Object.defineProperty;var Np=Object.getOwnPropertyDescriptor;var Op=Object.getOwnPropertyNames;var Mp=Object.getPrototypeOf,zp=Object.prototype.hasOwnProperty;var Qs=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var se=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}},ei=(t,e)=>{for(var n in e)_o(t,n,{get:e[n],enumerable:!0})},Dp=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Op(e))!zp.call(t,s)&&s!==n&&_o(t,s,{get:()=>e[s],enumerable:!(r=Np(e,s))||r.enumerable});return t};var R=(t,e,n)=>(n=t!=null?jp(Mp(t)):{},Dp(e||!t||!t.__esModule?_o(n,"default",{value:t,enumerable:!0}):n,t));var vs=se(To=>{var ti=class extends Error{constructor(e,n,r){super(r),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=n,this.exitCode=e,this.nestedError=void 0}},So=class extends ti{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};To.CommanderError=ti;To.InvalidArgumentError=So});var ni=se(Eo=>{var{InvalidArgumentError:Lp}=vs(),xo=class{constructor(e,n){switch(this.description=n||"",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,n){return n===this.defaultValue||!Array.isArray(n)?[e]:n.concat(e)}default(e,n){return this.defaultValue=e,this.defaultValueDescription=n,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(n,r)=>{if(!this.argChoices.includes(n))throw new Lp(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(n,r):n},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Up(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}Eo.Argument=xo;Eo.humanReadableArgName=Up});var Io=se(zl=>{var{humanReadableArgName:qp}=ni(),Ro=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let n=e.commands.filter(s=>!s._hidden),r=e._getHelpCommand();return r&&!r._hidden&&n.push(r),this.sortSubcommands&&n.sort((s,i)=>s.name().localeCompare(i.name())),n}compareOptions(e,n){let r=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return r(e).localeCompare(r(n))}visibleOptions(e){let n=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?n.push(r):r.long&&!i?n.push(e.createOption(r.long,r.description)):r.short&&!s&&n.push(e.createOption(r.short,r.description))}return this.sortOptions&&n.sort(this.compareOptions),n}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let n=[];for(let r=e.parent;r;r=r.parent){let s=r.options.filter(i=>!i.hidden);n.push(...s)}return this.sortOptions&&n.sort(this.compareOptions),n}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(n=>{n.description=n.description||e._argsDescription[n.name()]||""}),e.registeredArguments.find(n=>n.description)?e.registeredArguments:[]}subcommandTerm(e){let n=e.registeredArguments.map(r=>qp(r)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(n?" "+n:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,n){return n.visibleCommands(e).reduce((r,s)=>Math.max(r,n.subcommandTerm(s).length),0)}longestOptionTermLength(e,n){return n.visibleOptions(e).reduce((r,s)=>Math.max(r,n.optionTerm(s).length),0)}longestGlobalOptionTermLength(e,n){return n.visibleGlobalOptions(e).reduce((r,s)=>Math.max(r,n.optionTerm(s).length),0)}longestArgumentTermLength(e,n){return n.visibleArguments(e).reduce((r,s)=>Math.max(r,n.argumentTerm(s).length),0)}commandUsage(e){let n=e._name;e._aliases[0]&&(n=n+"|"+e._aliases[0]);let r="";for(let s=e.parent;s;s=s.parent)r=s.name()+" "+r;return r+n+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let n=[];return e.argChoices&&n.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&n.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&n.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&n.push(`env: ${e.envVar}`),n.length>0?`${e.description} (${n.join(", ")})`:e.description}argumentDescription(e){let n=[];if(e.argChoices&&n.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&n.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),n.length>0){let r=`(${n.join(", ")})`;return e.description?`${e.description} ${r}`:r}return e.description}formatHelp(e,n){let r=n.padWidth(e,n),s=n.helpWidth||80,i=2,o=2;function l(_,x){if(x){let $=`${_.padEnd(r+o)}${x}`;return n.wrap($,s-i,r+o)}return _}function c(_){return _.join(`
3
- `).replace(/^/gm," ".repeat(i))}let u=[`Usage: ${n.commandUsage(e)}`,""],p=n.commandDescription(e);p.length>0&&(u=u.concat([n.wrap(p,s,0),""]));let f=n.visibleArguments(e).map(_=>l(n.argumentTerm(_),n.argumentDescription(_)));f.length>0&&(u=u.concat(["Arguments:",c(f),""]));let b=n.visibleOptions(e).map(_=>l(n.optionTerm(_),n.optionDescription(_)));if(b.length>0&&(u=u.concat(["Options:",c(b),""])),this.showGlobalOptions){let _=n.visibleGlobalOptions(e).map(x=>l(n.optionTerm(x),n.optionDescription(x)));_.length>0&&(u=u.concat(["Global Options:",c(_),""]))}let v=n.visibleCommands(e).map(_=>l(n.subcommandTerm(_),n.subcommandDescription(_)));return v.length>0&&(u=u.concat(["Commands:",c(v),""])),u.join(`
2
+ "use strict";var tf=Object.create;var No=Object.defineProperty;var nf=Object.getOwnPropertyDescriptor;var rf=Object.getOwnPropertyNames;var sf=Object.getPrototypeOf,of=Object.prototype.hasOwnProperty;var xn=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var se=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}},xs=(t,e)=>{for(var n in e)No(t,n,{get:e[n],enumerable:!0})},af=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of rf(e))!of.call(t,s)&&s!==n&&No(t,s,{get:()=>e[s],enumerable:!(r=nf(e,s))||r.enumerable});return t};var R=(t,e,n)=>(n=t!=null?tf(sf(t)):{},af(e||!t||!t.__esModule?No(n,"default",{value:t,enumerable:!0}):n,t));var Es=se(Oo=>{var li=class extends Error{constructor(e,n,r){super(r),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=n,this.exitCode=e,this.nestedError=void 0}},jo=class extends li{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Oo.CommanderError=li;Oo.InvalidArgumentError=jo});var ci=se(zo=>{var{InvalidArgumentError:lf}=Es(),Mo=class{constructor(e,n){switch(this.description=n||"",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,n){return n===this.defaultValue||!Array.isArray(n)?[e]:n.concat(e)}default(e,n){return this.defaultValue=e,this.defaultValueDescription=n,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(n,r)=>{if(!this.argChoices.includes(n))throw new lf(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(n,r):n},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function cf(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}zo.Argument=Mo;zo.humanReadableArgName=cf});var Lo=se(Vl=>{var{humanReadableArgName:uf}=ci(),Do=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let n=e.commands.filter(s=>!s._hidden),r=e._getHelpCommand();return r&&!r._hidden&&n.push(r),this.sortSubcommands&&n.sort((s,i)=>s.name().localeCompare(i.name())),n}compareOptions(e,n){let r=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return r(e).localeCompare(r(n))}visibleOptions(e){let n=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?n.push(r):r.long&&!i?n.push(e.createOption(r.long,r.description)):r.short&&!s&&n.push(e.createOption(r.short,r.description))}return this.sortOptions&&n.sort(this.compareOptions),n}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let n=[];for(let r=e.parent;r;r=r.parent){let s=r.options.filter(i=>!i.hidden);n.push(...s)}return this.sortOptions&&n.sort(this.compareOptions),n}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(n=>{n.description=n.description||e._argsDescription[n.name()]||""}),e.registeredArguments.find(n=>n.description)?e.registeredArguments:[]}subcommandTerm(e){let n=e.registeredArguments.map(r=>uf(r)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(n?" "+n:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,n){return n.visibleCommands(e).reduce((r,s)=>Math.max(r,n.subcommandTerm(s).length),0)}longestOptionTermLength(e,n){return n.visibleOptions(e).reduce((r,s)=>Math.max(r,n.optionTerm(s).length),0)}longestGlobalOptionTermLength(e,n){return n.visibleGlobalOptions(e).reduce((r,s)=>Math.max(r,n.optionTerm(s).length),0)}longestArgumentTermLength(e,n){return n.visibleArguments(e).reduce((r,s)=>Math.max(r,n.argumentTerm(s).length),0)}commandUsage(e){let n=e._name;e._aliases[0]&&(n=n+"|"+e._aliases[0]);let r="";for(let s=e.parent;s;s=s.parent)r=s.name()+" "+r;return r+n+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let n=[];return e.argChoices&&n.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&n.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&n.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&n.push(`env: ${e.envVar}`),n.length>0?`${e.description} (${n.join(", ")})`:e.description}argumentDescription(e){let n=[];if(e.argChoices&&n.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&n.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),n.length>0){let r=`(${n.join(", ")})`;return e.description?`${e.description} ${r}`:r}return e.description}formatHelp(e,n){let r=n.padWidth(e,n),s=n.helpWidth||80,i=2,o=2;function l(w,x){if(x){let $=`${w.padEnd(r+o)}${x}`;return n.wrap($,s-i,r+o)}return w}function c(w){return w.join(`
3
+ `).replace(/^/gm," ".repeat(i))}let u=[`Usage: ${n.commandUsage(e)}`,""],p=n.commandDescription(e);p.length>0&&(u=u.concat([n.wrap(p,s,0),""]));let f=n.visibleArguments(e).map(w=>l(n.argumentTerm(w),n.argumentDescription(w)));f.length>0&&(u=u.concat(["Arguments:",c(f),""]));let b=n.visibleOptions(e).map(w=>l(n.optionTerm(w),n.optionDescription(w)));if(b.length>0&&(u=u.concat(["Options:",c(b),""])),this.showGlobalOptions){let w=n.visibleGlobalOptions(e).map(x=>l(n.optionTerm(x),n.optionDescription(x)));w.length>0&&(u=u.concat(["Global Options:",c(w),""]))}let v=n.visibleCommands(e).map(w=>l(n.subcommandTerm(w),n.subcommandDescription(w)));return v.length>0&&(u=u.concat(["Commands:",c(v),""])),u.join(`
4
4
  `)}padWidth(e,n){return Math.max(n.longestOptionTermLength(e,n),n.longestGlobalOptionTermLength(e,n),n.longestSubcommandTermLength(e,n),n.longestArgumentTermLength(e,n))}wrap(e,n,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=n-r;if(l<s)return e;let c=e.slice(0,r),u=e.slice(r).replace(`\r
5
5
  `,`
6
6
  `),p=" ".repeat(r),b="\\s\u200B",v=new RegExp(`
7
- |.{1,${l-1}}([${b}]|$)|[^${b}]+?([${b}]|$)`,"g"),_=u.match(v)||[];return c+_.map((x,$)=>x===`
7
+ |.{1,${l-1}}([${b}]|$)|[^${b}]+?([${b}]|$)`,"g"),w=u.match(v)||[];return c+w.map((x,$)=>x===`
8
8
  `?"":($>0?p:"")+x.trimEnd()).join(`
9
- `)}};zl.Help=Ro});var Po=se($o=>{var{InvalidArgumentError:Fp}=vs(),Ao=class{constructor(e,n){this.flags=e,this.description=n||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let r=Kp(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,n){return this.defaultValue=e,this.defaultValueDescription=n,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let n=e;return typeof e=="string"&&(n={[e]:!0}),this.implied=Object.assign(this.implied||{},n),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,n){return n===this.defaultValue||!Array.isArray(n)?[e]:n.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(n,r)=>{if(!this.argChoices.includes(n))throw new Fp(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(n,r):n},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return Bp(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(n=>{n.negate?this.negativeOptions.set(n.attributeName(),n):this.positiveOptions.set(n.attributeName(),n)}),this.negativeOptions.forEach((n,r)=>{this.positiveOptions.has(r)&&this.dualOptions.add(r)})}valueFromOption(e,n){let r=n.attributeName();if(!this.dualOptions.has(r))return!0;let s=this.negativeOptions.get(r).presetArg,i=s!==void 0?s:!1;return n.negate===(i===e)}};function Bp(t){return t.split("-").reduce((e,n)=>e+n[0].toUpperCase()+n.slice(1))}function Kp(t){let e,n,r=t.split(/[ |,]+/);return r.length>1&&!/^[[<]/.test(r[1])&&(e=r.shift()),n=r.shift(),!e&&/^-[^-]$/.test(n)&&(e=n,n=void 0),{shortFlag:e,longFlag:n}}$o.Option=Ao;$o.DualOptions=Co});var Ll=se(Dl=>{function Hp(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);let n=[];for(let r=0;r<=t.length;r++)n[r]=[r];for(let r=0;r<=e.length;r++)n[0][r]=r;for(let r=1;r<=e.length;r++)for(let s=1;s<=t.length;s++){let i=1;t[s-1]===e[r-1]?i=0:i=1,n[s][r]=Math.min(n[s-1][r]+1,n[s][r-1]+1,n[s-1][r-1]+i),s>1&&r>1&&t[s-1]===e[r-2]&&t[s-2]===e[r-1]&&(n[s][r]=Math.min(n[s][r],n[s-2][r-2]+1))}return n[t.length][e.length]}function Gp(t,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let n=t.startsWith("--");n&&(t=t.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=Hp(t,o),c=Math.max(t.length,o.length);(c-l)/c>i&&(l<s?(s=l,r=[o]):l===s&&r.push(o))}),r.sort((o,l)=>o.localeCompare(l)),n&&(r=r.map(o=>`--${o}`)),r.length>1?`
9
+ `)}};Vl.Help=Do});var Bo=se(Fo=>{var{InvalidArgumentError:df}=Es(),Uo=class{constructor(e,n){this.flags=e,this.description=n||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let r=pf(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,n){return this.defaultValue=e,this.defaultValueDescription=n,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let n=e;return typeof e=="string"&&(n={[e]:!0}),this.implied=Object.assign(this.implied||{},n),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,n){return n===this.defaultValue||!Array.isArray(n)?[e]:n.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(n,r)=>{if(!this.argChoices.includes(n))throw new df(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(n,r):n},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return hf(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},qo=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(n=>{n.negate?this.negativeOptions.set(n.attributeName(),n):this.positiveOptions.set(n.attributeName(),n)}),this.negativeOptions.forEach((n,r)=>{this.positiveOptions.has(r)&&this.dualOptions.add(r)})}valueFromOption(e,n){let r=n.attributeName();if(!this.dualOptions.has(r))return!0;let s=this.negativeOptions.get(r).presetArg,i=s!==void 0?s:!1;return n.negate===(i===e)}};function hf(t){return t.split("-").reduce((e,n)=>e+n[0].toUpperCase()+n.slice(1))}function pf(t){let e,n,r=t.split(/[ |,]+/);return r.length>1&&!/^[[<]/.test(r[1])&&(e=r.shift()),n=r.shift(),!e&&/^-[^-]$/.test(n)&&(e=n,n=void 0),{shortFlag:e,longFlag:n}}Fo.Option=Uo;Fo.DualOptions=qo});var Yl=se(Wl=>{function ff(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);let n=[];for(let r=0;r<=t.length;r++)n[r]=[r];for(let r=0;r<=e.length;r++)n[0][r]=r;for(let r=1;r<=e.length;r++)for(let s=1;s<=t.length;s++){let i=1;t[s-1]===e[r-1]?i=0:i=1,n[s][r]=Math.min(n[s-1][r]+1,n[s][r-1]+1,n[s-1][r-1]+i),s>1&&r>1&&t[s-1]===e[r-2]&&t[s-2]===e[r-1]&&(n[s][r]=Math.min(n[s][r],n[s-2][r-2]+1))}return n[t.length][e.length]}function mf(t,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let n=t.startsWith("--");n&&(t=t.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=ff(t,o),c=Math.max(t.length,o.length);(c-l)/c>i&&(l<s?(s=l,r=[o]):l===s&&r.push(o))}),r.sort((o,l)=>o.localeCompare(l)),n&&(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]}?)`:""}Dl.suggestSimilar=Gp});var Kl=se(Bl=>{var Zp=require("node:events").EventEmitter,jo=require("node:child_process"),Rt=require("node:path"),No=require("node:fs"),ge=require("node:process"),{Argument:Vp,humanReadableArgName:Wp}=ni(),{CommanderError:Oo}=vs(),{Help:Yp}=Io(),{Option:Ul,DualOptions:Jp}=Po(),{suggestSimilar:ql}=Ll(),Mo=class t extends Zp{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:n=>ge.stdout.write(n),writeErr:n=>ge.stderr.write(n),getOutHelpWidth:()=>ge.stdout.isTTY?ge.stdout.columns:void 0,getErrHelpWidth:()=>ge.stderr.isTTY?ge.stderr.columns:void 0,outputError:(n,r)=>r(n)},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 n=this;n;n=n.parent)e.push(n);return e}command(e,n,r){let s=n,i=r;typeof s=="object"&&s!==null&&(i=s,s=null),i=i||{};let[,o,l]=e.match(/([^ ]+) *(.*)/),c=this.createCommand(o);return s&&(c.description(s),c._executableHandler=!0),i.isDefault&&(this._defaultCommandName=c._name),c._hidden=!!(i.noHelp||i.hidden),c._executableFile=i.executableFile||null,l&&c.arguments(l),this._registerCommand(c),c.parent=this,c.copyInheritedSettings(this),s?this:c}createCommand(e){return new t(e)}createHelp(){return Object.assign(new Yp,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,n){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 n=n||{},n.isDefault&&(this._defaultCommandName=e._name),(n.noHelp||n.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,n){return new Vp(e,n)}argument(e,n,r,s){let i=this.createArgument(e,n);return typeof r=="function"?i.default(s).argParser(r):i.default(r),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(n=>{this.argument(n)}),this}addArgument(e){let n=this.registeredArguments.slice(-1)[0];if(n&&n.variadic)throw new Error(`only the last argument can be variadic '${n.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,n){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,r,s]=e.match(/([^ ]+) *(.*)/),i=n??"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,n){return typeof e!="object"?(this.helpCommand(e,n),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,n){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(n):this._lifeCycleHooks[e]=[n],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=n=>{if(n.code!=="commander.executeSubCommandAsync")throw n},this}_exit(e,n,r){this._exitCallback&&this._exitCallback(new Oo(e,n,r)),ge.exit(e)}action(e){let n=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=n,this}createOption(e,n){return new Ul(e,n)}_callParseArg(e,n,r,s){try{return e.parseArg(n,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 n=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(n){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 '${n.flags}'`)}this.options.push(e)}_registerCommand(e){let n=s=>[s.name()].concat(s.aliases()),r=n(e).find(s=>this._findCommand(s));if(r){let s=n(this._findCommand(r)).join("|"),i=n(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let n=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 c=this.getOptionValue(r);i!==null&&e.parseArg?i=this._callParseArg(e,i,c,o):i!==null&&e.variadic&&(i=e._concatValue(i,c)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(r,i,l)};return this.on("option:"+n,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;s(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+n,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;s(i,o,"env")}),this}_optionEx(e,n,r,s,i){if(typeof n=="object"&&n instanceof Ul)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(n,r);if(o.makeOptionMandatory(!!e.mandatory),typeof s=="function")o.default(i).argParser(s);else if(s instanceof RegExp){let l=s;s=(c,u)=>{let p=l.exec(c);return p?p[0]:u},o.default(i).argParser(s)}else o.default(s);return this.addOption(o)}option(e,n,r,s){return this._optionEx({},e,n,r,s)}requiredOption(e,n,r,s){return this._optionEx({mandatory:!0},e,n,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,n){return this.setOptionValueWithSource(e,n,void 0)}setOptionValueWithSource(e,n,r){return this._storeOptionsAsProperties?this[e]=n:this._optionValues[e]=n,this._optionValueSources[e]=r,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let n;return this._getCommandAndAncestors().forEach(r=>{r.getOptionValueSource(e)!==void 0&&(n=r.getOptionValueSource(e))}),n}_prepareUserArgs(e,n){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(n=n||{},e===void 0&&n.from===void 0){ge.versions?.electron&&(n.from="electron");let s=ge.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(n.from="eval")}e===void 0&&(e=ge.argv),this.rawArgs=e.slice();let r;switch(n.from){case void 0:case"node":this._scriptPath=e[1],r=e.slice(2);break;case"electron":ge.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: '${n.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",r}parse(e,n){let r=this._prepareUserArgs(e,n);return this._parseCommand([],r),this}async parseAsync(e,n){let r=this._prepareUserArgs(e,n);return await this._parseCommand([],r),this}_executeSubCommand(e,n){n=n.slice();let r=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function i(p,f){let b=Rt.resolve(p,f);if(No.existsSync(b))return b;if(s.includes(Rt.extname(f)))return;let v=s.find(_=>No.existsSync(`${b}${_}`));if(v)return`${b}${v}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,l=this._executableDir||"";if(this._scriptPath){let p;try{p=No.realpathSync(this._scriptPath)}catch{p=this._scriptPath}l=Rt.resolve(Rt.dirname(p),l)}if(l){let p=i(l,o);if(!p&&!e._executableFile&&this._scriptPath){let f=Rt.basename(this._scriptPath,Rt.extname(this._scriptPath));f!==this._name&&(p=i(l,`${f}-${e._name}`))}o=p||o}r=s.includes(Rt.extname(o));let c;ge.platform!=="win32"?r?(n.unshift(o),n=Fl(ge.execArgv).concat(n),c=jo.spawn(ge.argv[0],n,{stdio:"inherit"})):c=jo.spawn(o,n,{stdio:"inherit"}):(n.unshift(o),n=Fl(ge.execArgv).concat(n),c=jo.spawn(ge.execPath,n,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{ge.on(f,()=>{c.killed===!1&&c.exitCode===null&&c.kill(f)})});let u=this._exitCallback;c.on("close",p=>{p=p??1,u?u(new Oo(p,"commander.executeSubCommandAsync","(close)")):ge.exit(p)}),c.on("error",p=>{if(p.code==="ENOENT"){let f=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]}?)`:""}Wl.suggestSimilar=mf});var tc=se(ec=>{var gf=require("node:events").EventEmitter,Ko=require("node:child_process"),Ct=require("node:path"),Ho=require("node:fs"),ge=require("node:process"),{Argument:yf,humanReadableArgName:bf}=ci(),{CommanderError:Go}=Es(),{Help:vf}=Lo(),{Option:Jl,DualOptions:wf}=Bo(),{suggestSimilar:Xl}=Yl(),Zo=class t extends gf{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:n=>ge.stdout.write(n),writeErr:n=>ge.stderr.write(n),getOutHelpWidth:()=>ge.stdout.isTTY?ge.stdout.columns:void 0,getErrHelpWidth:()=>ge.stderr.isTTY?ge.stderr.columns:void 0,outputError:(n,r)=>r(n)},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 n=this;n;n=n.parent)e.push(n);return e}command(e,n,r){let s=n,i=r;typeof s=="object"&&s!==null&&(i=s,s=null),i=i||{};let[,o,l]=e.match(/([^ ]+) *(.*)/),c=this.createCommand(o);return s&&(c.description(s),c._executableHandler=!0),i.isDefault&&(this._defaultCommandName=c._name),c._hidden=!!(i.noHelp||i.hidden),c._executableFile=i.executableFile||null,l&&c.arguments(l),this._registerCommand(c),c.parent=this,c.copyInheritedSettings(this),s?this:c}createCommand(e){return new t(e)}createHelp(){return Object.assign(new vf,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,n){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 n=n||{},n.isDefault&&(this._defaultCommandName=e._name),(n.noHelp||n.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,n){return new yf(e,n)}argument(e,n,r,s){let i=this.createArgument(e,n);return typeof r=="function"?i.default(s).argParser(r):i.default(r),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(n=>{this.argument(n)}),this}addArgument(e){let n=this.registeredArguments.slice(-1)[0];if(n&&n.variadic)throw new Error(`only the last argument can be variadic '${n.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,n){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,r,s]=e.match(/([^ ]+) *(.*)/),i=n??"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,n){return typeof e!="object"?(this.helpCommand(e,n),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,n){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(n):this._lifeCycleHooks[e]=[n],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=n=>{if(n.code!=="commander.executeSubCommandAsync")throw n},this}_exit(e,n,r){this._exitCallback&&this._exitCallback(new Go(e,n,r)),ge.exit(e)}action(e){let n=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=n,this}createOption(e,n){return new Jl(e,n)}_callParseArg(e,n,r,s){try{return e.parseArg(n,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 n=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(n){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 '${n.flags}'`)}this.options.push(e)}_registerCommand(e){let n=s=>[s.name()].concat(s.aliases()),r=n(e).find(s=>this._findCommand(s));if(r){let s=n(this._findCommand(r)).join("|"),i=n(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let n=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 c=this.getOptionValue(r);i!==null&&e.parseArg?i=this._callParseArg(e,i,c,o):i!==null&&e.variadic&&(i=e._concatValue(i,c)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(r,i,l)};return this.on("option:"+n,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;s(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+n,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;s(i,o,"env")}),this}_optionEx(e,n,r,s,i){if(typeof n=="object"&&n instanceof Jl)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(n,r);if(o.makeOptionMandatory(!!e.mandatory),typeof s=="function")o.default(i).argParser(s);else if(s instanceof RegExp){let l=s;s=(c,u)=>{let p=l.exec(c);return p?p[0]:u},o.default(i).argParser(s)}else o.default(s);return this.addOption(o)}option(e,n,r,s){return this._optionEx({},e,n,r,s)}requiredOption(e,n,r,s){return this._optionEx({mandatory:!0},e,n,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,n){return this.setOptionValueWithSource(e,n,void 0)}setOptionValueWithSource(e,n,r){return this._storeOptionsAsProperties?this[e]=n:this._optionValues[e]=n,this._optionValueSources[e]=r,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let n;return this._getCommandAndAncestors().forEach(r=>{r.getOptionValueSource(e)!==void 0&&(n=r.getOptionValueSource(e))}),n}_prepareUserArgs(e,n){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(n=n||{},e===void 0&&n.from===void 0){ge.versions?.electron&&(n.from="electron");let s=ge.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(n.from="eval")}e===void 0&&(e=ge.argv),this.rawArgs=e.slice();let r;switch(n.from){case void 0:case"node":this._scriptPath=e[1],r=e.slice(2);break;case"electron":ge.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: '${n.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",r}parse(e,n){let r=this._prepareUserArgs(e,n);return this._parseCommand([],r),this}async parseAsync(e,n){let r=this._prepareUserArgs(e,n);return await this._parseCommand([],r),this}_executeSubCommand(e,n){n=n.slice();let r=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function i(p,f){let b=Ct.resolve(p,f);if(Ho.existsSync(b))return b;if(s.includes(Ct.extname(f)))return;let v=s.find(w=>Ho.existsSync(`${b}${w}`));if(v)return`${b}${v}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,l=this._executableDir||"";if(this._scriptPath){let p;try{p=Ho.realpathSync(this._scriptPath)}catch{p=this._scriptPath}l=Ct.resolve(Ct.dirname(p),l)}if(l){let p=i(l,o);if(!p&&!e._executableFile&&this._scriptPath){let f=Ct.basename(this._scriptPath,Ct.extname(this._scriptPath));f!==this._name&&(p=i(l,`${f}-${e._name}`))}o=p||o}r=s.includes(Ct.extname(o));let c;ge.platform!=="win32"?r?(n.unshift(o),n=Ql(ge.execArgv).concat(n),c=Ko.spawn(ge.argv[0],n,{stdio:"inherit"})):c=Ko.spawn(o,n,{stdio:"inherit"}):(n.unshift(o),n=Ql(ge.execArgv).concat(n),c=Ko.spawn(ge.execPath,n,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{ge.on(f,()=>{c.killed===!1&&c.exitCode===null&&c.kill(f)})});let u=this._exitCallback;c.on("close",p=>{p=p??1,u?u(new Go(p,"commander.executeSubCommandAsync","(close)")):ge.exit(p)}),c.on("error",p=>{if(p.code==="ENOENT"){let f=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
- - ${f}`;throw new Error(b)}else if(p.code==="EACCES")throw new Error(`'${o}' not executable`);if(!u)ge.exit(1);else{let f=new Oo(1,"commander.executeSubCommandAsync","(error)");f.nestedError=p,u(f)}}),this.runningCommand=c}_dispatchSubcommand(e,n,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,n.concat(r));else return s._parseCommand(n,r)}),i}_dispatchHelpCommand(e){e||this.help();let n=this._findCommand(e);return n&&!n._executableHandler&&n.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,n)=>{e.required&&this.args[n]==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 n=[];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))),n[s]=i}),this.processedArgs=n}_chainOrCall(e,n){return e&&e.then&&typeof e.then=="function"?e.then(()=>n()):n()}_chainOrCallHooks(e,n){let r=e,s=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[n]!==void 0).forEach(i=>{i._lifeCycleHooks[n].forEach(o=>{s.push({hookedCommand:i,callback:o})})}),n==="postAction"&&s.reverse(),s.forEach(i=>{r=this._chainOrCall(r,()=>i.callback(i.hookedCommand,this))}),r}_chainOrCallSubCommandHook(e,n,r){let s=e;return this._lifeCycleHooks[r]!==void 0&&this._lifeCycleHooks[r].forEach(i=>{s=this._chainOrCall(s,()=>i(this,n))}),s}_parseCommand(e,n){let r=this.parseOptions(n);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(r.operands),n=r.unknown,this.args=e.concat(n),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),n);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(n),this._dispatchSubcommand(this._defaultCommandName,e,n);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,n)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(i))s(),this._processArguments(),this.parent.emit(i,e,n);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,n);this.listenerCount("command:*")?this.emit("command:*",e,n):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(n=>n._name===e||n._aliases.includes(e))}_findOption(e){return this.options.find(n=>n.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(n=>{n.mandatory&&e.getOptionValue(n.attributeName())===void 0&&e.missingMandatoryOptionValue(n)})})}_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 n=[],r=[],s=n,i=e.slice();function o(c){return c.length>1&&c[0]==="-"}let l=null;for(;i.length;){let c=i.shift();if(c==="--"){s===r&&s.push(c),s.push(...i);break}if(l&&!o(c)){this.emit(`option:${l.name()}`,c);continue}if(l=null,o(c)){let u=this._findOption(c);if(u){if(u.required){let p=i.shift();p===void 0&&this.optionMissingArgument(u),this.emit(`option:${u.name()}`,p)}else if(u.optional){let p=null;i.length>0&&!o(i[0])&&(p=i.shift()),this.emit(`option:${u.name()}`,p)}else this.emit(`option:${u.name()}`);l=u.variadic?u:null;continue}}if(c.length>2&&c[0]==="-"&&c[1]!=="-"){let u=this._findOption(`-${c[1]}`);if(u){u.required||u.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${u.name()}`,c.slice(2)):(this.emit(`option:${u.name()}`),i.unshift(`-${c.slice(2)}`));continue}}if(/^--[^=]+=/.test(c)){let u=c.indexOf("="),p=this._findOption(c.slice(0,u));if(p&&(p.required||p.optional)){this.emit(`option:${p.name()}`,c.slice(u+1));continue}}if(o(c)&&(s=r),(this._enablePositionalOptions||this._passThroughOptions)&&n.length===0&&r.length===0){if(this._findCommand(c)){n.push(c),i.length>0&&r.push(...i);break}else if(this._getHelpCommand()&&c===this._getHelpCommand().name()){n.push(c),i.length>0&&n.push(...i);break}else if(this._defaultCommandName){r.push(c),i.length>0&&r.push(...i);break}}if(this._passThroughOptions){s.push(c),i.length>0&&s.push(...i);break}s.push(c)}return{operands:n,unknown:r}}opts(){if(this._storeOptionsAsProperties){let e={},n=this.options.length;for(let r=0;r<n;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,n)=>Object.assign(e,n.opts()),{})}error(e,n){this._outputConfiguration.outputError(`${e}
17
+ - ${f}`;throw new Error(b)}else if(p.code==="EACCES")throw new Error(`'${o}' not executable`);if(!u)ge.exit(1);else{let f=new Go(1,"commander.executeSubCommandAsync","(error)");f.nestedError=p,u(f)}}),this.runningCommand=c}_dispatchSubcommand(e,n,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,n.concat(r));else return s._parseCommand(n,r)}),i}_dispatchHelpCommand(e){e||this.help();let n=this._findCommand(e);return n&&!n._executableHandler&&n.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,n)=>{e.required&&this.args[n]==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 n=[];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))),n[s]=i}),this.processedArgs=n}_chainOrCall(e,n){return e&&e.then&&typeof e.then=="function"?e.then(()=>n()):n()}_chainOrCallHooks(e,n){let r=e,s=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[n]!==void 0).forEach(i=>{i._lifeCycleHooks[n].forEach(o=>{s.push({hookedCommand:i,callback:o})})}),n==="postAction"&&s.reverse(),s.forEach(i=>{r=this._chainOrCall(r,()=>i.callback(i.hookedCommand,this))}),r}_chainOrCallSubCommandHook(e,n,r){let s=e;return this._lifeCycleHooks[r]!==void 0&&this._lifeCycleHooks[r].forEach(i=>{s=this._chainOrCall(s,()=>i(this,n))}),s}_parseCommand(e,n){let r=this.parseOptions(n);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(r.operands),n=r.unknown,this.args=e.concat(n),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),n);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(n),this._dispatchSubcommand(this._defaultCommandName,e,n);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,n)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(i))s(),this._processArguments(),this.parent.emit(i,e,n);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,n);this.listenerCount("command:*")?this.emit("command:*",e,n):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(n=>n._name===e||n._aliases.includes(e))}_findOption(e){return this.options.find(n=>n.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(n=>{n.mandatory&&e.getOptionValue(n.attributeName())===void 0&&e.missingMandatoryOptionValue(n)})})}_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 n=[],r=[],s=n,i=e.slice();function o(c){return c.length>1&&c[0]==="-"}let l=null;for(;i.length;){let c=i.shift();if(c==="--"){s===r&&s.push(c),s.push(...i);break}if(l&&!o(c)){this.emit(`option:${l.name()}`,c);continue}if(l=null,o(c)){let u=this._findOption(c);if(u){if(u.required){let p=i.shift();p===void 0&&this.optionMissingArgument(u),this.emit(`option:${u.name()}`,p)}else if(u.optional){let p=null;i.length>0&&!o(i[0])&&(p=i.shift()),this.emit(`option:${u.name()}`,p)}else this.emit(`option:${u.name()}`);l=u.variadic?u:null;continue}}if(c.length>2&&c[0]==="-"&&c[1]!=="-"){let u=this._findOption(`-${c[1]}`);if(u){u.required||u.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${u.name()}`,c.slice(2)):(this.emit(`option:${u.name()}`),i.unshift(`-${c.slice(2)}`));continue}}if(/^--[^=]+=/.test(c)){let u=c.indexOf("="),p=this._findOption(c.slice(0,u));if(p&&(p.required||p.optional)){this.emit(`option:${p.name()}`,c.slice(u+1));continue}}if(o(c)&&(s=r),(this._enablePositionalOptions||this._passThroughOptions)&&n.length===0&&r.length===0){if(this._findCommand(c)){n.push(c),i.length>0&&r.push(...i);break}else if(this._getHelpCommand()&&c===this._getHelpCommand().name()){n.push(c),i.length>0&&n.push(...i);break}else if(this._defaultCommandName){r.push(c),i.length>0&&r.push(...i);break}}if(this._passThroughOptions){s.push(c),i.length>0&&s.push(...i);break}s.push(c)}return{operands:n,unknown:r}}opts(){if(this._storeOptionsAsProperties){let e={},n=this.options.length;for(let r=0;r<n;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,n)=>Object.assign(e,n.opts()),{})}error(e,n){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=n||{},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 ge.env){let n=e.attributeName();(this.getOptionValue(n)===void 0||["default","config","env"].includes(this.getOptionValueSource(n)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,ge.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Jp(this.options),n=r=>this.getOptionValue(r)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(r));this.options.filter(r=>r.implied!==void 0&&n(r.attributeName())&&e.valueFromOption(this.getOptionValue(r.attributeName()),r)).forEach(r=>{Object.keys(r.implied).filter(s=>!n(s)).forEach(s=>{this.setOptionValueWithSource(s,r.implied[s],"implied")})})}missingArgument(e){let n=`error: missing required argument '${e}'`;this.error(n,{code:"commander.missingArgument"})}optionMissingArgument(e){let n=`error: option '${e.flags}' argument missing`;this.error(n,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let n=`error: required option '${e.flags}' not specified`;this.error(n,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,n){let r=o=>{let l=o.attributeName(),c=this.getOptionValue(l),u=this.options.find(f=>f.negate&&l===f.attributeName()),p=this.options.find(f=>!f.negate&&l===f.attributeName());return u&&(u.presetArg===void 0&&c===!1||u.presetArg!==void 0&&c===u.presetArg)?u:p||o},s=o=>{let l=r(o),c=l.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${l.envVar}'`:`option '${l.flags}'`},i=`error: ${s(e)} cannot be used with ${s(n)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let n="";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);n=ql(e,s)}let r=`error: unknown option '${e}'${n}`;this.error(r,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let n=this.registeredArguments.length,r=n===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${n} argument${r} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],n="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(i=>{s.push(i.name()),i.alias()&&s.push(i.alias())}),n=ql(e,s)}let r=`error: unknown command '${e}'${n}`;this.error(r,{code:"commander.unknownCommand"})}version(e,n,r){if(e===void 0)return this._version;this._version=e,n=n||"-V, --version",r=r||"output the version number";let s=this.createOption(n,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,n){return e===void 0&&n===void 0?this._description:(this._description=e,n&&(this._argsDescription=n),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let n=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(n=this.commands[this.commands.length-1]),e===n._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 n._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(n=>this.alias(n)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let n=this.registeredArguments.map(r=>Wp(r));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?n:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=Rt.basename(e,Rt.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let n=this.createHelp();return n.helpWidth===void 0&&(n.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),n.formatHelp(this,n)}_getHelpContext(e){e=e||{};let n={error:!!e.error},r;return n.error?r=s=>this._outputConfiguration.writeErr(s):r=s=>this._outputConfiguration.writeOut(s),n.write=e.write||r,n.command=this,n}outputHelp(e){let n;typeof e=="function"&&(n=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(n&&(s=n(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,n){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",n=n??"display help for command",this._helpOption=this.createOption(e,n),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 n=ge.exitCode||0;n===0&&e&&typeof e!="function"&&e.error&&(n=1),this._exit(n,"commander.help","(outputHelp)")}addHelpText(e,n){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=n||{},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 ge.env){let n=e.attributeName();(this.getOptionValue(n)===void 0||["default","config","env"].includes(this.getOptionValueSource(n)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,ge.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new wf(this.options),n=r=>this.getOptionValue(r)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(r));this.options.filter(r=>r.implied!==void 0&&n(r.attributeName())&&e.valueFromOption(this.getOptionValue(r.attributeName()),r)).forEach(r=>{Object.keys(r.implied).filter(s=>!n(s)).forEach(s=>{this.setOptionValueWithSource(s,r.implied[s],"implied")})})}missingArgument(e){let n=`error: missing required argument '${e}'`;this.error(n,{code:"commander.missingArgument"})}optionMissingArgument(e){let n=`error: option '${e.flags}' argument missing`;this.error(n,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let n=`error: required option '${e.flags}' not specified`;this.error(n,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,n){let r=o=>{let l=o.attributeName(),c=this.getOptionValue(l),u=this.options.find(f=>f.negate&&l===f.attributeName()),p=this.options.find(f=>!f.negate&&l===f.attributeName());return u&&(u.presetArg===void 0&&c===!1||u.presetArg!==void 0&&c===u.presetArg)?u:p||o},s=o=>{let l=r(o),c=l.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${l.envVar}'`:`option '${l.flags}'`},i=`error: ${s(e)} cannot be used with ${s(n)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let n="";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);n=Xl(e,s)}let r=`error: unknown option '${e}'${n}`;this.error(r,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let n=this.registeredArguments.length,r=n===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${n} argument${r} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],n="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(i=>{s.push(i.name()),i.alias()&&s.push(i.alias())}),n=Xl(e,s)}let r=`error: unknown command '${e}'${n}`;this.error(r,{code:"commander.unknownCommand"})}version(e,n,r){if(e===void 0)return this._version;this._version=e,n=n||"-V, --version",r=r||"output the version number";let s=this.createOption(n,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,n){return e===void 0&&n===void 0?this._description:(this._description=e,n&&(this._argsDescription=n),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let n=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(n=this.commands[this.commands.length-1]),e===n._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 n._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(n=>this.alias(n)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let n=this.registeredArguments.map(r=>bf(r));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?n:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=Ct.basename(e,Ct.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let n=this.createHelp();return n.helpWidth===void 0&&(n.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),n.formatHelp(this,n)}_getHelpContext(e){e=e||{};let n={error:!!e.error},r;return n.error?r=s=>this._outputConfiguration.writeErr(s):r=s=>this._outputConfiguration.writeOut(s),n.write=e.write||r,n.command=this,n}outputHelp(e){let n;typeof e=="function"&&(n=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(n&&(s=n(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,n){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",n=n??"display help for command",this._helpOption=this.createOption(e,n),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 n=ge.exitCode||0;n===0&&e&&typeof e!="function"&&e.error&&(n=1),this._exit(n,"commander.help","(outputHelp)")}addHelpText(e,n){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 n=="function"?o=n({error:i.error,command:i.command}):o=n,o&&i.write(`${o}
23
- `)}),this}_outputHelpIfRequested(e){let n=this._getHelpOption();n&&e.find(s=>n.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Fl(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let n,r="127.0.0.1",s="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?n=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(n=i[1],/^\d+$/.test(i[3])?s=i[3]:r=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(n=i[1],r=i[3],s=i[4]),n&&s!=="0"?`${n}=${r}:${parseInt(s)+1}`:e})}Bl.Command=Mo});var Vl=se(We=>{var{Argument:Hl}=ni(),{Command:zo}=Kl(),{CommanderError:Xp,InvalidArgumentError:Gl}=vs(),{Help:Qp}=Io(),{Option:Zl}=Po();We.program=new zo;We.createCommand=t=>new zo(t);We.createOption=(t,e)=>new Zl(t,e);We.createArgument=(t,e)=>new Hl(t,e);We.Command=zo;We.Option=Zl;We.Argument=Hl;We.Help=Qp;We.CommanderError=Xp;We.InvalidArgumentError=Gl;We.InvalidOptionArgumentError=Gl});var Ss=se(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.getParsedType=ue.ZodParsedType=ue.objectUtil=ue.util=void 0;var Ho;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function n(s){throw new Error}t.assertNever=n,t.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},t.getValidEnumValues=s=>{let i=t.objectKeys(s).filter(l=>typeof s[s[l]]!="number"),o={};for(let l of i)o[l]=s[l];return t.objectValues(o)},t.objectValues=s=>t.objectKeys(s).map(function(i){return s[i]}),t.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},t.find=(s,i)=>{for(let o of s)if(i(o))return o},t.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)}t.joinValues=r,t.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(Ho||(ue.util=Ho={}));var vc;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(vc||(ue.objectUtil=vc={}));ue.ZodParsedType=Ho.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var bm=t=>{switch(typeof t){case"undefined":return ue.ZodParsedType.undefined;case"string":return ue.ZodParsedType.string;case"number":return Number.isNaN(t)?ue.ZodParsedType.nan:ue.ZodParsedType.number;case"boolean":return ue.ZodParsedType.boolean;case"function":return ue.ZodParsedType.function;case"bigint":return ue.ZodParsedType.bigint;case"symbol":return ue.ZodParsedType.symbol;case"object":return Array.isArray(t)?ue.ZodParsedType.array:t===null?ue.ZodParsedType.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?ue.ZodParsedType.promise:typeof Map<"u"&&t instanceof Map?ue.ZodParsedType.map:typeof Set<"u"&&t instanceof Set?ue.ZodParsedType.set:typeof Date<"u"&&t instanceof Date?ue.ZodParsedType.date:ue.ZodParsedType.object;default:return ue.ZodParsedType.unknown}};ue.getParsedType=bm});var gi=se(nn=>{"use strict";Object.defineProperty(nn,"__esModule",{value:!0});nn.ZodError=nn.quotelessJson=nn.ZodIssueCode=void 0;var wc=Ss();nn.ZodIssueCode=wc.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 vm=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");nn.quotelessJson=vm;var Ts=class t 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 n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=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(n(o));else{let l=r,c=0;for(;c<o.path.length;){let u=o.path[c];c===o.path.length-1?(l[u]=l[u]||{_errors:[]},l[u]._errors.push(n(o))):l[u]=l[u]||{_errors:[]},l=l[u],c++}}};return s(this),r}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,wc.util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];n[i]=n[i]||[],n[i].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};nn.ZodError=Ts;Ts.create=t=>new Ts(t)});var Zo=se(Go=>{"use strict";Object.defineProperty(Go,"__esModule",{value:!0});var Ae=gi(),Dn=Ss(),wm=(t,e)=>{let n;switch(t.code){case Ae.ZodIssueCode.invalid_type:t.received===Dn.ZodParsedType.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case Ae.ZodIssueCode.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,Dn.util.jsonStringifyReplacer)}`;break;case Ae.ZodIssueCode.unrecognized_keys:n=`Unrecognized key(s) in object: ${Dn.util.joinValues(t.keys,", ")}`;break;case Ae.ZodIssueCode.invalid_union:n="Invalid input";break;case Ae.ZodIssueCode.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Dn.util.joinValues(t.options)}`;break;case Ae.ZodIssueCode.invalid_enum_value:n=`Invalid enum value. Expected ${Dn.util.joinValues(t.options)}, received '${t.received}'`;break;case Ae.ZodIssueCode.invalid_arguments:n="Invalid function arguments";break;case Ae.ZodIssueCode.invalid_return_type:n="Invalid function return type";break;case Ae.ZodIssueCode.invalid_date:n="Invalid date";break;case Ae.ZodIssueCode.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:Dn.util.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case Ae.ZodIssueCode.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case Ae.ZodIssueCode.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case Ae.ZodIssueCode.custom:n="Invalid input";break;case Ae.ZodIssueCode.invalid_intersection_types:n="Intersection results could not be merged";break;case Ae.ZodIssueCode.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case Ae.ZodIssueCode.not_finite:n="Number must be finite";break;default:n=e.defaultError,Dn.util.assertNever(t)}return{message:n}};Go.default=wm});var yi=se(rn=>{"use strict";var km=rn&&rn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(rn,"__esModule",{value:!0});rn.defaultErrorMap=void 0;rn.setErrorMap=_m;rn.getErrorMap=Sm;var kc=km(Zo());rn.defaultErrorMap=kc.default;var _c=kc.default;function _m(t){_c=t}function Sm(){return _c}});var Wo=se(ae=>{"use strict";var Tm=ae&&ae.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(ae,"__esModule",{value:!0});ae.isAsync=ae.isValid=ae.isDirty=ae.isAborted=ae.OK=ae.DIRTY=ae.INVALID=ae.ParseStatus=ae.EMPTY_PATH=ae.makeIssue=void 0;ae.addIssueToContext=Rm;var xm=yi(),Sc=Tm(Zo()),Em=t=>{let{data:e,path:n,errorMaps:r,issueData:s}=t,i=[...n,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let l="",c=r.filter(u=>!!u).slice().reverse();for(let u of c)l=u(o,{data:e,defaultError:l}).message;return{...s,path:i,message:l}};ae.makeIssue=Em;ae.EMPTY_PATH=[];function Rm(t,e){let n=(0,xm.getErrorMap)(),r=(0,ae.makeIssue)({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Sc.default?void 0:Sc.default].filter(s=>!!s)});t.common.issues.push(r)}var Vo=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let s of n){if(s.status==="aborted")return ae.INVALID;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let s of n){let i=await s.key,o=await s.value;r.push({key:i,value:o})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let s of n){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return ae.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}}};ae.ParseStatus=Vo;ae.INVALID=Object.freeze({status:"aborted"});var Im=t=>({status:"dirty",value:t});ae.DIRTY=Im;var Am=t=>({status:"valid",value:t});ae.OK=Am;var Cm=t=>t.status==="aborted";ae.isAborted=Cm;var $m=t=>t.status==="dirty";ae.isDirty=$m;var Pm=t=>t.status==="valid";ae.isValid=Pm;var jm=t=>typeof Promise<"u"&&t instanceof Promise;ae.isAsync=jm});var xc=se(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0})});var Rc=se(bi=>{"use strict";Object.defineProperty(bi,"__esModule",{value:!0});bi.errorUtil=void 0;var Ec;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(Ec||(bi.errorUtil=Ec={}))});var Lc=se(k=>{"use strict";Object.defineProperty(k,"__esModule",{value:!0});k.discriminatedUnion=k.date=k.boolean=k.bigint=k.array=k.any=k.coerce=k.ZodFirstPartyTypeKind=k.late=k.ZodSchema=k.Schema=k.ZodReadonly=k.ZodPipeline=k.ZodBranded=k.BRAND=k.ZodNaN=k.ZodCatch=k.ZodDefault=k.ZodNullable=k.ZodOptional=k.ZodTransformer=k.ZodEffects=k.ZodPromise=k.ZodNativeEnum=k.ZodEnum=k.ZodLiteral=k.ZodLazy=k.ZodFunction=k.ZodSet=k.ZodMap=k.ZodRecord=k.ZodTuple=k.ZodIntersection=k.ZodDiscriminatedUnion=k.ZodUnion=k.ZodObject=k.ZodArray=k.ZodVoid=k.ZodNever=k.ZodUnknown=k.ZodAny=k.ZodNull=k.ZodUndefined=k.ZodSymbol=k.ZodDate=k.ZodBoolean=k.ZodBigInt=k.ZodNumber=k.ZodString=k.ZodType=void 0;k.NEVER=k.void=k.unknown=k.union=k.undefined=k.tuple=k.transformer=k.symbol=k.string=k.strictObject=k.set=k.record=k.promise=k.preprocess=k.pipeline=k.ostring=k.optional=k.onumber=k.oboolean=k.object=k.number=k.nullable=k.null=k.never=k.nativeEnum=k.nan=k.map=k.literal=k.lazy=k.intersection=k.instanceof=k.function=k.enum=k.effect=void 0;k.datetimeRegex=Pc;k.custom=Nc;var A=gi(),vi=yi(),q=Rc(),T=Wo(),C=Ss(),et=class{constructor(e,n,r,s){this._cachedPath=[],this.parent=e,this.data=n,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}},Ic=(t,e)=>{if((0,T.isValid)(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new A.ZodError(t.common.issues);return this._error=n,this._error}}};function X(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:s}=t;if(e&&(n||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:c}=t;return o.code==="invalid_enum_value"?{message:c??l.defaultError}:typeof l.data>"u"?{message:c??r??l.defaultError}:o.code!=="invalid_type"?{message:l.defaultError}:{message:c??n??l.defaultError}},description:s}}var Q=class{get description(){return this._def.description}_getType(e){return(0,C.getParsedType)(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:(0,C.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new T.ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:(0,C.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if((0,T.isAsync)(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,C.getParsedType)(e)},s=this._parseSync({data:e,path:r.path,parent:r});return Ic(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,C.getParsedType)(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return(0,T.isValid)(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>(0,T.isValid)(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,C.getParsedType)(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await((0,T.isAsync)(s)?s:Promise.resolve(s));return Ic(r,i)}refine(e,n){let r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,i)=>{let o=e(s),l=()=>i.addIssue({code:A.ZodIssueCode.custom,...r(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(l(),!1)):o?!0:(l(),!1)})}refinement(e,n){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(e){return new Fe({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:n=>this["~validate"](n)}}optional(){return Qe.create(this,this._def)}nullable(){return bt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return zt.create(this)}promise(){return an.create(this,this._def)}or(e){return Hn.create([this,e],this._def)}and(e){return Gn.create(this,e,this._def)}transform(e){return new Fe({...X(this._def),schema:this,typeName:Z.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new Jn({...X(this._def),innerType:this,defaultValue:n,typeName:Z.ZodDefault})}brand(){return new xs({typeName:Z.ZodBranded,type:this,...X(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Xn({...X(this._def),innerType:this,catchValue:n,typeName:Z.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Es.create(this,e)}readonly(){return Qn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};k.ZodType=Q;k.Schema=Q;k.ZodSchema=Q;var Nm=/^c[^\s-]{8,}$/i,Om=/^[0-9a-z]+$/,Mm=/^[0-9A-HJKMNP-TV-Z]{26}$/i,zm=/^[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,Dm=/^[a-z0-9_-]{21}$/i,Lm=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Um=/^[-+]?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)?)??$/,qm=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Fm="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Yo,Bm=/^(?:(?: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])$/,Km=/^(?:(?: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])$/,Hm=/^(([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]))$/,Gm=/^(([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])$/,Zm=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Vm=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Cc="((\\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])))",Wm=new RegExp(`^${Cc}$`);function $c(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function Ym(t){return new RegExp(`^${$c(t)}$`)}function Pc(t){let e=`${Cc}T${$c(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function Jm(t,e){return!!((e==="v4"||!e)&&Bm.test(t)||(e==="v6"||!e)&&Hm.test(t))}function Xm(t,e){if(!Lm.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.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 Qm(t,e){return!!((e==="v4"||!e)&&Km.test(t)||(e==="v6"||!e)&&Gm.test(t))}var sn=class t extends Q{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==C.ZodParsedType.string){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.string,received:i.parsedType}),T.INVALID}let r=new T.ParseStatus,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:A.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,T.addIssueToContext)(s,{code:A.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,T.addIssueToContext)(s,{code:A.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):l&&(0,T.addIssueToContext)(s,{code:A.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")qm.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"email",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Yo||(Yo=new RegExp(Fm,"u")),Yo.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"emoji",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")zm.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"uuid",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")Dm.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"nanoid",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")Nm.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"cuid",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")Om.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"cuid2",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")Mm.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"ulid",code:A.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,T.addIssueToContext)(s,{validation:"url",code:A.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,T.addIssueToContext)(s,{validation:"regex",code:A.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,T.addIssueToContext)(s,{code:A.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,T.addIssueToContext)(s,{code:A.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,T.addIssueToContext)(s,{code:A.ZodIssueCode.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Pc(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:A.ZodIssueCode.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?Wm.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:A.ZodIssueCode.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Ym(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:A.ZodIssueCode.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?Um.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"duration",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?Jm(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"ip",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?Xm(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"jwt",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?Qm(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"cidr",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?Zm.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"base64",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?Vm.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"base64url",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):C.util.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:A.ZodIssueCode.invalid_string,...q.errorUtil.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...q.errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...q.errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...q.errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...q.errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...q.errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...q.errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...q.errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...q.errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...q.errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...q.errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...q.errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...q.errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...q.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,...q.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,...q.errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...q.errorUtil.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...q.errorUtil.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...q.errorUtil.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...q.errorUtil.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...q.errorUtil.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...q.errorUtil.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...q.errorUtil.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...q.errorUtil.errToObj(n)})}nonempty(e){return this.min(1,q.errorUtil.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...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 n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};k.ZodString=sn;sn.create=t=>new sn({checks:[],typeName:Z.ZodString,coerce:t?.coerce??!1,...X(t)});function eg(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,i=Number.parseInt(t.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var Ln=class t extends Q{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)!==C.ZodParsedType.number){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.number,received:i.parsedType}),T.INVALID}let r,s=new T.ParseStatus;for(let i of this._def.checks)i.kind==="int"?C.util.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:A.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,T.addIssueToContext)(r,{code:A.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,T.addIssueToContext)(r,{code:A.ZodIssueCode.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?eg(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:A.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,T.addIssueToContext)(r,{code:A.ZodIssueCode.not_finite,message:i.message}),s.dirty()):C.util.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,q.errorUtil.toString(n))}gt(e,n){return this.setLimit("min",e,!1,q.errorUtil.toString(n))}lte(e,n){return this.setLimit("max",e,!0,q.errorUtil.toString(n))}lt(e,n){return this.setLimit("max",e,!1,q.errorUtil.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:q.errorUtil.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:q.errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:q.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:q.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:q.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:q.errorUtil.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:q.errorUtil.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:q.errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:q.errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:q.errorUtil.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&C.util.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};k.ZodNumber=Ln;Ln.create=t=>new Ln({checks:[],typeName:Z.ZodNumber,coerce:t?.coerce||!1,...X(t)});var Un=class t extends Q{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)!==C.ZodParsedType.bigint)return this._getInvalidInput(e);let r,s=new T.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,T.addIssueToContext)(r,{code:A.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,T.addIssueToContext)(r,{code:A.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,T.addIssueToContext)(r,{code:A.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):C.util.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(n,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.bigint,received:n.parsedType}),T.INVALID}gte(e,n){return this.setLimit("min",e,!0,q.errorUtil.toString(n))}gt(e,n){return this.setLimit("min",e,!1,q.errorUtil.toString(n))}lte(e,n){return this.setLimit("max",e,!0,q.errorUtil.toString(n))}lt(e,n){return this.setLimit("max",e,!1,q.errorUtil.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:q.errorUtil.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:q.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:q.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:q.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:q.errorUtil.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:q.errorUtil.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};k.ZodBigInt=Un;Un.create=t=>new Un({checks:[],typeName:Z.ZodBigInt,coerce:t?.coerce??!1,...X(t)});var qn=class extends Q{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==C.ZodParsedType.boolean){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.boolean,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};k.ZodBoolean=qn;qn.create=t=>new qn({typeName:Z.ZodBoolean,coerce:t?.coerce||!1,...X(t)});var Fn=class t extends Q{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==C.ZodParsedType.date){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.date,received:i.parsedType}),T.INVALID}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:A.ZodIssueCode.invalid_date}),T.INVALID}let r=new T.ParseStatus,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:A.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,T.addIssueToContext)(s,{code:A.ZodIssueCode.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):C.util.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:q.errorUtil.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:q.errorUtil.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};k.ZodDate=Fn;Fn.create=t=>new Fn({checks:[],coerce:t?.coerce||!1,typeName:Z.ZodDate,...X(t)});var Kr=class extends Q{_parse(e){if(this._getType(e)!==C.ZodParsedType.symbol){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.symbol,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};k.ZodSymbol=Kr;Kr.create=t=>new Kr({typeName:Z.ZodSymbol,...X(t)});var Bn=class extends Q{_parse(e){if(this._getType(e)!==C.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.undefined,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};k.ZodUndefined=Bn;Bn.create=t=>new Bn({typeName:Z.ZodUndefined,...X(t)});var Kn=class extends Q{_parse(e){if(this._getType(e)!==C.ZodParsedType.null){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.null,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};k.ZodNull=Kn;Kn.create=t=>new Kn({typeName:Z.ZodNull,...X(t)});var on=class extends Q{constructor(){super(...arguments),this._any=!0}_parse(e){return(0,T.OK)(e.data)}};k.ZodAny=on;on.create=t=>new on({typeName:Z.ZodAny,...X(t)});var Mt=class extends Q{constructor(){super(...arguments),this._unknown=!0}_parse(e){return(0,T.OK)(e.data)}};k.ZodUnknown=Mt;Mt.create=t=>new Mt({typeName:Z.ZodUnknown,...X(t)});var at=class extends Q{_parse(e){let n=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(n,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.never,received:n.parsedType}),T.INVALID}};k.ZodNever=at;at.create=t=>new at({typeName:Z.ZodNever,...X(t)});var Hr=class extends Q{_parse(e){if(this._getType(e)!==C.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.void,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};k.ZodVoid=Hr;Hr.create=t=>new Hr({typeName:Z.ZodVoid,...X(t)});var zt=class t extends Q{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==C.ZodParsedType.array)return(0,T.addIssueToContext)(n,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.array,received:n.parsedType}),T.INVALID;if(s.exactLength!==null){let o=n.data.length>s.exactLength.value,l=n.data.length<s.exactLength.value;(o||l)&&((0,T.addIssueToContext)(n,{code:o?A.ZodIssueCode.too_big:A.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&&n.data.length<s.minLength.value&&((0,T.addIssueToContext)(n,{code:A.ZodIssueCode.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&((0,T.addIssueToContext)(n,{code:A.ZodIssueCode.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((o,l)=>s.type._parseAsync(new et(n,o,n.path,l)))).then(o=>T.ParseStatus.mergeArray(r,o));let i=[...n.data].map((o,l)=>s.type._parseSync(new et(n,o,n.path,l)));return T.ParseStatus.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:q.errorUtil.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:q.errorUtil.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:q.errorUtil.toString(n)}})}nonempty(e){return this.min(1,e)}};k.ZodArray=zt;zt.create=(t,e)=>new zt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Z.ZodArray,...X(e)});function Br(t){if(t instanceof De){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=Qe.create(Br(r))}return new De({...t._def,shape:()=>e})}else return t instanceof zt?new zt({...t._def,type:Br(t.element)}):t instanceof Qe?Qe.create(Br(t.unwrap())):t instanceof bt?bt.create(Br(t.unwrap())):t instanceof yt?yt.create(t.items.map(e=>Br(e))):t}var De=class t extends Q{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(),n=C.util.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==C.ZodParsedType.object){let u=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(u,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.object,received:u.parsedType}),T.INVALID}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),l=[];if(!(this._def.catchall instanceof at&&this._def.unknownKeys==="strip"))for(let u in s.data)o.includes(u)||l.push(u);let c=[];for(let u of o){let p=i[u],f=s.data[u];c.push({key:{status:"valid",value:u},value:p._parse(new et(s,f,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof at){let u=this._def.unknownKeys;if(u==="passthrough")for(let p of l)c.push({key:{status:"valid",value:p},value:{status:"valid",value:s.data[p]}});else if(u==="strict")l.length>0&&((0,T.addIssueToContext)(s,{code:A.ZodIssueCode.unrecognized_keys,keys:l}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let p of l){let f=s.data[p];c.push({key:{status:"valid",value:p},value:u._parse(new et(s,f,s.path,p)),alwaysSet:p in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let u=[];for(let p of c){let f=await p.key,b=await p.value;u.push({key:f,value:b,alwaysSet:p.alwaysSet})}return u}).then(u=>T.ParseStatus.mergeObjectSync(r,u)):T.ParseStatus.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return q.errorUtil.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:q.errorUtil.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Z.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of C.util.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of C.util.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return Br(this)}partial(e){let n={};for(let r of C.util.objectKeys(this.shape)){let s=this.shape[r];e&&!e[r]?n[r]=s:n[r]=s.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of C.util.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Qe;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return jc(C.util.objectKeys(this.shape))}};k.ZodObject=De;De.create=(t,e)=>new De({shape:()=>t,unknownKeys:"strip",catchall:at.create(),typeName:Z.ZodObject,...X(e)});De.strictCreate=(t,e)=>new De({shape:()=>t,unknownKeys:"strict",catchall:at.create(),typeName:Z.ZodObject,...X(e)});De.lazycreate=(t,e)=>new De({shape:t,unknownKeys:"strip",catchall:at.create(),typeName:Z.ZodObject,...X(e)});var Hn=class extends Q{_parse(e){let{ctx:n}=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 n.common.issues.push(...l.ctx.common.issues),l.result;let o=i.map(l=>new A.ZodError(l.ctx.common.issues));return(0,T.addIssueToContext)(n,{code:A.ZodIssueCode.invalid_union,unionErrors:o}),T.INVALID}if(n.common.async)return Promise.all(r.map(async i=>{let o={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let c of r){let u={...n,common:{...n.common,issues:[]},parent:null},p=c._parseSync({data:n.data,path:n.path,parent:u});if(p.status==="valid")return p;p.status==="dirty"&&!i&&(i={result:p,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let l=o.map(c=>new A.ZodError(c));return(0,T.addIssueToContext)(n,{code:A.ZodIssueCode.invalid_union,unionErrors:l}),T.INVALID}}get options(){return this._def.options}};k.ZodUnion=Hn;Hn.create=(t,e)=>new Hn({options:t,typeName:Z.ZodUnion,...X(e)});var Ot=t=>t instanceof Zn?Ot(t.schema):t instanceof Fe?Ot(t.innerType()):t instanceof Vn?[t.value]:t instanceof Wn?t.options:t instanceof Yn?C.util.objectValues(t.enum):t instanceof Jn?Ot(t._def.innerType):t instanceof Bn?[void 0]:t instanceof Kn?[null]:t instanceof Qe?[void 0,...Ot(t.unwrap())]:t instanceof bt?[null,...Ot(t.unwrap())]:t instanceof xs||t instanceof Qn?Ot(t.unwrap()):t instanceof Xn?Ot(t._def.innerType):[],wi=class t extends Q{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==C.ZodParsedType.object)return(0,T.addIssueToContext)(n,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.object,received:n.parsedType}),T.INVALID;let r=this.discriminator,s=n.data[r],i=this.optionsMap.get(s);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):((0,T.addIssueToContext)(n,{code:A.ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),T.INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let s=new Map;for(let i of n){let o=Ot(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 t({typeName:Z.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...X(r)})}};k.ZodDiscriminatedUnion=wi;function Jo(t,e){let n=(0,C.getParsedType)(t),r=(0,C.getParsedType)(e);if(t===e)return{valid:!0,data:t};if(n===C.ZodParsedType.object&&r===C.ZodParsedType.object){let s=C.util.objectKeys(e),i=C.util.objectKeys(t).filter(l=>s.indexOf(l)!==-1),o={...t,...e};for(let l of i){let c=Jo(t[l],e[l]);if(!c.valid)return{valid:!1};o[l]=c.data}return{valid:!0,data:o}}else if(n===C.ZodParsedType.array&&r===C.ZodParsedType.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<t.length;i++){let o=t[i],l=e[i],c=Jo(o,l);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===C.ZodParsedType.date&&r===C.ZodParsedType.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Gn=class extends Q{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=(i,o)=>{if((0,T.isAborted)(i)||(0,T.isAborted)(o))return T.INVALID;let l=Jo(i.value,o.value);return l.valid?(((0,T.isDirty)(i)||(0,T.isDirty)(o))&&n.dirty(),{status:n.value,value:l.data}):((0,T.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_intersection_types}),T.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}))}};k.ZodIntersection=Gn;Gn.create=(t,e,n)=>new Gn({left:t,right:e,typeName:Z.ZodIntersection,...X(n)});var yt=class t extends Q{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==C.ZodParsedType.array)return(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.array,received:r.parsedType}),T.INVALID;if(r.data.length<this._def.items.length)return(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),T.INVALID;!this._def.rest&&r.data.length>this._def.items.length&&((0,T.addIssueToContext)(r,{code:A.ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let i=[...r.data].map((o,l)=>{let c=this._def.items[l]||this._def.rest;return c?c._parse(new et(r,o,r.path,l)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>T.ParseStatus.mergeArray(n,o)):T.ParseStatus.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};k.ZodTuple=yt;yt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new yt({items:t,typeName:Z.ZodTuple,rest:null,...X(e)})};var ki=class t extends Q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==C.ZodParsedType.object)return(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.object,received:r.parsedType}),T.INVALID;let s=[],i=this._def.keyType,o=this._def.valueType;for(let l in r.data)s.push({key:i._parse(new et(r,l,r.path,l)),value:o._parse(new et(r,r.data[l],r.path,l)),alwaysSet:l in r.data});return r.common.async?T.ParseStatus.mergeObjectAsync(n,s):T.ParseStatus.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof Q?new t({keyType:e,valueType:n,typeName:Z.ZodRecord,...X(r)}):new t({keyType:sn.create(),valueType:e,typeName:Z.ZodRecord,...X(n)})}};k.ZodRecord=ki;var Gr=class extends Q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==C.ZodParsedType.map)return(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.map,received:r.parsedType}),T.INVALID;let s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([l,c],u)=>({key:s._parse(new et(r,l,r.path,[u,"key"])),value:i._parse(new et(r,c,r.path,[u,"value"]))}));if(r.common.async){let l=new Map;return Promise.resolve().then(async()=>{for(let c of o){let u=await c.key,p=await c.value;if(u.status==="aborted"||p.status==="aborted")return T.INVALID;(u.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(u.value,p.value)}return{status:n.value,value:l}})}else{let l=new Map;for(let c of o){let u=c.key,p=c.value;if(u.status==="aborted"||p.status==="aborted")return T.INVALID;(u.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(u.value,p.value)}return{status:n.value,value:l}}}};k.ZodMap=Gr;Gr.create=(t,e,n)=>new Gr({valueType:e,keyType:t,typeName:Z.ZodMap,...X(n)});var Zr=class t extends Q{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==C.ZodParsedType.set)return(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.set,received:r.parsedType}),T.INVALID;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&((0,T.addIssueToContext)(r,{code:A.ZodIssueCode.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&((0,T.addIssueToContext)(r,{code:A.ZodIssueCode.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let i=this._def.valueType;function o(c){let u=new Set;for(let p of c){if(p.status==="aborted")return T.INVALID;p.status==="dirty"&&n.dirty(),u.add(p.value)}return{status:n.value,value:u}}let l=[...r.data.values()].map((c,u)=>i._parse(new et(r,c,r.path,u)));return r.common.async?Promise.all(l).then(c=>o(c)):o(l)}min(e,n){return new t({...this._def,minSize:{value:e,message:q.errorUtil.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:q.errorUtil.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};k.ZodSet=Zr;Zr.create=(t,e)=>new Zr({valueType:t,minSize:null,maxSize:null,typeName:Z.ZodSet,...X(e)});var _i=class t extends Q{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==C.ZodParsedType.function)return(0,T.addIssueToContext)(n,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.function,received:n.parsedType}),T.INVALID;function r(l,c){return(0,T.makeIssue)({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,(0,vi.getErrorMap)(),vi.defaultErrorMap].filter(u=>!!u),issueData:{code:A.ZodIssueCode.invalid_arguments,argumentsError:c}})}function s(l,c){return(0,T.makeIssue)({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,(0,vi.getErrorMap)(),vi.defaultErrorMap].filter(u=>!!u),issueData:{code:A.ZodIssueCode.invalid_return_type,returnTypeError:c}})}let i={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof an){let l=this;return(0,T.OK)(async function(...c){let u=new A.ZodError([]),p=await l._def.args.parseAsync(c,i).catch(v=>{throw u.addIssue(r(c,v)),u}),f=await Reflect.apply(o,this,p);return await l._def.returns._def.type.parseAsync(f,i).catch(v=>{throw u.addIssue(s(f,v)),u})})}else{let l=this;return(0,T.OK)(function(...c){let u=l._def.args.safeParse(c,i);if(!u.success)throw new A.ZodError([r(c,u.error)]);let p=Reflect.apply(o,this,u.data),f=l._def.returns.safeParse(p,i);if(!f.success)throw new A.ZodError([s(p,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:yt.create(e).rest(Mt.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new t({args:e||yt.create([]).rest(Mt.create()),returns:n||Mt.create(),typeName:Z.ZodFunction,...X(r)})}};k.ZodFunction=_i;var Zn=class extends Q{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};k.ZodLazy=Zn;Zn.create=(t,e)=>new Zn({getter:t,typeName:Z.ZodLazy,...X(e)});var Vn=class extends Q{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(n,{received:n.data,code:A.ZodIssueCode.invalid_literal,expected:this._def.value}),T.INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}};k.ZodLiteral=Vn;Vn.create=(t,e)=>new Vn({value:t,typeName:Z.ZodLiteral,...X(e)});function jc(t,e){return new Wn({values:t,typeName:Z.ZodEnum,...X(e)})}var Wn=class t extends Q{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return(0,T.addIssueToContext)(n,{expected:C.util.joinValues(r),received:n.parsedType,code:A.ZodIssueCode.invalid_type}),T.INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return(0,T.addIssueToContext)(n,{received:n.data,code:A.ZodIssueCode.invalid_enum_value,options:r}),T.INVALID}return(0,T.OK)(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};k.ZodEnum=Wn;Wn.create=jc;var Yn=class extends Q{_parse(e){let n=C.util.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==C.ZodParsedType.string&&r.parsedType!==C.ZodParsedType.number){let s=C.util.objectValues(n);return(0,T.addIssueToContext)(r,{expected:C.util.joinValues(s),received:r.parsedType,code:A.ZodIssueCode.invalid_type}),T.INVALID}if(this._cache||(this._cache=new Set(C.util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=C.util.objectValues(n);return(0,T.addIssueToContext)(r,{received:r.data,code:A.ZodIssueCode.invalid_enum_value,options:s}),T.INVALID}return(0,T.OK)(e.data)}get enum(){return this._def.values}};k.ZodNativeEnum=Yn;Yn.create=(t,e)=>new Yn({values:t,typeName:Z.ZodNativeEnum,...X(e)});var an=class extends Q{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==C.ZodParsedType.promise&&n.common.async===!1)return(0,T.addIssueToContext)(n,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.promise,received:n.parsedType}),T.INVALID;let r=n.parsedType===C.ZodParsedType.promise?n.data:Promise.resolve(n.data);return(0,T.OK)(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};k.ZodPromise=an;an.create=(t,e)=>new an({type:t,typeName:Z.ZodPromise,...X(e)});var Fe=class extends Q{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:n,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{(0,T.addIssueToContext)(r,o),o.fatal?n.abort():n.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(n.value==="aborted")return T.INVALID;let c=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return c.status==="aborted"?T.INVALID:c.status==="dirty"||n.value==="dirty"?(0,T.DIRTY)(c.value):c});{if(n.value==="aborted")return T.INVALID;let l=this._def.schema._parseSync({data:o,path:r.path,parent:r});return l.status==="aborted"?T.INVALID:l.status==="dirty"||n.value==="dirty"?(0,T.DIRTY)(l.value):l}}if(s.type==="refinement"){let o=l=>{let c=s.refinement(l,i);if(r.common.async)return Promise.resolve(c);if(c 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"?T.INVALID:(l.status==="dirty"&&n.dirty(),o(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?T.INVALID:(l.status==="dirty"&&n.dirty(),o(l.value).then(()=>({status:n.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,T.isValid)(o))return T.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:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>(0,T.isValid)(o)?Promise.resolve(s.transform(o.value,i)).then(l=>({status:n.value,value:l})):T.INVALID);C.util.assertNever(s)}};k.ZodEffects=Fe;k.ZodTransformer=Fe;Fe.create=(t,e,n)=>new Fe({schema:t,typeName:Z.ZodEffects,effect:e,...X(n)});Fe.createWithPreprocess=(t,e,n)=>new Fe({schema:e,effect:{type:"preprocess",transform:t},typeName:Z.ZodEffects,...X(n)});var Qe=class extends Q{_parse(e){return this._getType(e)===C.ZodParsedType.undefined?(0,T.OK)(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};k.ZodOptional=Qe;Qe.create=(t,e)=>new Qe({innerType:t,typeName:Z.ZodOptional,...X(e)});var bt=class extends Q{_parse(e){return this._getType(e)===C.ZodParsedType.null?(0,T.OK)(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};k.ZodNullable=bt;bt.create=(t,e)=>new bt({innerType:t,typeName:Z.ZodNullable,...X(e)});var Jn=class extends Q{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===C.ZodParsedType.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};k.ZodDefault=Jn;Jn.create=(t,e)=>new Jn({innerType:t,typeName:Z.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...X(e)});var Xn=class extends Q{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return(0,T.isAsync)(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new A.ZodError(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new A.ZodError(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};k.ZodCatch=Xn;Xn.create=(t,e)=>new Xn({innerType:t,typeName:Z.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...X(e)});var Vr=class extends Q{_parse(e){if(this._getType(e)!==C.ZodParsedType.nan){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.nan,received:r.parsedType}),T.INVALID}return{status:"valid",value:e.data}}};k.ZodNaN=Vr;Vr.create=t=>new Vr({typeName:Z.ZodNaN,...X(t)});k.BRAND=Symbol("zod_brand");var xs=class extends Q{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}};k.ZodBranded=xs;var Es=class t extends Q{_parse(e){let{status:n,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"?T.INVALID:i.status==="dirty"?(n.dirty(),(0,T.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"?T.INVALID:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:Z.ZodPipeline})}};k.ZodPipeline=Es;var Qn=class extends Q{_parse(e){let n=this._def.innerType._parse(e),r=s=>((0,T.isValid)(s)&&(s.value=Object.freeze(s.value)),s);return(0,T.isAsync)(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};k.ZodReadonly=Qn;Qn.create=(t,e)=>new Qn({innerType:t,typeName:Z.ZodReadonly,...X(e)});function Ac(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function Nc(t,e={},n){return t?on.create().superRefine((r,s)=>{let i=t(r);if(i instanceof Promise)return i.then(o=>{if(!o){let l=Ac(e,r),c=l.fatal??n??!0;s.addIssue({code:"custom",...l,fatal:c})}});if(!i){let o=Ac(e,r),l=o.fatal??n??!0;s.addIssue({code:"custom",...o,fatal:l})}}):on.create()}k.late={object:De.lazycreate};var Z;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(Z||(k.ZodFirstPartyTypeKind=Z={}));var tg=(t,e={message:`Input not instance of ${t.name}`})=>Nc(n=>n instanceof t,e);k.instanceof=tg;var Oc=sn.create;k.string=Oc;var Mc=Ln.create;k.number=Mc;var ng=Vr.create;k.nan=ng;var rg=Un.create;k.bigint=rg;var zc=qn.create;k.boolean=zc;var sg=Fn.create;k.date=sg;var ig=Kr.create;k.symbol=ig;var og=Bn.create;k.undefined=og;var ag=Kn.create;k.null=ag;var lg=on.create;k.any=lg;var cg=Mt.create;k.unknown=cg;var ug=at.create;k.never=ug;var dg=Hr.create;k.void=dg;var hg=zt.create;k.array=hg;var pg=De.create;k.object=pg;var fg=De.strictCreate;k.strictObject=fg;var mg=Hn.create;k.union=mg;var gg=wi.create;k.discriminatedUnion=gg;var yg=Gn.create;k.intersection=yg;var bg=yt.create;k.tuple=bg;var vg=ki.create;k.record=vg;var wg=Gr.create;k.map=wg;var kg=Zr.create;k.set=kg;var _g=_i.create;k.function=_g;var Sg=Zn.create;k.lazy=Sg;var Tg=Vn.create;k.literal=Tg;var xg=Wn.create;k.enum=xg;var Eg=Yn.create;k.nativeEnum=Eg;var Rg=an.create;k.promise=Rg;var Dc=Fe.create;k.effect=Dc;k.transformer=Dc;var Ig=Qe.create;k.optional=Ig;var Ag=bt.create;k.nullable=Ag;var Cg=Fe.createWithPreprocess;k.preprocess=Cg;var $g=Es.create;k.pipeline=$g;var Pg=()=>Oc().optional();k.ostring=Pg;var jg=()=>Mc().optional();k.onumber=jg;var Ng=()=>zc().optional();k.oboolean=Ng;k.coerce={string:(t=>sn.create({...t,coerce:!0})),number:(t=>Ln.create({...t,coerce:!0})),boolean:(t=>qn.create({...t,coerce:!0})),bigint:(t=>Un.create({...t,coerce:!0})),date:(t=>Fn.create({...t,coerce:!0}))};k.NEVER=T.INVALID});var Xo=se(tt=>{"use strict";var Og=tt&&tt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Wr=tt&&tt.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Og(e,t,n)};Object.defineProperty(tt,"__esModule",{value:!0});Wr(yi(),tt);Wr(Wo(),tt);Wr(xc(),tt);Wr(Ss(),tt);Wr(Lc(),tt);Wr(gi(),tt)});var Fc=se(Le=>{"use strict";var Uc=Le&&Le.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Mg=Le&&Le.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),zg=Le&&Le.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&Uc(e,t,n);return Mg(e,t),e},Dg=Le&&Le.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Uc(e,t,n)};Object.defineProperty(Le,"__esModule",{value:!0});Le.z=void 0;var qc=zg(Xo());Le.z=qc;Dg(Xo(),Le);Le.default=qc});var ke=se(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.ChatLoadResultMsg=h.REPLY_STYLES=h.BUILTIN_REPLY_LANGUAGES=h.ChatLoadMsg=h.ChatListResultMsg=h.ChatListMsg=h.ChatUsageMsg=h.ChatStreamMsg=h.JiraUsersResultMsg=h.DeployClaimResultMsg=h.DeployClaimMsg=h.RuleDiagnoseResultMsg=h.ProjectTestResultMsg=h.RunStatusMsg=h.FailedTest=h.RunUsageMsg=h.RunLogMsg=h.RunClaimMsg=h.HeartbeatMsg=h.HelloMsg=h.RuleConfig=h.ProjectConfig=h.ActionConfig=h.DeployAction=h.EnvironmentConfig=h.PromotionMode=h.DeployStep=h.RespondAction=h.ImplementAction=h.PlanOnlyAction=h.TriggerConfig=h.StatusChangedTrigger=h.CommentKeywordTrigger=h.LabelAddedTrigger=h.ActionType=h.TriggerType=h.ACTIVE_RUN_STATUSES=h.RunStatus=h.needsInputMarkerIn=h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=h.NEEDS_INPUT_COMMENT_MARKER=h.NEEDS_INPUT_LABEL=h.NEEDS_INPUT_ASK_FENCE=h.NEEDS_INPUT_MARKER=h.BRANCH_DEPLOY_ISSUE_KEY=h.REQUIRED_AGENT_CAPABILITIES=h.DEFAULT_AGENT_ID=h.REGISTERED_AGENTS=h.PROTOCOL_VERSION=h.GITHUB_TOKEN_PERMISSIONS=void 0;h.SetupStatusResultMsg=h.SetupStatusMsg=h.DeploySuggestResultMsg=h.SelfMigrationApplyResultMsg=h.SelfMigrationApplyMsg=h.SELF_MIGRATION_DIR=h.EnvPreflightResultMsg=h.EnvPreflightMsg=h.ChatCreateTicketResultMsg=h.ChatCreateTicketMsg=h.ChatTurnResultMsg=h.ChatTurnMsg=h.ChatFile=h.TeamCredsResultMsg=h.TeamCredsMsg=h.KnowledgeSaveResultMsg=h.KnowledgeSaveMsg=h.KnowledgeListResultMsg=h.KnowledgeFile=h.KnowledgeListMsg=h.AuditReviewResultMsg=h.AuditReviewMsg=h.AuditGetResultMsg=h.AuditGetMsg=h.AuditListResultMsg=h.AuditStatsResultMsg=h.AuditStatsMsg=h.AuditListMsg=h.AuditStartResultMsg=h.AuditStartMsg=h.AuditRecord=h.AuditFinding=h.AuditDetailLevel=h.AuditScope=h.AuditSeverity=h.KnowledgeRole=h.AuditRole=h.EpicSuggestResultMsg=h.EpicSuggestMsg=h.EpicListResultMsg=h.EpicChild=h.EpicListMsg=h.BoardTriggerResultMsg=h.BoardTriggerMsg=h.BoardFetchResultMsg=h.BoardFetchMsg=h.RepoDocReadResultMsg=h.RepoDocReadMsg=h.RepoDocsResultMsg=h.RepoDocsMsg=void 0;h.DEFAULT_RESPOND_PROMPT_TEMPLATE=h.BUGFIX_IMPLEMENT_PROMPT_TEMPLATE=h.BUG_INVESTIGATION_PROMPT_TEMPLATE=h.TECHNICAL_PLAN_PROMPT_TEMPLATE=h.MEMORY_UPDATE_PROMPT=h.DEFAULT_IMPLEMENT_PROMPT_TEMPLATE=h.WRITE_TESTS_PROMPT=h.NEEDS_INPUT_OPTIONS_PROMPT=h.DEFAULT_PLAN_PROMPT_TEMPLATE=h.EnrollResponse=h.EnrollRequest=h.ServerToRunnerMsg=h.JiraUsersMsg=h.DeploySuggestMsg=h.DeployFixMsg=h.DeployStartMsg=h.RunRetryPushMsg=h.RunRejectedMsg=h.RunApprovedMsg=h.RunCancelMsg=h.RuleDiagnoseMsg=h.ProjectTestMsg=h.RunClaimResultMsg=h.ConfigMsg=h.HelloAckMsg=h.RunnerToServerMsg=h.AutopilotReportMsg=h.AutopilotNextResultMsg=h.AutopilotNextMsg=h.RunnerUpdateResultMsg=h.AgentProfilesResultMsg=h.AgentProfilesMsg=h.RunPrConflictMsg=h.RunResolveConflictResultMsg=h.RunAnswerResultMsg=h.RunAnswerMsg=h.RunTestFixResultMsg=h.RunTestFixMsg=h.RunResolveConflictMsg=h.RunnerUpdateMsg=h.RepoDocSaveResultMsg=h.RepoDocSaveMsg=h.SetupClaudeMdSaveResultMsg=h.SetupClaudeMdSaveMsg=h.SetupClaudeMdGenerateResultMsg=h.SetupClaudeMdGenerateMsg=h.SetupRecheckResultMsg=h.SetupRecheckMsg=h.RepoUnmapResultMsg=h.RepoUnmapMsg=void 0;h.DEFAULT_DEPLOY_SUGGEST_PROMPT_TEMPLATE=h.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE=h.DEPLOY_FIX_PROMPT_TEMPLATE=h.PROMPT_PRESETS=void 0;h.missingAgentCapabilities=Lg;h.replyPreferenceAppendix=qg;h.pendingMigrationsAppendix=Fg;h.isSelfMigrationFilename=Bg;h.parseRunnerMsg=Kg;h.parseServerMsg=Hg;var a=Fc();h.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."};h.PROTOCOL_VERSION="1.65";h.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}];h.DEFAULT_AGENT_ID="claude-code";h.REQUIRED_AGENT_CAPABILITIES={plan_only:["readOnlyJail","sessionResume"],respond:["readOnlyJail"],implement:["editNoShellJail","sessionResume"],deploy:[],chat:["readOnlyJail","sessionResume"],assist:["readOnlyJail"]};function Lg(t,e){let n=h.REGISTERED_AGENTS.find(r=>r.id===t);return n?(h.REQUIRED_AGENT_CAPABILITIES[e]??[]).filter(r=>!n.capabilities[r]):null}h.BRANCH_DEPLOY_ISSUE_KEY="(branch deploy)";h.NEEDS_INPUT_MARKER="NEEDS-INPUT";h.NEEDS_INPUT_ASK_FENCE="ask";h.NEEDS_INPUT_LABEL="agent-needs-input";h.NEEDS_INPUT_COMMENT_MARKER="Allwright needs your input";h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=["TicketPilot needs your input"];var Ug=t=>t.includes(h.NEEDS_INPUT_COMMENT_MARKER)||h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS.some(e=>t.includes(e));h.needsInputMarkerIn=Ug;h.RunStatus=a.z.enum(["queued","running","posting","awaiting_approval","needs_input","succeeded","failed","timed_out"]);h.ACTIVE_RUN_STATUSES=["queued","running","posting","awaiting_approval"];h.TriggerType=a.z.enum(["label_added","comment_keyword","status_changed"]);h.ActionType=a.z.enum(["plan_only","implement","respond","deploy"]);h.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")});h.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")});h.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")});h.TriggerConfig=a.z.discriminatedUnion("type",[h.LabelAddedTrigger,h.CommentKeywordTrigger,h.StatusChangedTrigger]);h.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(h.DEFAULT_AGENT_ID),model:a.z.string().default("")});h.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(t=>t.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(h.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)});h.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(h.DEFAULT_AGENT_ID),model:a.z.string().default("")});h.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)});h.PromotionMode=a.z.enum(["deploy_only","merge_and_deploy"]);h.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:h.PromotionMode.default("deploy_only"),ticketBranchTemplate:a.z.string().default("agent/{{issueKey}}"),steps:a.z.array(h.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("")});h.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()});h.ActionConfig=a.z.discriminatedUnion("type",[h.PlanOnlyAction,h.ImplementAction,h.RespondAction,h.DeployAction]);h.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([])});h.RuleConfig=a.z.object({id:a.z.string(),projectId:a.z.string(),name:a.z.string(),enabled:a.z.boolean(),trigger:h.TriggerConfig,action:h.ActionConfig});h.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()});h.HeartbeatMsg=a.z.object({type:a.z.literal("heartbeat"),ts:a.z.string()});h.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()});h.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)});h.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()});h.FailedTest=a.z.object({command:a.z.string().max(500),exitCode:a.z.number().int(),tail:a.z.string().max(4e3)});h.RunStatusMsg=a.z.object({type:a.z.literal("run.status"),runId:a.z.string(),status:h.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(h.FailedTest).max(20).optional(),testsPassed:a.z.number().int().nonnegative().optional(),testsTotal:a.z.number().int().nonnegative().optional(),manualSteps:a.z.array(a.z.object({command:a.z.string().max(500),why:a.z.string().max(300).default("")})).max(20).optional(),goLiveDraft:a.z.string().max(4e3).optional(),inputQuestions:a.z.string().max(4e3).optional(),inputOptions:a.z.array(a.z.string().max(200)).max(5).optional()});h.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("")}))});h.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)});h.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()});h.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:h.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()});h.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()});h.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)});h.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()});h.ChatListMsg=a.z.object({type:a.z.literal("chat.list"),requestId:a.z.string(),projectId:a.z.string()});h.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([])});h.ChatLoadMsg=a.z.object({type:a.z.literal("chat.load"),requestId:a.z.string(),sessionId:a.z.string()});h.BUILTIN_REPLY_LANGUAGES=[{name:"English",instruction:"Write your prose in English."},{name:"Hindi",instruction:"Write your prose in Hindi, in the Devanagari script. Keep technical terms that have no everyday Hindi equivalent in English rather than inventing a translation."},{name:"Hinglish",instruction:"Write your prose in Hinglish: conversational Hindi written in the Latin alphabet, with English technical words left in English - the way an Indian developer talks at work."}];h.REPLY_STYLES=[{id:"technical",label:"Technical",hint:"Full detail - names files, functions and trade-offs",instruction:"Answer at full technical depth: name the files, functions and data structures involved, and state trade-offs precisely. Assume the reader reads code every day."},{id:"balanced",label:"Balanced",hint:"Plain explanation, with the technical detail that matters",instruction:"Explain in plain language first, then add the technical detail that actually matters for the decision. Assume the reader is technical but does not know this codebase."},{id:"simple",label:"Simple",hint:"Everyday words - no jargon unless it is unavoidable",instruction:"Answer in everyday words, as if to someone who does not write code. Avoid jargon; when a technical term is unavoidable, explain it in half a sentence. Prefer short paragraphs and concrete examples over precision about internals."}];function qg(t){let e=[],n=(t.language??"").trim();if(n){let s=h.BUILTIN_REPLY_LANGUAGES.find(i=>i.name.toLowerCase()===n.toLowerCase());e.push((t.languageInstruction??"").trim()||s?.instruction||`Write your prose in ${n}.`),e.push("Code, file paths, identifiers, commands, error text and log output stay exactly as they are - only your own prose changes language."),e.push("The ```ticket block is the exception: its summary and description are ALWAYS written in English, because the ticket is read by other people and by the implementing agent.")}let r=h.REPLY_STYLES.find(s=>s.id===(t.style??"").trim());return r&&e.push(r.instruction),e.length?`
23
+ `)}),this}_outputHelpIfRequested(e){let n=this._getHelpOption();n&&e.find(s=>n.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Ql(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let n,r="127.0.0.1",s="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?n=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(n=i[1],/^\d+$/.test(i[3])?s=i[3]:r=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(n=i[1],r=i[3],s=i[4]),n&&s!=="0"?`${n}=${r}:${parseInt(s)+1}`:e})}ec.Command=Zo});var ic=se(Je=>{var{Argument:nc}=ci(),{Command:Vo}=tc(),{CommanderError:kf,InvalidArgumentError:rc}=Es(),{Help:_f}=Lo(),{Option:sc}=Bo();Je.program=new Vo;Je.createCommand=t=>new Vo(t);Je.createOption=(t,e)=>new sc(t,e);Je.createArgument=(t,e)=>new nc(t,e);Je.Command=Vo;Je.Option=sc;Je.Argument=nc;Je.Help=_f;Je.CommanderError=kf;Je.InvalidArgumentError=rc;Je.InvalidOptionArgumentError=rc});var Cs=se(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.getParsedType=ue.ZodParsedType=ue.objectUtil=ue.util=void 0;var na;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function n(s){throw new Error}t.assertNever=n,t.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},t.getValidEnumValues=s=>{let i=t.objectKeys(s).filter(l=>typeof s[s[l]]!="number"),o={};for(let l of i)o[l]=s[l];return t.objectValues(o)},t.objectValues=s=>t.objectKeys(s).map(function(i){return s[i]}),t.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},t.find=(s,i)=>{for(let o of s)if(i(o))return o},t.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)}t.joinValues=r,t.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(na||(ue.util=na={}));var Cc;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Cc||(ue.objectUtil=Cc={}));ue.ZodParsedType=na.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var Um=t=>{switch(typeof t){case"undefined":return ue.ZodParsedType.undefined;case"string":return ue.ZodParsedType.string;case"number":return Number.isNaN(t)?ue.ZodParsedType.nan:ue.ZodParsedType.number;case"boolean":return ue.ZodParsedType.boolean;case"function":return ue.ZodParsedType.function;case"bigint":return ue.ZodParsedType.bigint;case"symbol":return ue.ZodParsedType.symbol;case"object":return Array.isArray(t)?ue.ZodParsedType.array:t===null?ue.ZodParsedType.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?ue.ZodParsedType.promise:typeof Map<"u"&&t instanceof Map?ue.ZodParsedType.map:typeof Set<"u"&&t instanceof Set?ue.ZodParsedType.set:typeof Date<"u"&&t instanceof Date?ue.ZodParsedType.date:ue.ZodParsedType.object;default:return ue.ZodParsedType.unknown}};ue.getParsedType=Um});var Si=se(ln=>{"use strict";Object.defineProperty(ln,"__esModule",{value:!0});ln.ZodError=ln.quotelessJson=ln.ZodIssueCode=void 0;var $c=Cs();ln.ZodIssueCode=$c.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 qm=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");ln.quotelessJson=qm;var $s=class t 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 n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=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(n(o));else{let l=r,c=0;for(;c<o.path.length;){let u=o.path[c];c===o.path.length-1?(l[u]=l[u]||{_errors:[]},l[u]._errors.push(n(o))):l[u]=l[u]||{_errors:[]},l=l[u],c++}}};return s(this),r}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,$c.util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];n[i]=n[i]||[],n[i].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};ln.ZodError=$s;$s.create=t=>new $s(t)});var sa=se(ra=>{"use strict";Object.defineProperty(ra,"__esModule",{value:!0});var Ce=Si(),Kn=Cs(),Fm=(t,e)=>{let n;switch(t.code){case Ce.ZodIssueCode.invalid_type:t.received===Kn.ZodParsedType.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case Ce.ZodIssueCode.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,Kn.util.jsonStringifyReplacer)}`;break;case Ce.ZodIssueCode.unrecognized_keys:n=`Unrecognized key(s) in object: ${Kn.util.joinValues(t.keys,", ")}`;break;case Ce.ZodIssueCode.invalid_union:n="Invalid input";break;case Ce.ZodIssueCode.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Kn.util.joinValues(t.options)}`;break;case Ce.ZodIssueCode.invalid_enum_value:n=`Invalid enum value. Expected ${Kn.util.joinValues(t.options)}, received '${t.received}'`;break;case Ce.ZodIssueCode.invalid_arguments:n="Invalid function arguments";break;case Ce.ZodIssueCode.invalid_return_type:n="Invalid function return type";break;case Ce.ZodIssueCode.invalid_date:n="Invalid date";break;case Ce.ZodIssueCode.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:Kn.util.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case Ce.ZodIssueCode.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case Ce.ZodIssueCode.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case Ce.ZodIssueCode.custom:n="Invalid input";break;case Ce.ZodIssueCode.invalid_intersection_types:n="Intersection results could not be merged";break;case Ce.ZodIssueCode.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case Ce.ZodIssueCode.not_finite:n="Number must be finite";break;default:n=e.defaultError,Kn.util.assertNever(t)}return{message:n}};ra.default=Fm});var Ti=se(cn=>{"use strict";var Bm=cn&&cn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(cn,"__esModule",{value:!0});cn.defaultErrorMap=void 0;cn.setErrorMap=Km;cn.getErrorMap=Hm;var Pc=Bm(sa());cn.defaultErrorMap=Pc.default;var Nc=Pc.default;function Km(t){Nc=t}function Hm(){return Nc}});var oa=se(ae=>{"use strict";var Gm=ae&&ae.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(ae,"__esModule",{value:!0});ae.isAsync=ae.isValid=ae.isDirty=ae.isAborted=ae.OK=ae.DIRTY=ae.INVALID=ae.ParseStatus=ae.EMPTY_PATH=ae.makeIssue=void 0;ae.addIssueToContext=Wm;var Zm=Ti(),jc=Gm(sa()),Vm=t=>{let{data:e,path:n,errorMaps:r,issueData:s}=t,i=[...n,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let l="",c=r.filter(u=>!!u).slice().reverse();for(let u of c)l=u(o,{data:e,defaultError:l}).message;return{...s,path:i,message:l}};ae.makeIssue=Vm;ae.EMPTY_PATH=[];function Wm(t,e){let n=(0,Zm.getErrorMap)(),r=(0,ae.makeIssue)({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===jc.default?void 0:jc.default].filter(s=>!!s)});t.common.issues.push(r)}var ia=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let s of n){if(s.status==="aborted")return ae.INVALID;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let s of n){let i=await s.key,o=await s.value;r.push({key:i,value:o})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let s of n){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return ae.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}}};ae.ParseStatus=ia;ae.INVALID=Object.freeze({status:"aborted"});var Ym=t=>({status:"dirty",value:t});ae.DIRTY=Ym;var Jm=t=>({status:"valid",value:t});ae.OK=Jm;var Xm=t=>t.status==="aborted";ae.isAborted=Xm;var Qm=t=>t.status==="dirty";ae.isDirty=Qm;var eg=t=>t.status==="valid";ae.isValid=eg;var tg=t=>typeof Promise<"u"&&t instanceof Promise;ae.isAsync=tg});var Mc=se(Oc=>{"use strict";Object.defineProperty(Oc,"__esModule",{value:!0})});var Dc=se(xi=>{"use strict";Object.defineProperty(xi,"__esModule",{value:!0});xi.errorUtil=void 0;var zc;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(zc||(xi.errorUtil=zc={}))});var Yc=se(_=>{"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=Bc;_.custom=Hc;var A=Si(),Ei=Ti(),q=Dc(),T=oa(),C=Cs(),nt=class{constructor(e,n,r,s){this._cachedPath=[],this.parent=e,this.data=n,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}},Lc=(t,e)=>{if((0,T.isValid)(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new A.ZodError(t.common.issues);return this._error=n,this._error}}};function X(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:s}=t;if(e&&(n||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:c}=t;return o.code==="invalid_enum_value"?{message:c??l.defaultError}:typeof l.data>"u"?{message:c??r??l.defaultError}:o.code!=="invalid_type"?{message:l.defaultError}:{message:c??n??l.defaultError}},description:s}}var Q=class{get description(){return this._def.description}_getType(e){return(0,C.getParsedType)(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:(0,C.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new T.ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:(0,C.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if((0,T.isAsync)(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,C.getParsedType)(e)},s=this._parseSync({data:e,path:r.path,parent:r});return Lc(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,C.getParsedType)(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return(0,T.isValid)(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>(0,T.isValid)(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,C.getParsedType)(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await((0,T.isAsync)(s)?s:Promise.resolve(s));return Lc(r,i)}refine(e,n){let r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,i)=>{let o=e(s),l=()=>i.addIssue({code:A.ZodIssueCode.custom,...r(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(l(),!1)):o?!0:(l(),!1)})}refinement(e,n){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(e){return new Be({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:n=>this["~validate"](n)}}optional(){return tt.create(this,this._def)}nullable(){return wt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ut.create(this)}promise(){return hn.create(this,this._def)}or(e){return Jn.create([this,e],this._def)}and(e){return Xn.create(this,e,this._def)}transform(e){return new Be({...X(this._def),schema:this,typeName:Z.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new rr({...X(this._def),innerType:this,defaultValue:n,typeName:Z.ZodDefault})}brand(){return new Ps({typeName:Z.ZodBranded,type:this,...X(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new sr({...X(this._def),innerType:this,catchValue:n,typeName:Z.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Ns.create(this,e)}readonly(){return ir.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};_.ZodType=Q;_.Schema=Q;_.ZodSchema=Q;var ng=/^c[^\s-]{8,}$/i,rg=/^[0-9a-z]+$/,sg=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ig=/^[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,og=/^[a-z0-9_-]{21}$/i,ag=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,lg=/^[-+]?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)?)??$/,cg=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ug="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",aa,dg=/^(?:(?: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])$/,hg=/^(?:(?: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])$/,pg=/^(([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]))$/,fg=/^(([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])$/,mg=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,gg=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,qc="((\\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])))",yg=new RegExp(`^${qc}$`);function Fc(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function bg(t){return new RegExp(`^${Fc(t)}$`)}function Bc(t){let e=`${qc}T${Fc(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function vg(t,e){return!!((e==="v4"||!e)&&dg.test(t)||(e==="v6"||!e)&&pg.test(t))}function wg(t,e){if(!ag.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.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 kg(t,e){return!!((e==="v4"||!e)&&hg.test(t)||(e==="v6"||!e)&&fg.test(t))}var un=class t extends Q{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==C.ZodParsedType.string){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.string,received:i.parsedType}),T.INVALID}let r=new T.ParseStatus,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:A.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,T.addIssueToContext)(s,{code:A.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,T.addIssueToContext)(s,{code:A.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):l&&(0,T.addIssueToContext)(s,{code:A.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")cg.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"email",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")aa||(aa=new RegExp(ug,"u")),aa.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"emoji",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")ig.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"uuid",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")og.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"nanoid",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")ng.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"cuid",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")rg.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"cuid2",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")sg.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"ulid",code:A.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,T.addIssueToContext)(s,{validation:"url",code:A.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,T.addIssueToContext)(s,{validation:"regex",code:A.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,T.addIssueToContext)(s,{code:A.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,T.addIssueToContext)(s,{code:A.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,T.addIssueToContext)(s,{code:A.ZodIssueCode.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Bc(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:A.ZodIssueCode.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?yg.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:A.ZodIssueCode.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?bg(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:A.ZodIssueCode.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?lg.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"duration",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?vg(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"ip",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?wg(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"jwt",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?kg(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"cidr",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?mg.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"base64",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?gg.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"base64url",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):C.util.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:A.ZodIssueCode.invalid_string,...q.errorUtil.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...q.errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...q.errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...q.errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...q.errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...q.errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...q.errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...q.errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...q.errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...q.errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...q.errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...q.errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...q.errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...q.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,...q.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,...q.errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...q.errorUtil.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...q.errorUtil.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...q.errorUtil.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...q.errorUtil.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...q.errorUtil.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...q.errorUtil.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...q.errorUtil.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...q.errorUtil.errToObj(n)})}nonempty(e){return this.min(1,q.errorUtil.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...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 n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};_.ZodString=un;un.create=t=>new un({checks:[],typeName:Z.ZodString,coerce:t?.coerce??!1,...X(t)});function _g(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,i=Number.parseInt(t.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var Hn=class t extends Q{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)!==C.ZodParsedType.number){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.number,received:i.parsedType}),T.INVALID}let r,s=new T.ParseStatus;for(let i of this._def.checks)i.kind==="int"?C.util.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:A.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,T.addIssueToContext)(r,{code:A.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,T.addIssueToContext)(r,{code:A.ZodIssueCode.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?_g(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:A.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,T.addIssueToContext)(r,{code:A.ZodIssueCode.not_finite,message:i.message}),s.dirty()):C.util.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,q.errorUtil.toString(n))}gt(e,n){return this.setLimit("min",e,!1,q.errorUtil.toString(n))}lte(e,n){return this.setLimit("max",e,!0,q.errorUtil.toString(n))}lt(e,n){return this.setLimit("max",e,!1,q.errorUtil.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:q.errorUtil.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:q.errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:q.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:q.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:q.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:q.errorUtil.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:q.errorUtil.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:q.errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:q.errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:q.errorUtil.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&C.util.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};_.ZodNumber=Hn;Hn.create=t=>new Hn({checks:[],typeName:Z.ZodNumber,coerce:t?.coerce||!1,...X(t)});var Gn=class t extends Q{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)!==C.ZodParsedType.bigint)return this._getInvalidInput(e);let r,s=new T.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,T.addIssueToContext)(r,{code:A.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,T.addIssueToContext)(r,{code:A.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,T.addIssueToContext)(r,{code:A.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):C.util.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(n,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.bigint,received:n.parsedType}),T.INVALID}gte(e,n){return this.setLimit("min",e,!0,q.errorUtil.toString(n))}gt(e,n){return this.setLimit("min",e,!1,q.errorUtil.toString(n))}lte(e,n){return this.setLimit("max",e,!0,q.errorUtil.toString(n))}lt(e,n){return this.setLimit("max",e,!1,q.errorUtil.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:q.errorUtil.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:q.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:q.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:q.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:q.errorUtil.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:q.errorUtil.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};_.ZodBigInt=Gn;Gn.create=t=>new Gn({checks:[],typeName:Z.ZodBigInt,coerce:t?.coerce??!1,...X(t)});var Zn=class extends Q{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==C.ZodParsedType.boolean){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.boolean,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};_.ZodBoolean=Zn;Zn.create=t=>new Zn({typeName:Z.ZodBoolean,coerce:t?.coerce||!1,...X(t)});var Vn=class t extends Q{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==C.ZodParsedType.date){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.date,received:i.parsedType}),T.INVALID}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:A.ZodIssueCode.invalid_date}),T.INVALID}let r=new T.ParseStatus,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:A.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,T.addIssueToContext)(s,{code:A.ZodIssueCode.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):C.util.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:q.errorUtil.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:q.errorUtil.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};_.ZodDate=Vn;Vn.create=t=>new Vn({checks:[],coerce:t?.coerce||!1,typeName:Z.ZodDate,...X(t)});var Yr=class extends Q{_parse(e){if(this._getType(e)!==C.ZodParsedType.symbol){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.symbol,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};_.ZodSymbol=Yr;Yr.create=t=>new Yr({typeName:Z.ZodSymbol,...X(t)});var Wn=class extends Q{_parse(e){if(this._getType(e)!==C.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.undefined,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};_.ZodUndefined=Wn;Wn.create=t=>new Wn({typeName:Z.ZodUndefined,...X(t)});var Yn=class extends Q{_parse(e){if(this._getType(e)!==C.ZodParsedType.null){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.null,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};_.ZodNull=Yn;Yn.create=t=>new Yn({typeName:Z.ZodNull,...X(t)});var dn=class extends Q{constructor(){super(...arguments),this._any=!0}_parse(e){return(0,T.OK)(e.data)}};_.ZodAny=dn;dn.create=t=>new dn({typeName:Z.ZodAny,...X(t)});var Lt=class extends Q{constructor(){super(...arguments),this._unknown=!0}_parse(e){return(0,T.OK)(e.data)}};_.ZodUnknown=Lt;Lt.create=t=>new Lt({typeName:Z.ZodUnknown,...X(t)});var ct=class extends Q{_parse(e){let n=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(n,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.never,received:n.parsedType}),T.INVALID}};_.ZodNever=ct;ct.create=t=>new ct({typeName:Z.ZodNever,...X(t)});var Jr=class extends Q{_parse(e){if(this._getType(e)!==C.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.void,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};_.ZodVoid=Jr;Jr.create=t=>new Jr({typeName:Z.ZodVoid,...X(t)});var Ut=class t extends Q{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==C.ZodParsedType.array)return(0,T.addIssueToContext)(n,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.array,received:n.parsedType}),T.INVALID;if(s.exactLength!==null){let o=n.data.length>s.exactLength.value,l=n.data.length<s.exactLength.value;(o||l)&&((0,T.addIssueToContext)(n,{code:o?A.ZodIssueCode.too_big:A.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&&n.data.length<s.minLength.value&&((0,T.addIssueToContext)(n,{code:A.ZodIssueCode.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&((0,T.addIssueToContext)(n,{code:A.ZodIssueCode.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((o,l)=>s.type._parseAsync(new nt(n,o,n.path,l)))).then(o=>T.ParseStatus.mergeArray(r,o));let i=[...n.data].map((o,l)=>s.type._parseSync(new nt(n,o,n.path,l)));return T.ParseStatus.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:q.errorUtil.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:q.errorUtil.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:q.errorUtil.toString(n)}})}nonempty(e){return this.min(1,e)}};_.ZodArray=Ut;Ut.create=(t,e)=>new Ut({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Z.ZodArray,...X(e)});function Wr(t){if(t instanceof Le){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=tt.create(Wr(r))}return new Le({...t._def,shape:()=>e})}else return t instanceof Ut?new Ut({...t._def,type:Wr(t.element)}):t instanceof tt?tt.create(Wr(t.unwrap())):t instanceof wt?wt.create(Wr(t.unwrap())):t instanceof vt?vt.create(t.items.map(e=>Wr(e))):t}var Le=class t extends Q{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(),n=C.util.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==C.ZodParsedType.object){let u=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(u,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.object,received:u.parsedType}),T.INVALID}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),l=[];if(!(this._def.catchall instanceof ct&&this._def.unknownKeys==="strip"))for(let u in s.data)o.includes(u)||l.push(u);let c=[];for(let u of o){let p=i[u],f=s.data[u];c.push({key:{status:"valid",value:u},value:p._parse(new nt(s,f,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof ct){let u=this._def.unknownKeys;if(u==="passthrough")for(let p of l)c.push({key:{status:"valid",value:p},value:{status:"valid",value:s.data[p]}});else if(u==="strict")l.length>0&&((0,T.addIssueToContext)(s,{code:A.ZodIssueCode.unrecognized_keys,keys:l}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let p of l){let f=s.data[p];c.push({key:{status:"valid",value:p},value:u._parse(new nt(s,f,s.path,p)),alwaysSet:p in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let u=[];for(let p of c){let f=await p.key,b=await p.value;u.push({key:f,value:b,alwaysSet:p.alwaysSet})}return u}).then(u=>T.ParseStatus.mergeObjectSync(r,u)):T.ParseStatus.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return q.errorUtil.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:q.errorUtil.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Z.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of C.util.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of C.util.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return Wr(this)}partial(e){let n={};for(let r of C.util.objectKeys(this.shape)){let s=this.shape[r];e&&!e[r]?n[r]=s:n[r]=s.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of C.util.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof tt;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return Kc(C.util.objectKeys(this.shape))}};_.ZodObject=Le;Le.create=(t,e)=>new Le({shape:()=>t,unknownKeys:"strip",catchall:ct.create(),typeName:Z.ZodObject,...X(e)});Le.strictCreate=(t,e)=>new Le({shape:()=>t,unknownKeys:"strict",catchall:ct.create(),typeName:Z.ZodObject,...X(e)});Le.lazycreate=(t,e)=>new Le({shape:t,unknownKeys:"strip",catchall:ct.create(),typeName:Z.ZodObject,...X(e)});var Jn=class extends Q{_parse(e){let{ctx:n}=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 n.common.issues.push(...l.ctx.common.issues),l.result;let o=i.map(l=>new A.ZodError(l.ctx.common.issues));return(0,T.addIssueToContext)(n,{code:A.ZodIssueCode.invalid_union,unionErrors:o}),T.INVALID}if(n.common.async)return Promise.all(r.map(async i=>{let o={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let c of r){let u={...n,common:{...n.common,issues:[]},parent:null},p=c._parseSync({data:n.data,path:n.path,parent:u});if(p.status==="valid")return p;p.status==="dirty"&&!i&&(i={result:p,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let l=o.map(c=>new A.ZodError(c));return(0,T.addIssueToContext)(n,{code:A.ZodIssueCode.invalid_union,unionErrors:l}),T.INVALID}}get options(){return this._def.options}};_.ZodUnion=Jn;Jn.create=(t,e)=>new Jn({options:t,typeName:Z.ZodUnion,...X(e)});var Dt=t=>t instanceof Qn?Dt(t.schema):t instanceof Be?Dt(t.innerType()):t instanceof er?[t.value]:t instanceof tr?t.options:t instanceof nr?C.util.objectValues(t.enum):t instanceof rr?Dt(t._def.innerType):t instanceof Wn?[void 0]:t instanceof Yn?[null]:t instanceof tt?[void 0,...Dt(t.unwrap())]:t instanceof wt?[null,...Dt(t.unwrap())]:t instanceof Ps||t instanceof ir?Dt(t.unwrap()):t instanceof sr?Dt(t._def.innerType):[],Ri=class t extends Q{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==C.ZodParsedType.object)return(0,T.addIssueToContext)(n,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.object,received:n.parsedType}),T.INVALID;let r=this.discriminator,s=n.data[r],i=this.optionsMap.get(s);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):((0,T.addIssueToContext)(n,{code:A.ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),T.INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let s=new Map;for(let i of n){let o=Dt(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 t({typeName:Z.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...X(r)})}};_.ZodDiscriminatedUnion=Ri;function la(t,e){let n=(0,C.getParsedType)(t),r=(0,C.getParsedType)(e);if(t===e)return{valid:!0,data:t};if(n===C.ZodParsedType.object&&r===C.ZodParsedType.object){let s=C.util.objectKeys(e),i=C.util.objectKeys(t).filter(l=>s.indexOf(l)!==-1),o={...t,...e};for(let l of i){let c=la(t[l],e[l]);if(!c.valid)return{valid:!1};o[l]=c.data}return{valid:!0,data:o}}else if(n===C.ZodParsedType.array&&r===C.ZodParsedType.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<t.length;i++){let o=t[i],l=e[i],c=la(o,l);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===C.ZodParsedType.date&&r===C.ZodParsedType.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Xn=class extends Q{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=(i,o)=>{if((0,T.isAborted)(i)||(0,T.isAborted)(o))return T.INVALID;let l=la(i.value,o.value);return l.valid?(((0,T.isDirty)(i)||(0,T.isDirty)(o))&&n.dirty(),{status:n.value,value:l.data}):((0,T.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_intersection_types}),T.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=Xn;Xn.create=(t,e,n)=>new Xn({left:t,right:e,typeName:Z.ZodIntersection,...X(n)});var vt=class t extends Q{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==C.ZodParsedType.array)return(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.array,received:r.parsedType}),T.INVALID;if(r.data.length<this._def.items.length)return(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),T.INVALID;!this._def.rest&&r.data.length>this._def.items.length&&((0,T.addIssueToContext)(r,{code:A.ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let i=[...r.data].map((o,l)=>{let c=this._def.items[l]||this._def.rest;return c?c._parse(new nt(r,o,r.path,l)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>T.ParseStatus.mergeArray(n,o)):T.ParseStatus.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};_.ZodTuple=vt;vt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new vt({items:t,typeName:Z.ZodTuple,rest:null,...X(e)})};var Ii=class t extends Q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==C.ZodParsedType.object)return(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.object,received:r.parsedType}),T.INVALID;let s=[],i=this._def.keyType,o=this._def.valueType;for(let l in r.data)s.push({key:i._parse(new nt(r,l,r.path,l)),value:o._parse(new nt(r,r.data[l],r.path,l)),alwaysSet:l in r.data});return r.common.async?T.ParseStatus.mergeObjectAsync(n,s):T.ParseStatus.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof Q?new t({keyType:e,valueType:n,typeName:Z.ZodRecord,...X(r)}):new t({keyType:un.create(),valueType:e,typeName:Z.ZodRecord,...X(n)})}};_.ZodRecord=Ii;var Xr=class extends Q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==C.ZodParsedType.map)return(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.map,received:r.parsedType}),T.INVALID;let s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([l,c],u)=>({key:s._parse(new nt(r,l,r.path,[u,"key"])),value:i._parse(new nt(r,c,r.path,[u,"value"]))}));if(r.common.async){let l=new Map;return Promise.resolve().then(async()=>{for(let c of o){let u=await c.key,p=await c.value;if(u.status==="aborted"||p.status==="aborted")return T.INVALID;(u.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(u.value,p.value)}return{status:n.value,value:l}})}else{let l=new Map;for(let c of o){let u=c.key,p=c.value;if(u.status==="aborted"||p.status==="aborted")return T.INVALID;(u.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(u.value,p.value)}return{status:n.value,value:l}}}};_.ZodMap=Xr;Xr.create=(t,e,n)=>new Xr({valueType:e,keyType:t,typeName:Z.ZodMap,...X(n)});var Qr=class t extends Q{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==C.ZodParsedType.set)return(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.set,received:r.parsedType}),T.INVALID;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&((0,T.addIssueToContext)(r,{code:A.ZodIssueCode.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&((0,T.addIssueToContext)(r,{code:A.ZodIssueCode.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let i=this._def.valueType;function o(c){let u=new Set;for(let p of c){if(p.status==="aborted")return T.INVALID;p.status==="dirty"&&n.dirty(),u.add(p.value)}return{status:n.value,value:u}}let l=[...r.data.values()].map((c,u)=>i._parse(new nt(r,c,r.path,u)));return r.common.async?Promise.all(l).then(c=>o(c)):o(l)}min(e,n){return new t({...this._def,minSize:{value:e,message:q.errorUtil.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:q.errorUtil.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};_.ZodSet=Qr;Qr.create=(t,e)=>new Qr({valueType:t,minSize:null,maxSize:null,typeName:Z.ZodSet,...X(e)});var Ai=class t extends Q{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==C.ZodParsedType.function)return(0,T.addIssueToContext)(n,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.function,received:n.parsedType}),T.INVALID;function r(l,c){return(0,T.makeIssue)({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,(0,Ei.getErrorMap)(),Ei.defaultErrorMap].filter(u=>!!u),issueData:{code:A.ZodIssueCode.invalid_arguments,argumentsError:c}})}function s(l,c){return(0,T.makeIssue)({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,(0,Ei.getErrorMap)(),Ei.defaultErrorMap].filter(u=>!!u),issueData:{code:A.ZodIssueCode.invalid_return_type,returnTypeError:c}})}let i={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof hn){let l=this;return(0,T.OK)(async function(...c){let u=new A.ZodError([]),p=await l._def.args.parseAsync(c,i).catch(v=>{throw u.addIssue(r(c,v)),u}),f=await Reflect.apply(o,this,p);return await l._def.returns._def.type.parseAsync(f,i).catch(v=>{throw u.addIssue(s(f,v)),u})})}else{let l=this;return(0,T.OK)(function(...c){let u=l._def.args.safeParse(c,i);if(!u.success)throw new A.ZodError([r(c,u.error)]);let p=Reflect.apply(o,this,u.data),f=l._def.returns.safeParse(p,i);if(!f.success)throw new A.ZodError([s(p,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:vt.create(e).rest(Lt.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new t({args:e||vt.create([]).rest(Lt.create()),returns:n||Lt.create(),typeName:Z.ZodFunction,...X(r)})}};_.ZodFunction=Ai;var Qn=class extends Q{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};_.ZodLazy=Qn;Qn.create=(t,e)=>new Qn({getter:t,typeName:Z.ZodLazy,...X(e)});var er=class extends Q{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(n,{received:n.data,code:A.ZodIssueCode.invalid_literal,expected:this._def.value}),T.INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}};_.ZodLiteral=er;er.create=(t,e)=>new er({value:t,typeName:Z.ZodLiteral,...X(e)});function Kc(t,e){return new tr({values:t,typeName:Z.ZodEnum,...X(e)})}var tr=class t extends Q{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return(0,T.addIssueToContext)(n,{expected:C.util.joinValues(r),received:n.parsedType,code:A.ZodIssueCode.invalid_type}),T.INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return(0,T.addIssueToContext)(n,{received:n.data,code:A.ZodIssueCode.invalid_enum_value,options:r}),T.INVALID}return(0,T.OK)(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};_.ZodEnum=tr;tr.create=Kc;var nr=class extends Q{_parse(e){let n=C.util.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==C.ZodParsedType.string&&r.parsedType!==C.ZodParsedType.number){let s=C.util.objectValues(n);return(0,T.addIssueToContext)(r,{expected:C.util.joinValues(s),received:r.parsedType,code:A.ZodIssueCode.invalid_type}),T.INVALID}if(this._cache||(this._cache=new Set(C.util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=C.util.objectValues(n);return(0,T.addIssueToContext)(r,{received:r.data,code:A.ZodIssueCode.invalid_enum_value,options:s}),T.INVALID}return(0,T.OK)(e.data)}get enum(){return this._def.values}};_.ZodNativeEnum=nr;nr.create=(t,e)=>new nr({values:t,typeName:Z.ZodNativeEnum,...X(e)});var hn=class extends Q{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==C.ZodParsedType.promise&&n.common.async===!1)return(0,T.addIssueToContext)(n,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.promise,received:n.parsedType}),T.INVALID;let r=n.parsedType===C.ZodParsedType.promise?n.data:Promise.resolve(n.data);return(0,T.OK)(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};_.ZodPromise=hn;hn.create=(t,e)=>new hn({type:t,typeName:Z.ZodPromise,...X(e)});var Be=class extends Q{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:n,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{(0,T.addIssueToContext)(r,o),o.fatal?n.abort():n.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(n.value==="aborted")return T.INVALID;let c=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return c.status==="aborted"?T.INVALID:c.status==="dirty"||n.value==="dirty"?(0,T.DIRTY)(c.value):c});{if(n.value==="aborted")return T.INVALID;let l=this._def.schema._parseSync({data:o,path:r.path,parent:r});return l.status==="aborted"?T.INVALID:l.status==="dirty"||n.value==="dirty"?(0,T.DIRTY)(l.value):l}}if(s.type==="refinement"){let o=l=>{let c=s.refinement(l,i);if(r.common.async)return Promise.resolve(c);if(c 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"?T.INVALID:(l.status==="dirty"&&n.dirty(),o(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?T.INVALID:(l.status==="dirty"&&n.dirty(),o(l.value).then(()=>({status:n.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,T.isValid)(o))return T.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:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>(0,T.isValid)(o)?Promise.resolve(s.transform(o.value,i)).then(l=>({status:n.value,value:l})):T.INVALID);C.util.assertNever(s)}};_.ZodEffects=Be;_.ZodTransformer=Be;Be.create=(t,e,n)=>new Be({schema:t,typeName:Z.ZodEffects,effect:e,...X(n)});Be.createWithPreprocess=(t,e,n)=>new Be({schema:e,effect:{type:"preprocess",transform:t},typeName:Z.ZodEffects,...X(n)});var tt=class extends Q{_parse(e){return this._getType(e)===C.ZodParsedType.undefined?(0,T.OK)(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};_.ZodOptional=tt;tt.create=(t,e)=>new tt({innerType:t,typeName:Z.ZodOptional,...X(e)});var wt=class extends Q{_parse(e){return this._getType(e)===C.ZodParsedType.null?(0,T.OK)(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};_.ZodNullable=wt;wt.create=(t,e)=>new wt({innerType:t,typeName:Z.ZodNullable,...X(e)});var rr=class extends Q{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===C.ZodParsedType.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};_.ZodDefault=rr;rr.create=(t,e)=>new rr({innerType:t,typeName:Z.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...X(e)});var sr=class extends Q{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return(0,T.isAsync)(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new A.ZodError(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new A.ZodError(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};_.ZodCatch=sr;sr.create=(t,e)=>new sr({innerType:t,typeName:Z.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...X(e)});var es=class extends Q{_parse(e){if(this._getType(e)!==C.ZodParsedType.nan){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:C.ZodParsedType.nan,received:r.parsedType}),T.INVALID}return{status:"valid",value:e.data}}};_.ZodNaN=es;es.create=t=>new es({typeName:Z.ZodNaN,...X(t)});_.BRAND=Symbol("zod_brand");var Ps=class extends Q{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}};_.ZodBranded=Ps;var Ns=class t extends Q{_parse(e){let{status:n,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"?T.INVALID:i.status==="dirty"?(n.dirty(),(0,T.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"?T.INVALID:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:Z.ZodPipeline})}};_.ZodPipeline=Ns;var ir=class extends Q{_parse(e){let n=this._def.innerType._parse(e),r=s=>((0,T.isValid)(s)&&(s.value=Object.freeze(s.value)),s);return(0,T.isAsync)(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};_.ZodReadonly=ir;ir.create=(t,e)=>new ir({innerType:t,typeName:Z.ZodReadonly,...X(e)});function Uc(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function Hc(t,e={},n){return t?dn.create().superRefine((r,s)=>{let i=t(r);if(i instanceof Promise)return i.then(o=>{if(!o){let l=Uc(e,r),c=l.fatal??n??!0;s.addIssue({code:"custom",...l,fatal:c})}});if(!i){let o=Uc(e,r),l=o.fatal??n??!0;s.addIssue({code:"custom",...o,fatal:l})}}):dn.create()}_.late={object:Le.lazycreate};var Z;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(Z||(_.ZodFirstPartyTypeKind=Z={}));var Sg=(t,e={message:`Input not instance of ${t.name}`})=>Hc(n=>n instanceof t,e);_.instanceof=Sg;var Gc=un.create;_.string=Gc;var Zc=Hn.create;_.number=Zc;var Tg=es.create;_.nan=Tg;var xg=Gn.create;_.bigint=xg;var Vc=Zn.create;_.boolean=Vc;var Eg=Vn.create;_.date=Eg;var Rg=Yr.create;_.symbol=Rg;var Ig=Wn.create;_.undefined=Ig;var Ag=Yn.create;_.null=Ag;var Cg=dn.create;_.any=Cg;var $g=Lt.create;_.unknown=$g;var Pg=ct.create;_.never=Pg;var Ng=Jr.create;_.void=Ng;var jg=Ut.create;_.array=jg;var Og=Le.create;_.object=Og;var Mg=Le.strictCreate;_.strictObject=Mg;var zg=Jn.create;_.union=zg;var Dg=Ri.create;_.discriminatedUnion=Dg;var Lg=Xn.create;_.intersection=Lg;var Ug=vt.create;_.tuple=Ug;var qg=Ii.create;_.record=qg;var Fg=Xr.create;_.map=Fg;var Bg=Qr.create;_.set=Bg;var Kg=Ai.create;_.function=Kg;var Hg=Qn.create;_.lazy=Hg;var Gg=er.create;_.literal=Gg;var Zg=tr.create;_.enum=Zg;var Vg=nr.create;_.nativeEnum=Vg;var Wg=hn.create;_.promise=Wg;var Wc=Be.create;_.effect=Wc;_.transformer=Wc;var Yg=tt.create;_.optional=Yg;var Jg=wt.create;_.nullable=Jg;var Xg=Be.createWithPreprocess;_.preprocess=Xg;var Qg=Ns.create;_.pipeline=Qg;var ey=()=>Gc().optional();_.ostring=ey;var ty=()=>Zc().optional();_.onumber=ty;var ny=()=>Vc().optional();_.oboolean=ny;_.coerce={string:(t=>un.create({...t,coerce:!0})),number:(t=>Hn.create({...t,coerce:!0})),boolean:(t=>Zn.create({...t,coerce:!0})),bigint:(t=>Gn.create({...t,coerce:!0})),date:(t=>Vn.create({...t,coerce:!0}))};_.NEVER=T.INVALID});var ca=se(rt=>{"use strict";var ry=rt&&rt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),ts=rt&&rt.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&ry(e,t,n)};Object.defineProperty(rt,"__esModule",{value:!0});ts(Ti(),rt);ts(oa(),rt);ts(Mc(),rt);ts(Cs(),rt);ts(Yc(),rt);ts(Si(),rt)});var Qc=se(Ue=>{"use strict";var Jc=Ue&&Ue.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),sy=Ue&&Ue.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),iy=Ue&&Ue.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&Jc(e,t,n);return sy(e,t),e},oy=Ue&&Ue.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Jc(e,t,n)};Object.defineProperty(Ue,"__esModule",{value:!0});Ue.z=void 0;var Xc=iy(ca());Ue.z=Xc;oy(ca(),Ue);Ue.default=Xc});var _e=se(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.ChatLoadResultMsg=h.REPLY_STYLES=h.BUILTIN_REPLY_LANGUAGES=h.ChatLoadMsg=h.ChatListResultMsg=h.ChatListMsg=h.ChatUsageMsg=h.ChatStreamMsg=h.JiraUsersResultMsg=h.DeployClaimResultMsg=h.DeployClaimMsg=h.RuleDiagnoseResultMsg=h.ProjectTestResultMsg=h.RunStatusMsg=h.FailedTest=h.RunUsageMsg=h.RunLogMsg=h.RunClaimMsg=h.HeartbeatMsg=h.HelloMsg=h.RuleConfig=h.ProjectConfig=h.ActionConfig=h.DeployAction=h.EnvironmentConfig=h.PromotionMode=h.DeployStep=h.RespondAction=h.ImplementAction=h.PlanOnlyAction=h.TriggerConfig=h.StatusChangedTrigger=h.CommentKeywordTrigger=h.LabelAddedTrigger=h.ActionType=h.TriggerType=h.ACTIVE_RUN_STATUSES=h.RunStatus=h.needsInputMarkerIn=h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=h.NEEDS_INPUT_COMMENT_MARKER=h.NEEDS_INPUT_LABEL=h.NEEDS_INPUT_ASK_FENCE=h.NEEDS_INPUT_MARKER=h.BRANCH_DEPLOY_ISSUE_KEY=h.REQUIRED_AGENT_CAPABILITIES=h.DEFAULT_AGENT_ID=h.REGISTERED_AGENTS=h.PROTOCOL_VERSION=h.GITHUB_TOKEN_PERMISSIONS=void 0;h.SetupStatusResultMsg=h.SetupStatusMsg=h.DeploySuggestResultMsg=h.SelfMigrationApplyResultMsg=h.SelfMigrationApplyMsg=h.SELF_MIGRATION_DIR=h.EnvPreflightResultMsg=h.EnvPreflightMsg=h.ChatCreateTicketResultMsg=h.ChatCreateTicketMsg=h.ChatTurnResultMsg=h.ChatTurnMsg=h.ChatFile=h.TeamCredsResultMsg=h.TeamCredsMsg=h.KnowledgeSaveResultMsg=h.KnowledgeSaveMsg=h.KnowledgeListResultMsg=h.KnowledgeFile=h.KnowledgeListMsg=h.AuditReviewResultMsg=h.AuditReviewMsg=h.AuditGetResultMsg=h.AuditGetMsg=h.AuditListResultMsg=h.AuditStatsResultMsg=h.AuditStatsMsg=h.AuditListMsg=h.AuditStartResultMsg=h.AuditStartMsg=h.AuditRecord=h.AuditFinding=h.AuditDetailLevel=h.AuditScope=h.AuditSeverity=h.KnowledgeRole=h.AuditRole=h.EpicSuggestResultMsg=h.EpicSuggestMsg=h.EpicListResultMsg=h.EpicChild=h.EpicListMsg=h.BoardTriggerResultMsg=h.BoardTriggerMsg=h.BoardFetchResultMsg=h.BoardFetchMsg=h.RepoDocReadResultMsg=h.RepoDocReadMsg=h.RepoDocsResultMsg=h.RepoDocsMsg=void 0;h.DEFAULT_RESPOND_PROMPT_TEMPLATE=h.BUGFIX_IMPLEMENT_PROMPT_TEMPLATE=h.BUG_INVESTIGATION_PROMPT_TEMPLATE=h.TECHNICAL_PLAN_PROMPT_TEMPLATE=h.MEMORY_UPDATE_PROMPT=h.DEFAULT_IMPLEMENT_PROMPT_TEMPLATE=h.WRITE_TESTS_PROMPT=h.NEEDS_INPUT_OPTIONS_PROMPT=h.DEFAULT_PLAN_PROMPT_TEMPLATE=h.EnrollResponse=h.EnrollRequest=h.ServerToRunnerMsg=h.JiraUsersMsg=h.DeploySuggestMsg=h.DeployFixMsg=h.DeployStartMsg=h.RunRetryPushMsg=h.RunRejectedMsg=h.RunApprovedMsg=h.RunCancelMsg=h.RuleDiagnoseMsg=h.ProjectTestMsg=h.RunClaimResultMsg=h.ConfigMsg=h.HelloAckMsg=h.RunnerToServerMsg=h.AutopilotReportMsg=h.AutopilotNextResultMsg=h.AutopilotNextMsg=h.RunnerUpdateResultMsg=h.AgentProfilesResultMsg=h.AgentProfilesMsg=h.RunPrConflictMsg=h.RunResolveConflictResultMsg=h.RunAnswerResultMsg=h.RunAnswerMsg=h.RunTestFixResultMsg=h.RunTestFixMsg=h.RunResolveConflictMsg=h.RunnerUpdateMsg=h.RepoDocSaveResultMsg=h.RepoDocSaveMsg=h.SetupClaudeMdSaveResultMsg=h.SetupClaudeMdSaveMsg=h.SetupClaudeMdGenerateResultMsg=h.SetupClaudeMdGenerateMsg=h.SetupRecheckResultMsg=h.SetupRecheckMsg=h.RepoUnmapResultMsg=h.RepoUnmapMsg=void 0;h.DEFAULT_DEPLOY_SUGGEST_PROMPT_TEMPLATE=h.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE=h.DEPLOY_FIX_PROMPT_TEMPLATE=h.PROMPT_PRESETS=void 0;h.missingAgentCapabilities=ay;h.replyPreferenceAppendix=cy;h.pendingMigrationsAppendix=uy;h.isSelfMigrationFilename=dy;h.parseRunnerMsg=hy;h.parseServerMsg=py;var a=Qc();h.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."};h.PROTOCOL_VERSION="1.65";h.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}];h.DEFAULT_AGENT_ID="claude-code";h.REQUIRED_AGENT_CAPABILITIES={plan_only:["readOnlyJail","sessionResume"],respond:["readOnlyJail"],implement:["editNoShellJail","sessionResume"],deploy:[],chat:["readOnlyJail","sessionResume"],assist:["readOnlyJail"]};function ay(t,e){let n=h.REGISTERED_AGENTS.find(r=>r.id===t);return n?(h.REQUIRED_AGENT_CAPABILITIES[e]??[]).filter(r=>!n.capabilities[r]):null}h.BRANCH_DEPLOY_ISSUE_KEY="(branch deploy)";h.NEEDS_INPUT_MARKER="NEEDS-INPUT";h.NEEDS_INPUT_ASK_FENCE="ask";h.NEEDS_INPUT_LABEL="agent-needs-input";h.NEEDS_INPUT_COMMENT_MARKER="Allwright needs your input";h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=["TicketPilot needs your input"];var ly=t=>t.includes(h.NEEDS_INPUT_COMMENT_MARKER)||h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS.some(e=>t.includes(e));h.needsInputMarkerIn=ly;h.RunStatus=a.z.enum(["queued","running","posting","awaiting_approval","needs_input","succeeded","failed","timed_out"]);h.ACTIVE_RUN_STATUSES=["queued","running","posting","awaiting_approval"];h.TriggerType=a.z.enum(["label_added","comment_keyword","status_changed"]);h.ActionType=a.z.enum(["plan_only","implement","respond","deploy"]);h.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")});h.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")});h.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")});h.TriggerConfig=a.z.discriminatedUnion("type",[h.LabelAddedTrigger,h.CommentKeywordTrigger,h.StatusChangedTrigger]);h.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(h.DEFAULT_AGENT_ID),model:a.z.string().default("")});h.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(t=>t.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(h.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)});h.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(h.DEFAULT_AGENT_ID),model:a.z.string().default("")});h.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)});h.PromotionMode=a.z.enum(["deploy_only","merge_and_deploy"]);h.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:h.PromotionMode.default("deploy_only"),ticketBranchTemplate:a.z.string().default("agent/{{issueKey}}"),steps:a.z.array(h.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("")});h.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()});h.ActionConfig=a.z.discriminatedUnion("type",[h.PlanOnlyAction,h.ImplementAction,h.RespondAction,h.DeployAction]);h.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([])});h.RuleConfig=a.z.object({id:a.z.string(),projectId:a.z.string(),name:a.z.string(),enabled:a.z.boolean(),trigger:h.TriggerConfig,action:h.ActionConfig});h.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()});h.HeartbeatMsg=a.z.object({type:a.z.literal("heartbeat"),ts:a.z.string()});h.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()});h.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)});h.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()});h.FailedTest=a.z.object({command:a.z.string().max(500),exitCode:a.z.number().int(),tail:a.z.string().max(4e3)});h.RunStatusMsg=a.z.object({type:a.z.literal("run.status"),runId:a.z.string(),status:h.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(h.FailedTest).max(20).optional(),testsPassed:a.z.number().int().nonnegative().optional(),testsTotal:a.z.number().int().nonnegative().optional(),manualSteps:a.z.array(a.z.object({command:a.z.string().max(500),why:a.z.string().max(300).default("")})).max(20).optional(),goLiveDraft:a.z.string().max(4e3).optional(),inputQuestions:a.z.string().max(4e3).optional(),inputOptions:a.z.array(a.z.string().max(200)).max(5).optional()});h.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("")}))});h.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)});h.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()});h.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:h.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()});h.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()});h.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)});h.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()});h.ChatListMsg=a.z.object({type:a.z.literal("chat.list"),requestId:a.z.string(),projectId:a.z.string()});h.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([])});h.ChatLoadMsg=a.z.object({type:a.z.literal("chat.load"),requestId:a.z.string(),sessionId:a.z.string()});h.BUILTIN_REPLY_LANGUAGES=[{name:"English",instruction:"Write your prose in English."},{name:"Hindi",instruction:"Write your prose in Hindi, in the Devanagari script. Keep technical terms that have no everyday Hindi equivalent in English rather than inventing a translation."},{name:"Hinglish",instruction:"Write your prose in Hinglish: conversational Hindi written in the Latin alphabet, with English technical words left in English - the way an Indian developer talks at work."}];h.REPLY_STYLES=[{id:"technical",label:"Technical",hint:"Full detail - names files, functions and trade-offs",instruction:"Answer at full technical depth: name the files, functions and data structures involved, and state trade-offs precisely. Assume the reader reads code every day."},{id:"balanced",label:"Balanced",hint:"Plain explanation, with the technical detail that matters",instruction:"Explain in plain language first, then add the technical detail that actually matters for the decision. Assume the reader is technical but does not know this codebase."},{id:"simple",label:"Simple",hint:"Everyday words - no jargon unless it is unavoidable",instruction:"Answer in everyday words, as if to someone who does not write code. Avoid jargon; when a technical term is unavoidable, explain it in half a sentence. Prefer short paragraphs and concrete examples over precision about internals."}];function cy(t){let e=[],n=(t.language??"").trim();if(n){let s=h.BUILTIN_REPLY_LANGUAGES.find(i=>i.name.toLowerCase()===n.toLowerCase());e.push((t.languageInstruction??"").trim()||s?.instruction||`Write your prose in ${n}.`),e.push("Code, file paths, identifiers, commands, error text and log output stay exactly as they are - only your own prose changes language."),e.push("The ```ticket block is the exception: its summary and description are ALWAYS written in English, because the ticket is read by other people and by the implementing agent.")}let r=h.REPLY_STYLES.find(s=>s.id===(t.style??"").trim());return r&&e.push(r.instruction),e.length?`
24
24
 
25
25
  HOW TO WRITE THE REPLY - the person you are answering chose this, so it applies to every reply in this conversation:
26
26
  - ${e.join(`
27
27
  - `)}
28
- `:""}function Fg(t){if(!t.length)return"";let e="```";return`
28
+ `:""}function uy(t){if(!t.length)return"";let e="```";return`
29
29
 
30
30
  PENDING DATABASE MIGRATIONS (fact, read from this database's own ledger just now):
31
31
  `+t.map(n=>`- ${h.SELF_MIGRATION_DIR}/${n}`).join(`
@@ -34,7 +34,7 @@ These files are checked in but NOT applied to the database this control plane ru
34
34
  ${e}action
35
35
  {"type": "apply-migration", "file": "<one filename from the list above>"}
36
36
  ${e}
37
- That is the only action block that exists - there is no free-form command form of it. Never mention the block itself in your prose.`}h.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(),steps:a.z.array(a.z.string()).default([]),files:a.z.array(a.z.string()).default([])})).default([]),error:a.z.string().optional()});h.RepoDocsMsg=a.z.object({type:a.z.literal("repo.docs"),requestId:a.z.string(),projectId:a.z.string()});h.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()});h.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)});h.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()});h.BoardFetchMsg=a.z.object({type:a.z.literal("board.fetch"),requestId:a.z.string(),projectId:a.z.string()});h.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()});h.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)});h.BoardTriggerResultMsg=a.z.object({type:a.z.literal("board.trigger.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional()});h.EpicListMsg=a.z.object({type:a.z.literal("epic.list"),requestId:a.z.string(),projectId:a.z.string(),epicKey:a.z.string().default("")});h.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([])});h.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(h.EpicChild).default([])});h.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("")});h.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)});h.AuditRole=a.z.enum(["security","testing","architecture"]);h.KnowledgeRole=a.z.enum(["security","testing","architecture","implement"]);h.AuditSeverity=a.z.enum(["critical","high","medium","low","info"]);h.AuditScope=a.z.object({kind:a.z.enum(["repo","ticket","branch"]).default("repo"),ref:a.z.string().default("")});h.AuditDetailLevel=a.z.enum(["simple","technical"]);h.AuditFinding=a.z.object({id:a.z.string().min(1),title:a.z.string().min(1),ruleId:a.z.string().max(20).default(""),severity:h.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("")});h.AuditRecord=a.z.object({id:a.z.string(),role:h.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(h.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:h.AuditScope.default({kind:"repo",ref:""}),detailLevel:h.AuditDetailLevel.default("technical"),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()});h.AuditStartMsg=a.z.object({type:a.z.literal("audit.start"),requestId:a.z.string(),projectId:a.z.string(),role:h.AuditRole,model:a.z.string().default(""),scope:h.AuditScope.default({kind:"repo",ref:""}),detailLevel:h.AuditDetailLevel.default("technical")});h.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:h.AuditRecord.optional()});h.AuditListMsg=a.z.object({type:a.z.literal("audit.list"),requestId:a.z.string(),projectId:a.z.string()});h.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("")});h.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({})});h.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:h.AuditRole,createdAt:a.z.string(),findingCount:a.z.number().int(),bySeverity:a.z.record(a.z.number().int()).default({}),detailLevel:h.AuditDetailLevel.default("technical")})).default([])});h.AuditGetMsg=a.z.object({type:a.z.literal("audit.get"),requestId:a.z.string(),projectId:a.z.string(),auditId:a.z.string()});h.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:h.AuditRecord.optional()});h.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("")});h.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:h.AuditRecord.optional()});h.KnowledgeListMsg=a.z.object({type:a.z.literal("knowledge.list"),requestId:a.z.string(),projectId:a.z.string()});h.KnowledgeFile=a.z.object({role:h.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)});h.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(h.KnowledgeFile).default([])});h.KnowledgeSaveMsg=a.z.object({type:a.z.literal("knowledge.save"),requestId:a.z.string(),projectId:a.z.string(),role:h.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("")});h.KnowledgeSaveResultMsg=a.z.object({type:a.z.literal("knowledge.save.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional()});h.TeamCredsMsg=a.z.object({type:a.z.literal("team.creds"),requestId:a.z.string(),emails:a.z.array(a.z.string()).max(200)});h.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([])});h.ChatFile=a.z.object({name:a.z.string().min(1).max(255),contentBase64:a.z.string().min(1).max(6e6)});h.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(h.ChatFile).max(8).default([]),replyLanguage:a.z.string().max(60).default(""),replyLanguageInstruction:a.z.string().max(600).default(""),replyStyle:a.z.string().max(30).default(""),pendingMigrations:a.z.array(a.z.string().max(200)).max(50).default([])});h.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(""),contextTokens:a.z.number().int().nonnegative().default(0),contextLimit:a.z.number().int().nonnegative().default(0),compacted:a.z.boolean().default(!1),compactedMessages:a.z.number().int().nonnegative().default(0)});h.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([]),createAs:a.z.enum(["epic_with_children","separate_epics","separate_tasks"]).default("epic_with_children"),files:a.z.array(h.ChatFile).max(8).default([])});h.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([])});h.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(h.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("")});h.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([])});h.SELF_MIGRATION_DIR="apps/api/prisma/manual";function Bg(t){return/^[A-Za-z0-9][A-Za-z0-9._-]*\.sql$/.test(t)&&!t.includes("..")}h.SelfMigrationApplyMsg=a.z.object({type:a.z.literal("selfmigration.apply"),requestId:a.z.string(),projectId:a.z.string(),environmentName:a.z.string().default(""),file:a.z.string(),urlSecret:a.z.string().default("DATABASE_URL")});h.SelfMigrationApplyResultMsg=a.z.object({type:a.z.literal("selfmigration.apply.result"),requestId:a.z.string(),ok:a.z.boolean(),file:a.z.string().default(""),checks:a.z.array(a.z.object({name:a.z.string(),ok:a.z.boolean(),detail:a.z.string().default(""),fix:a.z.array(a.z.string()).default([])})).default([]),output:a.z.string().max(2e4).default(""),error:a.z.string().default("")});h.DeploySuggestResultMsg=a.z.object({type:a.z.literal("deploy.suggest.result"),requestId:a.z.string(),ok:a.z.boolean(),steps:a.z.array(h.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("")});h.SetupStatusMsg=a.z.object({type:a.z.literal("setup.status"),requestId:a.z.string(),repoNames:a.z.array(a.z.string()).max(100).default([])});h.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(),path:a.z.string().default(""),mapped:a.z.boolean(),liveMapped:a.z.boolean().default(!0),pathExists:a.z.boolean().default(!1),currentBranch:a.z.string().default(""),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([])});h.RepoUnmapMsg=a.z.object({type:a.z.literal("repo.unmap"),requestId:a.z.string(),repoName:a.z.string()});h.RepoUnmapResultMsg=a.z.object({type:a.z.literal("repo.unmap.result"),requestId:a.z.string(),ok:a.z.boolean().default(!0),error:a.z.string().default(""),removedPath:a.z.string().default("")});h.SetupRecheckMsg=a.z.object({type:a.z.literal("setup.recheck"),requestId:a.z.string(),projectId:a.z.string(),environments:a.z.array(a.z.object({name:a.z.string(),branch:a.z.string().default(""),publicUrl:a.z.string().default(""),workdir:a.z.string().default("")})).default([])});h.SetupRecheckResultMsg=a.z.object({type:a.z.literal("setup.recheck.result"),requestId:a.z.string(),ok:a.z.boolean().default(!0),error:a.z.string().default(""),checks:a.z.array(a.z.object({environment:a.z.string().default(""),question:a.z.string(),ok:a.z.boolean(),detail:a.z.string().default(""),blocking:a.z.boolean().default(!0)})).default([])});h.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","unblock"]).default("claude"),blockers:a.z.array(a.z.string().max(400)).max(20).default([]),machineState:a.z.array(a.z.string().max(400)).max(40).default([]),streamId:a.z.string().default(""),environments:a.z.array(a.z.object({name:a.z.string(),branch:a.z.string().default(""),publicUrl:a.z.string().default(""),workdir:a.z.string().default(""),dedicatedCheckout:a.z.boolean().default(!1),onThisRunner:a.z.boolean().default(!0)})).default([])});h.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("")});h.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)});h.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("")});h.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)});h.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("")});h.RunnerUpdateMsg=a.z.object({type:a.z.literal("runner.update"),requestId:a.z.string()});h.RunResolveConflictMsg=a.z.object({type:a.z.literal("run.resolve.conflict"),requestId:a.z.string(),runId:a.z.string()});h.RunTestFixMsg=a.z.object({type:a.z.literal("run.testfix"),requestId:a.z.string(),runId:a.z.string(),failedTests:a.z.array(h.FailedTest).min(1).max(20)});h.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(h.FailedTest).default([]),costUsd:a.z.number().nonnegative().optional(),inputTokens:a.z.number().int().nonnegative().optional(),outputTokens:a.z.number().int().nonnegative().optional()});h.RunAnswerMsg=a.z.object({type:a.z.literal("run.answer"),requestId:a.z.string(),runId:a.z.string(),text:a.z.string().min(1).max(4e3),answeredBy:a.z.string().default("")});h.RunAnswerResultMsg=a.z.object({type:a.z.literal("run.answer.result"),requestId:a.z.string(),ok:a.z.boolean(),note:a.z.string().default(""),error:a.z.string().optional()});h.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()});h.RunPrConflictMsg=a.z.object({type:a.z.literal("run.pr.conflict"),runId:a.z.string(),conflicted:a.z.boolean()});h.AgentProfilesMsg=a.z.object({type:a.z.literal("agent.profiles"),requestId:a.z.string()});h.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([])});h.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)});h.AutopilotNextMsg=a.z.object({type:a.z.literal("autopilot.next"),requestId:a.z.string()});h.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("")});h.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("")});h.RunnerToServerMsg=a.z.discriminatedUnion("type",[h.HelloMsg,h.HeartbeatMsg,h.RunClaimMsg,h.RunLogMsg,h.RunUsageMsg,h.RunStatusMsg,h.ProjectTestResultMsg,h.RuleDiagnoseResultMsg,h.DeployClaimMsg,h.DeploySuggestResultMsg,h.EnvPreflightResultMsg,h.SelfMigrationApplyResultMsg,h.ChatTurnResultMsg,h.ChatStreamMsg,h.ChatUsageMsg,h.ChatCreateTicketResultMsg,h.ChatListResultMsg,h.RepoDocsResultMsg,h.RepoDocReadResultMsg,h.ChatLoadResultMsg,h.BoardFetchResultMsg,h.BoardTriggerResultMsg,h.TeamCredsResultMsg,h.AuditStartResultMsg,h.AuditListResultMsg,h.AuditGetResultMsg,h.AuditReviewResultMsg,h.KnowledgeListResultMsg,h.KnowledgeSaveResultMsg,h.EpicListResultMsg,h.EpicSuggestResultMsg,h.JiraUsersResultMsg,h.SetupStatusResultMsg,h.SetupClaudeMdGenerateResultMsg,h.SetupRecheckResultMsg,h.RepoUnmapResultMsg,h.SetupClaudeMdSaveResultMsg,h.RepoDocSaveResultMsg,h.RunnerUpdateResultMsg,h.AgentProfilesResultMsg,h.RunPrConflictMsg,h.RunResolveConflictResultMsg,h.RunTestFixResultMsg,h.RunAnswerResultMsg,h.AuditStatsResultMsg,h.AutopilotNextMsg,h.AutopilotReportMsg]);h.HelloAckMsg=a.z.object({type:a.z.literal("hello.ack"),runnerId:a.z.string(),runnerName:a.z.string(),serverTime:a.z.string()});h.ConfigMsg=a.z.object({type:a.z.literal("config"),projects:a.z.array(h.ProjectConfig),rules:a.z.array(h.RuleConfig),environments:a.z.array(h.EnvironmentConfig).default([]),pollingPaused:a.z.boolean().default(!1)});h.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()});h.ProjectTestMsg=a.z.object({type:a.z.literal("project.test"),requestId:a.z.string(),projectId:a.z.string()});h.RuleDiagnoseMsg=a.z.object({type:a.z.literal("rule.diagnose"),requestId:a.z.string(),ruleId:a.z.string()});h.RunCancelMsg=a.z.object({type:a.z.literal("run.cancel"),runId:a.z.string()});h.RunApprovedMsg=a.z.object({type:a.z.literal("run.approved"),runId:a.z.string(),headSha:a.z.string().optional()});h.RunRejectedMsg=a.z.object({type:a.z.literal("run.rejected"),runId:a.z.string()});h.RunRetryPushMsg=a.z.object({type:a.z.literal("run.retryPush"),runId:a.z.string()});h.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:h.EnvironmentConfig,requestedBy:a.z.string().default(""),attempt:a.z.number().int().positive().default(1)});h.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("")});h.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)});h.JiraUsersMsg=a.z.object({type:a.z.literal("jira.users"),requestId:a.z.string(),query:a.z.string().default("")});h.ServerToRunnerMsg=a.z.discriminatedUnion("type",[h.HelloAckMsg,h.ConfigMsg,h.RunClaimResultMsg,h.ProjectTestMsg,h.RuleDiagnoseMsg,h.RunCancelMsg,h.RunApprovedMsg,h.RunRejectedMsg,h.RunRetryPushMsg,h.DeployClaimResultMsg,h.DeployStartMsg,h.DeploySuggestMsg,h.DeployFixMsg,h.EnvPreflightMsg,h.SelfMigrationApplyMsg,h.ChatTurnMsg,h.ChatCreateTicketMsg,h.ChatListMsg,h.RepoDocsMsg,h.RepoDocReadMsg,h.ChatLoadMsg,h.BoardFetchMsg,h.BoardTriggerMsg,h.TeamCredsMsg,h.AuditStartMsg,h.AuditListMsg,h.AuditGetMsg,h.AuditReviewMsg,h.KnowledgeListMsg,h.KnowledgeSaveMsg,h.EpicListMsg,h.EpicSuggestMsg,h.JiraUsersMsg,h.SetupStatusMsg,h.SetupClaudeMdGenerateMsg,h.SetupRecheckMsg,h.RepoUnmapMsg,h.SetupClaudeMdSaveMsg,h.RepoDocSaveMsg,h.RunnerUpdateMsg,h.AgentProfilesMsg,h.RunResolveConflictMsg,h.RunTestFixMsg,h.RunAnswerMsg,h.AuditStatsMsg,h.AutopilotNextResultMsg]);h.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()});h.EnrollResponse=a.z.object({runnerId:a.z.string(),runnerToken:a.z.string(),controlPlaneWsUrl:a.z.string()});function Kg(t){return h.RunnerToServerMsg.parse(t)}function Hg(t){return h.ServerToRunnerMsg.parse(t)}h.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.
37
+ That is the only action block that exists - there is no free-form command form of it. Never mention the block itself in your prose.`}h.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(),steps:a.z.array(a.z.string()).default([]),files:a.z.array(a.z.string()).default([])})).default([]),error:a.z.string().optional()});h.RepoDocsMsg=a.z.object({type:a.z.literal("repo.docs"),requestId:a.z.string(),projectId:a.z.string()});h.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()});h.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)});h.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()});h.BoardFetchMsg=a.z.object({type:a.z.literal("board.fetch"),requestId:a.z.string(),projectId:a.z.string()});h.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()});h.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)});h.BoardTriggerResultMsg=a.z.object({type:a.z.literal("board.trigger.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional()});h.EpicListMsg=a.z.object({type:a.z.literal("epic.list"),requestId:a.z.string(),projectId:a.z.string(),epicKey:a.z.string().default("")});h.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([])});h.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(h.EpicChild).default([])});h.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("")});h.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)});h.AuditRole=a.z.enum(["security","testing","architecture"]);h.KnowledgeRole=a.z.enum(["security","testing","architecture","implement"]);h.AuditSeverity=a.z.enum(["critical","high","medium","low","info"]);h.AuditScope=a.z.object({kind:a.z.enum(["repo","ticket","branch"]).default("repo"),ref:a.z.string().default("")});h.AuditDetailLevel=a.z.enum(["simple","technical"]);h.AuditFinding=a.z.object({id:a.z.string().min(1),title:a.z.string().min(1),ruleId:a.z.string().max(20).default(""),severity:h.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("")});h.AuditRecord=a.z.object({id:a.z.string(),role:h.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(h.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:h.AuditScope.default({kind:"repo",ref:""}),detailLevel:h.AuditDetailLevel.default("technical"),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()});h.AuditStartMsg=a.z.object({type:a.z.literal("audit.start"),requestId:a.z.string(),projectId:a.z.string(),role:h.AuditRole,model:a.z.string().default(""),scope:h.AuditScope.default({kind:"repo",ref:""}),detailLevel:h.AuditDetailLevel.default("technical")});h.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:h.AuditRecord.optional()});h.AuditListMsg=a.z.object({type:a.z.literal("audit.list"),requestId:a.z.string(),projectId:a.z.string()});h.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("")});h.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({})});h.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:h.AuditRole,createdAt:a.z.string(),findingCount:a.z.number().int(),bySeverity:a.z.record(a.z.number().int()).default({}),detailLevel:h.AuditDetailLevel.default("technical")})).default([])});h.AuditGetMsg=a.z.object({type:a.z.literal("audit.get"),requestId:a.z.string(),projectId:a.z.string(),auditId:a.z.string()});h.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:h.AuditRecord.optional()});h.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("")});h.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:h.AuditRecord.optional()});h.KnowledgeListMsg=a.z.object({type:a.z.literal("knowledge.list"),requestId:a.z.string(),projectId:a.z.string()});h.KnowledgeFile=a.z.object({role:h.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)});h.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(h.KnowledgeFile).default([])});h.KnowledgeSaveMsg=a.z.object({type:a.z.literal("knowledge.save"),requestId:a.z.string(),projectId:a.z.string(),role:h.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("")});h.KnowledgeSaveResultMsg=a.z.object({type:a.z.literal("knowledge.save.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional()});h.TeamCredsMsg=a.z.object({type:a.z.literal("team.creds"),requestId:a.z.string(),emails:a.z.array(a.z.string()).max(200)});h.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([])});h.ChatFile=a.z.object({name:a.z.string().min(1).max(255),contentBase64:a.z.string().min(1).max(6e6)});h.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(h.ChatFile).max(8).default([]),replyLanguage:a.z.string().max(60).default(""),replyLanguageInstruction:a.z.string().max(600).default(""),replyStyle:a.z.string().max(30).default(""),pendingMigrations:a.z.array(a.z.string().max(200)).max(50).default([])});h.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(""),contextTokens:a.z.number().int().nonnegative().default(0),contextLimit:a.z.number().int().nonnegative().default(0),compacted:a.z.boolean().default(!1),compactedMessages:a.z.number().int().nonnegative().default(0)});h.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([]),createAs:a.z.enum(["epic_with_children","separate_epics","separate_tasks"]).default("epic_with_children"),files:a.z.array(h.ChatFile).max(8).default([])});h.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([])});h.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(h.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("")});h.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([])});h.SELF_MIGRATION_DIR="apps/api/prisma/manual";function dy(t){return/^[A-Za-z0-9][A-Za-z0-9._-]*\.sql$/.test(t)&&!t.includes("..")}h.SelfMigrationApplyMsg=a.z.object({type:a.z.literal("selfmigration.apply"),requestId:a.z.string(),projectId:a.z.string(),environmentName:a.z.string().default(""),file:a.z.string(),urlSecret:a.z.string().default("DATABASE_URL")});h.SelfMigrationApplyResultMsg=a.z.object({type:a.z.literal("selfmigration.apply.result"),requestId:a.z.string(),ok:a.z.boolean(),file:a.z.string().default(""),checks:a.z.array(a.z.object({name:a.z.string(),ok:a.z.boolean(),detail:a.z.string().default(""),fix:a.z.array(a.z.string()).default([])})).default([]),output:a.z.string().max(2e4).default(""),error:a.z.string().default("")});h.DeploySuggestResultMsg=a.z.object({type:a.z.literal("deploy.suggest.result"),requestId:a.z.string(),ok:a.z.boolean(),steps:a.z.array(h.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("")});h.SetupStatusMsg=a.z.object({type:a.z.literal("setup.status"),requestId:a.z.string(),repoNames:a.z.array(a.z.string()).max(100).default([])});h.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(),path:a.z.string().default(""),mapped:a.z.boolean(),liveMapped:a.z.boolean().default(!0),pathExists:a.z.boolean().default(!1),currentBranch:a.z.string().default(""),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([])});h.RepoUnmapMsg=a.z.object({type:a.z.literal("repo.unmap"),requestId:a.z.string(),repoName:a.z.string()});h.RepoUnmapResultMsg=a.z.object({type:a.z.literal("repo.unmap.result"),requestId:a.z.string(),ok:a.z.boolean().default(!0),error:a.z.string().default(""),removedPath:a.z.string().default("")});h.SetupRecheckMsg=a.z.object({type:a.z.literal("setup.recheck"),requestId:a.z.string(),projectId:a.z.string(),environments:a.z.array(a.z.object({name:a.z.string(),branch:a.z.string().default(""),publicUrl:a.z.string().default(""),workdir:a.z.string().default("")})).default([])});h.SetupRecheckResultMsg=a.z.object({type:a.z.literal("setup.recheck.result"),requestId:a.z.string(),ok:a.z.boolean().default(!0),error:a.z.string().default(""),checks:a.z.array(a.z.object({environment:a.z.string().default(""),question:a.z.string(),ok:a.z.boolean(),detail:a.z.string().default(""),blocking:a.z.boolean().default(!0)})).default([])});h.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","unblock"]).default("claude"),blockers:a.z.array(a.z.string().max(400)).max(20).default([]),machineState:a.z.array(a.z.string().max(400)).max(40).default([]),streamId:a.z.string().default(""),environments:a.z.array(a.z.object({name:a.z.string(),branch:a.z.string().default(""),publicUrl:a.z.string().default(""),workdir:a.z.string().default(""),dedicatedCheckout:a.z.boolean().default(!1),onThisRunner:a.z.boolean().default(!0)})).default([])});h.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("")});h.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)});h.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("")});h.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)});h.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("")});h.RunnerUpdateMsg=a.z.object({type:a.z.literal("runner.update"),requestId:a.z.string()});h.RunResolveConflictMsg=a.z.object({type:a.z.literal("run.resolve.conflict"),requestId:a.z.string(),runId:a.z.string()});h.RunTestFixMsg=a.z.object({type:a.z.literal("run.testfix"),requestId:a.z.string(),runId:a.z.string(),failedTests:a.z.array(h.FailedTest).min(1).max(20)});h.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(h.FailedTest).default([]),costUsd:a.z.number().nonnegative().optional(),inputTokens:a.z.number().int().nonnegative().optional(),outputTokens:a.z.number().int().nonnegative().optional()});h.RunAnswerMsg=a.z.object({type:a.z.literal("run.answer"),requestId:a.z.string(),runId:a.z.string(),text:a.z.string().min(1).max(4e3),answeredBy:a.z.string().default("")});h.RunAnswerResultMsg=a.z.object({type:a.z.literal("run.answer.result"),requestId:a.z.string(),ok:a.z.boolean(),note:a.z.string().default(""),error:a.z.string().optional()});h.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()});h.RunPrConflictMsg=a.z.object({type:a.z.literal("run.pr.conflict"),runId:a.z.string(),conflicted:a.z.boolean()});h.AgentProfilesMsg=a.z.object({type:a.z.literal("agent.profiles"),requestId:a.z.string()});h.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([])});h.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)});h.AutopilotNextMsg=a.z.object({type:a.z.literal("autopilot.next"),requestId:a.z.string()});h.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("")});h.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("")});h.RunnerToServerMsg=a.z.discriminatedUnion("type",[h.HelloMsg,h.HeartbeatMsg,h.RunClaimMsg,h.RunLogMsg,h.RunUsageMsg,h.RunStatusMsg,h.ProjectTestResultMsg,h.RuleDiagnoseResultMsg,h.DeployClaimMsg,h.DeploySuggestResultMsg,h.EnvPreflightResultMsg,h.SelfMigrationApplyResultMsg,h.ChatTurnResultMsg,h.ChatStreamMsg,h.ChatUsageMsg,h.ChatCreateTicketResultMsg,h.ChatListResultMsg,h.RepoDocsResultMsg,h.RepoDocReadResultMsg,h.ChatLoadResultMsg,h.BoardFetchResultMsg,h.BoardTriggerResultMsg,h.TeamCredsResultMsg,h.AuditStartResultMsg,h.AuditListResultMsg,h.AuditGetResultMsg,h.AuditReviewResultMsg,h.KnowledgeListResultMsg,h.KnowledgeSaveResultMsg,h.EpicListResultMsg,h.EpicSuggestResultMsg,h.JiraUsersResultMsg,h.SetupStatusResultMsg,h.SetupClaudeMdGenerateResultMsg,h.SetupRecheckResultMsg,h.RepoUnmapResultMsg,h.SetupClaudeMdSaveResultMsg,h.RepoDocSaveResultMsg,h.RunnerUpdateResultMsg,h.AgentProfilesResultMsg,h.RunPrConflictMsg,h.RunResolveConflictResultMsg,h.RunTestFixResultMsg,h.RunAnswerResultMsg,h.AuditStatsResultMsg,h.AutopilotNextMsg,h.AutopilotReportMsg]);h.HelloAckMsg=a.z.object({type:a.z.literal("hello.ack"),runnerId:a.z.string(),runnerName:a.z.string(),serverTime:a.z.string()});h.ConfigMsg=a.z.object({type:a.z.literal("config"),projects:a.z.array(h.ProjectConfig),rules:a.z.array(h.RuleConfig),environments:a.z.array(h.EnvironmentConfig).default([]),pollingPaused:a.z.boolean().default(!1)});h.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()});h.ProjectTestMsg=a.z.object({type:a.z.literal("project.test"),requestId:a.z.string(),projectId:a.z.string()});h.RuleDiagnoseMsg=a.z.object({type:a.z.literal("rule.diagnose"),requestId:a.z.string(),ruleId:a.z.string()});h.RunCancelMsg=a.z.object({type:a.z.literal("run.cancel"),runId:a.z.string()});h.RunApprovedMsg=a.z.object({type:a.z.literal("run.approved"),runId:a.z.string(),headSha:a.z.string().optional()});h.RunRejectedMsg=a.z.object({type:a.z.literal("run.rejected"),runId:a.z.string()});h.RunRetryPushMsg=a.z.object({type:a.z.literal("run.retryPush"),runId:a.z.string()});h.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:h.EnvironmentConfig,requestedBy:a.z.string().default(""),attempt:a.z.number().int().positive().default(1)});h.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("")});h.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)});h.JiraUsersMsg=a.z.object({type:a.z.literal("jira.users"),requestId:a.z.string(),query:a.z.string().default("")});h.ServerToRunnerMsg=a.z.discriminatedUnion("type",[h.HelloAckMsg,h.ConfigMsg,h.RunClaimResultMsg,h.ProjectTestMsg,h.RuleDiagnoseMsg,h.RunCancelMsg,h.RunApprovedMsg,h.RunRejectedMsg,h.RunRetryPushMsg,h.DeployClaimResultMsg,h.DeployStartMsg,h.DeploySuggestMsg,h.DeployFixMsg,h.EnvPreflightMsg,h.SelfMigrationApplyMsg,h.ChatTurnMsg,h.ChatCreateTicketMsg,h.ChatListMsg,h.RepoDocsMsg,h.RepoDocReadMsg,h.ChatLoadMsg,h.BoardFetchMsg,h.BoardTriggerMsg,h.TeamCredsMsg,h.AuditStartMsg,h.AuditListMsg,h.AuditGetMsg,h.AuditReviewMsg,h.KnowledgeListMsg,h.KnowledgeSaveMsg,h.EpicListMsg,h.EpicSuggestMsg,h.JiraUsersMsg,h.SetupStatusMsg,h.SetupClaudeMdGenerateMsg,h.SetupRecheckMsg,h.RepoUnmapMsg,h.SetupClaudeMdSaveMsg,h.RepoDocSaveMsg,h.RunnerUpdateMsg,h.AgentProfilesMsg,h.RunResolveConflictMsg,h.RunTestFixMsg,h.RunAnswerMsg,h.AuditStatsMsg,h.AutopilotNextResultMsg]);h.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()});h.EnrollResponse=a.z.object({runnerId:a.z.string(),runnerToken:a.z.string(),controlPlaneWsUrl:a.z.string()});function hy(t){return h.RunnerToServerMsg.parse(t)}function py(t){return h.ServerToRunnerMsg.parse(t)}h.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.
38
38
 
39
39
  Ticket {{issueKey}}: {{summary}}
40
40
 
@@ -287,57 +287,129 @@ Rules for the steps:
287
287
  - "requiredSecrets" is ONLY for values that must come from OUTSIDE - a token, a host, a key someone has to supply. A variable a step assigns itself (PRE=$(cat ...), POST=$(systemctl show ...)) is ordinary shell plumbing: never list it. Listing one makes every deploy refuse to start and demand a value that exists nowhere.
288
288
  - Prefer commands that are safe to re-run; a deploy may be retried.
289
289
  - Order matters: install, build, test (if cheap), then release.
290
- - If you genuinely cannot tell how this repo is deployed, return an empty "steps" array and explain what is missing in "notes".`});var Xc={};ei(Xc,{DELETE_MANIFEST_FILE:()=>Dt,MAX_CHANGED_FILES:()=>ln,MAX_CHANGED_LINES:()=>cn,abortMerge:()=>hn,applyDeleteManifest:()=>Yr,branchForIssue:()=>sa,branchSha:()=>Ii,branchesDiffer:()=>da,checkDiffSafety:()=>dn,commitAll:()=>tr,commitMergeResolution:()=>la,deleteStaleBranch:()=>ta,diffAgainstDefault:()=>Ai,envCheckoutPath:()=>Jc,envCheckoutsRoot:()=>Yc,fetchBase:()=>un,findConflictMarkers:()=>Ci,headSha:()=>nt,mergeBaseIntoWorktree:()=>aa,mergeTicketBranch:()=>oa,originUrl:()=>rr,parseOwnerRepo:()=>lt,prepareEnvCheckout:()=>ia,pruneWorktrees:()=>ra,pushBranch:()=>nr,pushEnvBranch:()=>ua,pushWipBranch:()=>Qo,removeWorktree:()=>vt,resetHard:()=>Jr,statusSnapshot:()=>ea,unresolvedAmong:()=>ca,worktreeAdd:()=>na,worktreeAddExisting:()=>Is,worktreeFingerprint:()=>Ri,worktreesRoot:()=>Lt});async function F(t,e,n={}){try{let{stdout:r}=await Vc("git",["-C",t,...e],{timeout:n.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 Yr(t){let e={deleted:[],refused:[]},n=he.default.join(t,Dt);if(!_e.default.existsSync(n))return e;let r=he.default.resolve(t),s=_e.default.readFileSync(n,"utf8").split(`
291
- `).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#"));for(let i of s.slice(0,200)){if(he.default.isAbsolute(i)){e.refused.push(`${i} - absolute paths are not allowed`);continue}let o=he.default.resolve(r,i);if(o!==r&&!o.startsWith(r+he.default.sep)){e.refused.push(`${i} - escapes the worktree`);continue}let l=he.default.relative(r,o).split(he.default.sep).join("/");if(l===Dt)continue;if(Wc.some(u=>u.test(l))){e.refused.push(`${i} - protected path (CI/hook files are never touched)`);continue}let c;try{c=_e.default.lstatSync(o)}catch{e.refused.push(`${i} - no such file`);continue}if(c.isDirectory()){e.refused.push(`${i} - is a directory (list the files inside it instead)`);continue}try{_e.default.rmSync(o),e.deleted.push(l)}catch(u){e.refused.push(`${i} - ${u instanceof Error?u.message:"delete failed"}`)}}return _e.default.rmSync(n,{force:!0}),e}async function Qo(t,e){await F(t,["push","--force","origin",`HEAD:refs/heads/${e}`],{timeoutMs:3e5})}async function Ri(t){let e=await F(t,["status","--porcelain"]),n=await F(t,["diff","--numstat"]),r=e.split(`
292
- `).filter(s=>s.startsWith("??")).map(s=>s.slice(3).trim()).slice(0,500).map(s=>{try{let i=_e.default.statSync(he.default.join(t,s));return`${s}:${i.size}:${i.mtimeMs}`}catch{return s}}).join(`
290
+ - If you genuinely cannot tell how this repo is deployed, return an empty "steps" array and explain what is missing in "notes".`});var cu={};xs(cu,{DELETE_MANIFEST_FILE:()=>qt,MAX_CHANGED_FILES:()=>pn,MAX_CHANGED_LINES:()=>fn,abortMerge:()=>yn,applyDeleteManifest:()=>ns,branchForIssue:()=>ma,branchSha:()=>Oi,branchesDiffer:()=>_a,checkDiffSafety:()=>gn,commitAll:()=>ar,commitMergeResolution:()=>va,deleteStaleBranch:()=>ha,diffAgainstDefault:()=>Mi,envCheckoutPath:()=>lu,envCheckoutsRoot:()=>au,fetchBase:()=>mn,findConflictMarkers:()=>zi,headSha:()=>st,mergeBaseIntoWorktree:()=>ba,mergeTicketBranch:()=>ya,originUrl:()=>cr,parseOwnerRepo:()=>ut,prepareEnvCheckout:()=>ga,pruneWorktrees:()=>fa,pushBranch:()=>lr,pushEnvBranch:()=>ka,pushWipBranch:()=>ua,removeWorktree:()=>kt,resetHard:()=>rs,statusSnapshot:()=>da,unresolvedAmong:()=>wa,worktreeAdd:()=>pa,worktreeAddExisting:()=>Os,worktreeFingerprint:()=>ji,worktreesRoot:()=>Ft});async function F(t,e,n={}){try{let{stdout:r}=await iu("git",["-C",t,...e],{timeout:n.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 ns(t){let e={deleted:[],refused:[]},n=he.default.join(t,qt);if(!Se.default.existsSync(n))return e;let r=he.default.resolve(t),s=Se.default.readFileSync(n,"utf8").split(`
291
+ `).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#"));for(let i of s.slice(0,200)){if(he.default.isAbsolute(i)){e.refused.push(`${i} - absolute paths are not allowed`);continue}let o=he.default.resolve(r,i);if(o!==r&&!o.startsWith(r+he.default.sep)){e.refused.push(`${i} - escapes the worktree`);continue}let l=he.default.relative(r,o).split(he.default.sep).join("/");if(l===qt)continue;if(ou.some(u=>u.test(l))){e.refused.push(`${i} - protected path (CI/hook files are never touched)`);continue}let c;try{c=Se.default.lstatSync(o)}catch{e.refused.push(`${i} - no such file`);continue}if(c.isDirectory()){e.refused.push(`${i} - is a directory (list the files inside it instead)`);continue}try{Se.default.rmSync(o),e.deleted.push(l)}catch(u){e.refused.push(`${i} - ${u instanceof Error?u.message:"delete failed"}`)}}return Se.default.rmSync(n,{force:!0}),e}async function ua(t,e){await F(t,["push","--force","origin",`HEAD:refs/heads/${e}`],{timeoutMs:3e5})}async function ji(t){let e=await F(t,["status","--porcelain"]),n=await F(t,["diff","--numstat"]),r=e.split(`
292
+ `).filter(s=>s.startsWith("??")).map(s=>s.slice(3).trim()).slice(0,500).map(s=>{try{let i=Se.default.statSync(he.default.join(t,s));return`${s}:${i.size}:${i.mtimeMs}`}catch{return s}}).join(`
293
293
  `);return`${e}
294
294
  --
295
295
  ${n}
296
296
  --
297
- ${r}`}async function ea(t){let e=(await F(t,["rev-parse","--abbrev-ref","HEAD"])).trim(),n=(await F(t,["log","--oneline","-1"])).trim(),r=(await F(t,["status","--porcelain"])).trim(),s=r?r.split(`
297
+ ${r}`}async function da(t){let e=(await F(t,["rev-parse","--abbrev-ref","HEAD"])).trim(),n=(await F(t,["log","--oneline","-1"])).trim(),r=(await F(t,["status","--porcelain"])).trim(),s=r?r.split(`
298
298
  `):[],i=s.slice(0,15).join(`
299
299
  `),o=s.length>15?`
300
300
  (\u2026 ${s.length-15} more)`:"";return`branch ${e} @ ${n}
301
301
  working tree: ${s.length?`
302
- ${i}${o}`:"clean"}`}function Lt(){let t=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(_e.default.existsSync(he.default.join(er.default.homedir(),".cache","ticketpilot"))?he.default.join(er.default.homedir(),".cache","ticketpilot"):he.default.join(er.default.homedir(),".cache","allwright"));return he.default.join(t,"worktrees")}async function un(t,e){try{await F(t,["fetch","origin",e])}catch(n){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 (${n instanceof Error?n.message:n})`)}}async function ta(t,e){try{let n=await F(t,["worktree","list","--porcelain"]),r=Lt(),s=null;for(let i of n.split(`
303
- `))i.startsWith("worktree ")&&(s=i.slice(9).trim()),i===`branch refs/heads/${e}`&&s&&s.startsWith(r)&&await F(t,["worktree","remove","--force",s]);await F(t,["worktree","prune"])}catch{}try{await F(t,["branch","-D",e])}catch{}}async function na(t,e,n,r){_e.default.mkdirSync(he.default.dirname(e),{recursive:!0,mode:448}),await F(t,["worktree","add","-b",n,e,`origin/${r}`])}async function tr(t,e){if(await F(t,["add","-A"]),!(await F(t,["status","--porcelain"])).trim())throw new Error("Claude wrote no changes - nothing to commit");await F(t,["-c",`user.name=${xi}`,"-c",`user.email=${Ei}`,"commit","-m",e])}async function dn(t,e){let r=(await F(t,["diff","--name-only",`origin/${e}...HEAD`])).split(`
304
- `).filter(Boolean),s=r.filter(u=>Wc.some(p=>p.test(u))),i=await F(t,["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<=ln&&o+l<=cn,files:r.length,insertions:o,deletions:l,forbidden:s}}async function nr(t,e){await F(t,["fetch","--prune","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],{timeoutMs:12e4}).catch(()=>F(t,["update-ref","-d",`refs/remotes/origin/${e}`]).catch(()=>{})),await F(t,["push","--force-with-lease","-u","origin",e],{timeoutMs:3e5})}async function nt(t){return(await F(t,["rev-parse","HEAD"])).trim()}async function Ii(t,e){try{return(await F(t,["rev-parse","--verify",`refs/heads/${e}`])).trim()}catch{return null}}async function Jr(t,e){await F(t,["reset","--hard",e])}async function vt(t,e){try{await F(t,["worktree","remove","--force",e])}catch{_e.default.rmSync(e,{recursive:!0,force:!0})}}async function ra(t,e=[]){let n=new Set(e.map(s=>he.default.basename(he.default.resolve(s))).filter(s=>s.length>0)),r=Lt();if(_e.default.existsSync(r))for(let s of _e.default.readdirSync(r))n.has(s)||_e.default.rmSync(he.default.join(r,s),{recursive:!0,force:!0});for(let s of t)try{await F(s,["worktree","prune"])}catch{}}async function sa(t,e){return await F(t,["fetch","origin","--prune"]).catch(()=>{}),(await F(t,["branch","-r","--list",`*${e}*`])).split(`
305
- `).map(s=>s.trim()).filter(s=>s&&!s.includes("->"))[0]??null}async function Ai(t,e,n=6e4){let s=(await F(t,["symbolic-ref","refs/remotes/origin/HEAD"]).catch(()=>"")).trim().replace("refs/remotes/","")||"origin/main",i=await F(t,["diff","--stat",`${s}...${e}`]),o=await F(t,["diff",`${s}...${e}`]);return{base:s,stat:i.slice(0,4e3),diff:o.slice(0,n)}}function Yc(){let t=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(_e.default.existsSync(he.default.join(er.default.homedir(),".cache","ticketpilot"))?he.default.join(er.default.homedir(),".cache","ticketpilot"):he.default.join(er.default.homedir(),".cache","allwright"));return he.default.join(t,"env-checkouts")}function Hc(t){return t.replace(/[^\w.-]+/g,"_")}function Jc(t,e){return he.default.join(Yc(),Hc(t),Hc(e))}async function ia(t){let e=Jc(t.repoName,t.envName);return await F(t.repoPath,["fetch","origin",t.branch],{timeoutMs:3e5}),_e.default.existsSync(he.default.join(e,".git"))?await F(e,["fetch","origin",t.branch],{timeoutMs:3e5}):(_e.default.rmSync(e,{recursive:!0,force:!0}),_e.default.mkdirSync(he.default.dirname(e),{recursive:!0,mode:448}),await F(t.repoPath,["worktree","prune"]).catch(()=>{}),await F(t.repoPath,["worktree","add","--detach",e,`origin/${t.branch}`])),t.attached?await F(e,["checkout","-B",t.branch,`origin/${t.branch}`]):await F(e,["checkout","--force","--detach",`origin/${t.branch}`]),e}async function oa(t,e,n){try{await F(t,["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 F(t,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyMerged:!0}}catch{}try{return await F(t,["-c",`user.name=${xi}`,"-c",`user.email=${Ei}`,"merge","--no-ff","-m",n,`origin/${e}`]),{ok:!0}}catch(r){return await F(t,["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 aa(t,e){await F(t,["fetch","origin",e],{timeoutMs:3e5});try{return await F(t,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyUpToDate:!0}}catch{}try{return await F(t,["-c",`user.name=${xi}`,"-c",`user.email=${Ei}`,"merge","--no-edit",`origin/${e}`]),{ok:!0,alreadyUpToDate:!1}}catch(n){let s=(await F(t,["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
306
- `).filter(Boolean);return s.length?{ok:!1,conflicts:s}:(await F(t,["merge","--abort"]).catch(()=>{}),{ok:!1,conflicts:null,reason:n instanceof Error?n.message.slice(0,300):String(n)})}}async function hn(t){await F(t,["merge","--abort"]).catch(()=>{})}async function la(t,e){await F(t,["add","-A"]),await F(t,["-c",`user.name=${xi}`,"-c",`user.email=${Ei}`,"commit","--no-edit","-m",e])}async function ca(t,e){let n=new Set(await Ci(t));return e.filter(r=>n.has(r))}async function Ci(t){let e=new Set;try{let r=await F(t,["grep","-l","-I","-E","^(<{7}|>{7})( |$)"]);for(let s of r.split(`
302
+ ${i}${o}`:"clean"}`}function Ft(){let t=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(Se.default.existsSync(he.default.join(or.default.homedir(),".cache","ticketpilot"))?he.default.join(or.default.homedir(),".cache","ticketpilot"):he.default.join(or.default.homedir(),".cache","allwright"));return he.default.join(t,"worktrees")}async function mn(t,e){try{await F(t,["fetch","origin",e])}catch(n){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 (${n instanceof Error?n.message:n})`)}}async function ha(t,e){try{let n=await F(t,["worktree","list","--porcelain"]),r=Ft(),s=null;for(let i of n.split(`
303
+ `))i.startsWith("worktree ")&&(s=i.slice(9).trim()),i===`branch refs/heads/${e}`&&s&&s.startsWith(r)&&await F(t,["worktree","remove","--force",s]);await F(t,["worktree","prune"])}catch{}try{await F(t,["branch","-D",e])}catch{}}async function pa(t,e,n,r){Se.default.mkdirSync(he.default.dirname(e),{recursive:!0,mode:448}),await F(t,["worktree","add","-b",n,e,`origin/${r}`])}async function ar(t,e){if(await F(t,["add","-A"]),!(await F(t,["status","--porcelain"])).trim())throw new Error("Claude wrote no changes - nothing to commit");await F(t,["-c",`user.name=${Pi}`,"-c",`user.email=${Ni}`,"commit","-m",e])}async function gn(t,e){let r=(await F(t,["diff","--name-only",`origin/${e}...HEAD`])).split(`
304
+ `).filter(Boolean),s=r.filter(u=>ou.some(p=>p.test(u))),i=await F(t,["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<=pn&&o+l<=fn,files:r.length,insertions:o,deletions:l,forbidden:s}}async function lr(t,e){await F(t,["fetch","--prune","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],{timeoutMs:12e4}).catch(()=>F(t,["update-ref","-d",`refs/remotes/origin/${e}`]).catch(()=>{})),await F(t,["push","--force-with-lease","-u","origin",e],{timeoutMs:3e5})}async function st(t){return(await F(t,["rev-parse","HEAD"])).trim()}async function Oi(t,e){try{return(await F(t,["rev-parse","--verify",`refs/heads/${e}`])).trim()}catch{return null}}async function rs(t,e){await F(t,["reset","--hard",e])}async function kt(t,e){try{await F(t,["worktree","remove","--force",e])}catch{Se.default.rmSync(e,{recursive:!0,force:!0})}}async function fa(t,e=[]){let n=new Set(e.map(s=>he.default.basename(he.default.resolve(s))).filter(s=>s.length>0)),r=Ft();if(Se.default.existsSync(r))for(let s of Se.default.readdirSync(r))n.has(s)||Se.default.rmSync(he.default.join(r,s),{recursive:!0,force:!0});for(let s of t)try{await F(s,["worktree","prune"])}catch{}}async function ma(t,e){return await F(t,["fetch","origin","--prune"]).catch(()=>{}),(await F(t,["branch","-r","--list",`*${e}*`])).split(`
305
+ `).map(s=>s.trim()).filter(s=>s&&!s.includes("->"))[0]??null}async function Mi(t,e,n=6e4){let s=(await F(t,["symbolic-ref","refs/remotes/origin/HEAD"]).catch(()=>"")).trim().replace("refs/remotes/","")||"origin/main",i=await F(t,["diff","--stat",`${s}...${e}`]),o=await F(t,["diff",`${s}...${e}`]);return{base:s,stat:i.slice(0,4e3),diff:o.slice(0,n)}}function au(){let t=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(Se.default.existsSync(he.default.join(or.default.homedir(),".cache","ticketpilot"))?he.default.join(or.default.homedir(),".cache","ticketpilot"):he.default.join(or.default.homedir(),".cache","allwright"));return he.default.join(t,"env-checkouts")}function nu(t){return t.replace(/[^\w.-]+/g,"_")}function lu(t,e){return he.default.join(au(),nu(t),nu(e))}async function ga(t){let e=lu(t.repoName,t.envName);return await F(t.repoPath,["fetch","origin",t.branch],{timeoutMs:3e5}),Se.default.existsSync(he.default.join(e,".git"))?await F(e,["fetch","origin",t.branch],{timeoutMs:3e5}):(Se.default.rmSync(e,{recursive:!0,force:!0}),Se.default.mkdirSync(he.default.dirname(e),{recursive:!0,mode:448}),await F(t.repoPath,["worktree","prune"]).catch(()=>{}),await F(t.repoPath,["worktree","add","--detach",e,`origin/${t.branch}`])),t.attached?await F(e,["checkout","-B",t.branch,`origin/${t.branch}`]):await F(e,["checkout","--force","--detach",`origin/${t.branch}`]),e}async function ya(t,e,n){try{await F(t,["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 F(t,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyMerged:!0}}catch{}try{return await F(t,["-c",`user.name=${Pi}`,"-c",`user.email=${Ni}`,"merge","--no-ff","-m",n,`origin/${e}`]),{ok:!0}}catch(r){return await F(t,["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 ba(t,e){await F(t,["fetch","origin",e],{timeoutMs:3e5});try{return await F(t,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyUpToDate:!0}}catch{}try{return await F(t,["-c",`user.name=${Pi}`,"-c",`user.email=${Ni}`,"merge","--no-edit",`origin/${e}`]),{ok:!0,alreadyUpToDate:!1}}catch(n){let s=(await F(t,["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
306
+ `).filter(Boolean);return s.length?{ok:!1,conflicts:s}:(await F(t,["merge","--abort"]).catch(()=>{}),{ok:!1,conflicts:null,reason:n instanceof Error?n.message.slice(0,300):String(n)})}}async function yn(t){await F(t,["merge","--abort"]).catch(()=>{})}async function va(t,e){await F(t,["add","-A"]),await F(t,["-c",`user.name=${Pi}`,"-c",`user.email=${Ni}`,"commit","--no-edit","-m",e])}async function wa(t,e){let n=new Set(await zi(t));return e.filter(r=>n.has(r))}async function zi(t){let e=new Set;try{let r=await F(t,["grep","-l","-I","-E","^(<{7}|>{7})( |$)"]);for(let s of r.split(`
307
307
  `).filter(Boolean))e.add(s)}catch{}let n=[];try{n=(await F(t,["grep","-l","-I","-E","^={7}$"])).split(`
308
- `).filter(Boolean).filter(s=>!e.has(s))}catch{}for(let r of n)try{let s=await F(t,["show",`HEAD:${r}`]);/^={7}$/m.test(s)||e.add(r)}catch{e.add(r)}return[...e]}async function Is(t,e,n){_e.default.mkdirSync(he.default.dirname(e),{recursive:!0,mode:448}),await F(t,["fetch","origin",n],{timeoutMs:3e5}),await F(t,["worktree","add","--detach",e,`origin/${n}`]),await F(e,["checkout","-B",n,`origin/${n}`])}async function ua(t,e){try{await F(t,["push","origin",e],{timeoutMs:3e5})}catch(n){throw new Error(`could not push "${e}" - ${n instanceof Error?n.message:n}. Someone may have pushed to it since this deploy started; retry.`)}}async function da(t,e,n){try{return await Vc("git",["-C",t,"diff","--quiet",e,n,"--"],{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}..${n}: ${(s.stderr||s.message||"").trim().slice(0,500)}`)}}async function rr(t){return(await F(t,["config","--get","remote.origin.url"])).trim()}function lt(t){let e=/^git@github\.com(?:-[\w.-]+)?:([^/]+)\/(.+?)(\.git)?$/.exec(t)??/^https:\/\/github\.com\/([^/]+)\/(.+?)(\.git)?\/?$/.exec(t)??/^ssh:\/\/git@github\.com(?:-[\w.-]+)?\/([^/]+)\/(.+?)(\.git)?$/.exec(t);return e?{owner:e[1],repo:e[2]}:null}var _e,er,he,Gc,Zc,Vc,xi,Ei,ln,cn,Wc,Dt,wt=Qs(()=>{"use strict";_e=R(require("node:fs"),1),er=R(require("node:os"),1),he=R(require("node:path"),1),Gc=require("node:child_process"),Zc=require("node:util"),Vc=(0,Zc.promisify)(Gc.execFile),xi="Allwright Agent",Ei="agent@ticketpilot.local",ln=200,cn=2e4,Wc=[/^\.github\/workflows\//,/^\.git\b/,/(^|\/)\.githooks\//];Dt=".ticketpilot-delete"});function $i(t,e,n){let r=(n??"").trim().toLowerCase(),s=r?t.githubUsers[r]?.token:void 0;if(s)return{token:s,source:"user"};let i=t.repos[e]?.github?.token;return i?{token:i,source:"repo"}:t.github?.token?{token:t.github.token,source:"global"}:null}function Ce(t,e){return t.repos[e]?.github?.token??t.github?.token??null}function nu(t,e){let n=[t.jira,...Object.values(t.repos).map(l=>l.jira)].filter(l=>!!l),r=new Set(n.map(l=>l.email.toLowerCase())),s=!!t.github?.token||Object.values(t.repos).some(l=>l.github?.token),i=t.github?.login??Object.values(t.repos).find(l=>l.github?.login)?.github?.login??"",o=e.map(l=>{let c=l.trim().toLowerCase(),u=t.jiraUsers[c]?"own":r.has(c)?"runner-account":"missing",p=u==="own"?t.jiraUsers[c].email:u==="runner-account"?c:"",f=t.githubUsers[c]?"own":s?"shared":"missing",b=f==="own"?t.githubUsers[c].login??"":f==="shared"?i:"";return{email:c,jira:u,jiraAs:p,github:f,githubAs:b}});return{githubShared:s,sharedGithubLogin:i,entries:o}}var sr=Qs(()=>{"use strict"});var lr={};ei(lr,{GitHubClient:()=>$e});var fy,$e,ut=Qs(()=>{"use strict";fy=process.env.TICKETPILOT_GITHUB_API??"https://api.github.com",$e=class{constructor(e){this.token=e}token;async request(e,n,r){let s=await fetch(`${fy}${n}`,{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} ${n} -> ${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,n,r){let{status:s,data:i}=await this.request("POST",`/repos/${e}/${n}/pulls`,r);if(s===422){let{data:o}=await this.request("GET",`/repos/${e}/${n}/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,n,r){let{data:s}=await this.request("GET",`/repos/${e}/${n}/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,n,r){try{let{data:s}=await this.request("GET",`/repos/${e}/${n}/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,n,r,s,i={}){try{return await this.request("PUT",`/repos/${e}/${n}/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}/${n}. It needs write access to the repository - or merge the PR yourself.`}:{merged:!1,reason:l}}}async repoAccess(e,n){try{let{data:r}=await this.request("GET",`/repos/${e}/${n}`);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,n,r){await this.request("PATCH",`/repos/${e}/${n}/pulls/${r}`,{state:"closed"})}async deleteBranch(e,n,r){try{await this.request("DELETE",`/repos/${e}/${n}/git/refs/heads/${encodeURIComponent(r)}`)}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return;throw s}}}});var Kt=se((jS,bh)=>{"use strict";var gh=["nodebuffer","arraybuffer","fragments"],yh=typeof Blob<"u";yh&&gh.push("blob");bh.exports={BINARY_TYPES:gh,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:yh,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var qs=se((NS,to)=>{"use strict";var{EMPTY_BUFFER:Ob}=Kt(),ol=Buffer[Symbol.species];function Mb(t,e){if(t.length===0)return Ob;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let s=0;s<t.length;s++){let i=t[s];n.set(i,r),r+=i.length}return r<e?new ol(n.buffer,n.byteOffset,r):n}function vh(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function wh(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function zb(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function al(t){if(al.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new ol(t):ArrayBuffer.isView(t)?e=new ol(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),al.readOnly=!1),e}to.exports={concat:Mb,mask:vh,toArrayBuffer:zb,toBuffer:al,unmask:wh};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");to.exports.mask=function(e,n,r,s,i){i<48?vh(e,n,r,s,i):t.mask(e,n,r,s,i)},to.exports.unmask=function(e,n){e.length<32?wh(e,n):t.unmask(e,n)}}catch{}});var Sh=se((OS,_h)=>{"use strict";var kh=Symbol("kDone"),ll=Symbol("kRun"),cl=class{constructor(e){this[kh]=()=>{this.pending--,this[ll]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[ll]()}[ll](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[kh])}}};_h.exports=cl});var us=se((MS,Rh)=>{"use strict";var Fs=require("zlib"),Th=qs(),Db=Sh(),{kStatusCode:xh}=Kt(),Lb=Buffer[Symbol.species],Ub=Buffer.from([0,0,255,255]),ro=Symbol("permessage-deflate"),Ht=Symbol("total-length"),ls=Symbol("callback"),mn=Symbol("buffers"),cs=Symbol("error"),no,ul=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,!no){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;no=new Db(n)}}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[ls];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(s=>!(n.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>s.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let s=n[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}"`);n[r]=s})}),e}decompress(e,n,r){no.add(s=>{this._decompress(e,n,(i,o)=>{s(),r(i,o)})})}compress(e,n,r){no.add(s=>{this._compress(e,n,(i,o)=>{s(),r(i,o)})})}_decompress(e,n,r){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Fs.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Fs.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[ro]=this,this._inflate[Ht]=0,this._inflate[mn]=[],this._inflate.on("error",Fb),this._inflate.on("data",Eh)}this._inflate[ls]=r,this._inflate.write(e),n&&this._inflate.write(Ub),this._inflate.flush(()=>{let i=this._inflate[cs];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=Th.concat(this._inflate[mn],this._inflate[Ht]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Ht]=0,this._inflate[mn]=[],n&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,n,r){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Fs.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Fs.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[Ht]=0,this._deflate[mn]=[],this._deflate.on("data",qb)}this._deflate[ls]=r,this._deflate.write(e),this._deflate.flush(Fs.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Th.concat(this._deflate[mn],this._deflate[Ht]);n&&(i=new Lb(i.buffer,i.byteOffset,i.length-4)),this._deflate[ls]=null,this._deflate[Ht]=0,this._deflate[mn]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};Rh.exports=ul;function qb(t){this[mn].push(t),this[Ht]+=t.length}function Eh(t){if(this[Ht]+=t.length,this[ro]._maxPayload<1||this[Ht]<=this[ro]._maxPayload){this[mn].push(t);return}this[cs]=new RangeError("Max payload size exceeded"),this[cs].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[cs][xh]=1009,this.removeListener("data",Eh),this.reset()}function Fb(t){if(this[ro]._inflate=null,this[cs]){this[ls](this[cs]);return}t[xh]=1007,this[ls](t)}});var ds=se((zS,so)=>{"use strict";var{isUtf8:Ih}=require("buffer"),{hasBlob:Bb}=Kt(),Kb=[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 Hb(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function dl(t){let e=t.length,n=0;for(;n<e;)if((t[n]&128)===0)n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function Gb(t){return Bb&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}so.exports={isBlob:Gb,isValidStatusCode:Hb,isValidUTF8:dl,tokenChars:Kb};if(Ih)so.exports.isValidUTF8=function(t){return t.length<24?dl(t):Ih(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");so.exports.isValidUTF8=function(e){return e.length<32?dl(e):t(e)}}catch{}});var gl=se((DS,Oh)=>{"use strict";var{Writable:Zb}=require("stream"),Ah=us(),{BINARY_TYPES:Vb,EMPTY_BUFFER:Ch,kStatusCode:Wb,kWebSocket:Yb}=Kt(),{concat:hl,toArrayBuffer:Jb,unmask:Xb}=qs(),{isValidStatusCode:Qb,isValidUTF8:$h}=ds(),io=Buffer[Symbol.species],st=0,Ph=1,jh=2,Nh=3,pl=4,fl=5,oo=6,ml=class extends Zb{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Vb[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[Yb]=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=st}_write(e,n,r){if(this._opcode===8&&this._state==st)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 io(r.buffer,r.byteOffset+e,r.length-e),new io(r.buffer,r.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let r=this._buffers[0],s=n.length-e;e>=r.length?n.set(this._buffers.shift(),s):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new io(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case st:this.getInfo(e);break;case Ph:this.getPayloadLength16(e);break;case jh:this.getPayloadLength64(e);break;case Nh:this.getMask();break;case pl:this.getData(e);break;case fl:case oo:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[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=(n[0]&64)===64;if(r&&!this._extensions[Ah.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[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=(n[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=Ph:this._payloadLength===127?this._state=jh: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 n=this.consume(8),r=n.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)+n.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 n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=Nh:this._state=pl}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=pl}getData(e){let n=Ch;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Xb(n,this._mask)}if(this._opcode>7){this.controlMessage(n,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=fl,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Ah.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return n(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");n(o);return}this._fragments.push(i)}this.dataMessage(n),this._state===st&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=st;return}let n=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=hl(r,n):this._binaryType==="arraybuffer"?s=Jb(hl(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=st):(this._state=oo,setImmediate(()=>{this.emit("message",s,!0),this._state=st,this.startLoop(e)}))}else{let s=hl(r,n);if(!this._skipUTF8Validation&&!$h(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===fl||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=st):(this._state=oo,setImmediate(()=>{this.emit("message",s,!1),this._state=st,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Ch),this.end();else{let r=e.readUInt16BE(0);if(!Qb(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new io(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!$h(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(i);return}this._loop=!1,this.emit("conclude",r,s),this.end()}this._state=st;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=st):(this._state=oo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=st,this.startLoop(n)}))}createError(e,n,r,s,i){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(o,this.createError),o.code=i,o[Wb]=s,o}};Oh.exports=ml});var vl=se((US,Dh)=>{"use strict";var{Duplex:LS}=require("stream"),{randomFillSync:ev}=require("crypto"),{types:{isUint8Array:tv}}=require("util"),Mh=us(),{EMPTY_BUFFER:nv,kWebSocket:rv,NOOP:sv}=Kt(),{isBlob:hs,isValidStatusCode:iv}=ds(),{mask:zh,toBuffer:Sr}=qs(),it=Symbol("kByteLength"),ov=Buffer.alloc(4),ao=8*1024,Tr,ps=ao,pt=0,av=1,lv=2,yl=class t{constructor(e,n,r){this._extensions=n||{},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=pt,this.onerror=sv,this[rv]=void 0}static frame(e,n){let r,s=!1,i=2,o=!1;n.mask&&(r=n.maskBuffer||ov,n.generateMask?n.generateMask(r):(ps===ao&&(Tr===void 0&&(Tr=Buffer.alloc(ao)),ev(Tr,0,ao),ps=0),r[0]=Tr[ps++],r[1]=Tr[ps++],r[2]=Tr[ps++],r[3]=Tr[ps++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let l;typeof e=="string"?(!n.mask||o)&&n[it]!==void 0?l=n[it]:(e=Buffer.from(e),l=e.length):(l=e.length,s=n.mask&&n.readOnly&&!o);let c=l;l>=65536?(i+=8,c=127):l>125&&(i+=2,c=126);let u=Buffer.allocUnsafe(s?l+i:i);return u[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(u[0]|=64),u[1]=c,c===126?u.writeUInt16BE(l,2):c===127&&(u[2]=u[3]=0,u.writeUIntBE(l,4,6)),n.mask?(u[1]|=128,u[i-4]=r[0],u[i-3]=r[1],u[i-2]=r[2],u[i-1]=r[3],o?[u,e]:s?(zh(e,r,u,i,l),[u]):(zh(e,r,e,0,l),[u,e])):[u,e]}close(e,n,r,s){let i;if(e===void 0)i=nv;else{if(typeof e!="number"||!iv(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let l=Buffer.byteLength(n);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 n=="string")i.write(n,2);else if(tv(n))i.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[it]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==pt?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(t.frame(i,o),s)}ping(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):hs(e)?(s=e.size,i=!1):(e=Sr(e),s=e.length,i=Sr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[it]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};hs(e)?this._state!==pt?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==pt?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}pong(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):hs(e)?(s=e.size,i=!1):(e=Sr(e),s=e.length,i=Sr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[it]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};hs(e)?this._state!==pt?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==pt?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let s=this._extensions[Mh.extensionName],i=n.binary?2:1,o=n.compress,l,c;typeof e=="string"?(l=Buffer.byteLength(e),c=!1):hs(e)?(l=e.size,c=!1):(e=Sr(e),l=e.length,c=Sr.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),n.fin&&(this._firstFragment=!0);let u={[it]:l,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};hs(e)?this._state!==pt?this.enqueue([this.getBlobData,e,this._compress,u,r]):this.getBlobData(e,this._compress,u,r):this._state!==pt?this.enqueue([this.dispatch,e,this._compress,u,r]):this.dispatch(e,this._compress,u,r)}getBlobData(e,n,r,s){this._bufferedBytes+=r[it],this._state=lv,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let l=new Error("The socket was closed while the blob was being read");process.nextTick(bl,this,l,s);return}this._bufferedBytes-=r[it];let o=Sr(i);n?this.dispatch(o,n,r,s):(this._state=pt,this.sendFrame(t.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(cv,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[Mh.extensionName];this._bufferedBytes+=r[it],this._state=av,i.compress(e,r.fin,(o,l)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");bl(this,c,s);return}this._bufferedBytes-=r[it],this._state=pt,r.readOnly=!1,this.sendFrame(t.frame(l,r),s),this.dequeue()})}dequeue(){for(;this._state===pt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][it],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][it],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};Dh.exports=yl;function bl(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let s=t._queue[r],i=s[s.length-1];typeof i=="function"&&i(e)}}function cv(t,e,n){bl(t,e,n),t.onerror(e)}});var Zh=se((qS,Gh)=>{"use strict";var{kForOnEventAttribute:Bs,kListener:wl}=Kt(),Lh=Symbol("kCode"),Uh=Symbol("kData"),qh=Symbol("kError"),Fh=Symbol("kMessage"),Bh=Symbol("kReason"),fs=Symbol("kTarget"),Kh=Symbol("kType"),Hh=Symbol("kWasClean"),Gt=class{constructor(e){this[fs]=null,this[Kh]=e}get target(){return this[fs]}get type(){return this[Kh]}};Object.defineProperty(Gt.prototype,"target",{enumerable:!0});Object.defineProperty(Gt.prototype,"type",{enumerable:!0});var xr=class extends Gt{constructor(e,n={}){super(e),this[Lh]=n.code===void 0?0:n.code,this[Bh]=n.reason===void 0?"":n.reason,this[Hh]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Lh]}get reason(){return this[Bh]}get wasClean(){return this[Hh]}};Object.defineProperty(xr.prototype,"code",{enumerable:!0});Object.defineProperty(xr.prototype,"reason",{enumerable:!0});Object.defineProperty(xr.prototype,"wasClean",{enumerable:!0});var ms=class extends Gt{constructor(e,n={}){super(e),this[qh]=n.error===void 0?null:n.error,this[Fh]=n.message===void 0?"":n.message}get error(){return this[qh]}get message(){return this[Fh]}};Object.defineProperty(ms.prototype,"error",{enumerable:!0});Object.defineProperty(ms.prototype,"message",{enumerable:!0});var Ks=class extends Gt{constructor(e,n={}){super(e),this[Uh]=n.data===void 0?null:n.data}get data(){return this[Uh]}};Object.defineProperty(Ks.prototype,"data",{enumerable:!0});var uv={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[Bs]&&s[wl]===e&&!s[Bs])return;let r;if(t==="message")r=function(i,o){let l=new Ks("message",{data:o?i:i.toString()});l[fs]=this,lo(e,this,l)};else if(t==="close")r=function(i,o){let l=new xr("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});l[fs]=this,lo(e,this,l)};else if(t==="error")r=function(i){let o=new ms("error",{error:i,message:i.message});o[fs]=this,lo(e,this,o)};else if(t==="open")r=function(){let i=new Gt("open");i[fs]=this,lo(e,this,i)};else return;r[Bs]=!!n[Bs],r[wl]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[wl]===e&&!n[Bs]){this.removeListener(t,n);break}}};Gh.exports={CloseEvent:xr,ErrorEvent:ms,Event:Gt,EventTarget:uv,MessageEvent:Ks};function lo(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var co=se((FS,Vh)=>{"use strict";var{tokenChars:Hs}=ds();function xt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function dv(t){let e=Object.create(null),n=Object.create(null),r=!1,s=!1,i=!1,o,l,c=-1,u=-1,p=-1,f=0;for(;f<t.length;f++)if(u=t.charCodeAt(f),o===void 0)if(p===-1&&Hs[u]===1)c===-1&&(c=f);else if(f!==0&&(u===32||u===9))p===-1&&c!==-1&&(p=f);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f);let v=t.slice(c,p);u===44?(xt(e,v,n),n=Object.create(null)):o=v,c=p=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);else if(l===void 0)if(p===-1&&Hs[u]===1)c===-1&&(c=f);else if(u===32||u===9)p===-1&&c!==-1&&(p=f);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f),xt(n,t.slice(c,p),!0),u===44&&(xt(e,o,n),n=Object.create(null),o=void 0),c=p=-1}else if(u===61&&c!==-1&&p===-1)l=t.slice(c,f),c=p=-1;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(s){if(Hs[u]!==1)throw new SyntaxError(`Unexpected character at index ${f}`);c===-1?c=f:r||(r=!0),s=!1}else if(i)if(Hs[u]===1)c===-1&&(c=f);else if(u===34&&c!==-1)i=!1,p=f;else if(u===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(u===34&&t.charCodeAt(f-1)===61)i=!0;else if(p===-1&&Hs[u]===1)c===-1&&(c=f);else if(c!==-1&&(u===32||u===9))p===-1&&(p=f);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f);let v=t.slice(c,p);r&&(v=v.replace(/\\/g,""),r=!1),xt(n,l,v),u===44&&(xt(e,o,n),n=Object.create(null),o=void 0),l=void 0,c=p=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);if(c===-1||i||u===32||u===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=f);let b=t.slice(c,p);return o===void 0?xt(e,b,n):(l===void 0?xt(n,b,!0):r?xt(n,l,b.replace(/\\/g,"")):xt(n,l,b),xt(e,o,n)),e}function hv(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.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(", ")}Vh.exports={format:hv,parse:dv}});var fo=se((HS,op)=>{"use strict";var pv=require("events"),fv=require("https"),mv=require("http"),Jh=require("net"),gv=require("tls"),{randomBytes:yv,createHash:bv}=require("crypto"),{Duplex:BS,Readable:KS}=require("stream"),{URL:kl}=require("url"),gn=us(),vv=gl(),wv=vl(),{isBlob:kv}=ds(),{BINARY_TYPES:Wh,CLOSE_TIMEOUT:_v,EMPTY_BUFFER:uo,GUID:Sv,kForOnEventAttribute:_l,kListener:Tv,kStatusCode:xv,kWebSocket:Se,NOOP:Xh}=Kt(),{EventTarget:{addEventListener:Ev,removeEventListener:Rv}}=Zh(),{format:Iv,parse:Av}=co(),{toBuffer:Cv}=qs(),Qh=Symbol("kAborted"),Sl=[8,13],Zt=["CONNECTING","OPEN","CLOSING","CLOSED"],$v=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,pe=class t extends pv{constructor(e,n,r){super(),this._binaryType=Wh[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=uo,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),ep(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Wh.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,n,r){let s=new vv({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 wv(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[Se]=this,i[Se]=this,e[Se]=this,s.on("conclude",Nv),s.on("drain",Ov),s.on("error",Mv),s.on("message",zv),s.on("ping",Dv),s.on("pong",Lv),i.onerror=Uv,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",rp),e.on("data",po),e.on("end",sp),e.on("error",ip),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[gn.extensionName]&&this._extensions[gn.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){He(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),np(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Tl(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||uo,n,r)}pong(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Tl(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||uo,n,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Tl(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[gn.extensionName]||(s.compress=!1),this._sender.send(e||uo,s,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){He(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(pe,"CONNECTING",{enumerable:!0,value:Zt.indexOf("CONNECTING")});Object.defineProperty(pe.prototype,"CONNECTING",{enumerable:!0,value:Zt.indexOf("CONNECTING")});Object.defineProperty(pe,"OPEN",{enumerable:!0,value:Zt.indexOf("OPEN")});Object.defineProperty(pe.prototype,"OPEN",{enumerable:!0,value:Zt.indexOf("OPEN")});Object.defineProperty(pe,"CLOSING",{enumerable:!0,value:Zt.indexOf("CLOSING")});Object.defineProperty(pe.prototype,"CLOSING",{enumerable:!0,value:Zt.indexOf("CLOSING")});Object.defineProperty(pe,"CLOSED",{enumerable:!0,value:Zt.indexOf("CLOSED")});Object.defineProperty(pe.prototype,"CLOSED",{enumerable:!0,value:Zt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(pe.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(pe.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[_l])return e[Tv];return null},set(e){for(let n of this.listeners(t))if(n[_l]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[_l]:!0})}})});pe.prototype.addEventListener=Ev;pe.prototype.removeEventListener=Rv;op.exports=pe;function ep(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:_v,protocolVersion:Sl[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(t._autoPong=s.autoPong,t._closeTimeout=s.closeTimeout,!Sl.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Sl.join(", ")})`);let i;if(e instanceof kl)i=e;else try{i=new kl(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),t._url=i.href;let o=i.protocol==="wss:",l=i.protocol==="ws+unix:",c;if(i.protocol!=="ws:"&&!o&&!l?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:l&&!i.pathname?c="The URL's pathname is empty":i.hash&&(c="The URL contains a fragment identifier"),c){let x=new SyntaxError(c);if(t._redirects===0)throw x;ho(t,x);return}let u=o?443:80,p=yv(16).toString("base64"),f=o?fv.request:mv.request,b=new Set,v;if(s.createConnection=s.createConnection||(o?jv:Pv),s.defaultPort=s.defaultPort||u,s.port=i.port||u,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(v=new gn({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=Iv({[gn.extensionName]:v.offer()})),n.length){for(let x of n){if(typeof x!="string"||!$v.test(x)||b.has(x))throw new SyntaxError("An invalid or duplicated subprotocol was specified");b.add(x)}s.headers["Sec-WebSocket-Protocol"]=n.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 _;if(s.followRedirects){if(t._redirects===0){t._originalIpc=l,t._originalSecure=o,t._originalHostOrSocketPath=l?s.socketPath:i.host;let x=r&&r.headers;if(r={...r,headers:{}},x)for(let[$,j]of Object.entries(x))r.headers[$.toLowerCase()]=j}else if(t.listenerCount("redirect")===0){let x=l?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!x||t._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._req=f(s),t._redirects&&t.emit("redirect",t.url,_)}else _=t._req=f(s);s.timeout&&_.on("timeout",()=>{He(t,_,"Opening handshake has timed out")}),_.on("error",x=>{_===null||_[Qh]||(_=t._req=null,ho(t,x))}),_.on("response",x=>{let $=x.headers.location,j=x.statusCode;if($&&s.followRedirects&&j>=300&&j<400){if(++t._redirects>s.maxRedirects){He(t,_,"Maximum redirects exceeded");return}_.abort();let S;try{S=new kl($,e)}catch{let O=new SyntaxError(`Invalid URL: ${$}`);ho(t,O);return}ep(t,S,n,r)}else t.emit("unexpected-response",_,x)||He(t,_,`Unexpected server response: ${x.statusCode}`)}),_.on("upgrade",(x,$,j)=>{if(t.emit("upgrade",x),t.readyState!==pe.CONNECTING)return;_=t._req=null;let S=x.headers.upgrade;if(S===void 0||S.toLowerCase()!=="websocket"){He(t,$,"Invalid Upgrade header");return}let G=bv("sha1").update(p+Sv).digest("base64");if(x.headers["sec-websocket-accept"]!==G){He(t,$,"Invalid Sec-WebSocket-Accept header");return}let O=x.headers["sec-websocket-protocol"],M;if(O!==void 0?b.size?b.has(O)||(M="Server sent an invalid subprotocol"):M="Server sent a subprotocol but none was requested":b.size&&(M="Server sent no subprotocol"),M){He(t,$,M);return}O&&(t._protocol=O);let W=x.headers["sec-websocket-extensions"];if(W!==void 0){if(!v){He(t,$,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let d;try{d=Av(W)}catch{He(t,$,"Invalid Sec-WebSocket-Extensions header");return}let m=Object.keys(d);if(m.length!==1||m[0]!==gn.extensionName){He(t,$,"Server indicated an extension that was not requested");return}try{v.accept(d[gn.extensionName])}catch{He(t,$,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[gn.extensionName]=v}t.setSocket($,j,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(_,t):_.end()}function ho(t,e){t._readyState=pe.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Pv(t){return t.path=t.socketPath,Jh.connect(t)}function jv(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Jh.isIP(t.host)?"":t.host),gv.connect(t)}function He(t,e,n){t._readyState=pe.CLOSING;let r=new Error(n);Error.captureStackTrace(r,He),e.setHeader?(e[Qh]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ho,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Tl(t,e,n){if(e){let r=kv(e)?e.size:Cv(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${Zt[t.readyState]})`);process.nextTick(n,r)}}function Nv(t,e){let n=this[Se];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[Se]!==void 0&&(n._socket.removeListener("data",po),process.nextTick(tp,n._socket),t===1005?n.close():n.close(t,e))}function Ov(){let t=this[Se];t.isPaused||t._socket.resume()}function Mv(t){let e=this[Se];e._socket[Se]!==void 0&&(e._socket.removeListener("data",po),process.nextTick(tp,e._socket),e.close(t[xv])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Yh(){this[Se].emitClose()}function zv(t,e){this[Se].emit("message",t,e)}function Dv(t){let e=this[Se];e._autoPong&&e.pong(t,!this._isServer,Xh),e.emit("ping",t)}function Lv(t){this[Se].emit("pong",t)}function tp(t){t.resume()}function Uv(t){let e=this[Se];e.readyState!==pe.CLOSED&&(e.readyState===pe.OPEN&&(e._readyState=pe.CLOSING,np(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function np(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function rp(){let t=this[Se];if(this.removeListener("close",rp),this.removeListener("data",po),this.removeListener("end",sp),t._readyState=pe.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[Se]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Yh),t._receiver.on("finish",Yh))}function po(t){this[Se]._receiver.write(t)||this.pause()}function sp(){let t=this[Se];t._readyState=pe.CLOSING,t._receiver.end(),this.end()}function ip(){let t=this[Se];this.removeListener("error",ip),this.on("error",Xh),t&&(t._readyState=pe.CLOSING,this.destroy())}});var up=se((ZS,cp)=>{"use strict";var GS=fo(),{Duplex:qv}=require("stream");function ap(t){t.emit("close")}function Fv(){!this.destroyed&&this._writableState.finished&&this.destroy()}function lp(t){this.removeListener("error",lp),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Bv(t,e){let n=!0,r=new qv({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,o){let l=!o&&r._readableState.objectMode?i.toString():i;r.push(l)||t.pause()}),t.once("error",function(i){r.destroyed||(n=!1,r.destroy(i))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(s,i){if(t.readyState===t.CLOSED){i(s),process.nextTick(ap,r);return}let o=!1;t.once("error",function(c){o=!0,i(c)}),t.once("close",function(){o||i(s),process.nextTick(ap,r)}),n&&t.terminate()},r._final=function(s){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(s)});return}t._socket!==null&&(t._socket._writableState.finished?(s(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){s()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(s,i,o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(s,i,o)});return}t.send(s,o)},r.on("end",Fv),r.on("error",lp),r}cp.exports=Bv});var xl=se((VS,dp)=>{"use strict";var{tokenChars:Kv}=ds();function Hv(t){let e=new Set,n=-1,r=-1,s=0;for(s;s<t.length;s++){let o=t.charCodeAt(s);if(r===-1&&Kv[o]===1)n===-1&&(n=s);else if(s!==0&&(o===32||o===9))r===-1&&n!==-1&&(r=s);else if(o===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${s}`);r===-1&&(r=s);let l=t.slice(n,r);if(e.has(l))throw new SyntaxError(`The "${l}" subprotocol is duplicated`);e.add(l),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(n,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}dp.exports={parse:Hv}});var bp=se((YS,yp)=>{"use strict";var Gv=require("events"),mo=require("http"),{Duplex:WS}=require("stream"),{createHash:Zv}=require("crypto"),hp=co(),Er=us(),Vv=xl(),Wv=fo(),{CLOSE_TIMEOUT:Yv,GUID:Jv,kWebSocket:Xv}=Kt(),Qv=/^[+/0-9A-Za-z]{22}==$/,pp=0,fp=1,gp=2,El=class extends Gv{constructor(e,n){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:Yv,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Wv,...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=mo.createServer((r,s)=>{let i=mo.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,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=ew(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=pp}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===gp){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Gs,this);return}if(e&&this.once("close",e),this._state!==fp)if(this._state=fp,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(Gs,this):process.nextTick(Gs,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Gs(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,r,s){n.on("error",mp);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,l=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Rr(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Rr(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!Qv.test(i)){Rr(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(l!==13&&l!==8){Rr(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Zs(n,400);return}let c=e.headers["sec-websocket-protocol"],u=new Set;if(c!==void 0)try{u=Vv.parse(c)}catch{Rr(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let p=e.headers["sec-websocket-extensions"],f={};if(this.options.perMessageDeflate&&p!==void 0){let b=new Er({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let v=hp.parse(p);v[Er.extensionName]&&(b.accept(v[Er.extensionName]),f[Er.extensionName]=b)}catch{Rr(this,e,n,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,(v,_,x,$)=>{if(!v)return Zs(n,_||401,x,$);this.completeUpgrade(f,i,u,e,n,r,s)});return}if(!this.options.verifyClient(b))return Zs(n,401)}this.completeUpgrade(f,i,u,e,n,r,s)}completeUpgrade(e,n,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>pp)return Zs(i,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Zv("sha1").update(n+Jv).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(r.size){let f=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;f&&(u.push(`Sec-WebSocket-Protocol: ${f}`),p._protocol=f)}if(e[Er.extensionName]){let f=e[Er.extensionName].params,b=hp.format({[Er.extensionName]:[f]});u.push(`Sec-WebSocket-Extensions: ${b}`),p._extensions=e}this.emit("headers",u,s),i.write(u.concat(`\r
308
+ `).filter(Boolean).filter(s=>!e.has(s))}catch{}for(let r of n)try{let s=await F(t,["show",`HEAD:${r}`]);/^={7}$/m.test(s)||e.add(r)}catch{e.add(r)}return[...e]}async function Os(t,e,n){Se.default.mkdirSync(he.default.dirname(e),{recursive:!0,mode:448}),await F(t,["fetch","origin",n],{timeoutMs:3e5}),await F(t,["worktree","add","--detach",e,`origin/${n}`]),await F(e,["checkout","-B",n,`origin/${n}`])}async function ka(t,e){try{await F(t,["push","origin",e],{timeoutMs:3e5})}catch(n){throw new Error(`could not push "${e}" - ${n instanceof Error?n.message:n}. Someone may have pushed to it since this deploy started; retry.`)}}async function _a(t,e,n){try{return await iu("git",["-C",t,"diff","--quiet",e,n,"--"],{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}..${n}: ${(s.stderr||s.message||"").trim().slice(0,500)}`)}}async function cr(t){return(await F(t,["config","--get","remote.origin.url"])).trim()}function ut(t){let e=/^git@github\.com(?:-[\w.-]+)?:([^/]+)\/(.+?)(\.git)?$/.exec(t)??/^https:\/\/github\.com\/([^/]+)\/(.+?)(\.git)?\/?$/.exec(t)??/^ssh:\/\/git@github\.com(?:-[\w.-]+)?\/([^/]+)\/(.+?)(\.git)?$/.exec(t);return e?{owner:e[1],repo:e[2]}:null}var Se,or,he,ru,su,iu,Pi,Ni,pn,fn,ou,qt,_t=xn(()=>{"use strict";Se=R(require("node:fs"),1),or=R(require("node:os"),1),he=R(require("node:path"),1),ru=require("node:child_process"),su=require("node:util"),iu=(0,su.promisify)(ru.execFile),Pi="Allwright Agent",Ni="agent@ticketpilot.local",pn=200,fn=2e4,ou=[/^\.github\/workflows\//,/^\.git\b/,/(^|\/)\.githooks\//];qt=".ticketpilot-delete"});function Di(t,e,n){let r=(n??"").trim().toLowerCase(),s=r?t.githubUsers[r]?.token:void 0;if(s)return{token:s,source:"user"};let i=t.repos[e]?.github?.token;return i?{token:i,source:"repo"}:t.github?.token?{token:t.github.token,source:"global"}:null}function $e(t,e){return t.repos[e]?.github?.token??t.github?.token??null}function pu(t,e){let n=[t.jira,...Object.values(t.repos).map(l=>l.jira)].filter(l=>!!l),r=new Set(n.map(l=>l.email.toLowerCase())),s=!!t.github?.token||Object.values(t.repos).some(l=>l.github?.token),i=t.github?.login??Object.values(t.repos).find(l=>l.github?.login)?.github?.login??"",o=e.map(l=>{let c=l.trim().toLowerCase(),u=t.jiraUsers[c]?"own":r.has(c)?"runner-account":"missing",p=u==="own"?t.jiraUsers[c].email:u==="runner-account"?c:"",f=t.githubUsers[c]?"own":s?"shared":"missing",b=f==="own"?t.githubUsers[c].login??"":f==="shared"?i:"";return{email:c,jira:u,jiraAs:p,github:f,githubAs:b}});return{githubShared:s,sharedGithubLogin:i,entries:o}}var ur=xn(()=>{"use strict"});var za,y,Kt=xn(()=>{"use strict";za=()=>new Date().toISOString(),y={info:t=>console.log(`${za()} [info] ${t}`),warn:t=>console.warn(`${za()} [warn] ${t}`),error:t=>console.error(`${za()} [error] ${t}`)}});var fr={};xs(fr,{GitHubClient:()=>Pe});var My,Pe,ht=xn(()=>{"use strict";My=process.env.TICKETPILOT_GITHUB_API??"https://api.github.com",Pe=class{constructor(e){this.token=e}token;async request(e,n,r){let s=await fetch(`${My}${n}`,{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} ${n} -> ${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,n,r){let{status:s,data:i}=await this.request("POST",`/repos/${e}/${n}/pulls`,r);if(s===422){let{data:o}=await this.request("GET",`/repos/${e}/${n}/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,n,r){let{data:s}=await this.request("GET",`/repos/${e}/${n}/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,n,r){try{let{data:s}=await this.request("GET",`/repos/${e}/${n}/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,n,r,s,i={}){try{return await this.request("PUT",`/repos/${e}/${n}/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}/${n}. It needs write access to the repository - or merge the PR yourself.`}:{merged:!1,reason:l}}}async repoAccess(e,n){try{let{data:r}=await this.request("GET",`/repos/${e}/${n}`);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,n,r){await this.request("PATCH",`/repos/${e}/${n}/pulls/${r}`,{state:"closed"})}async deleteBranch(e,n,r){try{await this.request("DELETE",`/repos/${e}/${n}/git/refs/heads/${encodeURIComponent(r)}`)}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return;throw s}}}});function Ad(t,e=512e3){try{let n=Gs.default.statSync(t);return!n.isFile()||n.size>e?null:Gs.default.readFileSync(t,"utf8")}catch{return null}}function Cd(t,e=60){try{return Gs.default.readdirSync(t).slice(0,e).map(n=>tl.default.join(t,n)).filter(n=>{try{return Gs.default.statSync(n).isFile()}catch{return!1}})}catch{return[]}}function to(t,e=lb){let n=t.replace(/\/+$/,"");if(!n)return[];let r=[];for(let s of e)for(let i of Cd(s)){if(!i.endsWith(".service"))continue;let o=Ad(i);if(!o||!o.includes(n))continue;let l=/^\s*ExecStart\s*=\s*(.+)$/m.exec(o)?.[1]?.trim()??"",c=/^\s*User\s*=\s*(.+)$/m.exec(o)?.[1]?.trim()??"root (no User= line)";r.push(`${tl.default.basename(i,".service")} (User=${c})`+(l?` runs: ${l}`:""))}return r}function $d(t,e=cb,n=ub){let r=t.map(o=>o.trim().toLowerCase()).filter(Boolean);if(!r.length)return[];let s=[...e,...n.flatMap(o=>Cd(o))],i=[];for(let o of s){let l=Ad(o);if(!l)continue;let c=l.toLowerCase(),u=r.find(f=>c.includes(f));if(!u)continue;let p=l.split(`
309
+ `).filter(f=>/reverse_proxy|proxy_pass|root\s+\*?\s*\//i.test(f)).map(f=>f.trim()).slice(0,8);i.push(`${o} mentions ${u}`+(p.length?` - routing lines: ${p.join(" | ")}`:" - no routing line found"))}return i}function ps(t){let e=l=>{try{return(0,eo.execFileSync)("git",l,{cwd:t,encoding:"utf8",timeout:2e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"true"},stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}},n=e(["ls-remote","--heads","origin"]),r=e(["branch","--format=%(refname:short)"]),s=e(["branch","-r","--format=%(refname:short)"]),i=n?n.split(`
310
+ `).map(l=>l.split(/\s+/)[1]??"").map(l=>l.replace(/^refs\/heads\//,"")).filter(Boolean):null,o=[`
311
+
312
+ BRANCHES - asked of git just now by the runner, which has a shell. Do NOT conclude a branch is missing from what is under .git/refs: that only says what this checkout has fetched, and a branch pushed from somewhere else is invisible there until someone runs git fetch.`];if(o.push(i?`- on origin: ${i.join(", ")||"(none)"}`:"- origin could not be reached (no credentials for this account, or the network refused). Say the branch could not be VERIFIED - do not say it does not exist."),r&&o.push(`- local branches in this checkout: ${r.split(`
313
+ `).join(", ")}`),s&&o.push(`- remote-tracking refs already fetched here: ${s.split(`
314
+ `).join(", ")}`),i&&s){let l=new Set(s.split(`
315
+ `).map(u=>u.replace(/^origin\//,""))),c=i.filter(u=>!l.has(u));c.length&&o.push(`- exists on origin but NOT fetched here yet: ${c.join(", ")}. This is a \`git fetch\`, not a missing branch - never report it as a blocker.`)}return o.join(`
316
+ `)}function db(){let t=o=>{try{return(0,eo.execFileSync)("bash",["-lc",`command -v ${JSON.stringify(o)}`],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}),!0}catch{return!1}},e=o=>{try{return(0,eo.execFileSync)("systemctl",["is-active",o],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim()==="active"}catch{return!1}},n=["caddy","nginx","apache2","haproxy","docker","pm2","systemctl","certbot"],r=n.filter(t),s=n.filter(o=>!r.includes(o)),i=["caddy","nginx","apache2","haproxy"].filter(o=>e(o));return`
317
+
318
+ WHAT THIS MACHINE ALREADY RUNS - build the answer on these, never on a tool that is not here:
319
+ - installed: ${r.join(", ")||"(none of the usual ones)"}
320
+ - NOT installed: ${s.join(", ")||"(none missing)"}
321
+ - reverse proxy currently running: ${i.join(", ")||"(none)"}
322
+ A proxy that is already running is almost certainly serving something else on this box. EXTEND its configuration; never introduce a second one. Two cannot hold port 80, so the best case is that yours refuses to start and the worst is that someone stops the running one to make room and takes an unrelated site down. Same for supervisors: if units already exist here, write one in that style rather than proposing docker or pm2 because they are more familiar.`}function hb(t){try{return new URL(t).hostname}catch{return""}}function nl(t){let e=t.urls.map(hb).filter(Boolean),n=to(t.repoPath),r=$d(e),s=[`
323
+
324
+ ABOUT THE MACHINE THIS RUNS ON - gathered by the runner just now, read-only. Trust these over anything you infer from the repository: the repo is exactly where supervision and proxying are NOT configured, so "the repo has no systemd unit" says nothing about whether a unit exists.`];return s.push(n.length?`- systemd units pointing at this checkout (${t.repoPath}):
325
+ `+n.map(i=>` - ${i}`).join(`
326
+ `)+`
327
+ Use the real unit name in the restart step. Do NOT write a bare foreground start command - it dies with the deploy session.`:`- NO systemd unit on this machine references ${t.repoPath}. If this project is served by something else (pm2, docker, a proxy serving static files), say which in the document; if nothing supervises it, that is a BLOCKER, not a detail.`),s.push(r.length?`- reverse-proxy configuration mentioning this environment's hostname:
328
+ `+r.map(i=>` - ${i}`).join(`
329
+ `)+`
330
+ Public checks must go through the public URL; a check against localhost only proves the app started, not that visitors can reach it.`:e.length?`- NO reverse-proxy file on this machine mentions ${e.join(", ")}. Either the site is served another way, or the public URL does not reach this machine at all - flag it, do not assume it works.`:"- no public URL was declared for these environments, so nothing could be checked against a proxy configuration."),s.join(`
331
+ `)+db()}function Pd(t){let e=[],n=o=>o.workdir.trim()||t.repoPath,r=ps(t.repoPath),s=t.environments.map(o=>({name:o.name,dir:n(o)})),i=s.filter((o,l)=>s.findIndex(c=>c.dir===o.dir)!==l);t.environments.length>1&&e.push({environment:"",question:"Each environment has a working directory of its own",ok:i.length===0,blocking:!0,detail:i.length===0?s.map(o=>`${o.name}: ${o.dir}`).join(" \xB7 "):`${s.map(o=>`${o.name}: ${o.dir}`).join(" \xB7 ")} - a deploy of one replaces the other's checkout and build. Set the Working directory on the environment; creating the directory on the machine is not enough on its own.`});for(let o of t.environments){let l=n(o),c=to(l);if(e.push({environment:o.name,question:`Something supervises the app in ${l}`,ok:c.length>0,blocking:!0,detail:c.length?c.join(" \xB7 "):`no systemd unit on this machine references ${l}`}),o.publicUrl){let u="";try{u=new URL(o.publicUrl).hostname}catch{u=""}let p=u?$d([u]):[];e.push({environment:o.name,question:`A reverse proxy here serves ${u||o.publicUrl}`,ok:p.length>0,blocking:!1,detail:p.length?p.join(" \xB7 "):`no proxy configuration on this machine mentions ${u||o.publicUrl}`})}if(o.branch){let u=new RegExp(`(^|[\\s,])${o.branch}([\\s,]|$)`,"m").test(/- on origin: (.*)/.exec(r)?.[1]??"");e.push({environment:o.name,question:`Branch "${o.branch}" exists on origin`,ok:u,blocking:!0,detail:u?"":`origin has no branch called ${o.branch} (or it could not be reached)`})}}return e}var eo,Gs,tl,lb,cb,ub,no=xn(()=>{"use strict";eo=require("node:child_process"),Gs=R(require("node:fs"),1),tl=R(require("node:path"),1),lb=["/etc/systemd/system","/lib/systemd/system","/usr/lib/systemd/system"],cb=["/etc/caddy/Caddyfile","/usr/local/etc/caddy/Caddyfile","/etc/nginx/nginx.conf"],ub=["/etc/nginx/sites-enabled","/etc/nginx/conf.d","/etc/caddy/conf.d","/etc/caddy/sites-enabled"]});var Vt=se((a0,Ih)=>{"use strict";var Eh=["nodebuffer","arraybuffer","fragments"],Rh=typeof Blob<"u";Rh&&Eh.push("blob");Ih.exports={BINARY_TYPES:Eh,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Rh,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Vs=se((l0,uo)=>{"use strict";var{EMPTY_BUFFER:rv}=Vt(),yl=Buffer[Symbol.species];function sv(t,e){if(t.length===0)return rv;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let s=0;s<t.length;s++){let i=t[s];n.set(i,r),r+=i.length}return r<e?new yl(n.buffer,n.byteOffset,r):n}function Ah(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function Ch(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function iv(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function bl(t){if(bl.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new yl(t):ArrayBuffer.isView(t)?e=new yl(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),bl.readOnly=!1),e}uo.exports={concat:sv,mask:Ah,toArrayBuffer:iv,toBuffer:bl,unmask:Ch};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");uo.exports.mask=function(e,n,r,s,i){i<48?Ah(e,n,r,s,i):t.mask(e,n,r,s,i)},uo.exports.unmask=function(e,n){e.length<32?Ch(e,n):t.unmask(e,n)}}catch{}});var Nh=se((c0,Ph)=>{"use strict";var $h=Symbol("kDone"),vl=Symbol("kRun"),wl=class{constructor(e){this[$h]=()=>{this.pending--,this[vl]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[vl]()}[vl](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[$h])}}};Ph.exports=wl});var gs=se((u0,zh)=>{"use strict";var Ws=require("zlib"),jh=Vs(),ov=Nh(),{kStatusCode:Oh}=Vt(),av=Buffer[Symbol.species],lv=Buffer.from([0,0,255,255]),po=Symbol("permessage-deflate"),Wt=Symbol("total-length"),fs=Symbol("callback"),wn=Symbol("buffers"),ms=Symbol("error"),ho,kl=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,!ho){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;ho=new ov(n)}}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[fs];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(s=>!(n.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>s.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let s=n[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}"`);n[r]=s})}),e}decompress(e,n,r){ho.add(s=>{this._decompress(e,n,(i,o)=>{s(),r(i,o)})})}compress(e,n,r){ho.add(s=>{this._compress(e,n,(i,o)=>{s(),r(i,o)})})}_decompress(e,n,r){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Ws.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Ws.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[po]=this,this._inflate[Wt]=0,this._inflate[wn]=[],this._inflate.on("error",uv),this._inflate.on("data",Mh)}this._inflate[fs]=r,this._inflate.write(e),n&&this._inflate.write(lv),this._inflate.flush(()=>{let i=this._inflate[ms];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=jh.concat(this._inflate[wn],this._inflate[Wt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Wt]=0,this._inflate[wn]=[],n&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,n,r){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Ws.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Ws.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[Wt]=0,this._deflate[wn]=[],this._deflate.on("data",cv)}this._deflate[fs]=r,this._deflate.write(e),this._deflate.flush(Ws.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=jh.concat(this._deflate[wn],this._deflate[Wt]);n&&(i=new av(i.buffer,i.byteOffset,i.length-4)),this._deflate[fs]=null,this._deflate[Wt]=0,this._deflate[wn]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};zh.exports=kl;function cv(t){this[wn].push(t),this[Wt]+=t.length}function Mh(t){if(this[Wt]+=t.length,this[po]._maxPayload<1||this[Wt]<=this[po]._maxPayload){this[wn].push(t);return}this[ms]=new RangeError("Max payload size exceeded"),this[ms].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ms][Oh]=1009,this.removeListener("data",Mh),this.reset()}function uv(t){if(this[po]._inflate=null,this[ms]){this[fs](this[ms]);return}t[Oh]=1007,this[fs](t)}});var ys=se((d0,fo)=>{"use strict";var{isUtf8:Dh}=require("buffer"),{hasBlob:dv}=Vt(),hv=[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 pv(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function _l(t){let e=t.length,n=0;for(;n<e;)if((t[n]&128)===0)n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function fv(t){return dv&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}fo.exports={isBlob:fv,isValidStatusCode:pv,isValidUTF8:_l,tokenChars:hv};if(Dh)fo.exports.isValidUTF8=function(t){return t.length<24?_l(t):Dh(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");fo.exports.isValidUTF8=function(e){return e.length<32?_l(e):t(e)}}catch{}});var Rl=se((h0,Hh)=>{"use strict";var{Writable:mv}=require("stream"),Lh=gs(),{BINARY_TYPES:gv,EMPTY_BUFFER:Uh,kStatusCode:yv,kWebSocket:bv}=Vt(),{concat:Sl,toArrayBuffer:vv,unmask:wv}=Vs(),{isValidStatusCode:kv,isValidUTF8:qh}=ys(),mo=Buffer[Symbol.species],ot=0,Fh=1,Bh=2,Kh=3,Tl=4,xl=5,go=6,El=class extends mv{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||gv[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[bv]=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=ot}_write(e,n,r){if(this._opcode===8&&this._state==ot)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 mo(r.buffer,r.byteOffset+e,r.length-e),new mo(r.buffer,r.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let r=this._buffers[0],s=n.length-e;e>=r.length?n.set(this._buffers.shift(),s):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new mo(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case ot:this.getInfo(e);break;case Fh:this.getPayloadLength16(e);break;case Bh:this.getPayloadLength64(e);break;case Kh:this.getMask();break;case Tl:this.getData(e);break;case xl:case go:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[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=(n[0]&64)===64;if(r&&!this._extensions[Lh.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[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=(n[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=Fh:this._payloadLength===127?this._state=Bh: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 n=this.consume(8),r=n.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)+n.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 n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=Kh:this._state=Tl}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Tl}getData(e){let n=Uh;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&wv(n,this._mask)}if(this._opcode>7){this.controlMessage(n,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=xl,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Lh.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return n(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");n(o);return}this._fragments.push(i)}this.dataMessage(n),this._state===ot&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=ot;return}let n=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=Sl(r,n):this._binaryType==="arraybuffer"?s=vv(Sl(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=ot):(this._state=go,setImmediate(()=>{this.emit("message",s,!0),this._state=ot,this.startLoop(e)}))}else{let s=Sl(r,n);if(!this._skipUTF8Validation&&!qh(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===xl||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=ot):(this._state=go,setImmediate(()=>{this.emit("message",s,!1),this._state=ot,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Uh),this.end();else{let r=e.readUInt16BE(0);if(!kv(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new mo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!qh(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(i);return}this._loop=!1,this.emit("conclude",r,s),this.end()}this._state=ot;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=ot):(this._state=go,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=ot,this.startLoop(n)}))}createError(e,n,r,s,i){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(o,this.createError),o.code=i,o[yv]=s,o}};Hh.exports=El});var Cl=se((f0,Vh)=>{"use strict";var{Duplex:p0}=require("stream"),{randomFillSync:_v}=require("crypto"),{types:{isUint8Array:Sv}}=require("util"),Gh=gs(),{EMPTY_BUFFER:Tv,kWebSocket:xv,NOOP:Ev}=Vt(),{isBlob:bs,isValidStatusCode:Rv}=ys(),{mask:Zh,toBuffer:Ar}=Vs(),at=Symbol("kByteLength"),Iv=Buffer.alloc(4),yo=8*1024,Cr,vs=yo,mt=0,Av=1,Cv=2,Il=class t{constructor(e,n,r){this._extensions=n||{},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=mt,this.onerror=Ev,this[xv]=void 0}static frame(e,n){let r,s=!1,i=2,o=!1;n.mask&&(r=n.maskBuffer||Iv,n.generateMask?n.generateMask(r):(vs===yo&&(Cr===void 0&&(Cr=Buffer.alloc(yo)),_v(Cr,0,yo),vs=0),r[0]=Cr[vs++],r[1]=Cr[vs++],r[2]=Cr[vs++],r[3]=Cr[vs++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let l;typeof e=="string"?(!n.mask||o)&&n[at]!==void 0?l=n[at]:(e=Buffer.from(e),l=e.length):(l=e.length,s=n.mask&&n.readOnly&&!o);let c=l;l>=65536?(i+=8,c=127):l>125&&(i+=2,c=126);let u=Buffer.allocUnsafe(s?l+i:i);return u[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(u[0]|=64),u[1]=c,c===126?u.writeUInt16BE(l,2):c===127&&(u[2]=u[3]=0,u.writeUIntBE(l,4,6)),n.mask?(u[1]|=128,u[i-4]=r[0],u[i-3]=r[1],u[i-2]=r[2],u[i-1]=r[3],o?[u,e]:s?(Zh(e,r,u,i,l),[u]):(Zh(e,r,e,0,l),[u,e])):[u,e]}close(e,n,r,s){let i;if(e===void 0)i=Tv;else{if(typeof e!="number"||!Rv(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let l=Buffer.byteLength(n);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 n=="string")i.write(n,2);else if(Sv(n))i.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[at]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==mt?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(t.frame(i,o),s)}ping(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):bs(e)?(s=e.size,i=!1):(e=Ar(e),s=e.length,i=Ar.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[at]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};bs(e)?this._state!==mt?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==mt?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}pong(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):bs(e)?(s=e.size,i=!1):(e=Ar(e),s=e.length,i=Ar.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[at]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};bs(e)?this._state!==mt?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==mt?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let s=this._extensions[Gh.extensionName],i=n.binary?2:1,o=n.compress,l,c;typeof e=="string"?(l=Buffer.byteLength(e),c=!1):bs(e)?(l=e.size,c=!1):(e=Ar(e),l=e.length,c=Ar.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),n.fin&&(this._firstFragment=!0);let u={[at]:l,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};bs(e)?this._state!==mt?this.enqueue([this.getBlobData,e,this._compress,u,r]):this.getBlobData(e,this._compress,u,r):this._state!==mt?this.enqueue([this.dispatch,e,this._compress,u,r]):this.dispatch(e,this._compress,u,r)}getBlobData(e,n,r,s){this._bufferedBytes+=r[at],this._state=Cv,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let l=new Error("The socket was closed while the blob was being read");process.nextTick(Al,this,l,s);return}this._bufferedBytes-=r[at];let o=Ar(i);n?this.dispatch(o,n,r,s):(this._state=mt,this.sendFrame(t.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick($v,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[Gh.extensionName];this._bufferedBytes+=r[at],this._state=Av,i.compress(e,r.fin,(o,l)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");Al(this,c,s);return}this._bufferedBytes-=r[at],this._state=mt,r.readOnly=!1,this.sendFrame(t.frame(l,r),s),this.dequeue()})}dequeue(){for(;this._state===mt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][at],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][at],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};Vh.exports=Il;function Al(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let s=t._queue[r],i=s[s.length-1];typeof i=="function"&&i(e)}}function $v(t,e,n){Al(t,e,n),t.onerror(e)}});var rp=se((m0,np)=>{"use strict";var{kForOnEventAttribute:Ys,kListener:$l}=Vt(),Wh=Symbol("kCode"),Yh=Symbol("kData"),Jh=Symbol("kError"),Xh=Symbol("kMessage"),Qh=Symbol("kReason"),ws=Symbol("kTarget"),ep=Symbol("kType"),tp=Symbol("kWasClean"),Yt=class{constructor(e){this[ws]=null,this[ep]=e}get target(){return this[ws]}get type(){return this[ep]}};Object.defineProperty(Yt.prototype,"target",{enumerable:!0});Object.defineProperty(Yt.prototype,"type",{enumerable:!0});var $r=class extends Yt{constructor(e,n={}){super(e),this[Wh]=n.code===void 0?0:n.code,this[Qh]=n.reason===void 0?"":n.reason,this[tp]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Wh]}get reason(){return this[Qh]}get wasClean(){return this[tp]}};Object.defineProperty($r.prototype,"code",{enumerable:!0});Object.defineProperty($r.prototype,"reason",{enumerable:!0});Object.defineProperty($r.prototype,"wasClean",{enumerable:!0});var ks=class extends Yt{constructor(e,n={}){super(e),this[Jh]=n.error===void 0?null:n.error,this[Xh]=n.message===void 0?"":n.message}get error(){return this[Jh]}get message(){return this[Xh]}};Object.defineProperty(ks.prototype,"error",{enumerable:!0});Object.defineProperty(ks.prototype,"message",{enumerable:!0});var Js=class extends Yt{constructor(e,n={}){super(e),this[Yh]=n.data===void 0?null:n.data}get data(){return this[Yh]}};Object.defineProperty(Js.prototype,"data",{enumerable:!0});var Pv={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[Ys]&&s[$l]===e&&!s[Ys])return;let r;if(t==="message")r=function(i,o){let l=new Js("message",{data:o?i:i.toString()});l[ws]=this,bo(e,this,l)};else if(t==="close")r=function(i,o){let l=new $r("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});l[ws]=this,bo(e,this,l)};else if(t==="error")r=function(i){let o=new ks("error",{error:i,message:i.message});o[ws]=this,bo(e,this,o)};else if(t==="open")r=function(){let i=new Yt("open");i[ws]=this,bo(e,this,i)};else return;r[Ys]=!!n[Ys],r[$l]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[$l]===e&&!n[Ys]){this.removeListener(t,n);break}}};np.exports={CloseEvent:$r,ErrorEvent:ks,Event:Yt,EventTarget:Pv,MessageEvent:Js};function bo(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var vo=se((g0,sp)=>{"use strict";var{tokenChars:Xs}=ys();function Rt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function Nv(t){let e=Object.create(null),n=Object.create(null),r=!1,s=!1,i=!1,o,l,c=-1,u=-1,p=-1,f=0;for(;f<t.length;f++)if(u=t.charCodeAt(f),o===void 0)if(p===-1&&Xs[u]===1)c===-1&&(c=f);else if(f!==0&&(u===32||u===9))p===-1&&c!==-1&&(p=f);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f);let v=t.slice(c,p);u===44?(Rt(e,v,n),n=Object.create(null)):o=v,c=p=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);else if(l===void 0)if(p===-1&&Xs[u]===1)c===-1&&(c=f);else if(u===32||u===9)p===-1&&c!==-1&&(p=f);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f),Rt(n,t.slice(c,p),!0),u===44&&(Rt(e,o,n),n=Object.create(null),o=void 0),c=p=-1}else if(u===61&&c!==-1&&p===-1)l=t.slice(c,f),c=p=-1;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(s){if(Xs[u]!==1)throw new SyntaxError(`Unexpected character at index ${f}`);c===-1?c=f:r||(r=!0),s=!1}else if(i)if(Xs[u]===1)c===-1&&(c=f);else if(u===34&&c!==-1)i=!1,p=f;else if(u===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(u===34&&t.charCodeAt(f-1)===61)i=!0;else if(p===-1&&Xs[u]===1)c===-1&&(c=f);else if(c!==-1&&(u===32||u===9))p===-1&&(p=f);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f);let v=t.slice(c,p);r&&(v=v.replace(/\\/g,""),r=!1),Rt(n,l,v),u===44&&(Rt(e,o,n),n=Object.create(null),o=void 0),l=void 0,c=p=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);if(c===-1||i||u===32||u===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=f);let b=t.slice(c,p);return o===void 0?Rt(e,b,n):(l===void 0?Rt(n,b,!0):r?Rt(n,l,b.replace(/\\/g,"")):Rt(n,l,b),Rt(e,o,n)),e}function jv(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.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(", ")}sp.exports={format:jv,parse:Nv}});var So=se((v0,gp)=>{"use strict";var Ov=require("events"),Mv=require("https"),zv=require("http"),ap=require("net"),Dv=require("tls"),{randomBytes:Lv,createHash:Uv}=require("crypto"),{Duplex:y0,Readable:b0}=require("stream"),{URL:Pl}=require("url"),kn=gs(),qv=Rl(),Fv=Cl(),{isBlob:Bv}=ys(),{BINARY_TYPES:ip,CLOSE_TIMEOUT:Kv,EMPTY_BUFFER:wo,GUID:Hv,kForOnEventAttribute:Nl,kListener:Gv,kStatusCode:Zv,kWebSocket:Te,NOOP:lp}=Vt(),{EventTarget:{addEventListener:Vv,removeEventListener:Wv}}=rp(),{format:Yv,parse:Jv}=vo(),{toBuffer:Xv}=Vs(),cp=Symbol("kAborted"),jl=[8,13],Jt=["CONNECTING","OPEN","CLOSING","CLOSED"],Qv=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,pe=class t extends Ov{constructor(e,n,r){super(),this._binaryType=ip[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=wo,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),up(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){ip.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,n,r){let s=new qv({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 Fv(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[Te]=this,i[Te]=this,e[Te]=this,s.on("conclude",nw),s.on("drain",rw),s.on("error",sw),s.on("message",iw),s.on("ping",ow),s.on("pong",aw),i.onerror=lw,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",pp),e.on("data",_o),e.on("end",fp),e.on("error",mp),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[kn.extensionName]&&this._extensions[kn.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Ge(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),hp(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Ol(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||wo,n,r)}pong(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Ol(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||wo,n,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Ol(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[kn.extensionName]||(s.compress=!1),this._sender.send(e||wo,s,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Ge(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(pe,"CONNECTING",{enumerable:!0,value:Jt.indexOf("CONNECTING")});Object.defineProperty(pe.prototype,"CONNECTING",{enumerable:!0,value:Jt.indexOf("CONNECTING")});Object.defineProperty(pe,"OPEN",{enumerable:!0,value:Jt.indexOf("OPEN")});Object.defineProperty(pe.prototype,"OPEN",{enumerable:!0,value:Jt.indexOf("OPEN")});Object.defineProperty(pe,"CLOSING",{enumerable:!0,value:Jt.indexOf("CLOSING")});Object.defineProperty(pe.prototype,"CLOSING",{enumerable:!0,value:Jt.indexOf("CLOSING")});Object.defineProperty(pe,"CLOSED",{enumerable:!0,value:Jt.indexOf("CLOSED")});Object.defineProperty(pe.prototype,"CLOSED",{enumerable:!0,value:Jt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(pe.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(pe.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Nl])return e[Gv];return null},set(e){for(let n of this.listeners(t))if(n[Nl]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Nl]:!0})}})});pe.prototype.addEventListener=Vv;pe.prototype.removeEventListener=Wv;gp.exports=pe;function up(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Kv,protocolVersion:jl[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(t._autoPong=s.autoPong,t._closeTimeout=s.closeTimeout,!jl.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${jl.join(", ")})`);let i;if(e instanceof Pl)i=e;else try{i=new Pl(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),t._url=i.href;let o=i.protocol==="wss:",l=i.protocol==="ws+unix:",c;if(i.protocol!=="ws:"&&!o&&!l?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:l&&!i.pathname?c="The URL's pathname is empty":i.hash&&(c="The URL contains a fragment identifier"),c){let x=new SyntaxError(c);if(t._redirects===0)throw x;ko(t,x);return}let u=o?443:80,p=Lv(16).toString("base64"),f=o?Mv.request:zv.request,b=new Set,v;if(s.createConnection=s.createConnection||(o?tw:ew),s.defaultPort=s.defaultPort||u,s.port=i.port||u,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(v=new kn({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=Yv({[kn.extensionName]:v.offer()})),n.length){for(let x of n){if(typeof x!="string"||!Qv.test(x)||b.has(x))throw new SyntaxError("An invalid or duplicated subprotocol was specified");b.add(x)}s.headers["Sec-WebSocket-Protocol"]=n.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 w;if(s.followRedirects){if(t._redirects===0){t._originalIpc=l,t._originalSecure=o,t._originalHostOrSocketPath=l?s.socketPath:i.host;let x=r&&r.headers;if(r={...r,headers:{}},x)for(let[$,N]of Object.entries(x))r.headers[$.toLowerCase()]=N}else if(t.listenerCount("redirect")===0){let x=l?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!x||t._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")),w=t._req=f(s),t._redirects&&t.emit("redirect",t.url,w)}else w=t._req=f(s);s.timeout&&w.on("timeout",()=>{Ge(t,w,"Opening handshake has timed out")}),w.on("error",x=>{w===null||w[cp]||(w=t._req=null,ko(t,x))}),w.on("response",x=>{let $=x.headers.location,N=x.statusCode;if($&&s.followRedirects&&N>=300&&N<400){if(++t._redirects>s.maxRedirects){Ge(t,w,"Maximum redirects exceeded");return}w.abort();let S;try{S=new Pl($,e)}catch{let O=new SyntaxError(`Invalid URL: ${$}`);ko(t,O);return}up(t,S,n,r)}else t.emit("unexpected-response",w,x)||Ge(t,w,`Unexpected server response: ${x.statusCode}`)}),w.on("upgrade",(x,$,N)=>{if(t.emit("upgrade",x),t.readyState!==pe.CONNECTING)return;w=t._req=null;let S=x.headers.upgrade;if(S===void 0||S.toLowerCase()!=="websocket"){Ge(t,$,"Invalid Upgrade header");return}let G=Uv("sha1").update(p+Hv).digest("base64");if(x.headers["sec-websocket-accept"]!==G){Ge(t,$,"Invalid Sec-WebSocket-Accept header");return}let O=x.headers["sec-websocket-protocol"],M;if(O!==void 0?b.size?b.has(O)||(M="Server sent an invalid subprotocol"):M="Server sent a subprotocol but none was requested":b.size&&(M="Server sent no subprotocol"),M){Ge(t,$,M);return}O&&(t._protocol=O);let W=x.headers["sec-websocket-extensions"];if(W!==void 0){if(!v){Ge(t,$,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let d;try{d=Jv(W)}catch{Ge(t,$,"Invalid Sec-WebSocket-Extensions header");return}let m=Object.keys(d);if(m.length!==1||m[0]!==kn.extensionName){Ge(t,$,"Server indicated an extension that was not requested");return}try{v.accept(d[kn.extensionName])}catch{Ge(t,$,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[kn.extensionName]=v}t.setSocket($,N,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(w,t):w.end()}function ko(t,e){t._readyState=pe.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function ew(t){return t.path=t.socketPath,ap.connect(t)}function tw(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=ap.isIP(t.host)?"":t.host),Dv.connect(t)}function Ge(t,e,n){t._readyState=pe.CLOSING;let r=new Error(n);Error.captureStackTrace(r,Ge),e.setHeader?(e[cp]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ko,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Ol(t,e,n){if(e){let r=Bv(e)?e.size:Xv(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${Jt[t.readyState]})`);process.nextTick(n,r)}}function nw(t,e){let n=this[Te];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[Te]!==void 0&&(n._socket.removeListener("data",_o),process.nextTick(dp,n._socket),t===1005?n.close():n.close(t,e))}function rw(){let t=this[Te];t.isPaused||t._socket.resume()}function sw(t){let e=this[Te];e._socket[Te]!==void 0&&(e._socket.removeListener("data",_o),process.nextTick(dp,e._socket),e.close(t[Zv])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function op(){this[Te].emitClose()}function iw(t,e){this[Te].emit("message",t,e)}function ow(t){let e=this[Te];e._autoPong&&e.pong(t,!this._isServer,lp),e.emit("ping",t)}function aw(t){this[Te].emit("pong",t)}function dp(t){t.resume()}function lw(t){let e=this[Te];e.readyState!==pe.CLOSED&&(e.readyState===pe.OPEN&&(e._readyState=pe.CLOSING,hp(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function hp(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function pp(){let t=this[Te];if(this.removeListener("close",pp),this.removeListener("data",_o),this.removeListener("end",fp),t._readyState=pe.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[Te]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",op),t._receiver.on("finish",op))}function _o(t){this[Te]._receiver.write(t)||this.pause()}function fp(){let t=this[Te];t._readyState=pe.CLOSING,t._receiver.end(),this.end()}function mp(){let t=this[Te];this.removeListener("error",mp),this.on("error",lp),t&&(t._readyState=pe.CLOSING,this.destroy())}});var wp=se((k0,vp)=>{"use strict";var w0=So(),{Duplex:cw}=require("stream");function yp(t){t.emit("close")}function uw(){!this.destroyed&&this._writableState.finished&&this.destroy()}function bp(t){this.removeListener("error",bp),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function dw(t,e){let n=!0,r=new cw({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,o){let l=!o&&r._readableState.objectMode?i.toString():i;r.push(l)||t.pause()}),t.once("error",function(i){r.destroyed||(n=!1,r.destroy(i))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(s,i){if(t.readyState===t.CLOSED){i(s),process.nextTick(yp,r);return}let o=!1;t.once("error",function(c){o=!0,i(c)}),t.once("close",function(){o||i(s),process.nextTick(yp,r)}),n&&t.terminate()},r._final=function(s){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(s)});return}t._socket!==null&&(t._socket._writableState.finished?(s(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){s()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(s,i,o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(s,i,o)});return}t.send(s,o)},r.on("end",uw),r.on("error",bp),r}vp.exports=dw});var Ml=se((_0,kp)=>{"use strict";var{tokenChars:hw}=ys();function pw(t){let e=new Set,n=-1,r=-1,s=0;for(s;s<t.length;s++){let o=t.charCodeAt(s);if(r===-1&&hw[o]===1)n===-1&&(n=s);else if(s!==0&&(o===32||o===9))r===-1&&n!==-1&&(r=s);else if(o===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${s}`);r===-1&&(r=s);let l=t.slice(n,r);if(e.has(l))throw new SyntaxError(`The "${l}" subprotocol is duplicated`);e.add(l),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(n,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}kp.exports={parse:pw}});var Ip=se((T0,Rp)=>{"use strict";var fw=require("events"),To=require("http"),{Duplex:S0}=require("stream"),{createHash:mw}=require("crypto"),_p=vo(),Pr=gs(),gw=Ml(),yw=So(),{CLOSE_TIMEOUT:bw,GUID:vw,kWebSocket:ww}=Vt(),kw=/^[+/0-9A-Za-z]{22}==$/,Sp=0,Tp=1,Ep=2,zl=class extends fw{constructor(e,n){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:bw,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:yw,...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=To.createServer((r,s)=>{let i=To.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,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=_w(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=Sp}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===Ep){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Qs,this);return}if(e&&this.once("close",e),this._state!==Tp)if(this._state=Tp,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(Qs,this):process.nextTick(Qs,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Qs(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,r,s){n.on("error",xp);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,l=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Nr(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Nr(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!kw.test(i)){Nr(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(l!==13&&l!==8){Nr(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){ei(n,400);return}let c=e.headers["sec-websocket-protocol"],u=new Set;if(c!==void 0)try{u=gw.parse(c)}catch{Nr(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let p=e.headers["sec-websocket-extensions"],f={};if(this.options.perMessageDeflate&&p!==void 0){let b=new Pr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let v=_p.parse(p);v[Pr.extensionName]&&(b.accept(v[Pr.extensionName]),f[Pr.extensionName]=b)}catch{Nr(this,e,n,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,(v,w,x,$)=>{if(!v)return ei(n,w||401,x,$);this.completeUpgrade(f,i,u,e,n,r,s)});return}if(!this.options.verifyClient(b))return ei(n,401)}this.completeUpgrade(f,i,u,e,n,r,s)}completeUpgrade(e,n,r,s,i,o,l){if(!i.readable||!i.writable)return i.destroy();if(i[ww])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Sp)return ei(i,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${mw("sha1").update(n+vw).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(r.size){let f=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;f&&(u.push(`Sec-WebSocket-Protocol: ${f}`),p._protocol=f)}if(e[Pr.extensionName]){let f=e[Pr.extensionName].params,b=_p.format({[Pr.extensionName]:[f]});u.push(`Sec-WebSocket-Extensions: ${b}`),p._extensions=e}this.emit("headers",u,s),i.write(u.concat(`\r
309
332
  `).join(`\r
310
- `)),i.removeListener("error",mp),p.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(p),p.on("close",()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Gs,this)})),l(p,s)}};yp.exports=El;function ew(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let r of Object.keys(e))t.removeListener(r,e[r])}}function Gs(t){t._state=gp,t.emit("close")}function mp(){this.destroy()}function Zs(t,e,n,r){n=n||mo.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...r},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${mo.STATUS_CODES[e]}\r
333
+ `)),i.removeListener("error",xp),p.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(p),p.on("close",()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Qs,this)})),l(p,s)}};Rp.exports=zl;function _w(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let r of Object.keys(e))t.removeListener(r,e[r])}}function Qs(t){t._state=Ep,t.emit("close")}function xp(){this.destroy()}function ei(t,e,n,r){n=n||To.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...r},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${To.STATUS_CODES[e]}\r
311
334
  `+Object.keys(r).map(s=>`${s}: ${r[s]}`).join(`\r
312
335
  `)+`\r
313
336
  \r
314
- `+n)}function Rr(t,e,n,r,s,i){if(t.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,Rr),t.emit("wsClientError",o,n,e)}else Zs(n,r,s,i)}});var Ap={};ei(Ap,{buildSetupReport:()=>vw,claudeLoggedIn:()=>Ip,repoCurrentBranch:()=>Ep,repoDefaultBranch:()=>Rp});function Ep(t){try{let e=(0,Js.execFileSync)("git",["-C",t,"rev-parse","--abbrev-ref","HEAD"],{encoding:"utf8",timeout:1e4}).trim();return e==="HEAD"?"":e}catch{return""}}function Rp(t){let e=(...s)=>{try{return(0,Js.execFileSync)("git",["-C",t,...s],{encoding:"utf8",timeout:1e4}).trim()}catch{return null}},n=e("symbolic-ref","--short","refs/remotes/origin/HEAD");if(n?.startsWith("origin/"))return n.slice(7);let r=e("rev-parse","--abbrev-ref","HEAD");return r&&r!=="HEAD"?r:""}function Ip(t=Tp.default.homedir()){if(yn.default.existsSync(Ar.default.join(t,".claude",".credentials.json")))return!0;try{return!!JSON.parse(yn.default.readFileSync(Ar.default.join(t,".claude.json"),"utf8")).oauthAccount}catch{return!1}}async function vw(t,e,n){let r=!1,s="";if(Ys&&Date.now()-Ys.at<6e4)r=Ys.installed,s=Ys.version;else{try{let{stdout:l}=await bw(t.claudeBin,["--version"],{timeout:1e4});r=!0,s=l.trim().slice(0,60)}catch{r=!1}Ys={at:Date.now(),installed:r,version:s}}let i=e.map(l=>{let c=t.repos[l];if(!c)return{repoName:l,path:"",mapped:!1,liveMapped:!!n?.repos?.[l],pathExists:!1,isGit:!1,currentBranch:"",claudeMd:!1,deployMd:!1,testMd:!1,githubToken:!1,githubTokenOwn:!1,defaultBranch:""};let u=yn.default.existsSync(c.path);return{repoName:l,path:c.path,mapped:!0,liveMapped:n?!!n.repos?.[l]:!0,pathExists:u,isGit:u&&yn.default.existsSync(Ar.default.join(c.path,".git")),currentBranch:u?Ep(c.path):"",claudeMd:u&&yn.default.existsSync(Ar.default.join(c.path,"CLAUDE.md")),deployMd:u&&yn.default.existsSync(Ar.default.join(c.path,"DEPLOY.md")),testMd:u&&yn.default.existsSync(Ar.default.join(c.path,"TEST.md")),githubToken:!!Ce(t,l),githubTokenOwn:!!c.github?.token,defaultBranch:u?Rp(c.path):""}}),o=Object.values(t.repos).find(l=>l.github?.token);return{jiraConfigured:!!t.jira,jiraEmail:t.jira?.email??"",claude:{installed:r,version:s,loggedIn:Ip()},githubTokenSet:!!(t.github?.token||o),githubLogin:t.github?.login??o?.github?.login??"",deploysEnabled:t.deploy.enabled,jiraUserCount:Object.keys(t.jiraUsers).length,repos:i}}var Js,yn,Tp,Ar,xp,bw,Ys,Cp=Qs(()=>{"use strict";Js=require("node:child_process"),yn=R(require("node:fs"),1),Tp=R(require("node:os"),1),Ar=R(require("node:path"),1),xp=require("node:util");sr();bw=(0,xp.promisify)(Js.execFile);Ys=null});var Ge=R(require("node:fs"),1),wo=R(require("node:os"),1),bn=R(require("node:path"),1),Wt=require("node:child_process"),Xs=require("node:crypto"),vn=R(require("node:readline/promises"),1);var Wl=R(Vl(),1),{program:Aw,createCommand:Cw,createArgument:$w,createOption:Pw,CommanderError:jw,InvalidArgumentError:Nw,InvalidOptionArgumentError:Ow,Command:Yl,Argument:Mw,Option:zw,Help:Dw}=Wl.default;var Pt=R(require("node:fs"),1),li=R(require("node:os"),1),ci=R(require("node:path"),1);var w={};ei(w,{BRAND:()=>Ef,DIRTY:()=>wn,EMPTY_PATH:()=>rf,INVALID:()=>K,NEVER:()=>um,OK:()=>Ie,ParseStatus:()=>xe,Schema:()=>te,ZodAny:()=>Xt,ZodArray:()=>$t,ZodBigInt:()=>_n,ZodBoolean:()=>Sn,ZodBranded:()=>ks,ZodCatch:()=>Nn,ZodDate:()=>Tn,ZodDefault:()=>jn,ZodDiscriminatedUnion:()=>ii,ZodEffects:()=>Xe,ZodEnum:()=>$n,ZodError:()=>Me,ZodFirstPartyTypeKind:()=>H,ZodFunction:()=>ai,ZodIntersection:()=>In,ZodIssueCode:()=>I,ZodLazy:()=>An,ZodLiteral:()=>Cn,ZodMap:()=>Mr,ZodNaN:()=>Dr,ZodNativeEnum:()=>Pn,ZodNever:()=>ot,ZodNull:()=>En,ZodNullable:()=>gt,ZodNumber:()=>kn,ZodObject:()=>ze,ZodOptional:()=>Ye,ZodParsedType:()=>z,ZodPipeline:()=>_s,ZodPromise:()=>Qt,ZodReadonly:()=>On,ZodRecord:()=>oi,ZodSchema:()=>te,ZodSet:()=>zr,ZodString:()=>Jt,ZodSymbol:()=>Nr,ZodTransformer:()=>Xe,ZodTuple:()=>mt,ZodType:()=>te,ZodUndefined:()=>xn,ZodUnion:()=>Rn,ZodUnknown:()=>Ct,ZodVoid:()=>Or,addIssueToContext:()=>N,any:()=>Of,array:()=>Lf,bigint:()=>Cf,boolean:()=>ac,coerce:()=>cm,custom:()=>sc,date:()=>$f,datetimeRegex:()=>nc,defaultErrorMap:()=>It,discriminatedUnion:()=>Bf,effect:()=>tm,enum:()=>Xf,function:()=>Wf,getErrorMap:()=>$r,getParsedType:()=>ft,instanceof:()=>If,intersection:()=>Kf,isAborted:()=>ri,isAsync:()=>Pr,isDirty:()=>si,isValid:()=>Yt,late:()=>Rf,lazy:()=>Yf,literal:()=>Jf,makeIssue:()=>ws,map:()=>Zf,nan:()=>Af,nativeEnum:()=>Qf,never:()=>zf,null:()=>Nf,nullable:()=>rm,number:()=>oc,object:()=>Uf,objectUtil:()=>Do,oboolean:()=>lm,onumber:()=>am,optional:()=>nm,ostring:()=>om,pipeline:()=>im,preprocess:()=>sm,promise:()=>em,quotelessJson:()=>ef,record:()=>Gf,set:()=>Vf,setErrorMap:()=>nf,strictObject:()=>qf,string:()=>ic,symbol:()=>Pf,transformer:()=>tm,tuple:()=>Hf,undefined:()=>jf,union:()=>Ff,unknown:()=>Mf,util:()=>ne,void:()=>Df});var ne;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function n(s){throw new Error}t.assertNever=n,t.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},t.getValidEnumValues=s=>{let i=t.objectKeys(s).filter(l=>typeof s[s[l]]!="number"),o={};for(let l of i)o[l]=s[l];return t.objectValues(o)},t.objectValues=s=>t.objectKeys(s).map(function(i){return s[i]}),t.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},t.find=(s,i)=>{for(let o of s)if(i(o))return o},t.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)}t.joinValues=r,t.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(ne||(ne={}));var Do;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Do||(Do={}));var z=ne.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ft=t=>{switch(typeof t){case"undefined":return z.undefined;case"string":return z.string;case"number":return Number.isNaN(t)?z.nan:z.number;case"boolean":return z.boolean;case"function":return z.function;case"bigint":return z.bigint;case"symbol":return z.symbol;case"object":return Array.isArray(t)?z.array:t===null?z.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?z.promise:typeof Map<"u"&&t instanceof Map?z.map:typeof Set<"u"&&t instanceof Set?z.set:typeof Date<"u"&&t instanceof Date?z.date:z.object;default:return z.unknown}};var I=ne.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"]),ef=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Me=class t 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 n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=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(n(o));else{let l=r,c=0;for(;c<o.path.length;){let u=o.path[c];c===o.path.length-1?(l[u]=l[u]||{_errors:[]},l[u]._errors.push(n(o))):l[u]=l[u]||{_errors:[]},l=l[u],c++}}};return s(this),r}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ne.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];n[i]=n[i]||[],n[i].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};Me.create=t=>new Me(t);var tf=(t,e)=>{let n;switch(t.code){case I.invalid_type:t.received===z.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case I.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,ne.jsonStringifyReplacer)}`;break;case I.unrecognized_keys:n=`Unrecognized key(s) in object: ${ne.joinValues(t.keys,", ")}`;break;case I.invalid_union:n="Invalid input";break;case I.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ne.joinValues(t.options)}`;break;case I.invalid_enum_value:n=`Invalid enum value. Expected ${ne.joinValues(t.options)}, received '${t.received}'`;break;case I.invalid_arguments:n="Invalid function arguments";break;case I.invalid_return_type:n="Invalid function return type";break;case I.invalid_date:n="Invalid date";break;case I.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:ne.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case I.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case I.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case I.custom:n="Invalid input";break;case I.invalid_intersection_types:n="Intersection results could not be merged";break;case I.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case I.not_finite:n="Number must be finite";break;default:n=e.defaultError,ne.assertNever(t)}return{message:n}},It=tf;var Jl=It;function nf(t){Jl=t}function $r(){return Jl}var ws=t=>{let{data:e,path:n,errorMaps:r,issueData:s}=t,i=[...n,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let l="",c=r.filter(u=>!!u).slice().reverse();for(let u of c)l=u(o,{data:e,defaultError:l}).message;return{...s,path:i,message:l}},rf=[];function N(t,e){let n=$r(),r=ws({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===It?void 0:It].filter(s=>!!s)});t.common.issues.push(r)}var xe=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let s of n){if(s.status==="aborted")return K;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let s of n){let i=await s.key,o=await s.value;r.push({key:i,value:o})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let s of n){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return K;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}}},K=Object.freeze({status:"aborted"}),wn=t=>({status:"dirty",value:t}),Ie=t=>({status:"valid",value:t}),ri=t=>t.status==="aborted",si=t=>t.status==="dirty",Yt=t=>t.status==="valid",Pr=t=>typeof Promise<"u"&&t instanceof Promise;var U;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(U||(U={}));var Je=class{constructor(e,n,r,s){this._cachedPath=[],this.parent=e,this.data=n,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}},Xl=(t,e)=>{if(Yt(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new Me(t.common.issues);return this._error=n,this._error}}};function J(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:s}=t;if(e&&(n||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:c}=t;return o.code==="invalid_enum_value"?{message:c??l.defaultError}:typeof l.data>"u"?{message:c??r??l.defaultError}:o.code!=="invalid_type"?{message:l.defaultError}:{message:c??n??l.defaultError}},description:s}}var te=class{get description(){return this._def.description}_getType(e){return ft(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:ft(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new xe,ctx:{common:e.parent.common,data:e.data,parsedType:ft(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(Pr(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ft(e)},s=this._parseSync({data:e,path:r.path,parent:r});return Xl(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ft(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return Yt(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>Yt(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ft(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(Pr(s)?s:Promise.resolve(s));return Xl(r,i)}refine(e,n){let r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;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(c=>c?!0:(l(),!1)):o?!0:(l(),!1)})}refinement(e,n){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(e){return new Xe({schema:this,typeName:H.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:n=>this["~validate"](n)}}optional(){return Ye.create(this,this._def)}nullable(){return gt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return $t.create(this)}promise(){return Qt.create(this,this._def)}or(e){return Rn.create([this,e],this._def)}and(e){return In.create(this,e,this._def)}transform(e){return new Xe({...J(this._def),schema:this,typeName:H.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new jn({...J(this._def),innerType:this,defaultValue:n,typeName:H.ZodDefault})}brand(){return new ks({typeName:H.ZodBranded,type:this,...J(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Nn({...J(this._def),innerType:this,catchValue:n,typeName:H.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return _s.create(this,e)}readonly(){return On.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},sf=/^c[^\s-]{8,}$/i,of=/^[0-9a-z]+$/,af=/^[0-9A-HJKMNP-TV-Z]{26}$/i,lf=/^[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,cf=/^[a-z0-9_-]{21}$/i,uf=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,df=/^[-+]?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)?)??$/,hf=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,pf="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Lo,ff=/^(?:(?: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])$/,mf=/^(?:(?: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])$/,gf=/^(([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]))$/,yf=/^(([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])$/,bf=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,vf=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ec="((\\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])))",wf=new RegExp(`^${ec}$`);function tc(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function kf(t){return new RegExp(`^${tc(t)}$`)}function nc(t){let e=`${ec}T${tc(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function _f(t,e){return!!((e==="v4"||!e)&&ff.test(t)||(e==="v6"||!e)&&gf.test(t))}function Sf(t,e){if(!uf.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.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 Tf(t,e){return!!((e==="v4"||!e)&&mf.test(t)||(e==="v6"||!e)&&yf.test(t))}var Jt=class t extends te{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==z.string){let i=this._getOrReturnCtx(e);return N(i,{code:I.invalid_type,expected:z.string,received:i.parsedType}),K}let r=new xe,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),N(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),N(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?N(s,{code:I.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):l&&N(s,{code:I.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")hf.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"email",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Lo||(Lo=new RegExp(pf,"u")),Lo.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"emoji",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")lf.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"uuid",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")cf.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"nanoid",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")sf.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"cuid",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")of.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"cuid2",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")af.test(e.data)||(s=this._getOrReturnCtx(e,s),N(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),N(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),N(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),N(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),N(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),N(s,{code:I.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?nc(i).test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{code:I.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?wf.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{code:I.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?kf(i).test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{code:I.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?df.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"duration",code:I.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?_f(e.data,i.version)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"ip",code:I.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?Sf(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"jwt",code:I.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?Tf(e.data,i.version)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"cidr",code:I.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?bf.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"base64",code:I.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?vf.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"base64url",code:I.invalid_string,message:i.message}),r.dirty()):ne.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:I.invalid_string,...U.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...U.errToObj(e)})}url(e){return this._addCheck({kind:"url",...U.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...U.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...U.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...U.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...U.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...U.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...U.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...U.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...U.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...U.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...U.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...U.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.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.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...U.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...U.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...U.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...U.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...U.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...U.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...U.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...U.errToObj(n)})}nonempty(e){return this.min(1,U.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...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 n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};Jt.create=t=>new Jt({checks:[],typeName:H.ZodString,coerce:t?.coerce??!1,...J(t)});function xf(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,i=Number.parseInt(t.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var kn=class t extends te{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)!==z.number){let i=this._getOrReturnCtx(e);return N(i,{code:I.invalid_type,expected:z.number,received:i.parsedType}),K}let r,s=new xe;for(let i of this._def.checks)i.kind==="int"?ne.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),N(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),N(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),N(r,{code:I.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?xf(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),N(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),N(r,{code:I.not_finite,message:i.message}),s.dirty()):ne.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,U.toString(n))}gt(e,n){return this.setLimit("min",e,!1,U.toString(n))}lte(e,n){return this.setLimit("max",e,!0,U.toString(n))}lt(e,n){return this.setLimit("max",e,!1,U.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:U.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:U.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:U.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:U.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:U.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:U.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:U.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:U.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:U.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:U.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ne.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};kn.create=t=>new kn({checks:[],typeName:H.ZodNumber,coerce:t?.coerce||!1,...J(t)});var _n=class t extends te{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)!==z.bigint)return this._getInvalidInput(e);let r,s=new xe;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),N(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),N(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),N(r,{code:I.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):ne.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return N(n,{code:I.invalid_type,expected:z.bigint,received:n.parsedType}),K}gte(e,n){return this.setLimit("min",e,!0,U.toString(n))}gt(e,n){return this.setLimit("min",e,!1,U.toString(n))}lte(e,n){return this.setLimit("max",e,!0,U.toString(n))}lt(e,n){return this.setLimit("max",e,!1,U.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:U.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:U.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:U.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:U.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:U.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:U.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};_n.create=t=>new _n({checks:[],typeName:H.ZodBigInt,coerce:t?.coerce??!1,...J(t)});var Sn=class extends te{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==z.boolean){let r=this._getOrReturnCtx(e);return N(r,{code:I.invalid_type,expected:z.boolean,received:r.parsedType}),K}return Ie(e.data)}};Sn.create=t=>new Sn({typeName:H.ZodBoolean,coerce:t?.coerce||!1,...J(t)});var Tn=class t extends te{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==z.date){let i=this._getOrReturnCtx(e);return N(i,{code:I.invalid_type,expected:z.date,received:i.parsedType}),K}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return N(i,{code:I.invalid_date}),K}let r=new xe,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),N(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),N(s,{code:I.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):ne.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:U.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:U.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};Tn.create=t=>new Tn({checks:[],coerce:t?.coerce||!1,typeName:H.ZodDate,...J(t)});var Nr=class extends te{_parse(e){if(this._getType(e)!==z.symbol){let r=this._getOrReturnCtx(e);return N(r,{code:I.invalid_type,expected:z.symbol,received:r.parsedType}),K}return Ie(e.data)}};Nr.create=t=>new Nr({typeName:H.ZodSymbol,...J(t)});var xn=class extends te{_parse(e){if(this._getType(e)!==z.undefined){let r=this._getOrReturnCtx(e);return N(r,{code:I.invalid_type,expected:z.undefined,received:r.parsedType}),K}return Ie(e.data)}};xn.create=t=>new xn({typeName:H.ZodUndefined,...J(t)});var En=class extends te{_parse(e){if(this._getType(e)!==z.null){let r=this._getOrReturnCtx(e);return N(r,{code:I.invalid_type,expected:z.null,received:r.parsedType}),K}return Ie(e.data)}};En.create=t=>new En({typeName:H.ZodNull,...J(t)});var Xt=class extends te{constructor(){super(...arguments),this._any=!0}_parse(e){return Ie(e.data)}};Xt.create=t=>new Xt({typeName:H.ZodAny,...J(t)});var Ct=class extends te{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ie(e.data)}};Ct.create=t=>new Ct({typeName:H.ZodUnknown,...J(t)});var ot=class extends te{_parse(e){let n=this._getOrReturnCtx(e);return N(n,{code:I.invalid_type,expected:z.never,received:n.parsedType}),K}};ot.create=t=>new ot({typeName:H.ZodNever,...J(t)});var Or=class extends te{_parse(e){if(this._getType(e)!==z.undefined){let r=this._getOrReturnCtx(e);return N(r,{code:I.invalid_type,expected:z.void,received:r.parsedType}),K}return Ie(e.data)}};Or.create=t=>new Or({typeName:H.ZodVoid,...J(t)});var $t=class t extends te{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==z.array)return N(n,{code:I.invalid_type,expected:z.array,received:n.parsedType}),K;if(s.exactLength!==null){let o=n.data.length>s.exactLength.value,l=n.data.length<s.exactLength.value;(o||l)&&(N(n,{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&&n.data.length<s.minLength.value&&(N(n,{code:I.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(N(n,{code:I.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((o,l)=>s.type._parseAsync(new Je(n,o,n.path,l)))).then(o=>xe.mergeArray(r,o));let i=[...n.data].map((o,l)=>s.type._parseSync(new Je(n,o,n.path,l)));return xe.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:U.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:U.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:U.toString(n)}})}nonempty(e){return this.min(1,e)}};$t.create=(t,e)=>new $t({type:t,minLength:null,maxLength:null,exactLength:null,typeName:H.ZodArray,...J(e)});function jr(t){if(t instanceof ze){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=Ye.create(jr(r))}return new ze({...t._def,shape:()=>e})}else return t instanceof $t?new $t({...t._def,type:jr(t.element)}):t instanceof Ye?Ye.create(jr(t.unwrap())):t instanceof gt?gt.create(jr(t.unwrap())):t instanceof mt?mt.create(t.items.map(e=>jr(e))):t}var ze=class t extends te{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(),n=ne.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==z.object){let u=this._getOrReturnCtx(e);return N(u,{code:I.invalid_type,expected:z.object,received:u.parsedType}),K}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),l=[];if(!(this._def.catchall instanceof ot&&this._def.unknownKeys==="strip"))for(let u in s.data)o.includes(u)||l.push(u);let c=[];for(let u of o){let p=i[u],f=s.data[u];c.push({key:{status:"valid",value:u},value:p._parse(new Je(s,f,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof ot){let u=this._def.unknownKeys;if(u==="passthrough")for(let p of l)c.push({key:{status:"valid",value:p},value:{status:"valid",value:s.data[p]}});else if(u==="strict")l.length>0&&(N(s,{code:I.unrecognized_keys,keys:l}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let p of l){let f=s.data[p];c.push({key:{status:"valid",value:p},value:u._parse(new Je(s,f,s.path,p)),alwaysSet:p in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let u=[];for(let p of c){let f=await p.key,b=await p.value;u.push({key:f,value:b,alwaysSet:p.alwaysSet})}return u}).then(u=>xe.mergeObjectSync(r,u)):xe.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return U.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:U.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:H.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of ne.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of ne.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return jr(this)}partial(e){let n={};for(let r of ne.objectKeys(this.shape)){let s=this.shape[r];e&&!e[r]?n[r]=s:n[r]=s.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of ne.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Ye;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return rc(ne.objectKeys(this.shape))}};ze.create=(t,e)=>new ze({shape:()=>t,unknownKeys:"strip",catchall:ot.create(),typeName:H.ZodObject,...J(e)});ze.strictCreate=(t,e)=>new ze({shape:()=>t,unknownKeys:"strict",catchall:ot.create(),typeName:H.ZodObject,...J(e)});ze.lazycreate=(t,e)=>new ze({shape:t,unknownKeys:"strip",catchall:ot.create(),typeName:H.ZodObject,...J(e)});var Rn=class extends te{_parse(e){let{ctx:n}=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 n.common.issues.push(...l.ctx.common.issues),l.result;let o=i.map(l=>new Me(l.ctx.common.issues));return N(n,{code:I.invalid_union,unionErrors:o}),K}if(n.common.async)return Promise.all(r.map(async i=>{let o={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let c of r){let u={...n,common:{...n.common,issues:[]},parent:null},p=c._parseSync({data:n.data,path:n.path,parent:u});if(p.status==="valid")return p;p.status==="dirty"&&!i&&(i={result:p,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let l=o.map(c=>new Me(c));return N(n,{code:I.invalid_union,unionErrors:l}),K}}get options(){return this._def.options}};Rn.create=(t,e)=>new Rn({options:t,typeName:H.ZodUnion,...J(e)});var At=t=>t instanceof An?At(t.schema):t instanceof Xe?At(t.innerType()):t instanceof Cn?[t.value]:t instanceof $n?t.options:t instanceof Pn?ne.objectValues(t.enum):t instanceof jn?At(t._def.innerType):t instanceof xn?[void 0]:t instanceof En?[null]:t instanceof Ye?[void 0,...At(t.unwrap())]:t instanceof gt?[null,...At(t.unwrap())]:t instanceof ks||t instanceof On?At(t.unwrap()):t instanceof Nn?At(t._def.innerType):[],ii=class t extends te{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==z.object)return N(n,{code:I.invalid_type,expected:z.object,received:n.parsedType}),K;let r=this.discriminator,s=n.data[r],i=this.optionsMap.get(s);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(N(n,{code:I.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),K)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let s=new Map;for(let i of n){let o=At(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 t({typeName:H.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...J(r)})}};function Uo(t,e){let n=ft(t),r=ft(e);if(t===e)return{valid:!0,data:t};if(n===z.object&&r===z.object){let s=ne.objectKeys(e),i=ne.objectKeys(t).filter(l=>s.indexOf(l)!==-1),o={...t,...e};for(let l of i){let c=Uo(t[l],e[l]);if(!c.valid)return{valid:!1};o[l]=c.data}return{valid:!0,data:o}}else if(n===z.array&&r===z.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<t.length;i++){let o=t[i],l=e[i],c=Uo(o,l);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===z.date&&r===z.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var In=class extends te{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=(i,o)=>{if(ri(i)||ri(o))return K;let l=Uo(i.value,o.value);return l.valid?((si(i)||si(o))&&n.dirty(),{status:n.value,value:l.data}):(N(r,{code:I.invalid_intersection_types}),K)};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}))}};In.create=(t,e,n)=>new In({left:t,right:e,typeName:H.ZodIntersection,...J(n)});var mt=class t extends te{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==z.array)return N(r,{code:I.invalid_type,expected:z.array,received:r.parsedType}),K;if(r.data.length<this._def.items.length)return N(r,{code:I.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),K;!this._def.rest&&r.data.length>this._def.items.length&&(N(r,{code:I.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let i=[...r.data].map((o,l)=>{let c=this._def.items[l]||this._def.rest;return c?c._parse(new Je(r,o,r.path,l)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>xe.mergeArray(n,o)):xe.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};mt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new mt({items:t,typeName:H.ZodTuple,rest:null,...J(e)})};var oi=class t extends te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==z.object)return N(r,{code:I.invalid_type,expected:z.object,received:r.parsedType}),K;let s=[],i=this._def.keyType,o=this._def.valueType;for(let l in r.data)s.push({key:i._parse(new Je(r,l,r.path,l)),value:o._parse(new Je(r,r.data[l],r.path,l)),alwaysSet:l in r.data});return r.common.async?xe.mergeObjectAsync(n,s):xe.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof te?new t({keyType:e,valueType:n,typeName:H.ZodRecord,...J(r)}):new t({keyType:Jt.create(),valueType:e,typeName:H.ZodRecord,...J(n)})}},Mr=class extends te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==z.map)return N(r,{code:I.invalid_type,expected:z.map,received:r.parsedType}),K;let s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([l,c],u)=>({key:s._parse(new Je(r,l,r.path,[u,"key"])),value:i._parse(new Je(r,c,r.path,[u,"value"]))}));if(r.common.async){let l=new Map;return Promise.resolve().then(async()=>{for(let c of o){let u=await c.key,p=await c.value;if(u.status==="aborted"||p.status==="aborted")return K;(u.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(u.value,p.value)}return{status:n.value,value:l}})}else{let l=new Map;for(let c of o){let u=c.key,p=c.value;if(u.status==="aborted"||p.status==="aborted")return K;(u.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(u.value,p.value)}return{status:n.value,value:l}}}};Mr.create=(t,e,n)=>new Mr({valueType:e,keyType:t,typeName:H.ZodMap,...J(n)});var zr=class t extends te{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==z.set)return N(r,{code:I.invalid_type,expected:z.set,received:r.parsedType}),K;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(N(r,{code:I.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(N(r,{code:I.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let i=this._def.valueType;function o(c){let u=new Set;for(let p of c){if(p.status==="aborted")return K;p.status==="dirty"&&n.dirty(),u.add(p.value)}return{status:n.value,value:u}}let l=[...r.data.values()].map((c,u)=>i._parse(new Je(r,c,r.path,u)));return r.common.async?Promise.all(l).then(c=>o(c)):o(l)}min(e,n){return new t({...this._def,minSize:{value:e,message:U.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:U.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};zr.create=(t,e)=>new zr({valueType:t,minSize:null,maxSize:null,typeName:H.ZodSet,...J(e)});var ai=class t extends te{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==z.function)return N(n,{code:I.invalid_type,expected:z.function,received:n.parsedType}),K;function r(l,c){return ws({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,$r(),It].filter(u=>!!u),issueData:{code:I.invalid_arguments,argumentsError:c}})}function s(l,c){return ws({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,$r(),It].filter(u=>!!u),issueData:{code:I.invalid_return_type,returnTypeError:c}})}let i={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof Qt){let l=this;return Ie(async function(...c){let u=new Me([]),p=await l._def.args.parseAsync(c,i).catch(v=>{throw u.addIssue(r(c,v)),u}),f=await Reflect.apply(o,this,p);return await l._def.returns._def.type.parseAsync(f,i).catch(v=>{throw u.addIssue(s(f,v)),u})})}else{let l=this;return Ie(function(...c){let u=l._def.args.safeParse(c,i);if(!u.success)throw new Me([r(c,u.error)]);let p=Reflect.apply(o,this,u.data),f=l._def.returns.safeParse(p,i);if(!f.success)throw new Me([s(p,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:mt.create(e).rest(Ct.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new t({args:e||mt.create([]).rest(Ct.create()),returns:n||Ct.create(),typeName:H.ZodFunction,...J(r)})}},An=class extends te{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};An.create=(t,e)=>new An({getter:t,typeName:H.ZodLazy,...J(e)});var Cn=class extends te{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return N(n,{received:n.data,code:I.invalid_literal,expected:this._def.value}),K}return{status:"valid",value:e.data}}get value(){return this._def.value}};Cn.create=(t,e)=>new Cn({value:t,typeName:H.ZodLiteral,...J(e)});function rc(t,e){return new $n({values:t,typeName:H.ZodEnum,...J(e)})}var $n=class t extends te{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return N(n,{expected:ne.joinValues(r),received:n.parsedType,code:I.invalid_type}),K}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return N(n,{received:n.data,code:I.invalid_enum_value,options:r}),K}return Ie(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};$n.create=rc;var Pn=class extends te{_parse(e){let n=ne.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==z.string&&r.parsedType!==z.number){let s=ne.objectValues(n);return N(r,{expected:ne.joinValues(s),received:r.parsedType,code:I.invalid_type}),K}if(this._cache||(this._cache=new Set(ne.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=ne.objectValues(n);return N(r,{received:r.data,code:I.invalid_enum_value,options:s}),K}return Ie(e.data)}get enum(){return this._def.values}};Pn.create=(t,e)=>new Pn({values:t,typeName:H.ZodNativeEnum,...J(e)});var Qt=class extends te{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==z.promise&&n.common.async===!1)return N(n,{code:I.invalid_type,expected:z.promise,received:n.parsedType}),K;let r=n.parsedType===z.promise?n.data:Promise.resolve(n.data);return Ie(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Qt.create=(t,e)=>new Qt({type:t,typeName:H.ZodPromise,...J(e)});var Xe=class extends te{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===H.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{N(r,o),o.fatal?n.abort():n.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(n.value==="aborted")return K;let c=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return c.status==="aborted"?K:c.status==="dirty"?wn(c.value):n.value==="dirty"?wn(c.value):c});{if(n.value==="aborted")return K;let l=this._def.schema._parseSync({data:o,path:r.path,parent:r});return l.status==="aborted"?K:l.status==="dirty"?wn(l.value):n.value==="dirty"?wn(l.value):l}}if(s.type==="refinement"){let o=l=>{let c=s.refinement(l,i);if(r.common.async)return Promise.resolve(c);if(c 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"?K:(l.status==="dirty"&&n.dirty(),o(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?K:(l.status==="dirty"&&n.dirty(),o(l.value).then(()=>({status:n.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(!Yt(o))return K;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:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>Yt(o)?Promise.resolve(s.transform(o.value,i)).then(l=>({status:n.value,value:l})):K);ne.assertNever(s)}};Xe.create=(t,e,n)=>new Xe({schema:t,typeName:H.ZodEffects,effect:e,...J(n)});Xe.createWithPreprocess=(t,e,n)=>new Xe({schema:e,effect:{type:"preprocess",transform:t},typeName:H.ZodEffects,...J(n)});var Ye=class extends te{_parse(e){return this._getType(e)===z.undefined?Ie(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ye.create=(t,e)=>new Ye({innerType:t,typeName:H.ZodOptional,...J(e)});var gt=class extends te{_parse(e){return this._getType(e)===z.null?Ie(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};gt.create=(t,e)=>new gt({innerType:t,typeName:H.ZodNullable,...J(e)});var jn=class extends te{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===z.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};jn.create=(t,e)=>new jn({innerType:t,typeName:H.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...J(e)});var Nn=class extends te{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Pr(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Me(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Me(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Nn.create=(t,e)=>new Nn({innerType:t,typeName:H.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...J(e)});var Dr=class extends te{_parse(e){if(this._getType(e)!==z.nan){let r=this._getOrReturnCtx(e);return N(r,{code:I.invalid_type,expected:z.nan,received:r.parsedType}),K}return{status:"valid",value:e.data}}};Dr.create=t=>new Dr({typeName:H.ZodNaN,...J(t)});var Ef=Symbol("zod_brand"),ks=class extends te{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},_s=class t extends te{_parse(e){let{status:n,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"?K:i.status==="dirty"?(n.dirty(),wn(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"?K:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:H.ZodPipeline})}},On=class extends te{_parse(e){let n=this._def.innerType._parse(e),r=s=>(Yt(s)&&(s.value=Object.freeze(s.value)),s);return Pr(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};On.create=(t,e)=>new On({innerType:t,typeName:H.ZodReadonly,...J(e)});function Ql(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function sc(t,e={},n){return t?Xt.create().superRefine((r,s)=>{let i=t(r);if(i instanceof Promise)return i.then(o=>{if(!o){let l=Ql(e,r),c=l.fatal??n??!0;s.addIssue({code:"custom",...l,fatal:c})}});if(!i){let o=Ql(e,r),l=o.fatal??n??!0;s.addIssue({code:"custom",...o,fatal:l})}}):Xt.create()}var Rf={object:ze.lazycreate},H;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(H||(H={}));var If=(t,e={message:`Input not instance of ${t.name}`})=>sc(n=>n instanceof t,e),ic=Jt.create,oc=kn.create,Af=Dr.create,Cf=_n.create,ac=Sn.create,$f=Tn.create,Pf=Nr.create,jf=xn.create,Nf=En.create,Of=Xt.create,Mf=Ct.create,zf=ot.create,Df=Or.create,Lf=$t.create,Uf=ze.create,qf=ze.strictCreate,Ff=Rn.create,Bf=ii.create,Kf=In.create,Hf=mt.create,Gf=oi.create,Zf=Mr.create,Vf=zr.create,Wf=ai.create,Yf=An.create,Jf=Cn.create,Xf=$n.create,Qf=Pn.create,em=Qt.create,tm=Xe.create,nm=Ye.create,rm=gt.create,sm=Xe.createWithPreprocess,im=_s.create,om=()=>ic().optional(),am=()=>oc().optional(),lm=()=>ac().optional(),cm={string:(t=>Jt.create({...t,coerce:!0})),number:(t=>kn.create({...t,coerce:!0})),boolean:(t=>Sn.create({...t,coerce:!0})),bigint:(t=>_n.create({...t,coerce:!0})),date:(t=>Tn.create({...t,coerce:!0}))};var um=K;var lc=w.object({baseUrl:w.string().url(),email:w.string().email(),apiToken:w.string().min(1)}),qo=w.object({controlPlaneUrl:w.string().url(),runnerId:w.string().optional(),runnerToken:w.string().optional(),runnerName:w.string().default(li.default.hostname()),jira:lc.optional(),repos:w.record(w.object({path:w.string(),jira:lc.optional(),github:w.object({token:w.string().min(1),login:w.string().optional()}).optional()})).default({}),github:w.object({token:w.string().min(1),login:w.string().optional()}).optional(),githubUsers:w.record(w.object({token:w.string().min(1),login:w.string().optional()})).default({}),deploy:w.object({enabled:w.boolean().default(!1)}).default({enabled:!1}),environments:w.record(w.object({secrets:w.record(w.string()).default({})})).default({}),claudeProfiles:w.record(w.object({configDir:w.string()})).default({}),claudeBin:w.string().default("claude"),agents:w.record(w.object({bin:w.string()})).default({}),jiraUsers:w.record(w.object({email:w.string().email(),apiToken:w.string().min(1)})).default({}),auditSchedules:w.array(w.object({repoName:w.string(),role:w.enum(["security","testing"]),intervalHours:w.number().int().min(6).max(720)})).default([]),pollIntervalSeconds:w.number().int().min(10).max(600).default(30)});function ie(){let t=process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR;if(t)return t;let e=ci.default.join(li.default.homedir(),".config","allwright"),n=ci.default.join(li.default.homedir(),".config","ticketpilot");return!Pt.default.existsSync(e)&&Pt.default.existsSync(n)?n:e}function jt(){return ci.default.join(ie(),"runner.json")}function ye(){let t=jt();if(!Pt.default.existsSync(t))return null;let e=JSON.parse(Pt.default.readFileSync(t,"utf8"));return qo.parse(e)}function fe(t){let e=ie();Pt.default.mkdirSync(e,{recursive:!0,mode:448});let n=jt(),r=n+".tmp";Pt.default.writeFileSync(r,JSON.stringify(t,null,2)+`
315
- `,{mode:384}),Pt.default.renameSync(r,n),Pt.default.chmodSync(n,384)}function ui(t,e){return`${t}:${e}`}function Nt(t,e,n){return t.environments[ui(e,n)]?.secrets??{}}function oe(){let t=ye();if(!t)throw new Error(`No runner config found at ${jt()}. Run \`allwright init\` first.`);return t}var di=require("node:child_process"),qe=R(require("node:fs"),1),hi=R(require("node:path"),1);var dm=new Set(["runner.log","runner.pid"]);function hm(t){return qe.default.readdirSync(t).filter(e=>!dm.has(e)&&!/\.bak-\d+$/.test(e)).sort()}function cc(t){let e=ie();if(!qe.default.existsSync(e))throw new Error(`nothing to export - ${e} does not exist`);let n=hm(e);if(!n.length)throw new Error(`nothing to export - ${e} is empty`);let r=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),s=hi.default.resolve(t||`ticketpilot-backup-${r}.tgz`);return qe.default.writeFileSync(s,"",{mode:384}),(0,di.execFileSync)("tar",["-czf",s,"-C",e,...n]),qe.default.chmodSync(s,384),{file:s,entries:n}}function uc(t){let e=hi.default.resolve(t);if(!qe.default.existsSync(e))throw new Error(`backup file not found: ${e}`);let n=(0,di.execFileSync)("tar",["-tzf",e],{encoding:"utf8"}).split(`
316
- `).filter(Boolean);for(let i of n)if(i.startsWith("/")||i.split("/").includes(".."))throw new Error(`refusing to import - unsafe path in archive: ${i}`);let r=ie(),s;qe.default.existsSync(r)&&qe.default.readdirSync(r).length&&(s=`${r}.bak-${Date.now()}`,qe.default.renameSync(r,s)),qe.default.mkdirSync(r,{recursive:!0,mode:448}),(0,di.execFileSync)("tar",["-xzf",e,"-C",r]);for(let i of qe.default.readdirSync(r)){let o=hi.default.join(r,i);qe.default.statSync(o).isFile()&&qe.default.chmodSync(o,384)}return{restored:n.map(i=>i.replace(/\/$/,"")).sort(),previousDir:s}}var Lr=R(require("node:fs"),1),en=R(require("node:path"),1),pi=".ticketpilot-attachments",pm=15*1024*1024,fm=50*1024*1024,dc=20;function hc(t,e){let n=en.default.basename(t).replace(/[^\w.\- ()]/g,"_").replace(/^\.+/,"").slice(-100)||"file",r=n,s=1;for(;e.has(r);)r=`${s++}-${n}`;return e.add(r),r}async function Ur(t,e,n,r){if(!e.length)return"";let s=en.default.join(n,pi);Lr.default.mkdirSync(s,{recursive:!0});let i=new Set,o=[],l=0;for(let c of e){if(o.length>=dc){r("warn",`attachment cap reached (${dc} files) - skipping the rest`);break}if(c.size>pm){r("warn",`skipping attachment "${c.filename}" - ${ym(c.size)} MB exceeds the 15 MB limit`);continue}if(l+c.size>fm){r("warn",`attachment size budget reached - skipping "${c.filename}" and the rest`);break}try{let u=await t.downloadAttachment(c.contentUrl),p=hc(c.filename,i);Lr.default.writeFileSync(en.default.join(s,p),u),l+=u.length,o.push(`- ${pi}/${p} (${c.mimeType||"unknown type"}, ${Fo(u.length)} KB)`),r("info",`Downloaded attachment "${c.filename}" (${Fo(u.length)} KB)`)}catch(u){r("warn",`could not download attachment "${c.filename}": ${u instanceof Error?u.message:u}`)}}return o.length?`
337
+ `+n)}function Nr(t,e,n,r,s,i){if(t.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,Nr),t.emit("wsClientError",o,n,e)}else ei(n,r,s,i)}});var Kp={};xs(Kp,{MANAGED_MARKER:()=>Co,caddyBlock:()=>Ao,checkoutOwner:()=>Fp,detectApp:()=>Mp,envPrepare:()=>Fw,nodeBinDir:()=>Op,pickPort:()=>Dp,portsClaimedByUnits:()=>zp,spliceCaddyBlock:()=>qp,sudoersText:()=>Up,unitSlug:()=>jp,unitText:()=>Lp});function jp(t,e){let n=r=>r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return`${n(t)}-${n(e)}`.slice(0,60)}function Op(t){let e=n=>{try{let r=(0,_n.execFileSync)(n[0],n.slice(1),{encoding:"utf8",timeout:1e4}).trim();return r?At.default.dirname(r):null}catch{return null}};return t&&t!==ri.default.userInfo().username?e(["sudo","-u",t,"bash","-lc","command -v node"]):e(["bash","-lc","command -v node"])}function Mp(t){let e=At.default.join(t,"package.json");if(!ke.default.existsSync(e))return{kind:"unknown",reason:"no package.json - only Node apps are supported so far"};let n;try{n=JSON.parse(ke.default.readFileSync(e,"utf8"))}catch{return{kind:"unknown",reason:"package.json could not be parsed"}}return n.scripts?.start?{kind:"node-start"}:{kind:"static"}}function zp(){let t=new Set;try{for(let e of ke.default.readdirSync("/etc/systemd/system"))if(e.endsWith(".service"))try{let n=ke.default.readFileSync(At.default.join("/etc/systemd/system",e),"utf8");for(let r of n.matchAll(/^Environment=PORT=(\d+)$/gm))t.add(Number(r[1]))}catch{}}catch{}return t}async function Dp(t){let e=zp(),n=r=>new Promise(s=>{let i=Bl.default.createServer();i.once("error",()=>s(!1)),i.listen(r,"127.0.0.1",()=>i.close(()=>s(!0)))});if(t){if(!await n(t))throw new Error(`port ${t} is already in use on this machine - pick another`);return t}for(let r=3e3;r<3100;r++)if(!e.has(r)&&await n(r))return r;throw new Error("no free port found between 3000 and 3099 - pass one with --port")}function Lp(t){return`${Co}
338
+ [Unit]
339
+ Description=${t.repoName} ${t.envName} (Allwright-prepared)
340
+ After=network-online.target
341
+ Wants=network-online.target
342
+ # A broken unit must FAIL VISIBLY, not loop forever. A hand-written unit here
343
+ # once restarted 554 times with exit 127 while every deploy reported that "a
344
+ # restart really happened".
345
+ StartLimitIntervalSec=60
346
+ StartLimitBurst=5
347
+
348
+ [Service]
349
+ Type=simple
350
+ User=${t.user}
351
+ WorkingDirectory=${t.dir}
352
+ Environment=NODE_ENV=production
353
+ Environment=PORT=${t.port}
354
+ # npm's own first line is "#!/usr/bin/env node" - an absolute ExecStart is not
355
+ # enough, npm still has to FIND node, and systemd's bare PATH has never heard
356
+ # of nvm. This line is the single most common reason a Node unit exits 127.
357
+ Environment=PATH=${t.nodeBin}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
358
+ # Optional on purpose (the leading "-"): the unit starts before any secret
359
+ # exists. Fill it with: sudoedit /etc/allwright/env.d/${t.slug}.env
360
+ EnvironmentFile=-/etc/allwright/env.d/${t.slug}.env
361
+ ExecStart=${t.nodeBin}/npm start
362
+ Restart=on-failure
363
+ RestartSec=3
364
+
365
+ [Install]
366
+ WantedBy=multi-user.target
367
+ `}function Up(t){return`${Co}
368
+ # Exactly two commands, exactly one unit - what a deploy needs and nothing else.
369
+ ${t.user} ALL=(root) NOPASSWD: /usr/bin/systemctl restart ${t.slug}, /usr/bin/systemctl is-active ${t.slug}
370
+ `}function Ao(t){return`# BEGIN allwright ${t.slug}
371
+ ${t.hostname} {
372
+ reverse_proxy 127.0.0.1:${t.port}
373
+ }
374
+ # END allwright ${t.slug}`}function qp(t,e,n){let r=`# BEGIN allwright ${e}`,s=`# END allwright ${e}`,i=t.indexOf(r);if(i!==-1){let o=t.indexOf(s,i);if(o!==-1)return t.slice(0,i)+n+t.slice(o+s.length)}return t.replace(/\s*$/,"")+`
375
+
376
+ `+n+`
377
+ `}function Fp(t){let e=ke.default.statSync(t).uid;if(e===0)throw new Error(`${t} is owned by root. A web app must not run as root - chown the checkout to the user that deploys it first (sudo chown -R <user>: ${t}).`);try{return(0,_n.execFileSync)("id",["-nu",String(e)],{encoding:"utf8",timeout:5e3}).trim()}catch{return ri.default.userInfo().username}}function Ze(t,e){(0,_n.execFileSync)("sudo",t,{encoding:"utf8",timeout:6e4,...e!==void 0?{input:e}:{},stdio:[e!==void 0?"pipe":"inherit","inherit","inherit"]})}function Uw(t){if(t.sudoers){let e=At.default.join(ri.default.tmpdir(),`allwright-sudoers-${process.pid}`);ke.default.writeFileSync(e,t.content,{mode:384});try{(0,_n.execFileSync)("sudo",["visudo","-cf",e],{encoding:"utf8",timeout:3e4}),Ze(["install","-m",t.mode,"-o","root","-g","root",e,t.path])}finally{ke.default.rmSync(e,{force:!0})}return}Ze(["mkdir","-p",At.default.dirname(t.path)]),Ze(["tee",t.path],t.content),Ze(["chmod",t.mode,t.path])}function qw(t){try{return ke.default.readFileSync(t,"utf8").includes(Co)}catch{return!0}}async function Fw(t){if(!ke.default.existsSync(t.dir))throw new Error(`${t.dir} does not exist - clone the repo there first`);if(!ke.default.existsSync(At.default.join(t.dir,".git")))throw new Error(`${t.dir} is not a git checkout`);let e=Mp(t.dir);if(e.kind==="unknown")throw new Error(`cannot prepare this checkout: ${e.reason}. Write the service by hand, or ask in Compose - this command only automates what it can verify.`);let n=jp(t.repoName,t.envName),r=t.publicUrl?Bw(t.publicUrl):"";if(e.kind==="static"){if(y.info(`${t.repoName} has no "start" script - it is a static site, and a static site needs no service: the proxy serves its files directly. Nothing to supervise.`),!r){y.info("Pass --url to wire the proxy, or configure it in your web server by hand.");return}y.info("Add a site block for it to /etc/caddy/Caddyfile yourself, for example:"),y.info(`
378
+ ${r} {
379
+ root * ${t.dir}/<your build output>
380
+ file_server
381
+ }
382
+ `);return}let s=to(t.dir).filter(w=>!w.startsWith(n)),i=`/etc/systemd/system/${n}.service`;if(s.length&&!ke.default.existsSync(i)){y.info(`this checkout is already supervised: ${s.join(" \xB7 ")}. Leaving it alone - remove that unit first if you want Allwright to manage this environment.`);return}if(!qw(i))throw new Error(`${i} exists and was not written by this command - refusing to overwrite a hand-written unit. Delete it yourself if you want it replaced.`);let o=Fp(t.dir),l=Op(o);if(!l)throw new Error(`node is not on ${o}'s PATH - the service will run as ${o} (the checkout's owner), so Node must be installed for THAT user (or system-wide). Install it, then re-run.`);let c=await Dp(t.port),u=[{path:i,content:Lp({slug:n,repoName:t.repoName,envName:t.envName,dir:t.dir,user:o,port:c,nodeBin:l}),mode:"644"},{path:`/etc/sudoers.d/allwright-${n}`,content:Up({slug:n,user:o}),mode:"440",sudoers:!0}];if(t.dryRun){y.info(`DRY RUN - nothing will be written. Planned (port ${c}, user ${o}):`);for(let w of u)y.info(`
383
+ --- ${w.path} (mode ${w.mode}) ---
384
+ ${w.content}`);r&&y.info(`--- appended to /etc/caddy/Caddyfile ---
385
+ ${Ao({slug:n,hostname:r,port:c})}`);return}for(let w of u)Uw(w);let p=`/etc/allwright/env.d/${n}.env`;ke.default.existsSync(p)||(Ze(["install","-d","-m","755","/etc/allwright"]),Ze(["install","-d","-m","750","/etc/allwright/env.d"]),Ze(["install","-m","600","-o","root","-g","root","/dev/null",p]),y.info(`created empty ${p} - add secrets with: sudoedit ${p}`));let f=ke.default.existsSync(At.default.join(t.dir,".next"))||ke.default.existsSync(At.default.join(t.dir,"dist"));f||y.warn(`no build output in ${t.dir} yet - the service would exit immediately. Run your install+build once (or run the first deploy), then: sudo systemctl restart ${n}`),Ze(["systemctl","daemon-reload"]),Ze(["systemctl","reset-failed",n]),Ze(["systemctl","enable","--now",n]),r&&Hw({slug:n,hostname:r,port:c});let b=f?await Kw(c,3e4):!1,v=Bp(n);y.info(""),y.info(`${v?"\u2713":"\u2717"} service ${n}: ${v?"active":"NOT active - journalctl -u "+n+" -n 40"}`),f&&y.info(`${b?"\u2713":"\u2717"} listening on 127.0.0.1:${c}${b?"":" - not yet; check the journal"}`),y.info("\u2713 deploys may restart it without a password (sudoers drop-in installed)"),y.info(""),y.info(`Deploy steps should end with: sudo systemctl restart ${n}`),r&&y.info(`Health checks should target: http://127.0.0.1:${c}/ (and later https://${r}/)`),y.info(`DNS stays yours: point ${r||"your hostname"} at this machine when you are ready.`)}function Bw(t){try{return new URL(t).hostname}catch{throw new Error(`--url must be a full URL like https://staging.example.com (got "${t}")`)}}function Bp(t){try{return(0,_n.execFileSync)("systemctl",["is-active",t],{encoding:"utf8",timeout:1e4}).trim()==="active"}catch{return!1}}async function Kw(t,e){let n=Date.now()+e;for(;Date.now()<n;){if(await new Promise(s=>{let i=Bl.default.connect({port:t,host:"127.0.0.1",timeout:2e3});i.once("connect",()=>{i.destroy(),s(!0)}),i.once("error",()=>s(!1)),i.once("timeout",()=>{i.destroy(),s(!1)})}))return!0;await new Promise(s=>setTimeout(s,2e3))}return!1}function Hw(t){let e="/etc/caddy/Caddyfile";if(!ke.default.existsSync(e)||!Bp("caddy")){y.warn(`caddy is not running here (or ${e} does not exist) - add this to your web server yourself:
386
+ ${Ao(t)}`);return}let n;try{n=ke.default.readFileSync(e,"utf8")}catch{n=(0,_n.execFileSync)("sudo",["cat",e],{encoding:"utf8",timeout:1e4})}let r=qp(n,t.slug,Ao(t));if(r===n){y.info(`caddy already routes ${t.hostname} - unchanged`);return}let s=At.default.join(ri.default.tmpdir(),`Caddyfile-allwright-${process.pid}`);ke.default.writeFileSync(s,r,{mode:420});try{(0,_n.execFileSync)("sudo",["caddy","validate","--config",s,"--adapter","caddyfile"],{encoding:"utf8",timeout:3e4}),Ze(["cp",e,`${e}.bak.${Math.floor(Date.now()/1e3)}`]),Ze(["cp",s,e]),Ze(["systemctl","reload","caddy"]),y.info(`\u2713 caddy: ${t.hostname} \u2192 127.0.0.1:${t.port} (validated, reloaded, backup kept)`)}finally{ke.default.rmSync(s,{force:!0})}}var _n,ke,Bl,ri,At,Co,Hp=xn(()=>{"use strict";_n=require("node:child_process"),ke=R(require("node:fs"),1),Bl=R(require("node:net"),1),ri=R(require("node:os"),1),At=R(require("node:path"),1);Kt();no();Co="# managed by allwright env prepare"});var Jp={};xs(Jp,{buildSetupReport:()=>Zw,claudeLoggedIn:()=>Yp,repoCurrentBranch:()=>Vp,repoDefaultBranch:()=>Wp});function Vp(t){try{let e=(0,ii.execFileSync)("git",["-C",t,"rev-parse","--abbrev-ref","HEAD"],{encoding:"utf8",timeout:1e4}).trim();return e==="HEAD"?"":e}catch{return""}}function Wp(t){let e=(...s)=>{try{return(0,ii.execFileSync)("git",["-C",t,...s],{encoding:"utf8",timeout:1e4}).trim()}catch{return null}},n=e("symbolic-ref","--short","refs/remotes/origin/HEAD");if(n?.startsWith("origin/"))return n.slice(7);let r=e("rev-parse","--abbrev-ref","HEAD");return r&&r!=="HEAD"?r:""}function Yp(t=Gp.default.homedir()){if(Sn.default.existsSync(Or.default.join(t,".claude",".credentials.json")))return!0;try{return!!JSON.parse(Sn.default.readFileSync(Or.default.join(t,".claude.json"),"utf8")).oauthAccount}catch{return!1}}async function Zw(t,e,n){let r=!1,s="";if(si&&Date.now()-si.at<6e4)r=si.installed,s=si.version;else{try{let{stdout:l}=await Gw(t.claudeBin,["--version"],{timeout:1e4});r=!0,s=l.trim().slice(0,60)}catch{r=!1}si={at:Date.now(),installed:r,version:s}}let i=e.map(l=>{let c=t.repos[l];if(!c)return{repoName:l,path:"",mapped:!1,liveMapped:!!n?.repos?.[l],pathExists:!1,isGit:!1,currentBranch:"",claudeMd:!1,deployMd:!1,testMd:!1,githubToken:!1,githubTokenOwn:!1,defaultBranch:""};let u=Sn.default.existsSync(c.path);return{repoName:l,path:c.path,mapped:!0,liveMapped:n?!!n.repos?.[l]:!0,pathExists:u,isGit:u&&Sn.default.existsSync(Or.default.join(c.path,".git")),currentBranch:u?Vp(c.path):"",claudeMd:u&&Sn.default.existsSync(Or.default.join(c.path,"CLAUDE.md")),deployMd:u&&Sn.default.existsSync(Or.default.join(c.path,"DEPLOY.md")),testMd:u&&Sn.default.existsSync(Or.default.join(c.path,"TEST.md")),githubToken:!!$e(t,l),githubTokenOwn:!!c.github?.token,defaultBranch:u?Wp(c.path):""}}),o=Object.values(t.repos).find(l=>l.github?.token);return{jiraConfigured:!!t.jira,jiraEmail:t.jira?.email??"",claude:{installed:r,version:s,loggedIn:Yp()},githubTokenSet:!!(t.github?.token||o),githubLogin:t.github?.login??o?.github?.login??"",deploysEnabled:t.deploy.enabled,jiraUserCount:Object.keys(t.jiraUsers).length,repos:i}}var ii,Sn,Gp,Or,Zp,Gw,si,Xp=xn(()=>{"use strict";ii=require("node:child_process"),Sn=R(require("node:fs"),1),Gp=R(require("node:os"),1),Or=R(require("node:path"),1),Zp=require("node:util");ur();Gw=(0,Zp.promisify)(ii.execFile);si=null});var Ve=R(require("node:fs"),1),ai=R(require("node:os"),1),Xt=R(require("node:path"),1),en=require("node:child_process"),oi=require("node:crypto"),Tn=R(require("node:readline/promises"),1);var oc=R(ic(),1),{program:rk,createCommand:sk,createArgument:ik,createOption:ok,CommanderError:ak,InvalidArgumentError:lk,InvalidOptionArgumentError:ck,Command:ac,Argument:uk,Option:dk,Help:hk}=oc.default;var Ot=R(require("node:fs"),1),mi=R(require("node:os"),1),gi=R(require("node:path"),1);var k={};xs(k,{BRAND:()=>Vf,DIRTY:()=>En,EMPTY_PATH:()=>Ef,INVALID:()=>K,NEVER:()=>Pm,OK:()=>Ae,ParseStatus:()=>Ee,Schema:()=>te,ZodAny:()=>rn,ZodArray:()=>jt,ZodBigInt:()=>In,ZodBoolean:()=>An,ZodBranded:()=>Is,ZodCatch:()=>Un,ZodDate:()=>Cn,ZodDefault:()=>Ln,ZodDiscriminatedUnion:()=>hi,ZodEffects:()=>et,ZodEnum:()=>zn,ZodError:()=>ze,ZodFirstPartyTypeKind:()=>H,ZodFunction:()=>fi,ZodIntersection:()=>jn,ZodIssueCode:()=>I,ZodLazy:()=>On,ZodLiteral:()=>Mn,ZodMap:()=>Fr,ZodNaN:()=>Kr,ZodNativeEnum:()=>Dn,ZodNever:()=>lt,ZodNull:()=>Pn,ZodNullable:()=>bt,ZodNumber:()=>Rn,ZodObject:()=>De,ZodOptional:()=>Xe,ZodParsedType:()=>z,ZodPipeline:()=>As,ZodPromise:()=>sn,ZodReadonly:()=>qn,ZodRecord:()=>pi,ZodSchema:()=>te,ZodSet:()=>Br,ZodString:()=>nn,ZodSymbol:()=>Ur,ZodTransformer:()=>et,ZodTuple:()=>yt,ZodType:()=>te,ZodUndefined:()=>$n,ZodUnion:()=>Nn,ZodUnknown:()=>Nt,ZodVoid:()=>qr,addIssueToContext:()=>j,any:()=>rm,array:()=>am,bigint:()=>Xf,boolean:()=>bc,coerce:()=>$m,custom:()=>mc,date:()=>Qf,datetimeRegex:()=>pc,defaultErrorMap:()=>$t,discriminatedUnion:()=>dm,effect:()=>Sm,enum:()=>wm,function:()=>ym,getErrorMap:()=>zr,getParsedType:()=>gt,instanceof:()=>Yf,intersection:()=>hm,isAborted:()=>ui,isAsync:()=>Dr,isDirty:()=>di,isValid:()=>tn,late:()=>Wf,lazy:()=>bm,literal:()=>vm,makeIssue:()=>Rs,map:()=>mm,nan:()=>Jf,nativeEnum:()=>km,never:()=>im,null:()=>nm,nullable:()=>xm,number:()=>yc,object:()=>lm,objectUtil:()=>Wo,oboolean:()=>Cm,onumber:()=>Am,optional:()=>Tm,ostring:()=>Im,pipeline:()=>Rm,preprocess:()=>Em,promise:()=>_m,quotelessJson:()=>Sf,record:()=>fm,set:()=>gm,setErrorMap:()=>xf,strictObject:()=>cm,string:()=>gc,symbol:()=>em,transformer:()=>Sm,tuple:()=>pm,undefined:()=>tm,union:()=>um,unknown:()=>sm,util:()=>ne,void:()=>om});var ne;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function n(s){throw new Error}t.assertNever=n,t.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},t.getValidEnumValues=s=>{let i=t.objectKeys(s).filter(l=>typeof s[s[l]]!="number"),o={};for(let l of i)o[l]=s[l];return t.objectValues(o)},t.objectValues=s=>t.objectKeys(s).map(function(i){return s[i]}),t.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},t.find=(s,i)=>{for(let o of s)if(i(o))return o},t.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)}t.joinValues=r,t.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(ne||(ne={}));var Wo;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Wo||(Wo={}));var z=ne.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),gt=t=>{switch(typeof t){case"undefined":return z.undefined;case"string":return z.string;case"number":return Number.isNaN(t)?z.nan:z.number;case"boolean":return z.boolean;case"function":return z.function;case"bigint":return z.bigint;case"symbol":return z.symbol;case"object":return Array.isArray(t)?z.array:t===null?z.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?z.promise:typeof Map<"u"&&t instanceof Map?z.map:typeof Set<"u"&&t instanceof Set?z.set:typeof Date<"u"&&t instanceof Date?z.date:z.object;default:return z.unknown}};var I=ne.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"]),Sf=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),ze=class t 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 n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=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(n(o));else{let l=r,c=0;for(;c<o.path.length;){let u=o.path[c];c===o.path.length-1?(l[u]=l[u]||{_errors:[]},l[u]._errors.push(n(o))):l[u]=l[u]||{_errors:[]},l=l[u],c++}}};return s(this),r}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ne.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];n[i]=n[i]||[],n[i].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};ze.create=t=>new ze(t);var Tf=(t,e)=>{let n;switch(t.code){case I.invalid_type:t.received===z.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case I.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,ne.jsonStringifyReplacer)}`;break;case I.unrecognized_keys:n=`Unrecognized key(s) in object: ${ne.joinValues(t.keys,", ")}`;break;case I.invalid_union:n="Invalid input";break;case I.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ne.joinValues(t.options)}`;break;case I.invalid_enum_value:n=`Invalid enum value. Expected ${ne.joinValues(t.options)}, received '${t.received}'`;break;case I.invalid_arguments:n="Invalid function arguments";break;case I.invalid_return_type:n="Invalid function return type";break;case I.invalid_date:n="Invalid date";break;case I.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:ne.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case I.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case I.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case I.custom:n="Invalid input";break;case I.invalid_intersection_types:n="Intersection results could not be merged";break;case I.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case I.not_finite:n="Number must be finite";break;default:n=e.defaultError,ne.assertNever(t)}return{message:n}},$t=Tf;var lc=$t;function xf(t){lc=t}function zr(){return lc}var Rs=t=>{let{data:e,path:n,errorMaps:r,issueData:s}=t,i=[...n,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let l="",c=r.filter(u=>!!u).slice().reverse();for(let u of c)l=u(o,{data:e,defaultError:l}).message;return{...s,path:i,message:l}},Ef=[];function j(t,e){let n=zr(),r=Rs({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===$t?void 0:$t].filter(s=>!!s)});t.common.issues.push(r)}var Ee=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let s of n){if(s.status==="aborted")return K;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let s of n){let i=await s.key,o=await s.value;r.push({key:i,value:o})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let s of n){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return K;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}}},K=Object.freeze({status:"aborted"}),En=t=>({status:"dirty",value:t}),Ae=t=>({status:"valid",value:t}),ui=t=>t.status==="aborted",di=t=>t.status==="dirty",tn=t=>t.status==="valid",Dr=t=>typeof Promise<"u"&&t instanceof Promise;var U;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(U||(U={}));var Qe=class{constructor(e,n,r,s){this._cachedPath=[],this.parent=e,this.data=n,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}},cc=(t,e)=>{if(tn(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new ze(t.common.issues);return this._error=n,this._error}}};function J(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:s}=t;if(e&&(n||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:c}=t;return o.code==="invalid_enum_value"?{message:c??l.defaultError}:typeof l.data>"u"?{message:c??r??l.defaultError}:o.code!=="invalid_type"?{message:l.defaultError}:{message:c??n??l.defaultError}},description:s}}var te=class{get description(){return this._def.description}_getType(e){return gt(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:gt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ee,ctx:{common:e.parent.common,data:e.data,parsedType:gt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(Dr(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:gt(e)},s=this._parseSync({data:e,path:r.path,parent:r});return cc(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:gt(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return tn(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>tn(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:gt(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(Dr(s)?s:Promise.resolve(s));return cc(r,i)}refine(e,n){let r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;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(c=>c?!0:(l(),!1)):o?!0:(l(),!1)})}refinement(e,n){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(e){return new et({schema:this,typeName:H.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:n=>this["~validate"](n)}}optional(){return Xe.create(this,this._def)}nullable(){return bt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return jt.create(this)}promise(){return sn.create(this,this._def)}or(e){return Nn.create([this,e],this._def)}and(e){return jn.create(this,e,this._def)}transform(e){return new et({...J(this._def),schema:this,typeName:H.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new Ln({...J(this._def),innerType:this,defaultValue:n,typeName:H.ZodDefault})}brand(){return new Is({typeName:H.ZodBranded,type:this,...J(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Un({...J(this._def),innerType:this,catchValue:n,typeName:H.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return As.create(this,e)}readonly(){return qn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Rf=/^c[^\s-]{8,}$/i,If=/^[0-9a-z]+$/,Af=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Cf=/^[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,$f=/^[a-z0-9_-]{21}$/i,Pf=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Nf=/^[-+]?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)?)??$/,jf=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Of="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Yo,Mf=/^(?:(?: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])$/,zf=/^(?:(?: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])$/,Df=/^(([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]))$/,Lf=/^(([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])$/,Uf=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,qf=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dc="((\\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])))",Ff=new RegExp(`^${dc}$`);function hc(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function Bf(t){return new RegExp(`^${hc(t)}$`)}function pc(t){let e=`${dc}T${hc(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function Kf(t,e){return!!((e==="v4"||!e)&&Mf.test(t)||(e==="v6"||!e)&&Df.test(t))}function Hf(t,e){if(!Pf.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.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 Gf(t,e){return!!((e==="v4"||!e)&&zf.test(t)||(e==="v6"||!e)&&Lf.test(t))}var nn=class t extends te{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==z.string){let i=this._getOrReturnCtx(e);return j(i,{code:I.invalid_type,expected:z.string,received:i.parsedType}),K}let r=new Ee,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")jf.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")Yo||(Yo=new RegExp(Of,"u")),Yo.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")Cf.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")$f.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")Rf.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")If.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")Af.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"?pc(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"?Ff.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{code:I.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Bf(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"?Nf.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"duration",code:I.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?Kf(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"?Hf(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"?Gf(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"?Uf.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"base64",code:I.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?qf.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"base64url",code:I.invalid_string,message:i.message}),r.dirty()):ne.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:I.invalid_string,...U.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...U.errToObj(e)})}url(e){return this._addCheck({kind:"url",...U.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...U.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...U.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...U.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...U.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...U.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...U.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...U.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...U.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...U.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...U.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...U.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.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.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...U.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...U.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...U.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...U.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...U.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...U.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...U.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...U.errToObj(n)})}nonempty(e){return this.min(1,U.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...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 n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};nn.create=t=>new nn({checks:[],typeName:H.ZodString,coerce:t?.coerce??!1,...J(t)});function Zf(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,i=Number.parseInt(t.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var Rn=class t extends te{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)!==z.number){let i=this._getOrReturnCtx(e);return j(i,{code:I.invalid_type,expected:z.number,received:i.parsedType}),K}let r,s=new Ee;for(let i of this._def.checks)i.kind==="int"?ne.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"?Zf(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()):ne.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,U.toString(n))}gt(e,n){return this.setLimit("min",e,!1,U.toString(n))}lte(e,n){return this.setLimit("max",e,!0,U.toString(n))}lt(e,n){return this.setLimit("max",e,!1,U.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:U.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:U.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:U.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:U.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:U.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:U.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:U.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:U.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:U.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:U.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ne.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};Rn.create=t=>new Rn({checks:[],typeName:H.ZodNumber,coerce:t?.coerce||!1,...J(t)});var In=class t extends te{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)!==z.bigint)return this._getInvalidInput(e);let r,s=new Ee;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()):ne.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return j(n,{code:I.invalid_type,expected:z.bigint,received:n.parsedType}),K}gte(e,n){return this.setLimit("min",e,!0,U.toString(n))}gt(e,n){return this.setLimit("min",e,!1,U.toString(n))}lte(e,n){return this.setLimit("max",e,!0,U.toString(n))}lt(e,n){return this.setLimit("max",e,!1,U.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:U.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:U.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:U.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:U.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:U.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:U.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};In.create=t=>new In({checks:[],typeName:H.ZodBigInt,coerce:t?.coerce??!1,...J(t)});var An=class extends te{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==z.boolean){let r=this._getOrReturnCtx(e);return j(r,{code:I.invalid_type,expected:z.boolean,received:r.parsedType}),K}return Ae(e.data)}};An.create=t=>new An({typeName:H.ZodBoolean,coerce:t?.coerce||!1,...J(t)});var Cn=class t extends te{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==z.date){let i=this._getOrReturnCtx(e);return j(i,{code:I.invalid_type,expected:z.date,received:i.parsedType}),K}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return j(i,{code:I.invalid_date}),K}let r=new Ee,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()):ne.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:U.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:U.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};Cn.create=t=>new Cn({checks:[],coerce:t?.coerce||!1,typeName:H.ZodDate,...J(t)});var Ur=class extends te{_parse(e){if(this._getType(e)!==z.symbol){let r=this._getOrReturnCtx(e);return j(r,{code:I.invalid_type,expected:z.symbol,received:r.parsedType}),K}return Ae(e.data)}};Ur.create=t=>new Ur({typeName:H.ZodSymbol,...J(t)});var $n=class extends te{_parse(e){if(this._getType(e)!==z.undefined){let r=this._getOrReturnCtx(e);return j(r,{code:I.invalid_type,expected:z.undefined,received:r.parsedType}),K}return Ae(e.data)}};$n.create=t=>new $n({typeName:H.ZodUndefined,...J(t)});var Pn=class extends te{_parse(e){if(this._getType(e)!==z.null){let r=this._getOrReturnCtx(e);return j(r,{code:I.invalid_type,expected:z.null,received:r.parsedType}),K}return Ae(e.data)}};Pn.create=t=>new Pn({typeName:H.ZodNull,...J(t)});var rn=class extends te{constructor(){super(...arguments),this._any=!0}_parse(e){return Ae(e.data)}};rn.create=t=>new rn({typeName:H.ZodAny,...J(t)});var Nt=class extends te{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ae(e.data)}};Nt.create=t=>new Nt({typeName:H.ZodUnknown,...J(t)});var lt=class extends te{_parse(e){let n=this._getOrReturnCtx(e);return j(n,{code:I.invalid_type,expected:z.never,received:n.parsedType}),K}};lt.create=t=>new lt({typeName:H.ZodNever,...J(t)});var qr=class extends te{_parse(e){if(this._getType(e)!==z.undefined){let r=this._getOrReturnCtx(e);return j(r,{code:I.invalid_type,expected:z.void,received:r.parsedType}),K}return Ae(e.data)}};qr.create=t=>new qr({typeName:H.ZodVoid,...J(t)});var jt=class t extends te{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==z.array)return j(n,{code:I.invalid_type,expected:z.array,received:n.parsedType}),K;if(s.exactLength!==null){let o=n.data.length>s.exactLength.value,l=n.data.length<s.exactLength.value;(o||l)&&(j(n,{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&&n.data.length<s.minLength.value&&(j(n,{code:I.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(j(n,{code:I.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((o,l)=>s.type._parseAsync(new Qe(n,o,n.path,l)))).then(o=>Ee.mergeArray(r,o));let i=[...n.data].map((o,l)=>s.type._parseSync(new Qe(n,o,n.path,l)));return Ee.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:U.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:U.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:U.toString(n)}})}nonempty(e){return this.min(1,e)}};jt.create=(t,e)=>new jt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:H.ZodArray,...J(e)});function Lr(t){if(t instanceof De){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=Xe.create(Lr(r))}return new De({...t._def,shape:()=>e})}else return t instanceof jt?new jt({...t._def,type:Lr(t.element)}):t instanceof Xe?Xe.create(Lr(t.unwrap())):t instanceof bt?bt.create(Lr(t.unwrap())):t instanceof yt?yt.create(t.items.map(e=>Lr(e))):t}var De=class t extends te{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(),n=ne.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==z.object){let u=this._getOrReturnCtx(e);return j(u,{code:I.invalid_type,expected:z.object,received:u.parsedType}),K}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),l=[];if(!(this._def.catchall instanceof lt&&this._def.unknownKeys==="strip"))for(let u in s.data)o.includes(u)||l.push(u);let c=[];for(let u of o){let p=i[u],f=s.data[u];c.push({key:{status:"valid",value:u},value:p._parse(new Qe(s,f,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof lt){let u=this._def.unknownKeys;if(u==="passthrough")for(let p of l)c.push({key:{status:"valid",value:p},value:{status:"valid",value:s.data[p]}});else if(u==="strict")l.length>0&&(j(s,{code:I.unrecognized_keys,keys:l}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let p of l){let f=s.data[p];c.push({key:{status:"valid",value:p},value:u._parse(new Qe(s,f,s.path,p)),alwaysSet:p in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let u=[];for(let p of c){let f=await p.key,b=await p.value;u.push({key:f,value:b,alwaysSet:p.alwaysSet})}return u}).then(u=>Ee.mergeObjectSync(r,u)):Ee.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return U.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:U.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:H.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of ne.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of ne.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return Lr(this)}partial(e){let n={};for(let r of ne.objectKeys(this.shape)){let s=this.shape[r];e&&!e[r]?n[r]=s:n[r]=s.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of ne.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Xe;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return fc(ne.objectKeys(this.shape))}};De.create=(t,e)=>new De({shape:()=>t,unknownKeys:"strip",catchall:lt.create(),typeName:H.ZodObject,...J(e)});De.strictCreate=(t,e)=>new De({shape:()=>t,unknownKeys:"strict",catchall:lt.create(),typeName:H.ZodObject,...J(e)});De.lazycreate=(t,e)=>new De({shape:t,unknownKeys:"strip",catchall:lt.create(),typeName:H.ZodObject,...J(e)});var Nn=class extends te{_parse(e){let{ctx:n}=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 n.common.issues.push(...l.ctx.common.issues),l.result;let o=i.map(l=>new ze(l.ctx.common.issues));return j(n,{code:I.invalid_union,unionErrors:o}),K}if(n.common.async)return Promise.all(r.map(async i=>{let o={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let c of r){let u={...n,common:{...n.common,issues:[]},parent:null},p=c._parseSync({data:n.data,path:n.path,parent:u});if(p.status==="valid")return p;p.status==="dirty"&&!i&&(i={result:p,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let l=o.map(c=>new ze(c));return j(n,{code:I.invalid_union,unionErrors:l}),K}}get options(){return this._def.options}};Nn.create=(t,e)=>new Nn({options:t,typeName:H.ZodUnion,...J(e)});var Pt=t=>t instanceof On?Pt(t.schema):t instanceof et?Pt(t.innerType()):t instanceof Mn?[t.value]:t instanceof zn?t.options:t instanceof Dn?ne.objectValues(t.enum):t instanceof Ln?Pt(t._def.innerType):t instanceof $n?[void 0]:t instanceof Pn?[null]:t instanceof Xe?[void 0,...Pt(t.unwrap())]:t instanceof bt?[null,...Pt(t.unwrap())]:t instanceof Is||t instanceof qn?Pt(t.unwrap()):t instanceof Un?Pt(t._def.innerType):[],hi=class t extends te{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==z.object)return j(n,{code:I.invalid_type,expected:z.object,received:n.parsedType}),K;let r=this.discriminator,s=n.data[r],i=this.optionsMap.get(s);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(j(n,{code:I.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),K)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let s=new Map;for(let i of n){let o=Pt(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 t({typeName:H.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...J(r)})}};function Jo(t,e){let n=gt(t),r=gt(e);if(t===e)return{valid:!0,data:t};if(n===z.object&&r===z.object){let s=ne.objectKeys(e),i=ne.objectKeys(t).filter(l=>s.indexOf(l)!==-1),o={...t,...e};for(let l of i){let c=Jo(t[l],e[l]);if(!c.valid)return{valid:!1};o[l]=c.data}return{valid:!0,data:o}}else if(n===z.array&&r===z.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<t.length;i++){let o=t[i],l=e[i],c=Jo(o,l);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===z.date&&r===z.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var jn=class extends te{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=(i,o)=>{if(ui(i)||ui(o))return K;let l=Jo(i.value,o.value);return l.valid?((di(i)||di(o))&&n.dirty(),{status:n.value,value:l.data}):(j(r,{code:I.invalid_intersection_types}),K)};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}))}};jn.create=(t,e,n)=>new jn({left:t,right:e,typeName:H.ZodIntersection,...J(n)});var yt=class t extends te{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==z.array)return j(r,{code:I.invalid_type,expected:z.array,received:r.parsedType}),K;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"}),K;!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"}),n.dirty());let i=[...r.data].map((o,l)=>{let c=this._def.items[l]||this._def.rest;return c?c._parse(new Qe(r,o,r.path,l)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>Ee.mergeArray(n,o)):Ee.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};yt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new yt({items:t,typeName:H.ZodTuple,rest:null,...J(e)})};var pi=class t extends te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==z.object)return j(r,{code:I.invalid_type,expected:z.object,received:r.parsedType}),K;let s=[],i=this._def.keyType,o=this._def.valueType;for(let l in r.data)s.push({key:i._parse(new Qe(r,l,r.path,l)),value:o._parse(new Qe(r,r.data[l],r.path,l)),alwaysSet:l in r.data});return r.common.async?Ee.mergeObjectAsync(n,s):Ee.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof te?new t({keyType:e,valueType:n,typeName:H.ZodRecord,...J(r)}):new t({keyType:nn.create(),valueType:e,typeName:H.ZodRecord,...J(n)})}},Fr=class extends te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==z.map)return j(r,{code:I.invalid_type,expected:z.map,received:r.parsedType}),K;let s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([l,c],u)=>({key:s._parse(new Qe(r,l,r.path,[u,"key"])),value:i._parse(new Qe(r,c,r.path,[u,"value"]))}));if(r.common.async){let l=new Map;return Promise.resolve().then(async()=>{for(let c of o){let u=await c.key,p=await c.value;if(u.status==="aborted"||p.status==="aborted")return K;(u.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(u.value,p.value)}return{status:n.value,value:l}})}else{let l=new Map;for(let c of o){let u=c.key,p=c.value;if(u.status==="aborted"||p.status==="aborted")return K;(u.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(u.value,p.value)}return{status:n.value,value:l}}}};Fr.create=(t,e,n)=>new Fr({valueType:e,keyType:t,typeName:H.ZodMap,...J(n)});var Br=class t extends te{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==z.set)return j(r,{code:I.invalid_type,expected:z.set,received:r.parsedType}),K;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}),n.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}),n.dirty());let i=this._def.valueType;function o(c){let u=new Set;for(let p of c){if(p.status==="aborted")return K;p.status==="dirty"&&n.dirty(),u.add(p.value)}return{status:n.value,value:u}}let l=[...r.data.values()].map((c,u)=>i._parse(new Qe(r,c,r.path,u)));return r.common.async?Promise.all(l).then(c=>o(c)):o(l)}min(e,n){return new t({...this._def,minSize:{value:e,message:U.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:U.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};Br.create=(t,e)=>new Br({valueType:t,minSize:null,maxSize:null,typeName:H.ZodSet,...J(e)});var fi=class t extends te{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==z.function)return j(n,{code:I.invalid_type,expected:z.function,received:n.parsedType}),K;function r(l,c){return Rs({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,zr(),$t].filter(u=>!!u),issueData:{code:I.invalid_arguments,argumentsError:c}})}function s(l,c){return Rs({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,zr(),$t].filter(u=>!!u),issueData:{code:I.invalid_return_type,returnTypeError:c}})}let i={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof sn){let l=this;return Ae(async function(...c){let u=new ze([]),p=await l._def.args.parseAsync(c,i).catch(v=>{throw u.addIssue(r(c,v)),u}),f=await Reflect.apply(o,this,p);return await l._def.returns._def.type.parseAsync(f,i).catch(v=>{throw u.addIssue(s(f,v)),u})})}else{let l=this;return Ae(function(...c){let u=l._def.args.safeParse(c,i);if(!u.success)throw new ze([r(c,u.error)]);let p=Reflect.apply(o,this,u.data),f=l._def.returns.safeParse(p,i);if(!f.success)throw new ze([s(p,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:yt.create(e).rest(Nt.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new t({args:e||yt.create([]).rest(Nt.create()),returns:n||Nt.create(),typeName:H.ZodFunction,...J(r)})}},On=class extends te{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};On.create=(t,e)=>new On({getter:t,typeName:H.ZodLazy,...J(e)});var Mn=class extends te{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return j(n,{received:n.data,code:I.invalid_literal,expected:this._def.value}),K}return{status:"valid",value:e.data}}get value(){return this._def.value}};Mn.create=(t,e)=>new Mn({value:t,typeName:H.ZodLiteral,...J(e)});function fc(t,e){return new zn({values:t,typeName:H.ZodEnum,...J(e)})}var zn=class t extends te{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return j(n,{expected:ne.joinValues(r),received:n.parsedType,code:I.invalid_type}),K}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return j(n,{received:n.data,code:I.invalid_enum_value,options:r}),K}return Ae(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};zn.create=fc;var Dn=class extends te{_parse(e){let n=ne.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==z.string&&r.parsedType!==z.number){let s=ne.objectValues(n);return j(r,{expected:ne.joinValues(s),received:r.parsedType,code:I.invalid_type}),K}if(this._cache||(this._cache=new Set(ne.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=ne.objectValues(n);return j(r,{received:r.data,code:I.invalid_enum_value,options:s}),K}return Ae(e.data)}get enum(){return this._def.values}};Dn.create=(t,e)=>new Dn({values:t,typeName:H.ZodNativeEnum,...J(e)});var sn=class extends te{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==z.promise&&n.common.async===!1)return j(n,{code:I.invalid_type,expected:z.promise,received:n.parsedType}),K;let r=n.parsedType===z.promise?n.data:Promise.resolve(n.data);return Ae(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};sn.create=(t,e)=>new sn({type:t,typeName:H.ZodPromise,...J(e)});var et=class extends te{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===H.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{j(r,o),o.fatal?n.abort():n.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(n.value==="aborted")return K;let c=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return c.status==="aborted"?K:c.status==="dirty"?En(c.value):n.value==="dirty"?En(c.value):c});{if(n.value==="aborted")return K;let l=this._def.schema._parseSync({data:o,path:r.path,parent:r});return l.status==="aborted"?K:l.status==="dirty"?En(l.value):n.value==="dirty"?En(l.value):l}}if(s.type==="refinement"){let o=l=>{let c=s.refinement(l,i);if(r.common.async)return Promise.resolve(c);if(c 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"?K:(l.status==="dirty"&&n.dirty(),o(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?K:(l.status==="dirty"&&n.dirty(),o(l.value).then(()=>({status:n.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(!tn(o))return K;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:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>tn(o)?Promise.resolve(s.transform(o.value,i)).then(l=>({status:n.value,value:l})):K);ne.assertNever(s)}};et.create=(t,e,n)=>new et({schema:t,typeName:H.ZodEffects,effect:e,...J(n)});et.createWithPreprocess=(t,e,n)=>new et({schema:e,effect:{type:"preprocess",transform:t},typeName:H.ZodEffects,...J(n)});var Xe=class extends te{_parse(e){return this._getType(e)===z.undefined?Ae(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Xe.create=(t,e)=>new Xe({innerType:t,typeName:H.ZodOptional,...J(e)});var bt=class extends te{_parse(e){return this._getType(e)===z.null?Ae(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};bt.create=(t,e)=>new bt({innerType:t,typeName:H.ZodNullable,...J(e)});var Ln=class extends te{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===z.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Ln.create=(t,e)=>new Ln({innerType:t,typeName:H.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...J(e)});var Un=class extends te{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Dr(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ze(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ze(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Un.create=(t,e)=>new Un({innerType:t,typeName:H.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...J(e)});var Kr=class extends te{_parse(e){if(this._getType(e)!==z.nan){let r=this._getOrReturnCtx(e);return j(r,{code:I.invalid_type,expected:z.nan,received:r.parsedType}),K}return{status:"valid",value:e.data}}};Kr.create=t=>new Kr({typeName:H.ZodNaN,...J(t)});var Vf=Symbol("zod_brand"),Is=class extends te{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},As=class t extends te{_parse(e){let{status:n,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"?K:i.status==="dirty"?(n.dirty(),En(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"?K:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:H.ZodPipeline})}},qn=class extends te{_parse(e){let n=this._def.innerType._parse(e),r=s=>(tn(s)&&(s.value=Object.freeze(s.value)),s);return Dr(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};qn.create=(t,e)=>new qn({innerType:t,typeName:H.ZodReadonly,...J(e)});function uc(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function mc(t,e={},n){return t?rn.create().superRefine((r,s)=>{let i=t(r);if(i instanceof Promise)return i.then(o=>{if(!o){let l=uc(e,r),c=l.fatal??n??!0;s.addIssue({code:"custom",...l,fatal:c})}});if(!i){let o=uc(e,r),l=o.fatal??n??!0;s.addIssue({code:"custom",...o,fatal:l})}}):rn.create()}var Wf={object:De.lazycreate},H;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(H||(H={}));var Yf=(t,e={message:`Input not instance of ${t.name}`})=>mc(n=>n instanceof t,e),gc=nn.create,yc=Rn.create,Jf=Kr.create,Xf=In.create,bc=An.create,Qf=Cn.create,em=Ur.create,tm=$n.create,nm=Pn.create,rm=rn.create,sm=Nt.create,im=lt.create,om=qr.create,am=jt.create,lm=De.create,cm=De.strictCreate,um=Nn.create,dm=hi.create,hm=jn.create,pm=yt.create,fm=pi.create,mm=Fr.create,gm=Br.create,ym=fi.create,bm=On.create,vm=Mn.create,wm=zn.create,km=Dn.create,_m=sn.create,Sm=et.create,Tm=Xe.create,xm=bt.create,Em=et.createWithPreprocess,Rm=As.create,Im=()=>gc().optional(),Am=()=>yc().optional(),Cm=()=>bc().optional(),$m={string:(t=>nn.create({...t,coerce:!0})),number:(t=>Rn.create({...t,coerce:!0})),boolean:(t=>An.create({...t,coerce:!0})),bigint:(t=>In.create({...t,coerce:!0})),date:(t=>Cn.create({...t,coerce:!0}))};var Pm=K;var vc=k.object({baseUrl:k.string().url(),email:k.string().email(),apiToken:k.string().min(1)}),Xo=k.object({controlPlaneUrl:k.string().url(),runnerId:k.string().optional(),runnerToken:k.string().optional(),runnerName:k.string().default(mi.default.hostname()),jira:vc.optional(),repos:k.record(k.object({path:k.string(),jira:vc.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 ie(){let t=process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR;if(t)return t;let e=gi.default.join(mi.default.homedir(),".config","allwright"),n=gi.default.join(mi.default.homedir(),".config","ticketpilot");return!Ot.default.existsSync(e)&&Ot.default.existsSync(n)?n:e}function Mt(){return gi.default.join(ie(),"runner.json")}function ye(){let t=Mt();if(!Ot.default.existsSync(t))return null;let e=JSON.parse(Ot.default.readFileSync(t,"utf8"));return Xo.parse(e)}function fe(t){let e=ie();Ot.default.mkdirSync(e,{recursive:!0,mode:448});let n=Mt(),r=n+".tmp";Ot.default.writeFileSync(r,JSON.stringify(t,null,2)+`
387
+ `,{mode:384}),Ot.default.renameSync(r,n),Ot.default.chmodSync(n,384)}function yi(t,e){return`${t}:${e}`}function zt(t,e,n){return t.environments[yi(e,n)]?.secrets??{}}function oe(){let t=ye();if(!t)throw new Error(`No runner config found at ${Mt()}. Run \`allwright init\` first.`);return t}var bi=require("node:child_process"),Fe=R(require("node:fs"),1),vi=R(require("node:path"),1);var Nm=new Set(["runner.log","runner.pid"]);function jm(t){return Fe.default.readdirSync(t).filter(e=>!Nm.has(e)&&!/\.bak-\d+$/.test(e)).sort()}function wc(t){let e=ie();if(!Fe.default.existsSync(e))throw new Error(`nothing to export - ${e} does not exist`);let n=jm(e);if(!n.length)throw new Error(`nothing to export - ${e} is empty`);let r=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),s=vi.default.resolve(t||`ticketpilot-backup-${r}.tgz`);return Fe.default.writeFileSync(s,"",{mode:384}),(0,bi.execFileSync)("tar",["-czf",s,"-C",e,...n]),Fe.default.chmodSync(s,384),{file:s,entries:n}}function kc(t){let e=vi.default.resolve(t);if(!Fe.default.existsSync(e))throw new Error(`backup file not found: ${e}`);let n=(0,bi.execFileSync)("tar",["-tzf",e],{encoding:"utf8"}).split(`
388
+ `).filter(Boolean);for(let i of n)if(i.startsWith("/")||i.split("/").includes(".."))throw new Error(`refusing to import - unsafe path in archive: ${i}`);let r=ie(),s;Fe.default.existsSync(r)&&Fe.default.readdirSync(r).length&&(s=`${r}.bak-${Date.now()}`,Fe.default.renameSync(r,s)),Fe.default.mkdirSync(r,{recursive:!0,mode:448}),(0,bi.execFileSync)("tar",["-xzf",e,"-C",r]);for(let i of Fe.default.readdirSync(r)){let o=vi.default.join(r,i);Fe.default.statSync(o).isFile()&&Fe.default.chmodSync(o,384)}return{restored:n.map(i=>i.replace(/\/$/,"")).sort(),previousDir:s}}var Hr=R(require("node:fs"),1),on=R(require("node:path"),1),wi=".ticketpilot-attachments",Om=15*1024*1024,Mm=50*1024*1024,_c=20;function Sc(t,e){let n=on.default.basename(t).replace(/[^\w.\- ()]/g,"_").replace(/^\.+/,"").slice(-100)||"file",r=n,s=1;for(;e.has(r);)r=`${s++}-${n}`;return e.add(r),r}async function Gr(t,e,n,r){if(!e.length)return"";let s=on.default.join(n,wi);Hr.default.mkdirSync(s,{recursive:!0});let i=new Set,o=[],l=0;for(let c of e){if(o.length>=_c){r("warn",`attachment cap reached (${_c} files) - skipping the rest`);break}if(c.size>Om){r("warn",`skipping attachment "${c.filename}" - ${Lm(c.size)} MB exceeds the 15 MB limit`);continue}if(l+c.size>Mm){r("warn",`attachment size budget reached - skipping "${c.filename}" and the rest`);break}try{let u=await t.downloadAttachment(c.contentUrl),p=Sc(c.filename,i);Hr.default.writeFileSync(on.default.join(s,p),u),l+=u.length,o.push(`- ${wi}/${p} (${c.mimeType||"unknown type"}, ${Qo(u.length)} KB)`),r("info",`Downloaded attachment "${c.filename}" (${Qo(u.length)} KB)`)}catch(u){r("warn",`could not download attachment "${c.filename}": ${u instanceof Error?u.message:u}`)}}return o.length?`
317
389
 
318
390
  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:
319
391
  ${o.join(`
320
392
  `)}
321
- Read them with the Read tool when relevant; images (screenshots) can be viewed directly.`:(tn(n),"")}function tn(t){Lr.default.rmSync(en.default.join(t,pi),{recursive:!0,force:!0})}var mm=4*1024*1024,gm=16*1024*1024;function pc(t,e,n){let r=en.default.join(t,pi,`chat-${e.replace(/[^\w-]/g,"")}`);if(!n.length)return{section:"",dir:r};Lr.default.mkdirSync(r,{recursive:!0});let s=new Set,i=[],o=0,l=en.default.relative(t,r);for(let u of n){let p=Buffer.from(u.contentBase64,"base64");if(p.length>mm||o+p.length>gm){i.push(`- (skipped "${u.name}" - over the upload size budget)`);continue}let f=hc(u.name,s);Lr.default.writeFileSync(en.default.join(r,f),p),o+=p.length,i.push(`- ${l}/${f} (${Fo(p.length)} KB)`)}return{section:`
393
+ Read them with the Read tool when relevant; images (screenshots) can be viewed directly.`:(an(n),"")}function an(t){Hr.default.rmSync(on.default.join(t,wi),{recursive:!0,force:!0})}var zm=4*1024*1024,Dm=16*1024*1024;function Tc(t,e,n){let r=on.default.join(t,wi,`chat-${e.replace(/[^\w-]/g,"")}`);if(!n.length)return{section:"",dir:r};Hr.default.mkdirSync(r,{recursive:!0});let s=new Set,i=[],o=0,l=on.default.relative(t,r);for(let u of n){let p=Buffer.from(u.contentBase64,"base64");if(p.length>zm||o+p.length>Dm){i.push(`- (skipped "${u.name}" - over the upload size budget)`);continue}let f=Sc(u.name,s);Hr.default.writeFileSync(on.default.join(r,f),p),o+=p.length,i.push(`- ${l}/${f} (${Qo(p.length)} KB)`)}return{section:`
322
394
 
323
395
  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:
324
396
  ${i.join(`
325
397
  `)}
326
- Read them with the Read tool; images can be viewed directly.`,dir:r}}var Fo=t=>Math.max(1,Math.round(t/1024)),ym=t=>Math.round(t/(1024*1024)*10)/10;var Ee=R(require("node:fs"),1),mi=R(require("node:path"),1);function qr(){return mi.default.join(ie(),"runner.pid")}function fi(){return mi.default.join(ie(),"runner.log")}function fc(){Ee.default.mkdirSync(ie(),{recursive:!0,mode:448});let t=Ee.default.openSync(fi(),"a",384);try{Ee.default.chmodSync(fi(),384)}catch{}return t}function Mn(){let t=qr();if(!Ee.default.existsSync(t))return null;let e=Number(Ee.default.readFileSync(t,"utf8").trim());return Number.isFinite(e)&&e>0?e:null}function zn(t){try{return process.kill(t,0),!0}catch{return!1}}function mc(t){Ee.default.mkdirSync(ie(),{recursive:!0,mode:448}),Ee.default.writeFileSync(qr(),String(t),{mode:384})}function gc(t){Mn()===t&&Ee.default.rmSync(qr(),{force:!0})}function Bo(){return mi.default.join(ie(),"runner.lock")}function Fr(){let t=Bo();if(!Ee.default.existsSync(t))return null;let e=Number(Ee.default.readFileSync(t,"utf8").trim());return!Number.isFinite(e)||e<=0||e===process.pid?null:zn(e)?e:null}function yc(){let t=Fr();return t?{ok:!1,pid:t}:(Ee.default.mkdirSync(ie(),{recursive:!0,mode:448}),Ee.default.writeFileSync(Bo(),String(process.pid),{mode:384}),{ok:!0})}function Ko(){try{let t=Bo();Ee.default.existsSync(t)&&Number(Ee.default.readFileSync(t,"utf8").trim())===process.pid&&Ee.default.rmSync(t,{force:!0})}catch{}}function bc(t){try{let e=Ee.default.readFileSync(`/proc/${t}/cgroup`,"utf8"),n=/\/([A-Za-z0-9._@-]+)\.service/.exec(e);return n?n[1]:null}catch{return null}}var Si=R(require("node:fs"),1),Rs=R(require("node:path"),1),Bc=R(ke(),1);async function Kc(t,e){let n=await fetch(new URL("/api/runners/enroll",t.controlPlaneUrl),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enrollToken:e,name:t.runnerName,platform:`${process.platform}/${process.arch}`,runnerVersion:Ti})});if(!n.ok){let i=await n.text().catch(()=>"");throw new Error(`enrollment failed (${n.status}): ${i.slice(0,300)}`)}let r=Bc.EnrollResponse.parse(await n.json()),s={...t,runnerId:r.runnerId,runnerToken:r.runnerToken};return fe(s),s}function Gg(){try{let t=process.argv[1]?Si.default.realpathSync(process.argv[1]):"";for(let e of[Rs.default.dirname(t),Rs.default.dirname(Rs.default.dirname(t))]){let n=Rs.default.join(e,"package.json");if(!Si.default.existsSync(n))continue;let r=JSON.parse(Si.default.readFileSync(n,"utf8")).version;if(typeof r=="string"&&r)return r}}catch{}return"0.0.0"}var Ti=Gg();wt();var eu="Posted automatically by Allwright",Zg=["Posted automatically by TicketPilot"],kt=t=>t.includes(eu)||Zg.some(e=>t.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,n,r){let s=new URL(n,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} ${n} -> ${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,n=20){let r=await this.userSearch(e,n);return r.length||!e.includes("@")?r:this.userSearch(e.slice(0,e.indexOf("@")),n)}async userSearch(e,n){return e.trim()?(await this.request("GET",`/rest/api/3/user/search?query=${encodeURIComponent(e)}&maxResults=${n}`)??[]).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,n=20){return((await this.request("POST","/rest/api/3/search/jql",{jql:e,maxResults:n,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 n=await this.request("GET",`/rest/api/3/project/${encodeURIComponent(e)}/statuses`),r=new Map;for(let i of n??[])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,n=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:n,fields:["summary","status"]})).issues??[]).map(s=>({key:s.key,summary:s.fields?.summary??"",status:s.fields?.status?.name??""}))}async epicChildren(e,n=50){return((await this.request("POST","/rest/api/3/search/jql",{jql:`parent = "${e}" ORDER BY created ASC`,maxResults:n,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,n=100){return((await this.request("POST","/rest/api/3/search/jql",{jql:e,maxResults:n,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 n=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=n.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:Qc(o.body)})),i=(n.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:n.key,summary:n.fields.summary??"",description:Qc(n.fields.description),labels:n.fields.labels??[],status:n.fields.status?.name??"",comments:s,attachments:i}}async listAllComments(e){let n=await this.fetchCommentPage(e,0),r=n.total??n.comments.length;if(r<=n.comments.length)return n.comments;let s=Math.max(0,r-200),i=s===0?[...n.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,n){let r=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}/comment?startAt=${n}&maxResults=100`);return{comments:r.comments??[],total:r.total}}async downloadAttachment(e){let n=await fetch(e,{headers:this.headers()});if(!n.ok)throw new Error(`attachment download failed: ${n.status}`);return Buffer.from(await n.arrayBuffer())}async lastEnteredStatus(e,n){let r=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}?expand=changelog&fields=status`),s=n.toLowerCase(),i=null;for(let o of r.changelog?.histories??[])(o.items??[]).some(c=>(c.field==="status"||c.fieldId==="status")&&(c.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,n,r,s="Task",i){return{key:(await this.request("POST","/rest/api/3/issue",{fields:{project:{key:e},issuetype:{name:s},summary:n.slice(0,250),description:ha(r),...i?{parent:{key:i}}:{}}})).key}}async addAttachments(e,n){if(!n.length)return;let r=new FormData;for(let l of n)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,n){await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/comment`,{body:ha(n)})}async addComment(e,n){let r=`${n}
398
+ Read them with the Read tool; images can be viewed directly.`,dir:r}}var Qo=t=>Math.max(1,Math.round(t/1024)),Lm=t=>Math.round(t/(1024*1024)*10)/10;var Re=R(require("node:fs"),1),_i=R(require("node:path"),1);function Zr(){return _i.default.join(ie(),"runner.pid")}function ki(){return _i.default.join(ie(),"runner.log")}function xc(){Re.default.mkdirSync(ie(),{recursive:!0,mode:448});let t=Re.default.openSync(ki(),"a",384);try{Re.default.chmodSync(ki(),384)}catch{}return t}function Fn(){let t=Zr();if(!Re.default.existsSync(t))return null;let e=Number(Re.default.readFileSync(t,"utf8").trim());return Number.isFinite(e)&&e>0?e:null}function Bn(t){try{return process.kill(t,0),!0}catch{return!1}}function Ec(t){Re.default.mkdirSync(ie(),{recursive:!0,mode:448}),Re.default.writeFileSync(Zr(),String(t),{mode:384})}function Rc(t){Fn()===t&&Re.default.rmSync(Zr(),{force:!0})}function ea(){return _i.default.join(ie(),"runner.lock")}function Vr(){let t=ea();if(!Re.default.existsSync(t))return null;let e=Number(Re.default.readFileSync(t,"utf8").trim());return!Number.isFinite(e)||e<=0||e===process.pid?null:Bn(e)?e:null}function Ic(){let t=Vr();return t?{ok:!1,pid:t}:(Re.default.mkdirSync(ie(),{recursive:!0,mode:448}),Re.default.writeFileSync(ea(),String(process.pid),{mode:384}),{ok:!0})}function ta(){try{let t=ea();Re.default.existsSync(t)&&Number(Re.default.readFileSync(t,"utf8").trim())===process.pid&&Re.default.rmSync(t,{force:!0})}catch{}}function Ac(t){try{let e=Re.default.readFileSync(`/proc/${t}/cgroup`,"utf8"),n=/\/([A-Za-z0-9._@-]+)\.service/.exec(e);return n?n[1]:null}catch{return null}}var Ci=R(require("node:fs"),1),js=R(require("node:path"),1),eu=R(_e(),1);async function tu(t,e){let n=await fetch(new URL("/api/runners/enroll",t.controlPlaneUrl),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enrollToken:e,name:t.runnerName,platform:`${process.platform}/${process.arch}`,runnerVersion:$i})});if(!n.ok){let i=await n.text().catch(()=>"");throw new Error(`enrollment failed (${n.status}): ${i.slice(0,300)}`)}let r=eu.EnrollResponse.parse(await n.json()),s={...t,runnerId:r.runnerId,runnerToken:r.runnerToken};return fe(s),s}function fy(){try{let t=process.argv[1]?Ci.default.realpathSync(process.argv[1]):"";for(let e of[js.default.dirname(t),js.default.dirname(js.default.dirname(t))]){let n=js.default.join(e,"package.json");if(!Ci.default.existsSync(n))continue;let r=JSON.parse(Ci.default.readFileSync(n,"utf8")).version;if(typeof r=="string"&&r)return r}}catch{}return"0.0.0"}var $i=fy();_t();var du="Posted automatically by Allwright",my=["Posted automatically by TicketPilot"],St=t=>t.includes(du)||my.some(e=>t.includes(e));var Ne=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,n,r){let s=new URL(n,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} ${n} -> ${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,n=20){let r=await this.userSearch(e,n);return r.length||!e.includes("@")?r:this.userSearch(e.slice(0,e.indexOf("@")),n)}async userSearch(e,n){return e.trim()?(await this.request("GET",`/rest/api/3/user/search?query=${encodeURIComponent(e)}&maxResults=${n}`)??[]).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,n=20){return((await this.request("POST","/rest/api/3/search/jql",{jql:e,maxResults:n,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 n=await this.request("GET",`/rest/api/3/project/${encodeURIComponent(e)}/statuses`),r=new Map;for(let i of n??[])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,n=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:n,fields:["summary","status"]})).issues??[]).map(s=>({key:s.key,summary:s.fields?.summary??"",status:s.fields?.status?.name??""}))}async epicChildren(e,n=50){return((await this.request("POST","/rest/api/3/search/jql",{jql:`parent = "${e}" ORDER BY created ASC`,maxResults:n,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,n=100){return((await this.request("POST","/rest/api/3/search/jql",{jql:e,maxResults:n,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 n=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=n.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:uu(o.body)})),i=(n.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:n.key,summary:n.fields.summary??"",description:uu(n.fields.description),labels:n.fields.labels??[],status:n.fields.status?.name??"",comments:s,attachments:i}}async listAllComments(e){let n=await this.fetchCommentPage(e,0),r=n.total??n.comments.length;if(r<=n.comments.length)return n.comments;let s=Math.max(0,r-200),i=s===0?[...n.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,n){let r=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}/comment?startAt=${n}&maxResults=100`);return{comments:r.comments??[],total:r.total}}async downloadAttachment(e){let n=await fetch(e,{headers:this.headers()});if(!n.ok)throw new Error(`attachment download failed: ${n.status}`);return Buffer.from(await n.arrayBuffer())}async lastEnteredStatus(e,n){let r=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}?expand=changelog&fields=status`),s=n.toLowerCase(),i=null;for(let o of r.changelog?.histories??[])(o.items??[]).some(c=>(c.field==="status"||c.fieldId==="status")&&(c.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,n,r,s="Task",i){return{key:(await this.request("POST","/rest/api/3/issue",{fields:{project:{key:e},issuetype:{name:s},summary:n.slice(0,250),description:Sa(r),...i?{parent:{key:i}}:{}}})).key}}async addAttachments(e,n){if(!n.length)return;let r=new FormData;for(let l of n)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,n){await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/comment`,{body:Sa(n)})}async addComment(e,n){let r=`${n}
327
399
 
328
400
  ---
329
- _${eu} - never treated as a trigger._`;await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/comment`,{body:ha(r)})}async editLabels(e,n){let r=[...(n.add??[]).map(s=>({add:s})),...(n.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,n){await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/transitions`,{transition:{id:n}})}async transitionByName(e,n){let s=(await this.getTransitions(e)).find(i=>i.name.toLowerCase()===n.toLowerCase());return s?(await this.transition(e,s.id),!0):!1}};function Qc(t){if(!t)return"";let e=[],n=r=>{r.text&&e.push(r.text),r.type==="hardBreak"&&e.push(`
401
+ _${du} - never treated as a trigger._`;await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/comment`,{body:Sa(r)})}async editLabels(e,n){let r=[...(n.add??[]).map(s=>({add:s})),...(n.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,n){await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/transitions`,{transition:{id:n}})}async transitionByName(e,n){let s=(await this.getTransitions(e)).find(i=>i.name.toLowerCase()===n.toLowerCase());return s?(await this.transition(e,s.id),!0):!1}};function uu(t){if(!t)return"";let e=[],n=r=>{r.text&&e.push(r.text),r.type==="hardBreak"&&e.push(`
330
402
  `);for(let s of r.content??[])n(s);r.type&&["paragraph","heading","listItem","codeBlock","blockquote"].includes(r.type)&&e.push(`
331
403
  `)};return n(t),e.join("").replace(/\n{3,}/g,`
332
404
 
333
- `).trim()}function ha(t){let e=t.replace(/\r\n/g,`
405
+ `).trim()}function Sa(t){let e=t.replace(/\r\n/g,`
334
406
  `).split(`
335
407
  `),n=[],r=0,s=i=>{let o=[],l=/(\*\*[^*]+\*\*|`[^`]+`)/g,c=0,u;for(;(u=l.exec(i))!==null;){u.index>c&&o.push({type:"text",text:i.slice(c,u.index)});let p=u[0];p.startsWith("**")?o.push({type:"text",text:p.slice(2,-2),marks:[{type:"strong"}]}):o.push({type:"text",text:p.slice(1,-1),marks:[{type:"code"}]}),c=u.index+p.length}return c<i.length&&o.push({type:"text",text:i.slice(c)}),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 f=[];for(r++;r<e.length&&!/^```\s*$/.test(e[r]);)f.push(e[r]),r++;r++,n.push({type:"codeBlock",attrs:o[1]?{language:o[1]}:{},content:[{type:"text",text:f.join(`
336
- `)||" "}]});continue}let l=i.match(/^(#{1,6})\s+(.*)$/);if(l){n.push({type:"heading",attrs:{level:l[1].length},content:s(l[2])}),r++;continue}if(i.match(/^\s*[-*]\s+(.*)$/)){let f=[];for(;r<e.length;){let b=e[r].match(/^\s*[-*]\s+(.*)$/);if(!b)break;f.push({type:"listItem",content:[{type:"paragraph",content:s(b[1])}]}),r++}n.push({type:"bulletList",content:f});continue}if(i.match(/^\s*\d+[.)]\s+(.*)$/)){let f=[];for(;r<e.length;){let b=e[r].match(/^\s*\d+[.)]\s+(.*)$/);if(!b)break;f.push({type:"listItem",content:[{type:"paragraph",content:s(b[1])}]}),r++}n.push({type:"orderedList",content:f});continue}let p=[i];for(r++;r<e.length&&e[r].trim()!==""&&!/^(#{1,6}\s|```|\s*[-*]\s|\s*\d+[.)]\s)/.test(e[r]);)p.push(e[r]),r++;n.push({type:"paragraph",content:s(p.join(" "))})}return{type:"doc",version:1,content:n}}function tu(t,e,n){let r=t.repos[e]?.jira??t.jira;if(!r)return{kind:"legacy"};let s=n.trim().toLowerCase();if(!s)return{kind:"legacy"};if(s===r.email.toLowerCase())return{kind:"self"};let i=t.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:
408
+ `)||" "}]});continue}let l=i.match(/^(#{1,6})\s+(.*)$/);if(l){n.push({type:"heading",attrs:{level:l[1].length},content:s(l[2])}),r++;continue}if(i.match(/^\s*[-*]\s+(.*)$/)){let f=[];for(;r<e.length;){let b=e[r].match(/^\s*[-*]\s+(.*)$/);if(!b)break;f.push({type:"listItem",content:[{type:"paragraph",content:s(b[1])}]}),r++}n.push({type:"bulletList",content:f});continue}if(i.match(/^\s*\d+[.)]\s+(.*)$/)){let f=[];for(;r<e.length;){let b=e[r].match(/^\s*\d+[.)]\s+(.*)$/);if(!b)break;f.push({type:"listItem",content:[{type:"paragraph",content:s(b[1])}]}),r++}n.push({type:"orderedList",content:f});continue}let p=[i];for(r++;r<e.length&&e[r].trim()!==""&&!/^(#{1,6}\s|```|\s*[-*]\s|\s*\d+[.)]\s)/.test(e[r]);)p.push(e[r]),r++;n.push({type:"paragraph",content:s(p.join(" "))})}return{type:"doc",version:1,content:n}}function hu(t,e,n){let r=t.repos[e]?.jira??t.jira;if(!r)return{kind:"legacy"};let s=n.trim().toLowerCase();if(!s)return{kind:"legacy"};if(s===r.email.toLowerCase())return{kind:"self"};let i=t.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:
337
409
 
338
410
  allwright jira user-add ${s}
339
411
 
340
- 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.`}}sr();var ir=require("node:child_process"),Xr=R(require("node:fs"),1),pa=R(require("node:os"),1),ma=R(require("node:path"),1);var As="allwright",ru=`/etc/systemd/system/${As}.service`,fa="ticketpilot-runner";function ga(){let t=process.env.SUDO_USER&&process.env.SUDO_USER!=="root"?process.env.SUDO_USER:"",e=t||pa.default.userInfo().username,n=t?ma.default.join("/home",t):pa.default.homedir();return{nodePath:process.execPath,scriptPath:Xr.default.realpathSync(process.argv[1]),user:e,home:n}}function ya(t){let e=ma.default.dirname(t.nodePath);return`[Unit]
412
+ 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.`}}ur();var dr=require("node:child_process"),ss=R(require("node:fs"),1),Ta=R(require("node:os"),1),Ea=R(require("node:path"),1);var Ms="allwright",fu=`/etc/systemd/system/${Ms}.service`,xa="ticketpilot-runner";function Ra(){let t=process.env.SUDO_USER&&process.env.SUDO_USER!=="root"?process.env.SUDO_USER:"",e=t||Ta.default.userInfo().username,n=t?Ea.default.join("/home",t):Ta.default.homedir();return{nodePath:process.execPath,scriptPath:ss.default.realpathSync(process.argv[1]),user:e,home:n}}function Ia(t){let e=Ea.default.dirname(t.nodePath);return`[Unit]
341
413
  Description=Allwright runner
342
414
  After=network-online.target
343
415
 
@@ -355,8 +427,8 @@ TimeoutStopSec=2h
355
427
 
356
428
  [Install]
357
429
  WantedBy=multi-user.target
358
- `}function su(){return process.platform==="linux"&&Xr.default.existsSync("/run/systemd/system")}function iu(t){if(!su())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=ga(),n=ya(e);if(typeof process.getuid=="function"&&process.getuid()!==0){t.info("Root is needed to write the unit. Re-run as:"),t.info(' sudo env "PATH=$PATH" allwright service install'),t.info("(the env PATH part matters when node is installed via nvm - plain sudo can't find it)"),t.info(""),t.info(`This is exactly what it will write to ${ru}:`),t.info(`
359
- `+n);return}try{(0,ir.execFileSync)("systemctl",["disable","--now",fa]),t.info(`stopped the old ${fa} service - this one replaces it`)}catch{}let r=Fr();if(r)try{process.kill(r,"SIGTERM"),t.info(`stopped the running runner (pid ${r}) - the service takes over`)}catch{}Xr.default.writeFileSync(ru,n),(0,ir.execFileSync)("systemctl",["daemon-reload"]),(0,ir.execFileSync)("systemctl",["enable","--now",As]),(0,ir.execFileSync)("systemctl",["restart",As]),t.info(`Installed and started (runs as ${e.user}, survives reboots).`),t.info(`Watch it: journalctl -u ${As} -f`),t.info("Status: allwright service status")}function ou(t){if(!su())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[As,fa]){try{(0,ir.execFileSync)("systemctl",["disable","--now",e])}catch{}let n=`/etc/systemd/system/${e}.service`;Xr.default.existsSync(n)&&Xr.default.rmSync(n)}(0,ir.execFileSync)("systemctl",["daemon-reload"]),t.info("Service removed. The runner config and credentials were not touched.")}var au=R(ke(),1);function lu(t){return t.filter(e=>e.statusCategory!=="done"&&!e.labels.includes("agent-implemented")&&!e.labels.includes(au.NEEDS_INPUT_LABEL))}function cu(t,e,n){let r=n.map(s=>{let i=(s.description??"").trim().slice(0,600);return`- ${s.key} [${s.status}] ${s.summary}${i?`
430
+ `}function mu(){return process.platform==="linux"&&ss.default.existsSync("/run/systemd/system")}function gu(t){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=Ra(),n=Ia(e);if(typeof process.getuid=="function"&&process.getuid()!==0){t.info("Root is needed to write the unit. Re-run as:"),t.info(' sudo env "PATH=$PATH" allwright service install'),t.info("(the env PATH part matters when node is installed via nvm - plain sudo can't find it)"),t.info(""),t.info(`This is exactly what it will write to ${fu}:`),t.info(`
431
+ `+n);return}try{(0,dr.execFileSync)("systemctl",["disable","--now",xa]),t.info(`stopped the old ${xa} service - this one replaces it`)}catch{}let r=Vr();if(r)try{process.kill(r,"SIGTERM"),t.info(`stopped the running runner (pid ${r}) - the service takes over`)}catch{}ss.default.writeFileSync(fu,n),(0,dr.execFileSync)("systemctl",["daemon-reload"]),(0,dr.execFileSync)("systemctl",["enable","--now",Ms]),(0,dr.execFileSync)("systemctl",["restart",Ms]),t.info(`Installed and started (runs as ${e.user}, survives reboots).`),t.info(`Watch it: journalctl -u ${Ms} -f`),t.info("Status: allwright service status")}function yu(t){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[Ms,xa]){try{(0,dr.execFileSync)("systemctl",["disable","--now",e])}catch{}let n=`/etc/systemd/system/${e}.service`;ss.default.existsSync(n)&&ss.default.rmSync(n)}(0,dr.execFileSync)("systemctl",["daemon-reload"]),t.info("Service removed. The runner config and credentials were not touched.")}var bu=R(_e(),1);function vu(t){return t.filter(e=>e.statusCategory!=="done"&&!e.labels.includes("agent-implemented")&&!e.labels.includes(bu.NEEDS_INPUT_LABEL))}function wu(t,e,n){let r=n.map(s=>{let i=(s.description??"").trim().slice(0,600);return`- ${s.key} [${s.status}] ${s.summary}${i?`
360
432
  ${i.replace(/\n+/g," ")}`:""}`}).join(`
361
433
  `);return`You are looking at this repository to help sequence work on the Jira epic ${t} ("${e}"). These child tickets are still pending:
362
434
 
@@ -367,7 +439,7 @@ Pick the ONE ticket that should be implemented FIRST. Weigh, in this order: (1)
367
439
  Answer with ONLY a fenced json block, nothing after it:
368
440
  \`\`\`json
369
441
  {"issueKey": "<one of the keys above>", "reason": "<2-3 sentences: why this one first, and what it unblocks>"}
370
- \`\`\``}function uu(t,e){let r=t.match(/```(?:json)?\s*(\{[\s\S]*?\})\s*```/)?.[1]??t.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 Ra=require("node:crypto"),Mu=R(require("node:fs"),1);var ba=R(require("node:fs"),1),Pi=R(require("node:path"),1),ji=R(ke(),1),Vg={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 hu(t,e,n,r={}){let s=e.map(u=>`### Pack: ${u.name}
442
+ \`\`\``}function ku(t,e){let r=t.match(/```(?:json)?\s*(\{[\s\S]*?\})\s*```/)?.[1]??t.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 Da=require("node:crypto"),Zu=R(require("node:fs"),1);var Aa=R(require("node:fs"),1),Li=R(require("node:path"),1),Ui=R(_e(),1),gy={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 Su(t,e,n,r={}){let s=e.map(u=>`### Pack: ${u.name}
371
443
 
372
444
  ${u.content}`).join(`
373
445
 
@@ -392,7 +464,7 @@ Fold what these results show - failures, flaky exits, suspiciously green suites
392
464
  ### WRITING STYLE - plain language
393
465
 
394
466
  This report is for a non-technical reader. Write "summary", every finding's "title" and every "fix" in plain, everyday English: no jargon, no acronyms, no framework or library names in the title, no code in the prose. For each finding say in 2-3 short sentences what the problem means for the business or for a user - what could go wrong, who it affects, what to do about it - rather than how it is implemented.
395
- This changes the WORDING ONLY. "evidence" (real file, real line), "ruleId", "severity" and "area" are filled in EXACTLY as they would be otherwise - the same evidence rule applies, and a finding without real evidence is still DELETED. Never skip or soften evidence to keep the text simple.`:"";return`${Vg[t]}
467
+ This changes the WORDING ONLY. "evidence" (real file, real line), "ruleId", "severity" and "area" are filled in EXACTLY as they would be otherwise - the same evidence rule applies, and a finding without real evidence is still DELETED. Never skip or soften evidence to keep the text simple.`:"";return`${gy[t]}
396
468
 
397
469
  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.
398
470
 
@@ -406,20 +478,20 @@ Explore the repository first - entry points, routes, storage, tests - then audit
406
478
  "evidence": [{"file": "<repo-relative path>", "line": <number, omit if n/a>, "note": "<what is there>"}],
407
479
  "fix": "<2-4 sentences: concrete fix, specific to this code>"}]}
408
480
  \`\`\`
409
- 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.`+c}function pu(t){let n=t.match(/```(?:json)?\s*(\{[\s\S]*\})\s*```(?![\s\S]*```)/)?.[1]??t.match(/\{[\s\S]*"findings"[\s\S]*\}/)?.[0];if(!n)return{error:"the agent's report contained no JSON block"};let r;try{r=JSON.parse(n)}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 c=Wg(l),u=c?ji.AuditFinding.safeParse(c):null;if(!u?.success){i++;continue}let p=u.data.id;for(;o.has(p);)p=`${p}-2`;o.add(p),s.push({...u.data,id:p})}return{summary:typeof r.summary=="string"?r.summary.trim().slice(0,2e3):"",findings:s,dropped:i}}function Wg(t){if(typeof t!="object"||t===null)return null;let e=t,n=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:"",...du(i.line)?{line:du(i.line)}:{},note:typeof i.note=="string"?i.note:""})).filter(i=>i.file):[],s=typeof e.ruleId=="string"?e.ruleId.trim().toUpperCase():"";return{id:Yg(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:ji.AuditSeverity.options.includes(n)?n: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 du(t){let e=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):NaN;return Number.isInteger(e)&&e>0?e:void 0}function Yg(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"finding"}function Jg(t){try{let e=ba.default.readFileSync(t,"utf8");return e?e.split(`
410
- `).length:0}catch{return null}}function fu(t,e){let n=Pi.default.resolve(t),r=[],s=[],i=0;for(let o of e){let l=[];for(let c of o.evidence){let u=c.file.trim().replace(/^\.\//,""),p=Pi.default.resolve(n,u);if(p!==n&&!p.startsWith(n+Pi.default.sep))continue;let f;try{f=ba.default.statSync(p)}catch{continue}if(f.isFile()){if(c.line!==void 0){let b=Jg(p);if(b!==null&&c.line>b){l.push({...c,line:void 0}),i++;continue}}l.push(c)}}if(!l.length){s.push({title:o.title,files:o.evidence.map(c=>c.file)});continue}r.push({...o,evidence:l})}return{findings:r,droppedFindings:s,correctedLines:i}}var Cs=R(require("node:fs"),1),va=R(require("node:path"),1),mu=R(ke(),1);var Xg=20;function gu(){return va.default.join(ie(),"audits.json")}function Qr(){try{return{byProject:JSON.parse(Cs.default.readFileSync(gu(),"utf8")).byProject??{}}}catch{return{byProject:{}}}}function yu(t){let e=gu();Cs.default.mkdirSync(va.default.dirname(e),{recursive:!0,mode:448});let n=e+".tmp";Cs.default.writeFileSync(n,JSON.stringify(t,null,2),{mode:384}),Cs.default.renameSync(n,e)}function bu(t,e){let n=Qr(),r=n.byProject[t]??[];r.unshift(mu.AuditRecord.parse(e)),n.byProject[t]=r.slice(0,Xg),yu(n)}function vu(t){return(Qr().byProject[t]??[]).map(e=>{let n={};for(let r of e.findings)n[r.severity]=(n[r.severity]??0)+1;return{id:e.id,role:e.role,createdAt:e.createdAt,findingCount:e.findings.length,bySeverity:n,detailLevel:e.detailLevel??"technical"}})}function wu(t,e){let n=Qr(),r=e?Date.parse(e):NaN,s={};for(let i of t){let o=(n.byProject[i]??[]).filter(c=>!Number.isFinite(r)||Date.parse(c.createdAt)>=r);if(!o.length)continue;let l={audits:o.length,findings:0,valid:0,falsePositive:0,wontFix:0,unreviewed:0};for(let c of o){l.findings+=c.findings.length;for(let u of c.findings){let p=c.verdicts[u.id]?.verdict;p==="valid"?l.valid++:p==="false-positive"?l.falsePositive++:p==="wont-fix"?l.wontFix++:l.unreviewed++}}s[i]=l}return s}function wa(t,e,n){let r=Qr(),i=(r.byProject[t]??[]).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));n.selected&&(i.review={selected:n.selected.filter(l=>o.has(l)),updatedAt:new Date().toISOString()});for(let l of n.ticketed??[])o.has(l.findingId)&&(i.ticketed={...i.ticketed,[l.findingId]:l.issueKey});for(let l of n.verdicts??[])o.has(l.findingId)&&(i.verdicts={...i.verdicts,[l.findingId]:{verdict:l.verdict,note:l.note,by:n.verdictBy??"",at:new Date().toISOString()}});for(let l of n.markLessonsWritten??[])o.has(l)&&!i.lessonsWritten.includes(l)&&i.lessonsWritten.push(l);return yu(r),i}function ku(t,e){return(Qr().byProject[t]??[]).find(s=>s.role===e&&(s.scope?.kind??"repo")==="repo")?.createdAt??null}function _u(t,e){return(Qr().byProject[t]??[]).find(n=>n.id===e)??null}wt();var je=R(require("node:fs"),1),_t=R(require("node:path"),1),Eu=R(ke(),1);var Ut=R(require("node:fs"),1),ka=R(require("node:path"),1),Qg=25e4,ey=2e5,Su=`# Incident ledger
481
+ 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.`+c}function Tu(t){let n=t.match(/```(?:json)?\s*(\{[\s\S]*\})\s*```(?![\s\S]*```)/)?.[1]??t.match(/\{[\s\S]*"findings"[\s\S]*\}/)?.[0];if(!n)return{error:"the agent's report contained no JSON block"};let r;try{r=JSON.parse(n)}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 c=yy(l),u=c?Ui.AuditFinding.safeParse(c):null;if(!u?.success){i++;continue}let p=u.data.id;for(;o.has(p);)p=`${p}-2`;o.add(p),s.push({...u.data,id:p})}return{summary:typeof r.summary=="string"?r.summary.trim().slice(0,2e3):"",findings:s,dropped:i}}function yy(t){if(typeof t!="object"||t===null)return null;let e=t,n=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:"",..._u(i.line)?{line:_u(i.line)}:{},note:typeof i.note=="string"?i.note:""})).filter(i=>i.file):[],s=typeof e.ruleId=="string"?e.ruleId.trim().toUpperCase():"";return{id:by(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:Ui.AuditSeverity.options.includes(n)?n: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 _u(t){let e=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):NaN;return Number.isInteger(e)&&e>0?e:void 0}function by(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"finding"}function vy(t){try{let e=Aa.default.readFileSync(t,"utf8");return e?e.split(`
482
+ `).length:0}catch{return null}}function xu(t,e){let n=Li.default.resolve(t),r=[],s=[],i=0;for(let o of e){let l=[];for(let c of o.evidence){let u=c.file.trim().replace(/^\.\//,""),p=Li.default.resolve(n,u);if(p!==n&&!p.startsWith(n+Li.default.sep))continue;let f;try{f=Aa.default.statSync(p)}catch{continue}if(f.isFile()){if(c.line!==void 0){let b=vy(p);if(b!==null&&c.line>b){l.push({...c,line:void 0}),i++;continue}}l.push(c)}}if(!l.length){s.push({title:o.title,files:o.evidence.map(c=>c.file)});continue}r.push({...o,evidence:l})}return{findings:r,droppedFindings:s,correctedLines:i}}var zs=R(require("node:fs"),1),Ca=R(require("node:path"),1),Eu=R(_e(),1);var wy=20;function Ru(){return Ca.default.join(ie(),"audits.json")}function is(){try{return{byProject:JSON.parse(zs.default.readFileSync(Ru(),"utf8")).byProject??{}}}catch{return{byProject:{}}}}function Iu(t){let e=Ru();zs.default.mkdirSync(Ca.default.dirname(e),{recursive:!0,mode:448});let n=e+".tmp";zs.default.writeFileSync(n,JSON.stringify(t,null,2),{mode:384}),zs.default.renameSync(n,e)}function Au(t,e){let n=is(),r=n.byProject[t]??[];r.unshift(Eu.AuditRecord.parse(e)),n.byProject[t]=r.slice(0,wy),Iu(n)}function Cu(t){return(is().byProject[t]??[]).map(e=>{let n={};for(let r of e.findings)n[r.severity]=(n[r.severity]??0)+1;return{id:e.id,role:e.role,createdAt:e.createdAt,findingCount:e.findings.length,bySeverity:n,detailLevel:e.detailLevel??"technical"}})}function $u(t,e){let n=is(),r=e?Date.parse(e):NaN,s={};for(let i of t){let o=(n.byProject[i]??[]).filter(c=>!Number.isFinite(r)||Date.parse(c.createdAt)>=r);if(!o.length)continue;let l={audits:o.length,findings:0,valid:0,falsePositive:0,wontFix:0,unreviewed:0};for(let c of o){l.findings+=c.findings.length;for(let u of c.findings){let p=c.verdicts[u.id]?.verdict;p==="valid"?l.valid++:p==="false-positive"?l.falsePositive++:p==="wont-fix"?l.wontFix++:l.unreviewed++}}s[i]=l}return s}function $a(t,e,n){let r=is(),i=(r.byProject[t]??[]).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));n.selected&&(i.review={selected:n.selected.filter(l=>o.has(l)),updatedAt:new Date().toISOString()});for(let l of n.ticketed??[])o.has(l.findingId)&&(i.ticketed={...i.ticketed,[l.findingId]:l.issueKey});for(let l of n.verdicts??[])o.has(l.findingId)&&(i.verdicts={...i.verdicts,[l.findingId]:{verdict:l.verdict,note:l.note,by:n.verdictBy??"",at:new Date().toISOString()}});for(let l of n.markLessonsWritten??[])o.has(l)&&!i.lessonsWritten.includes(l)&&i.lessonsWritten.push(l);return Iu(r),i}function Pu(t,e){return(is().byProject[t]??[]).find(s=>s.role===e&&(s.scope?.kind??"repo")==="repo")?.createdAt??null}function Nu(t,e){return(is().byProject[t]??[]).find(n=>n.id===e)??null}_t();var je=R(require("node:fs"),1),Tt=R(require("node:path"),1),zu=R(_e(),1);var Bt=R(require("node:fs"),1),Pa=R(require("node:path"),1),ky=25e4,_y=2e5,ju=`# Incident ledger
411
483
 
412
484
  Machine-written facts about this repository's runs: what failed, what
413
485
  resolved it. Appended by the Allwright runner; humans may edit freely.
414
486
  Newest entries are at the bottom.
415
487
 
416
- `;function _a(t){return ka.default.join(t,".ticketpilot","memory","incidents.md")}function ct(t,e){try{let n=_a(t);Ut.default.mkdirSync(ka.default.dirname(n),{recursive:!0});let r=Ut.default.existsSync(n)?"":Su,s=new Date().toISOString().slice(0,10),i=e.detail?.trim();Ut.default.appendFileSync(n,r+`## ${s} \xB7 ${e.issueKey} \xB7 ${e.title} (run ${e.runId})
488
+ `;function Na(t){return Pa.default.join(t,".ticketpilot","memory","incidents.md")}function dt(t,e){try{let n=Na(t);Bt.default.mkdirSync(Pa.default.dirname(n),{recursive:!0});let r=Bt.default.existsSync(n)?"":ju,s=new Date().toISOString().slice(0,10),i=e.detail?.trim();Bt.default.appendFileSync(n,r+`## ${s} \xB7 ${e.issueKey} \xB7 ${e.title} (run ${e.runId})
417
489
  `+(i?`${i.slice(0,1500)}
418
490
  `:"")+`
419
- `),ty(n)}catch{}}function $s(t,e){try{return Ut.default.readFileSync(_a(t),"utf8").includes(`\xB7 ${e} \xB7`)}catch{return!1}}function ty(t){if(Ut.default.statSync(t).size<=Qg)return;let r=Ut.default.readFileSync(t,"utf8").slice(-ey),s=r.indexOf(`
420
- ## `),i=s===-1?r:r.slice(s+1);Ut.default.writeFileSync(t,Su+`*(older entries were rotated out)*
491
+ `),Sy(n)}catch{}}function Ds(t,e){try{return Bt.default.readFileSync(Na(t),"utf8").includes(`\xB7 ${e} \xB7`)}catch{return!1}}function Sy(t){if(Bt.default.statSync(t).size<=ky)return;let r=Bt.default.readFileSync(t,"utf8").slice(-_y),s=r.indexOf(`
492
+ ## `),i=s===-1?r:r.slice(s+1);Bt.default.writeFileSync(t,ju+`*(older entries were rotated out)*
421
493
 
422
- `+i)}function Tu(t){try{return Ut.default.readFileSync(_a(t),"utf8")}catch{return null}}var ny=`# Security baseline - what to check in any repo
494
+ `+i)}function Ou(t){try{return Bt.default.readFileSync(Na(t),"utf8")}catch{return null}}var Ty=`# Security baseline - what to check in any repo
423
495
 
424
496
  Every rule has a stable id. Findings must cite the id they violate.
425
497
 
@@ -462,7 +534,7 @@ Every rule has a stable id. Findings must cite the id they violate.
462
534
  - **SEC-042** TLS/redirect handling that downgrades to http.
463
535
 
464
536
  Prioritize by real exploitability in THIS codebase, not by rule order.
465
- `,ry=`# Test gaps - what to check in any repo
537
+ `,xy=`# Test gaps - what to check in any repo
466
538
 
467
539
  Every rule has a stable id. Findings must cite the id they violate.
468
540
 
@@ -492,7 +564,7 @@ Every rule has a stable id. Findings must cite the id they violate.
492
564
  flaky suspects.
493
565
 
494
566
  Report the GAP and why it is risky here, not generic coverage philosophy.
495
- `,sy=`# GDPR readiness - data-protection audit for repos with EU exposure
567
+ `,Ey=`# GDPR readiness - data-protection audit for repos with EU exposure
496
568
 
497
569
  FIRST decide exposure: if this product clearly has no EU users, no personal
498
570
  data, or is a purely static/internal tool, say so in ONE summary sentence and
@@ -536,7 +608,7 @@ rules below. Cite the rule id AND map the area to the closest GDPR article
536
608
 
537
609
  Severity: many users' data exposed or a missing legal-basis mechanism is
538
610
  high/critical; hygiene and documentation gaps are medium/low.
539
- `,iy=`# Architecture health - is this repository structurally sound?
611
+ `,Ry=`# Architecture health - is this repository structurally sound?
540
612
 
541
613
  Every rule has a stable id. Findings must cite the id they violate. Judge
542
614
  against what THIS codebase is trying to be (a static site does not need
@@ -575,7 +647,7 @@ deviations.
575
647
 
576
648
  Summarize with an overall verdict: is this repository HEALTHY for its
577
649
  purpose, and what are the 2-3 structural moves with the best payoff?
578
- `,xu={security:[{name:"baseline.md",content:ny},{name:"gdpr.md",content:sy}],testing:[{name:"test-gaps.md",content:ry}],architecture:[{name:"architecture-health.md",content:iy}],implement:[]},oy=["You are auditing code you can READ but never run or change.","You are auditing test coverage by READING code and tests","\\`area\\`"];function Sa(t){return _t.default.join(ie(),"knowledge",t)}function Ru(t,e){return _t.default.join(t,".ticketpilot","knowledge",`${e}.md`)}function Ta(t,e){return _t.default.join(t,".ticketpilot","lessons",`${e}.md`)}function Iu(t,e){let n=[],r=Sa(t),s=[];if(je.default.existsSync(r)){for(let c of je.default.readdirSync(r)){if(!c.endsWith(".md"))continue;let u=_t.default.join(r,c),p=je.default.readFileSync(u,"utf8");if(oy.some(f=>p.includes(f))&&xu[t].map(b=>b.name).includes(c)&&!p.includes("SEC-0")&&!p.includes("TEST-0")&&!p.includes("GDPR-0")){je.default.rmSync(u);continue}s.push(c)}s.sort()}let i=new Set(s);for(let c of xu[t])i.has(c.name)||n.push({level:"global",source:"pack",name:c.name,content:c.content,editable:!1});for(let c of s)n.push({level:"org",source:"pack",name:c,content:je.default.readFileSync(_t.default.join(r,c),"utf8").slice(0,3e4),editable:!0});let o=Ru(e,t);je.default.existsSync(o)&&n.push({level:"project",source:"pack",name:`${t}.md`,content:je.default.readFileSync(o,"utf8").slice(0,3e4),editable:!0});let l=Ta(e,t);return je.default.existsSync(l)&&n.push({level:"project",source:"lessons",name:`${t}.md`,content:je.default.readFileSync(l,"utf8").slice(0,2e4),editable:!0}),n}function Ni(t,e){let n=Iu(t,e);return{packs:n.filter(r=>r.source==="pack").map(r=>({name:`${r.level}/${r.name}`,content:r.content})),lessons:n.find(r=>r.source==="lessons")?.content??"",layers:n}}function xa(t,e,n,r="project"){let s=r==="org"?_t.default.join(Sa(e),"org-lessons.md"):Ta(t,e);je.default.mkdirSync(_t.default.dirname(s),{recursive:!0});let i=je.default.existsSync(s)?"":`# ${e} lessons (${r} level)
650
+ `,Mu={security:[{name:"baseline.md",content:Ty},{name:"gdpr.md",content:Ey}],testing:[{name:"test-gaps.md",content:xy}],architecture:[{name:"architecture-health.md",content:Ry}],implement:[]},Iy=["You are auditing code you can READ but never run or change.","You are auditing test coverage by READING code and tests","\\`area\\`"];function ja(t){return Tt.default.join(ie(),"knowledge",t)}function Du(t,e){return Tt.default.join(t,".ticketpilot","knowledge",`${e}.md`)}function Oa(t,e){return Tt.default.join(t,".ticketpilot","lessons",`${e}.md`)}function Lu(t,e){let n=[],r=ja(t),s=[];if(je.default.existsSync(r)){for(let c of je.default.readdirSync(r)){if(!c.endsWith(".md"))continue;let u=Tt.default.join(r,c),p=je.default.readFileSync(u,"utf8");if(Iy.some(f=>p.includes(f))&&Mu[t].map(b=>b.name).includes(c)&&!p.includes("SEC-0")&&!p.includes("TEST-0")&&!p.includes("GDPR-0")){je.default.rmSync(u);continue}s.push(c)}s.sort()}let i=new Set(s);for(let c of Mu[t])i.has(c.name)||n.push({level:"global",source:"pack",name:c.name,content:c.content,editable:!1});for(let c of s)n.push({level:"org",source:"pack",name:c,content:je.default.readFileSync(Tt.default.join(r,c),"utf8").slice(0,3e4),editable:!0});let o=Du(e,t);je.default.existsSync(o)&&n.push({level:"project",source:"pack",name:`${t}.md`,content:je.default.readFileSync(o,"utf8").slice(0,3e4),editable:!0});let l=Oa(e,t);return je.default.existsSync(l)&&n.push({level:"project",source:"lessons",name:`${t}.md`,content:je.default.readFileSync(l,"utf8").slice(0,2e4),editable:!0}),n}function qi(t,e){let n=Lu(t,e);return{packs:n.filter(r=>r.source==="pack").map(r=>({name:`${r.level}/${r.name}`,content:r.content})),lessons:n.find(r=>r.source==="lessons")?.content??"",layers:n}}function Ma(t,e,n,r="project"){let s=r==="org"?Tt.default.join(ja(e),"org-lessons.md"):Oa(t,e);je.default.mkdirSync(Tt.default.dirname(s),{recursive:!0});let i=je.default.existsSync(s)?"":`# ${e} lessons (${r} level)
579
651
 
580
652
  Human-confirmed corrections and rules. `+(e==="implement"?`Every implement run on this repo reads this BEFORE starting work.
581
653
 
@@ -583,47 +655,47 @@ Human-confirmed corrections and rules. `+(e==="implement"?`Every implement run o
583
655
 
584
656
  `);je.default.appendFileSync(s,i+n.trimEnd()+`
585
657
 
586
- `)}function Au(t,e,n,r){let s=new Date().toISOString().slice(0,10),i=t.evidence[0]?` (${t.evidence[0].file}${t.evidence[0].line?`:${t.evidence[0].line}`:""})`:"",o=t.ruleId?` \xB7 rule ${t.ruleId}`:"";return`## ${s} \xB7 ${e}${o} \xB7 ${t.title}${i}
658
+ `)}function Uu(t,e,n,r){let s=new Date().toISOString().slice(0,10),i=t.evidence[0]?` (${t.evidence[0].file}${t.evidence[0].line?`:${t.evidence[0].line}`:""})`:"",o=t.ruleId?` \xB7 rule ${t.ruleId}`:"";return`## ${s} \xB7 ${e}${o} \xB7 ${t.title}${i}
587
659
  Finding \`${t.id}\` [${t.severity}] was marked **${e}**`+(r?` by ${r}`:"")+`.${n?` Reason: ${n}`:""}
588
- `+(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 Cu(t,e){return`## ${new Date().toISOString().slice(0,10)} \xB7 taught${e?` by ${e}`:""}
589
- ${t.trim()}`}function $u(t){let e=[];for(let r of Eu.KnowledgeRole.options)for(let s of Iu(r,t))e.push({role:r,...s});let n=Tu(t);return n&&e.push({role:"implement",level:"project",source:"memory",name:"incidents.md",content:n.slice(-3e4),editable:!1}),e}function Pu(t,e,n,r,s,i){if(!/^[a-zA-Z0-9._-]+\.md$/.test(s))throw new Error("file name must be a simple .md name");let o=n==="org"?_t.default.join(Sa(e),s):r==="lessons"?Ta(t,e):Ru(t,e);je.default.mkdirSync(_t.default.dirname(o),{recursive:!0}),je.default.writeFileSync(o,i,{mode:n==="org"?384:420})}var Ea=()=>new Date().toISOString(),y={info:t=>console.log(`${Ea()} [info] ${t}`),warn:t=>console.warn(`${Ea()} [warn] ${t}`),error:t=>console.error(`${Ea()} [error] ${t}`)};var ju=require("node:child_process"),Nu=R(require("node:fs"),1),Ou=R(require("node:path"),1);function es(t){for(let e of["TEST.md","TESTING.md","docs/TEST.md"]){let n=Ou.default.join(t,e);if(Nu.default.existsSync(n))return n}return null}var ay=/(^|\n)\s*(if|for|while|case|until)\s|\{\s*$|\)\s*\{|<<[-~]?\s*['"]?\w+|\\\s*$/;function ts(t){let e=[];for(let n of t.matchAll(/```(?:bash|sh|shell)?\s*\n([\s\S]*?)```/g)){let r=n[1],s=r.split(`
590
- `).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#"));if(s.length){if(ay.test(r)){e.push(r.trim());continue}e.push(...s)}}return e.slice(0,10)}async function or(t,e,n={}){let r=[],s=n.perCommandTimeoutMs??6e5;for(let i of e){n.onProgress?.(`running: ${i}`);let o=Date.now(),l=await new Promise(c=>{let u=(0,ju.spawn)("bash",["-lc",i],{cwd:t,env:{...process.env,CI:"1",FORCE_COLOR:"0"}}),p="",f=v=>{p+=v.toString(),p.length>2e5&&(p=p.slice(-1e5))};u.stdout.on("data",f),u.stderr.on("data",f);let b=setTimeout(()=>{u.kill("SIGKILL"),p+=`
591
- [killed: timed out]`},s);u.on("close",v=>{clearTimeout(b),c({command:i,exitCode:v??-1,durationMs:Date.now()-o,tail:p.slice(-4e3)})}),u.on("error",v=>{clearTimeout(b),c({command:i,exitCode:-1,durationMs:Date.now()-o,tail:String(v)})})});n.onProgress?.(`exit ${l.exitCode} in ${Math.round(l.durationMs/1e3)}s: ${i}`),r.push(l)}return r}async function ns(t){let{packs:e,lessons:n}=Ni(t.role,t.repoPath);if(!e.length)return{ok:!1,error:`no knowledge packs found for the ${t.role} role - add markdown files under ~/.config/ticketpilot/knowledge/${t.role}/ on the runner`};let r="";if(t.scope.kind==="ticket"&&t.scope.ref){let b=t.scope.ref,v="";try{let x=await t.jira.getIssue(b);v=`Ticket ${b}: ${x.summary}
660
+ `+(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(t,e){return`## ${new Date().toISOString().slice(0,10)} \xB7 taught${e?` by ${e}`:""}
661
+ ${t.trim()}`}function Fu(t){let e=[];for(let r of zu.KnowledgeRole.options)for(let s of Lu(r,t))e.push({role:r,...s});let n=Ou(t);return n&&e.push({role:"implement",level:"project",source:"memory",name:"incidents.md",content:n.slice(-3e4),editable:!1}),e}function Bu(t,e,n,r,s,i){if(!/^[a-zA-Z0-9._-]+\.md$/.test(s))throw new Error("file name must be a simple .md name");let o=n==="org"?Tt.default.join(ja(e),s):r==="lessons"?Oa(t,e):Du(t,e);je.default.mkdirSync(Tt.default.dirname(o),{recursive:!0}),je.default.writeFileSync(o,i,{mode:n==="org"?384:420})}Kt();var Ku=require("node:child_process"),Hu=R(require("node:fs"),1),Gu=R(require("node:path"),1);function os(t){for(let e of["TEST.md","TESTING.md","docs/TEST.md"]){let n=Gu.default.join(t,e);if(Hu.default.existsSync(n))return n}return null}var Ay=/(^|\n)\s*(if|for|while|case|until)\s|\{\s*$|\)\s*\{|<<[-~]?\s*['"]?\w+|\\\s*$/;function as(t){let e=[];for(let n of t.matchAll(/```(?:bash|sh|shell)?\s*\n([\s\S]*?)```/g)){let r=n[1],s=r.split(`
662
+ `).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#"));if(s.length){if(Ay.test(r)){e.push(r.trim());continue}e.push(...s)}}return e.slice(0,10)}async function hr(t,e,n={}){let r=[],s=n.perCommandTimeoutMs??6e5;for(let i of e){n.onProgress?.(`running: ${i}`);let o=Date.now(),l=await new Promise(c=>{let u=(0,Ku.spawn)("bash",["-lc",i],{cwd:t,env:{...process.env,CI:"1",FORCE_COLOR:"0"}}),p="",f=v=>{p+=v.toString(),p.length>2e5&&(p=p.slice(-1e5))};u.stdout.on("data",f),u.stderr.on("data",f);let b=setTimeout(()=>{u.kill("SIGKILL"),p+=`
663
+ [killed: timed out]`},s);u.on("close",v=>{clearTimeout(b),c({command:i,exitCode:v??-1,durationMs:Date.now()-o,tail:p.slice(-4e3)})}),u.on("error",v=>{clearTimeout(b),c({command:i,exitCode:-1,durationMs:Date.now()-o,tail:String(v)})})});n.onProgress?.(`exit ${l.exitCode} in ${Math.round(l.durationMs/1e3)}s: ${i}`),r.push(l)}return r}async function ls(t){let{packs:e,lessons:n}=qi(t.role,t.repoPath);if(!e.length)return{ok:!1,error:`no knowledge packs found for the ${t.role} role - add markdown files under ~/.config/ticketpilot/knowledge/${t.role}/ on the runner`};let r="";if(t.scope.kind==="ticket"&&t.scope.ref){let b=t.scope.ref,v="";try{let x=await t.jira.getIssue(b);v=`Ticket ${b}: ${x.summary}
592
664
 
593
- ${x.description}`.slice(0,4e3)}catch{v=`Ticket ${b} (could not fetch its text from Jira).`}let _=await sa(t.repoPath,b).catch(()=>null);if(_){let{base:x,stat:$,diff:j}=await Ai(t.repoPath,_).catch(()=>({base:"",stat:"",diff:""}));r=`${v}
665
+ ${x.description}`.slice(0,4e3)}catch{v=`Ticket ${b} (could not fetch its text from Jira).`}let w=await ma(t.repoPath,b).catch(()=>null);if(w){let{base:x,stat:$,diff:N}=await Mi(t.repoPath,w).catch(()=>({base:"",stat:"",diff:""}));r=`${v}
594
666
 
595
- Its implementation branch \`${_}\` vs \`${x}\`:
667
+ Its implementation branch \`${w}\` vs \`${x}\`:
596
668
  \`\`\`
597
669
  ${$}\`\`\`
598
670
  \`\`\`diff
599
- ${j}
671
+ ${N}
600
672
  \`\`\``}else r=`${v}
601
673
 
602
- No implementation branch found for ${b} - audit the parts of the codebase this ticket touches or would touch.`}else if(t.scope.kind==="branch"&&t.scope.ref){let{base:b,stat:v,diff:_}=await Ai(t.repoPath,t.scope.ref);r=`The diff of \`${t.scope.ref}\` vs \`${b}\`:
674
+ No implementation branch found for ${b} - audit the parts of the codebase this ticket touches or would touch.`}else if(t.scope.kind==="branch"&&t.scope.ref){let{base:b,stat:v,diff:w}=await Mi(t.repoPath,t.scope.ref);r=`The diff of \`${t.scope.ref}\` vs \`${b}\`:
603
675
  \`\`\`
604
676
  ${v}\`\`\`
605
677
  \`\`\`diff
606
- ${_}
607
- \`\`\``}let s,i;if(t.role==="testing"){let b=es(t.repoPath),v=b?ts(Mu.default.readFileSync(b,"utf8")):[];v.length&&(y.info(`Audit (testing): executing ${v.length} TEST.md command(s)`),i=await or(t.repoPath,v,{onProgress:_=>y.info(`[test-run] ${_}`)}),s=i.map(_=>`$ ${_.command}
608
- (exit ${_.exitCode}, ${Math.round(_.durationMs/1e3)}s)
609
- ${_.tail.slice(-2e3)}`).join(`
678
+ ${w}
679
+ \`\`\``}let s,i;if(t.role==="testing"){let b=os(t.repoPath),v=b?as(Zu.default.readFileSync(b,"utf8")):[];v.length&&(y.info(`Audit (testing): executing ${v.length} TEST.md command(s)`),i=await hr(t.repoPath,v,{onProgress:w=>y.info(`[test-run] ${w}`)}),s=i.map(w=>`$ ${w.command}
680
+ (exit ${w.exitCode}, ${Math.round(w.durationMs/1e3)}s)
681
+ ${w.tail.slice(-2e3)}`).join(`
610
682
 
611
683
  ---
612
684
 
613
- `))}let o=t.model||t.agent.adapter.deepModel,l=t.detailLevel??"technical",c=await t.agent.adapter.run({repoPath:t.repoPath,prompt:hu(t.role,e,n,{scopeNote:r,testResults:s,detailLevel:l}),timeoutSeconds:480,bin:t.agent.bin,mode:"read_only",maxTurns:120,sessionId:(0,Ra.randomUUID)(),model:o,onLog:(b,v)=>{b==="agent"&&y.info(`[audit:${t.role}] ${v.slice(0,160)}`)}}),u=pu(c.resultText);if("error"in u)return{ok:!1,error:u.error};let p=fu(t.repoPath,u.findings);for(let b of p.droppedFindings)y.warn(`[audit:${t.role}] dropped "${b.title}" - cited files do not exist: `+b.files.join(", "));let f={id:(0,Ra.randomUUID)(),role:t.role,createdAt:new Date().toISOString(),model:c.model||o,summary:u.summary,packNames:e.map(b=>b.name),findings:p.findings,costUsd:c.costUsd??0,ticketed:{},verdicts:{},lessonsWritten:[],scope:t.scope,detailLevel:l,...i?{testRun:i}:{}};return bu(t.projectId,f),y.info(`Audit (${t.role}${t.scope.kind!=="repo"?` \xB7 ${t.scope.kind}:${t.scope.ref}`:""}) done: ${p.findings.length} finding(s)`+(u.dropped?`, ${u.dropped} malformed`:"")+(p.droppedFindings.length?`, ${p.droppedFindings.length} dropped for citing files that do not exist`:"")+(p.correctedLines?`, ${p.correctedLines} bad line number(s) stripped`:"")),{ok:!0,audit:f}}var fn=R(ke(),1);var Da=R(require("node:fs"),1),Bi=R(require("node:path"),1),Ki=require("node:crypto"),we=R(ke(),1);var ar=R(ke(),1);var Ia=R(require("node:fs"),1),zu=R(require("node:os"),1),Mi=R(require("node:path"),1),Du=require("node:child_process"),Lu=R(require("node:readline"),1),Uu=R(ke(),1);function Oi(t){return`
685
+ `))}let o=t.model||t.agent.adapter.deepModel,l=t.detailLevel??"technical",c=await t.agent.adapter.run({repoPath:t.repoPath,prompt:Su(t.role,e,n,{scopeNote:r,testResults:s,detailLevel:l}),timeoutSeconds:480,bin:t.agent.bin,mode:"read_only",maxTurns:120,sessionId:(0,Da.randomUUID)(),model:o,onLog:(b,v)=>{b==="agent"&&y.info(`[audit:${t.role}] ${v.slice(0,160)}`)}}),u=Tu(c.resultText);if("error"in u)return{ok:!1,error:u.error};let p=xu(t.repoPath,u.findings);for(let b of p.droppedFindings)y.warn(`[audit:${t.role}] dropped "${b.title}" - cited files do not exist: `+b.files.join(", "));let f={id:(0,Da.randomUUID)(),role:t.role,createdAt:new Date().toISOString(),model:c.model||o,summary:u.summary,packNames:e.map(b=>b.name),findings:p.findings,costUsd:c.costUsd??0,ticketed:{},verdicts:{},lessonsWritten:[],scope:t.scope,detailLevel:l,...i?{testRun:i}:{}};return Au(t.projectId,f),y.info(`Audit (${t.role}${t.scope.kind!=="repo"?` \xB7 ${t.scope.kind}:${t.scope.ref}`:""}) done: ${p.findings.length} finding(s)`+(u.dropped?`, ${u.dropped} malformed`:"")+(p.droppedFindings.length?`, ${p.droppedFindings.length} dropped for citing files that do not exist`:"")+(p.correctedLines?`, ${p.correctedLines} bad line number(s) stripped`:"")),{ok:!0,audit:f}}var vn=R(_e(),1);var Wa=R(require("node:fs"),1),Yi=R(require("node:path"),1),Ji=require("node:crypto"),we=R(_e(),1);var pr=R(_e(),1);var La=R(require("node:fs"),1),Vu=R(require("node:os"),1),Bi=R(require("node:path"),1),Wu=require("node:child_process"),Yu=R(require("node:readline"),1),Ju=R(_e(),1);function Fi(t){return`
614
686
 
615
687
  YOUR CAPABILITIES IN THIS RUN - state them accurately, never guess:
616
688
  - You CANNOT run shell commands, install anything, restart services, touch a database, or reach any machine. There is no shell tool here and asking for permission will not create one.
617
689
  `+(t==="edit_no_shell"?`- You CAN read files and CREATE or EDIT files inside this working directory.
618
690
  `:`- You can ONLY read: Read, Glob and Grep inside this working directory. You cannot create or change a single file.
619
- `)+'NEVER offer to do something outside this list, and never ask "shall I do X?" when X is outside it - offering it and then failing costs the person a whole turn and their trust. Say plainly what you cannot do here, then name the route that CAN do it (a ticket, an implement run, or a command for a human to run).'}var ly=4e3,cy={read_only:["Read(./**)","Glob(./**)","Grep(./**)"],edit_no_shell:["Read(./**)","Glob(./**)","Grep(./**)","Edit(./**)","Write(./**)"]};function uy(t){if(process.env.ANTHROPIC_API_KEY)return"API key";let e=t??Mi.default.join(zu.default.homedir(),".claude");try{if(Ia.default.existsSync(Mi.default.join(e,".credentials.json"))||Ia.default.existsSync(Mi.default.join(e,"credentials.json")))return"subscription"}catch{}return"unknown"}async function dy(t){let e=["-p","--output-format","stream-json","--verbose","--allowedTools",cy[t.mode].join(","),"--max-turns",String(t.maxTurns??60),...t.model?["--model",t.model]:[],...t.resume?["--resume",t.sessionId]:["--session-id",t.sessionId]],n=uy(t.configDir);return n!=="unknown"&&t.onLog("info",n==="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,Du.spawn)(t.bin,e,{cwd:t.repoPath,env:t.configDir?{...process.env,CLAUDE_CONFIG_DIR:t.configDir}:process.env,stdio:["pipe","pipe","pipe"]}),i={ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,billingMode:n==="subscription"?"subscription":n==="API key"?"api":"unknown"},o=0,l=0,c=0,u=0,p=0,f=()=>{if(!t.onUsage)return;let S=Date.now();S-p<ly||(p=S,t.onUsage({inputTokens:l,outputTokens:c,cacheReadTokens:u,turns:o}))},b=!1,v=()=>{b||(b=!0,clearTimeout(x),t.signal?.removeEventListener("abort",_),r(i))},_=()=>{i.cancelled=!0,i.error="stopped from the dashboard",t.onLog("error",i.error),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),3e3).unref()};t.signal?.addEventListener("abort",_,{once:!0});let x=setTimeout(()=>{i.timedOut=!0,i.error=`run exceeded ${t.timeoutSeconds}s wall-clock limit`,t.onLog("error",i.error),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),5e3).unref()},t.timeoutSeconds*1e3);s.stdin.write(t.prompt+Oi(t.mode)),s.stdin.end(),Lu.default.createInterface({input:s.stdout}).on("line",S=>{if(!S.trim())return;let G;try{G=JSON.parse(S)}catch{t.onLog("agent",S.slice(0,1e3));return}if(G.type==="system"&&G.subtype==="init")i.model=typeof G.model=="string"?G.model:void 0,t.onLog("info",`Claude Code session started (model: ${G.model??"default"})`);else if(G.type==="assistant"){o+=1;let O=G.message?.usage;O&&(l+=Number(O.input_tokens??0)+Number(O.cache_creation_input_tokens??0),c+=Number(O.output_tokens??0),u+=Number(O.cache_read_input_tokens??0),f());for(let M of G.message?.content??[])if(M.type==="text"&&M.text?.trim())t.onLog("agent",M.text.trim().slice(0,4e3));else if(M.type==="tool_use"){let W=M.input??{},d=["file_path","path","pattern","command","description","url"].map(g=>typeof W[g]=="string"?`${g}=${W[g]}`:null).filter(Boolean).join(" "),m=JSON.stringify(W).slice(0,400);t.onLog("info",`tool ${M.name} ${d?`${d} `:""}${m}`)}}else G.type==="result"&&(i.costUsd=Number(G.total_cost_usd??0),i.inputTokens=Number(G.usage?.input_tokens??0)+Number(G.usage?.cache_creation_input_tokens??0),i.outputTokens=Number(G.usage?.output_tokens??0),l=Math.max(i.inputTokens,l),c=Math.max(i.outputTokens,c),i.inputTokens=l,i.outputTokens=c,u=Number(G.usage?.cache_read_input_tokens??u),i.cacheReadTokens=u,t.onUsage&&(t.onUsage({inputTokens:l,outputTokens:c,cacheReadTokens:u,costUsd:i.costUsd,turns:o}),p=Date.now()),G.subtype==="success"&&!G.is_error?(i.ok=!0,i.resultText=String(G.result??"")):G.subtype==="error_max_turns"?(i.turnLimitHit=!0,i.error=`hit the ${t.maxTurns??60}-turn limit before finishing`):(i.error=String(G.result??G.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 j="";s.stderr.on("data",S=>{j=(j+S.toString()).slice(-2e3)}),s.on("error",S=>{i.error=`failed to start ${t.bin}: ${S.message}`,t.onLog("error",i.error),v()}),s.on("close",S=>{!i.ok&&!i.error&&(i.error=i.timedOut?i.error:`claude exited with code ${S}${j?`: ${j.slice(-500)}`:""}`),v()})})}var zi={id:"claude-code",displayName:"Claude Code",fastModel:"claude-sonnet-5",deepModel:"claude-fable-5",capabilities:Uu.REGISTERED_AGENTS.find(t=>t.id==="claude-code").capabilities,run:dy};var qu=require("node:child_process"),Fu=R(require("node:readline"),1),Bu=R(ke(),1);async function hy(t){if(t.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(t.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",t.repoPath,...t.model?["--model",t.model]:[],"-"];return new Promise(n=>{let r=(0,qu.spawn)(t.bin,e,{cwd:t.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(c),n(s))},c=setTimeout(()=>{s.timedOut=!0,s.error=`run exceeded ${t.timeoutSeconds}s wall-clock limit`,t.onLog("error",s.error),r.kill("SIGTERM"),setTimeout(()=>r.kill("SIGKILL"),5e3).unref()},t.timeoutSeconds*1e3);r.stdin.write(t.prompt+Oi(t.mode)),r.stdin.end(),Fu.default.createInterface({input:r.stdout}).on("line",f=>{if(!f.trim())return;let b;try{b=JSON.parse(f)}catch{t.onLog("agent",f.slice(0,1e3));return}let v=b.item??b.msg??b,_=v?.type??b.type,x=v?.text??v?.message??"";_==="agent_message"&&typeof x=="string"&&x.trim()?(i=x,t.onLog("agent",x.trim().slice(0,4e3))):_==="command_execution"||_==="exec_command_begin"?t.onLog("info",`tool ${String(v?.command??"").slice(0,300)}`):_==="error"&&typeof x=="string"&&x&&t.onLog("error",x.slice(0,1e3))});let p="";r.stderr.on("data",f=>{p=(p+f.toString()).slice(-2e3)}),r.on("error",f=>{s.error=`failed to start ${t.bin}: ${f.message} - is the Codex CLI installed and logged in?`,t.onLog("error",s.error),l()}),r.on("close",f=>{f===0&&i.trim()?(s.ok=!0,s.resultText=i):s.error||(s.error=`codex exited with code ${f}`+(i?"":" and produced no answer")+(p?`: ${p.slice(-500)}`:"")),l()})})}var Aa={id:"codex",fastModel:"",deepModel:"",displayName:"OpenAI Codex CLI (experimental)",capabilities:Bu.REGISTERED_AGENTS.find(t=>t.id==="codex").capabilities,run:hy};var py={[zi.id]:zi,[Aa.id]:Aa};function Be(t){return py[t||ar.DEFAULT_AGENT_ID]??null}function Ue(t,e){return!e||e===zi.id?t.claudeBin:t.agents[e]?.bin??e}function pn(t,e){let n=Be(t);if(!n)return`no agent adapter named "${t}" on this runner - update the runner, or set the rule's agent to "${ar.DEFAULT_AGENT_ID}"`;let r=(0,ar.missingAgentCapabilities)(n.id,e);return r&&r.length?`agent "${n.displayName}" cannot run ${e} rules: it cannot guarantee ${r.join(", ")}. Allwright refuses rather than weakening the isolation silently.`:null}function Ke(t,e,n){let r=e.defaultAgent||ar.DEFAULT_AGENT_ID,s=Be(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,ar.missingAgentCapabilities)(s.id,n);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:Ue(t,s.id)}}function qt(t,e){return t.replace(/\{\{(\w+)\}\}/g,(n,r)=>r in e?e[r]:n)}var ed=R(ke(),1);ut();sr();wt();var Ne=R(require("node:fs"),1),rs=R(require("node:path"),1);var my=w.object({runId:w.string(),issueKey:w.string(),repoName:w.string(),owner:w.string(),repo:w.string(),prNumber:w.number().int(),prUrl:w.string(),branch:w.string(),headSha:w.string(),doneLabel:w.string(),failedLabel:w.string(),jiraTransition:w.string().optional(),mergeOnApprove:w.boolean().default(!1),mergeMethod:w.enum(["squash","merge","rebase"]).default("squash"),autoMerge:w.boolean().default(!1),nextDecisionSeq:w.number().int().default(1e5),changesRequestedNotified:w.boolean().optional(),conflictNotified:w.boolean().optional(),agentConfigDir:w.string().optional()}),gy=w.record(my),yy=w.object({runId:w.string(),issueKey:w.string(),issueSummary:w.string().default(""),projectId:w.string(),repoName:w.string(),environmentName:w.string(),requestedBy:w.string().default(""),createdAt:w.string()}),by=w.record(yy),vy=w.object({runId:w.string(),issueKey:w.string(),kind:w.enum(["plan","implement"]),repoPath:w.string(),sessionId:w.string(),doneLabel:w.string(),failedLabel:w.string(),timeoutSeconds:w.number(),createdAt:w.string(),questionsPostedAt:w.string(),rounds:w.number().int().default(1),nextLogSeq:w.number().int().nonnegative().default(0),baseRepoPath:w.string().optional(),repoName:w.string().optional(),branch:w.string().optional(),baseBranch:w.string().optional(),jiraTransition:w.string().optional(),jiraTransitionOnMerge:w.string().optional(),requireApproval:w.boolean().optional(),maxTurns:w.number().int().optional(),runTests:w.boolean().default(!0),mergeOnApprove:w.boolean().default(!1),mergeMethod:w.enum(["squash","merge","rebase"]).default("squash"),autoMerge:w.boolean().default(!1),issueSummary:w.string().default(""),claudeConfigDir:w.string().optional(),agent:w.string().optional(),model:w.string().optional(),actorEmail:w.string().optional()}),wy=w.object({runId:w.string(),issueKey:w.string(),issueSummary:w.string().default(""),repoName:w.string(),baseRepoPath:w.string(),branch:w.string(),baseBranch:w.string(),headSha:w.string(),requireApproval:w.boolean(),mergeOnApprove:w.boolean().default(!1),mergeMethod:w.enum(["squash","merge","rebase"]).default("squash"),autoMerge:w.boolean().default(!1),doneLabel:w.string(),failedLabel:w.string(),jiraTransition:w.string().optional(),jiraTransitionOnMerge:w.string().optional(),actorEmail:w.string().optional(),resultSummary:w.string().default(""),prSummary:w.string().default(""),costUsd:w.number().default(0),nextLogSeq:w.number().int().default(1e5),createdAt:w.string()}),ky=w.record(wy),_y=w.object({runId:w.string(),issueKey:w.string(),repoName:w.string(),owner:w.string(),repo:w.string(),prNumber:w.number().int(),prUrl:w.string(),jiraTransitionOnMerge:w.string().default(""),createdAt:w.string()}),Sy=w.record(_y),Ty=w.record(vy);function Ku(){return rs.default.join(ie(),"pending-runs.json")}function Ca(){return rs.default.join(ie(),"pending-deploys.json")}function $a(){return rs.default.join(ie(),"pending-inputs.json")}function Pa(){return rs.default.join(ie(),"merge-watch.json")}function ja(){return rs.default.join(ie(),"pending-pushes.json")}function Na(){let t=ja();if(!Ne.default.existsSync(t))return{};try{return ky.parse(JSON.parse(Ne.default.readFileSync(t,"utf8")))}catch{return{}}}function Di(t){let e=Na();e[t.runId]=t,Ft(ja(),e)}function Li(t){return Na()[t]??null}function Oa(t){let e=Na();t in e&&(delete e[t],Ft(ja(),e))}function Ui(){let t=Pa();if(!Ne.default.existsSync(t))return{};try{return Sy.parse(JSON.parse(Ne.default.readFileSync(t,"utf8")))}catch{return{}}}function Hu(t){let e=Ui();e[t.runId]=t,Ft(Pa(),e)}function Ps(t){let e=Ui();t in e&&(delete e[t],Ft(Pa(),e))}function js(){let t=Ku();if(!Ne.default.existsSync(t))return{};try{return gy.parse(JSON.parse(Ne.default.readFileSync(t,"utf8")))}catch{return{}}}function Ft(t,e){Ne.default.mkdirSync(ie(),{recursive:!0,mode:448});let n=t+".tmp";Ne.default.writeFileSync(n,JSON.stringify(e,null,2)+`
620
- `,{mode:384}),Ne.default.renameSync(n,t),Ne.default.chmodSync(t,384)}function Gu(t){Ft(Ku(),t)}function dt(t){let e=js();e[t.runId]=t,Gu(e)}function ss(t){return js()[t]??null}function cr(t){let e=js();t in e&&(delete e[t],Gu(e))}function Ma(){let t=Ca();if(!Ne.default.existsSync(t))return{};try{return by.parse(JSON.parse(Ne.default.readFileSync(t,"utf8")))}catch{return{}}}function Zu(t){let e=Ma();e[t.runId]=t,Ft(Ca(),e)}function qi(t){return Ma()[t]??null}function Fi(t){let e=Ma();t in e&&(delete e[t],Ft(Ca(),e))}function ur(){let t=$a();if(!Ne.default.existsSync(t))return{};try{return Ty.parse(JSON.parse(Ne.default.readFileSync(t,"utf8")))}catch{return{}}}function Vu(t){let e=ur();e[t.runId]=t,Ft($a(),e)}function Wu(t){return ur()[t]??null}function St(t){let e=ur();t in e&&(delete e[t],Ft($a(),e))}var xy=`
691
+ `)+'NEVER offer to do something outside this list, and never ask "shall I do X?" when X is outside it - offering it and then failing costs the person a whole turn and their trust. Say plainly what you cannot do here, then name the route that CAN do it (a ticket, an implement run, or a command for a human to run).'}var Cy=4e3,$y={read_only:["Read(./**)","Glob(./**)","Grep(./**)"],edit_no_shell:["Read(./**)","Glob(./**)","Grep(./**)","Edit(./**)","Write(./**)"]};function Py(t){if(process.env.ANTHROPIC_API_KEY)return"API key";let e=t??Bi.default.join(Vu.default.homedir(),".claude");try{if(La.default.existsSync(Bi.default.join(e,".credentials.json"))||La.default.existsSync(Bi.default.join(e,"credentials.json")))return"subscription"}catch{}return"unknown"}async function Ny(t){let e=["-p","--output-format","stream-json","--verbose","--allowedTools",$y[t.mode].join(","),"--max-turns",String(t.maxTurns??60),...t.model?["--model",t.model]:[],...t.resume?["--resume",t.sessionId]:["--session-id",t.sessionId]],n=Py(t.configDir);return n!=="unknown"&&t.onLog("info",n==="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,Wu.spawn)(t.bin,e,{cwd:t.repoPath,env:t.configDir?{...process.env,CLAUDE_CONFIG_DIR:t.configDir}:process.env,stdio:["pipe","pipe","pipe"]}),i={ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,billingMode:n==="subscription"?"subscription":n==="API key"?"api":"unknown"},o=0,l=0,c=0,u=0,p=0,f=()=>{if(!t.onUsage)return;let S=Date.now();S-p<Cy||(p=S,t.onUsage({inputTokens:l,outputTokens:c,cacheReadTokens:u,turns:o}))},b=!1,v=()=>{b||(b=!0,clearTimeout(x),t.signal?.removeEventListener("abort",w),r(i))},w=()=>{i.cancelled=!0,i.error="stopped from the dashboard",t.onLog("error",i.error),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),3e3).unref()};t.signal?.addEventListener("abort",w,{once:!0});let x=setTimeout(()=>{i.timedOut=!0,i.error=`run exceeded ${t.timeoutSeconds}s wall-clock limit`,t.onLog("error",i.error),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),5e3).unref()},t.timeoutSeconds*1e3);s.stdin.write(t.prompt+Fi(t.mode)),s.stdin.end(),Yu.default.createInterface({input:s.stdout}).on("line",S=>{if(!S.trim())return;let G;try{G=JSON.parse(S)}catch{t.onLog("agent",S.slice(0,1e3));return}if(G.type==="system"&&G.subtype==="init")i.model=typeof G.model=="string"?G.model:void 0,t.onLog("info",`Claude Code session started (model: ${G.model??"default"})`);else if(G.type==="assistant"){o+=1;let O=G.message?.usage;O&&(l+=Number(O.input_tokens??0)+Number(O.cache_creation_input_tokens??0),c+=Number(O.output_tokens??0),u+=Number(O.cache_read_input_tokens??0),f());for(let M of G.message?.content??[])if(M.type==="text"&&M.text?.trim())t.onLog("agent",M.text.trim().slice(0,4e3));else if(M.type==="tool_use"){let W=M.input??{},d=["file_path","path","pattern","command","description","url"].map(g=>typeof W[g]=="string"?`${g}=${W[g]}`:null).filter(Boolean).join(" "),m=JSON.stringify(W).slice(0,400);t.onLog("info",`tool ${M.name} ${d?`${d} `:""}${m}`)}}else G.type==="result"&&(i.costUsd=Number(G.total_cost_usd??0),i.inputTokens=Number(G.usage?.input_tokens??0)+Number(G.usage?.cache_creation_input_tokens??0),i.outputTokens=Number(G.usage?.output_tokens??0),l=Math.max(i.inputTokens,l),c=Math.max(i.outputTokens,c),i.inputTokens=l,i.outputTokens=c,u=Number(G.usage?.cache_read_input_tokens??u),i.cacheReadTokens=u,t.onUsage&&(t.onUsage({inputTokens:l,outputTokens:c,cacheReadTokens:u,costUsd:i.costUsd,turns:o}),p=Date.now()),G.subtype==="success"&&!G.is_error?(i.ok=!0,i.resultText=String(G.result??"")):G.subtype==="error_max_turns"?(i.turnLimitHit=!0,i.error=`hit the ${t.maxTurns??60}-turn limit before finishing`):(i.error=String(G.result??G.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 N="";s.stderr.on("data",S=>{N=(N+S.toString()).slice(-2e3)}),s.on("error",S=>{i.error=`failed to start ${t.bin}: ${S.message}`,t.onLog("error",i.error),v()}),s.on("close",S=>{!i.ok&&!i.error&&(i.error=i.timedOut?i.error:`claude exited with code ${S}${N?`: ${N.slice(-500)}`:""}`),v()})})}var Ki={id:"claude-code",displayName:"Claude Code",fastModel:"claude-sonnet-5",deepModel:"claude-fable-5",capabilities:Ju.REGISTERED_AGENTS.find(t=>t.id==="claude-code").capabilities,run:Ny};var Xu=require("node:child_process"),Qu=R(require("node:readline"),1),ed=R(_e(),1);async function jy(t){if(t.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(t.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",t.repoPath,...t.model?["--model",t.model]:[],"-"];return new Promise(n=>{let r=(0,Xu.spawn)(t.bin,e,{cwd:t.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(c),n(s))},c=setTimeout(()=>{s.timedOut=!0,s.error=`run exceeded ${t.timeoutSeconds}s wall-clock limit`,t.onLog("error",s.error),r.kill("SIGTERM"),setTimeout(()=>r.kill("SIGKILL"),5e3).unref()},t.timeoutSeconds*1e3);r.stdin.write(t.prompt+Fi(t.mode)),r.stdin.end(),Qu.default.createInterface({input:r.stdout}).on("line",f=>{if(!f.trim())return;let b;try{b=JSON.parse(f)}catch{t.onLog("agent",f.slice(0,1e3));return}let v=b.item??b.msg??b,w=v?.type??b.type,x=v?.text??v?.message??"";w==="agent_message"&&typeof x=="string"&&x.trim()?(i=x,t.onLog("agent",x.trim().slice(0,4e3))):w==="command_execution"||w==="exec_command_begin"?t.onLog("info",`tool ${String(v?.command??"").slice(0,300)}`):w==="error"&&typeof x=="string"&&x&&t.onLog("error",x.slice(0,1e3))});let p="";r.stderr.on("data",f=>{p=(p+f.toString()).slice(-2e3)}),r.on("error",f=>{s.error=`failed to start ${t.bin}: ${f.message} - is the Codex CLI installed and logged in?`,t.onLog("error",s.error),l()}),r.on("close",f=>{f===0&&i.trim()?(s.ok=!0,s.resultText=i):s.error||(s.error=`codex exited with code ${f}`+(i?"":" and produced no answer")+(p?`: ${p.slice(-500)}`:"")),l()})})}var Ua={id:"codex",fastModel:"",deepModel:"",displayName:"OpenAI Codex CLI (experimental)",capabilities:ed.REGISTERED_AGENTS.find(t=>t.id==="codex").capabilities,run:jy};var Oy={[Ki.id]:Ki,[Ua.id]:Ua};function Ke(t){return Oy[t||pr.DEFAULT_AGENT_ID]??null}function qe(t,e){return!e||e===Ki.id?t.claudeBin:t.agents[e]?.bin??e}function bn(t,e){let n=Ke(t);if(!n)return`no agent adapter named "${t}" on this runner - update the runner, or set the rule's agent to "${pr.DEFAULT_AGENT_ID}"`;let r=(0,pr.missingAgentCapabilities)(n.id,e);return r&&r.length?`agent "${n.displayName}" cannot run ${e} rules: it cannot guarantee ${r.join(", ")}. Allwright refuses rather than weakening the isolation silently.`:null}function He(t,e,n){let r=e.defaultAgent||pr.DEFAULT_AGENT_ID,s=Ke(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,pr.missingAgentCapabilities)(s.id,n);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:qe(t,s.id)}}function Ht(t,e){return t.replace(/\{\{(\w+)\}\}/g,(n,r)=>r in e?e[r]:n)}var dd=R(_e(),1);ht();ur();_t();var Oe=R(require("node:fs"),1),cs=R(require("node:path"),1);var zy=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()}),Dy=k.record(zy),Ly=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()}),Uy=k.record(Ly),qy=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()}),Fy=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()}),By=k.record(Fy),Ky=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()}),Hy=k.record(Ky),Gy=k.record(qy);function td(){return cs.default.join(ie(),"pending-runs.json")}function qa(){return cs.default.join(ie(),"pending-deploys.json")}function Fa(){return cs.default.join(ie(),"pending-inputs.json")}function Ba(){return cs.default.join(ie(),"merge-watch.json")}function Ka(){return cs.default.join(ie(),"pending-pushes.json")}function Ha(){let t=Ka();if(!Oe.default.existsSync(t))return{};try{return By.parse(JSON.parse(Oe.default.readFileSync(t,"utf8")))}catch{return{}}}function Hi(t){let e=Ha();e[t.runId]=t,Gt(Ka(),e)}function Gi(t){return Ha()[t]??null}function Ga(t){let e=Ha();t in e&&(delete e[t],Gt(Ka(),e))}function Zi(){let t=Ba();if(!Oe.default.existsSync(t))return{};try{return Hy.parse(JSON.parse(Oe.default.readFileSync(t,"utf8")))}catch{return{}}}function nd(t){let e=Zi();e[t.runId]=t,Gt(Ba(),e)}function Ls(t){let e=Zi();t in e&&(delete e[t],Gt(Ba(),e))}function Us(){let t=td();if(!Oe.default.existsSync(t))return{};try{return Dy.parse(JSON.parse(Oe.default.readFileSync(t,"utf8")))}catch{return{}}}function Gt(t,e){Oe.default.mkdirSync(ie(),{recursive:!0,mode:448});let n=t+".tmp";Oe.default.writeFileSync(n,JSON.stringify(e,null,2)+`
692
+ `,{mode:384}),Oe.default.renameSync(n,t),Oe.default.chmodSync(t,384)}function rd(t){Gt(td(),t)}function pt(t){let e=Us();e[t.runId]=t,rd(e)}function us(t){return Us()[t]??null}function mr(t){let e=Us();t in e&&(delete e[t],rd(e))}function Za(){let t=qa();if(!Oe.default.existsSync(t))return{};try{return Uy.parse(JSON.parse(Oe.default.readFileSync(t,"utf8")))}catch{return{}}}function sd(t){let e=Za();e[t.runId]=t,Gt(qa(),e)}function Vi(t){return Za()[t]??null}function Wi(t){let e=Za();t in e&&(delete e[t],Gt(qa(),e))}function gr(){let t=Fa();if(!Oe.default.existsSync(t))return{};try{return Gy.parse(JSON.parse(Oe.default.readFileSync(t,"utf8")))}catch{return{}}}function id(t){let e=gr();e[t.runId]=t,Gt(Fa(),e)}function od(t){return gr()[t]??null}function xt(t){let e=gr();t in e&&(delete e[t],Gt(Fa(),e))}Kt();var Zy=`
621
693
 
622
- 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.`,Ey=`
694
+ 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.`,Vy=`
623
695
 
624
- 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.`,Ry=`
696
+ 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.`,Wy=`
625
697
 
626
- 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 Yu(t){let e=/##\s*Go-live draft\s*\n([\s\S]*?)(?=\n##\s|$)/i.exec(t),n=e?e[1].trim():"";return n?n.slice(0,3500):null}function Iy(t){let e=t.map(n=>`$ ${n.command} (exit ${n.exitCode})
698
+ 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 ad(t){let e=/##\s*Go-live draft\s*\n([\s\S]*?)(?=\n##\s|$)/i.exec(t),n=e?e[1].trim():"";return n?n.slice(0,3500):null}function Yy(t){let e=t.map(n=>`$ ${n.command} (exit ${n.exitCode})
627
699
  ${n.tail.slice(-2e3)}`).join(`
628
700
 
629
701
  `);return`After you finished, the runner executed this repository's documented TEST.md commands (you cannot run them yourself - you have no shell). ${t.length} failed:
@@ -635,7 +707,7 @@ Fix what these failures point at, with the smallest change that makes them pass.
635
707
  - 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.
636
708
  - Do not ask questions; if you cannot fix something safely, say what you found and stop.
637
709
  - The runner re-runs every documented command after you finish, so a fix that breaks a previously passing command will be caught.
638
- 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 Ay(t){try{let{packs:e,lessons:n}=Ni("implement",t),r="",s=e.map(o=>`### ${o.name}
710
+ 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 Jy(t){try{let{packs:e,lessons:n}=qi("implement",t),r="",s=e.map(o=>`### ${o.name}
639
711
  ${o.content}`).join(`
640
712
 
641
713
  `).trim();s&&(r+=`
@@ -645,40 +717,40 @@ This repository has working rules taught to Allwright - follow them:
645
717
  \u2026${i.slice(-6e3)}`:i;r+=`
646
718
 
647
719
  Lessons from earlier runs on this repository (human-confirmed - follow them BEFORE writing code, they exist because a run got this wrong once):
648
- `+o}return r}catch{return""}}function La(t){return Da.default.existsSync(Bi.default.join(t,"DESIGN.md"))?`
720
+ `+o}return r}catch{return""}}function Ya(t){return Wa.default.existsSync(Yi.default.join(t,"DESIGN.md"))?`
649
721
 
650
- 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 td=5,Ju=2,Cy=8,Xu=2,$y="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 Os(t,e,n,r){let s=Date.now(),i="";r&&(i=await r().catch(()=>""));let o=await t.run(e),l=0,c="",u=r?Cy:Ju;for(;!o.ok&&o.turnLimitHit&&!o.cancelled&&t.capabilities.sessionResume;){if(l>=u){c=`resume cap (${u}) reached`;break}if(r&&l>=Ju){let f=await r().catch(()=>""),b=f!==""&&f!==i;if(i=f,!b){c="the last resume produced no new work";break}if(Date.now()-s>e.timeoutSeconds*Xu*1e3){c=`wall-clock budget (${Xu}x the rule's timeout) exhausted`;break}}l++,n("info",`Turn limit hit mid-work - auto-resuming the same session (resume ${l}, cap ${u})`);let p=await t.run({...e,prompt:$y,resume:!0});p.costUsd+=o.costUsd,p.inputTokens+=o.inputTokens,p.outputTokens+=o.outputTokens,o=p}return!o.ok&&o.turnLimitHit&&t.capabilities.sessionResume&&(o.error=`${o.error??"hit the turn limit"} - even after ${l} automatic same-session resume(s)${c?` (stopped: ${c})`:""}. The ticket is probably too large for one run: raise the rule's max turns, or split the ticket.`),o}var Ns=new Map;function nd(t){let e=Ns.get(t);return e?(e.abort(),!0):!1}function rd(t){let e=new AbortController;return Ns.set(t,e),e}function sd(t){Ns.delete(t)}async function os(t,e,n,r,s){let i=new AbortController;Ns.set(t,i);try{return await Os(e,{...n,signal:i.signal},r,s)}finally{Ns.delete(t)}}function dr(t,e,n=0){let r=n;return{emit:(l,c)=>{e.send({type:"run.log",runId:t,seq:r++,ts:new Date().toISOString(),level:l,message:c}),l!=="agent"&&y.info(`[run ${t}] ${c}`)},setStatus:(l,c={})=>{e.send({type:"run.status",runId:t,status:l,...c})},sendUsage:l=>{e.send({type:"run.usage",runId:t,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 Hi(t){return t.rule.action.type==="implement"?Ny(t):t.rule.action.type==="respond"?jy(t):Py(t)}async function Py(t){let{emit:e,setStatus:n,sendUsage:r,nextSeq:s}=dr(t.runId,t.transport),{trigger:i}=t.rule,o=t.rule.action;if(o.type!=="plan_only")return;let l=pn(o.agent,o.type);if(l){e("error",l),await is(t,l),n("failed",{error:l});return}let c=(0,Ki.randomUUID)();try{n("running"),e("info",`Run started for ${t.issueKey} (rule "${t.rule.name}", plan-only)`),e("info",`Fetching ${t.issueKey} from Jira`);let u=await t.jira.getIssue(t.issueKey),p=qt(o.promptTemplate,{issueKey:u.key,summary:u.summary,description:u.description||"(no description)",comments:zs(u.comments)})+await Ur(t.jira,u.attachments,t.repoPath,e)+La(t.repoPath)+we.NEEDS_INPUT_OPTIONS_PROMPT;e("info",`Starting Claude Code in ${t.repoPath} - read-only tools, path-jailed to the repo, timeout ${o.timeoutSeconds}s`);let f=await os(t.runId,Be(o.agent),{repoPath:t.repoPath,prompt:p,timeoutSeconds:o.timeoutSeconds,bin:Ue(t.cfg,o.agent),configDir:t.claudeConfigDir,mode:"read_only",model:o.model||void 0,sessionId:c,onLog:(_,x)=>e(_,x),onUsage:r},e),b={costUsd:f.costUsd,inputTokens:f.inputTokens,outputTokens:f.outputTokens,billingMode:f.billingMode,model:f.model};if(!f.ok||!f.resultText.trim()){let _=f.error??"Claude Code produced no output";e("error",`Run failed: ${_}`),await is(t,_),n(f.timedOut?"timed_out":"failed",{error:_,...f.cancelled?{errorKind:"guard"}:{},...b});return}let v=Ds(f.resultText);if(v){await Gi({kind:"plan",runId:t.runId,issueKey:t.issueKey,repoPath:t.repoPath,sessionId:c,doneLabel:i.doneLabel,failedLabel:i.failedLabel,timeoutSeconds:o.timeoutSeconds,jira:t.jira,nextLogSeq:s(),rounds:1,claudeConfigDir:t.claudeConfigDir,agent:o.agent,model:o.model},v,e,n,b);return}await id({runId:t.runId,issueKey:t.issueKey,doneLabel:i.doneLabel,jira:t.jira,resultText:f.resultText,costFields:b,emit:e,setStatus:n})}catch(u){let p=u instanceof Error?u.message:String(u);e("error",`Run failed: ${p}`),await is(t,p),n("failed",{error:p})}finally{tn(t.repoPath)}}async function Ua(t,e,n,r){let{emit:s,setStatus:i,sendUsage:o,nextSeq:l}=dr(t.runId,r.transport,t.nextLogSeq);try{i("running"),s("info",`Reply received on ${t.issueKey} - continuing run \`${t.runId}\``);let c=md(e)+await Ur(r.jiraFor(t.repoName??""),n,t.repoPath,s),u=await os(t.runId,Be(t.agent),{repoPath:t.repoPath,prompt:c,timeoutSeconds:t.timeoutSeconds,bin:Ue(r.cfg,t.agent??""),configDir:t.claudeConfigDir,mode:"read_only",model:t.model||void 0,sessionId:t.sessionId,resume:!0,onLog:(b,v)=>s(b,v),onUsage:o},s),p={costUsd:u.costUsd,inputTokens:u.inputTokens,outputTokens:u.outputTokens,billingMode:u.billingMode,model:u.model};if(!u.ok||!u.resultText.trim()){let b=u.error??"Claude Code produced no output";s("error",`Run failed: ${b}`),await Tt(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,b),St(t.runId),i(u.timedOut?"timed_out":"failed",{error:b,...u.cancelled?{errorKind:"guard"}:{},...p});return}let f=Ds(u.resultText);if(f){if(t.rounds>=td){await gd(r.jiraFor(t.repoName??""),t,s,i,p);return}await Gi({kind:"plan",runId:t.runId,issueKey:t.issueKey,repoPath:t.repoPath,sessionId:t.sessionId,doneLabel:t.doneLabel,failedLabel:t.failedLabel,timeoutSeconds:t.timeoutSeconds,jira:r.jiraFor(t.repoName??""),nextLogSeq:l(),rounds:t.rounds+1,createdAt:t.createdAt,claudeConfigDir:t.claudeConfigDir,actorEmail:t.actorEmail,agent:t.agent,model:t.model},f,s,i,p);return}await id({runId:t.runId,issueKey:t.issueKey,doneLabel:t.doneLabel,jira:r.jiraFor(t.repoName??""),resultText:u.resultText,costFields:p,emit:s,setStatus:i}),St(t.runId)}catch(c){let u=c instanceof Error?c.message:String(c);s("error",`Run failed: ${u}`),await Tt(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,u),St(t.runId),i("failed",{error:u})}finally{tn(t.repoPath)}}async function id(t){let{runId:e,issueKey:n,doneLabel:r,jira:s,resultText:i,costFields:o,emit:l,setStatus:c}=t;c("posting",o),l("info",`Posting plan to ${n} (${i.length} chars)`);let u=`
722
+ 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 hd=5,ld=2,Xy=8,cd=2,Qy="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 Fs(t,e,n,r){let s=Date.now(),i="";r&&(i=await r().catch(()=>""));let o=await t.run(e),l=0,c="",u=r?Xy:ld;for(;!o.ok&&o.turnLimitHit&&!o.cancelled&&t.capabilities.sessionResume;){if(l>=u){c=`resume cap (${u}) reached`;break}if(r&&l>=ld){let f=await r().catch(()=>""),b=f!==""&&f!==i;if(i=f,!b){c="the last resume produced no new work";break}if(Date.now()-s>e.timeoutSeconds*cd*1e3){c=`wall-clock budget (${cd}x the rule's timeout) exhausted`;break}}l++,n("info",`Turn limit hit mid-work - auto-resuming the same session (resume ${l}, cap ${u})`);let p=await t.run({...e,prompt:Qy,resume:!0});p.costUsd+=o.costUsd,p.inputTokens+=o.inputTokens,p.outputTokens+=o.outputTokens,o=p}return!o.ok&&o.turnLimitHit&&t.capabilities.sessionResume&&(o.error=`${o.error??"hit the turn limit"} - even after ${l} automatic same-session resume(s)${c?` (stopped: ${c})`:""}. The ticket is probably too large for one run: raise the rule's max turns, or split the ticket.`),o}var qs=new Map;function pd(t){let e=qs.get(t);return e?(e.abort(),!0):!1}function fd(t){let e=new AbortController;return qs.set(t,e),e}function md(t){qs.delete(t)}async function hs(t,e,n,r,s){let i=new AbortController;qs.set(t,i);try{return await Fs(e,{...n,signal:i.signal},r,s)}finally{qs.delete(t)}}function yr(t,e,n=0){let r=n;return{emit:(l,c)=>{e.send({type:"run.log",runId:t,seq:r++,ts:new Date().toISOString(),level:l,message:c}),l!=="agent"&&y.info(`[run ${t}] ${c}`)},setStatus:(l,c={})=>{e.send({type:"run.status",runId:t,status:l,...c})},sendUsage:l=>{e.send({type:"run.usage",runId:t,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 Xi(t){return t.rule.action.type==="implement"?nb(t):t.rule.action.type==="respond"?tb(t):eb(t)}async function eb(t){let{emit:e,setStatus:n,sendUsage:r,nextSeq:s}=yr(t.runId,t.transport),{trigger:i}=t.rule,o=t.rule.action;if(o.type!=="plan_only")return;let l=bn(o.agent,o.type);if(l){e("error",l),await ds(t,l),n("failed",{error:l});return}let c=(0,Ji.randomUUID)();try{n("running"),e("info",`Run started for ${t.issueKey} (rule "${t.rule.name}", plan-only)`),e("info",`Fetching ${t.issueKey} from Jira`);let u=await t.jira.getIssue(t.issueKey),p=Ht(o.promptTemplate,{issueKey:u.key,summary:u.summary,description:u.description||"(no description)",comments:Ks(u.comments)})+await Gr(t.jira,u.attachments,t.repoPath,e)+Ya(t.repoPath)+we.NEEDS_INPUT_OPTIONS_PROMPT;e("info",`Starting Claude Code in ${t.repoPath} - read-only tools, path-jailed to the repo, timeout ${o.timeoutSeconds}s`);let f=await hs(t.runId,Ke(o.agent),{repoPath:t.repoPath,prompt:p,timeoutSeconds:o.timeoutSeconds,bin:qe(t.cfg,o.agent),configDir:t.claudeConfigDir,mode:"read_only",model:o.model||void 0,sessionId:c,onLog:(w,x)=>e(w,x),onUsage:r},e),b={costUsd:f.costUsd,inputTokens:f.inputTokens,outputTokens:f.outputTokens,billingMode:f.billingMode,model:f.model};if(!f.ok||!f.resultText.trim()){let w=f.error??"Claude Code produced no output";e("error",`Run failed: ${w}`),await ds(t,w),n(f.timedOut?"timed_out":"failed",{error:w,...f.cancelled?{errorKind:"guard"}:{},...b});return}let v=Hs(f.resultText);if(v){await Qi({kind:"plan",runId:t.runId,issueKey:t.issueKey,repoPath:t.repoPath,sessionId:c,doneLabel:i.doneLabel,failedLabel:i.failedLabel,timeoutSeconds:o.timeoutSeconds,jira:t.jira,nextLogSeq:s(),rounds:1,claudeConfigDir:t.claudeConfigDir,agent:o.agent,model:o.model},v,e,n,b);return}await gd({runId:t.runId,issueKey:t.issueKey,doneLabel:i.doneLabel,jira:t.jira,resultText:f.resultText,costFields:b,emit:e,setStatus:n})}catch(u){let p=u instanceof Error?u.message:String(u);e("error",`Run failed: ${p}`),await ds(t,p),n("failed",{error:p})}finally{an(t.repoPath)}}async function Ja(t,e,n,r){let{emit:s,setStatus:i,sendUsage:o,nextSeq:l}=yr(t.runId,r.transport,t.nextLogSeq);try{i("running"),s("info",`Reply received on ${t.issueKey} - continuing run \`${t.runId}\``);let c=Ed(e)+await Gr(r.jiraFor(t.repoName??""),n,t.repoPath,s),u=await hs(t.runId,Ke(t.agent),{repoPath:t.repoPath,prompt:c,timeoutSeconds:t.timeoutSeconds,bin:qe(r.cfg,t.agent??""),configDir:t.claudeConfigDir,mode:"read_only",model:t.model||void 0,sessionId:t.sessionId,resume:!0,onLog:(b,v)=>s(b,v),onUsage:o},s),p={costUsd:u.costUsd,inputTokens:u.inputTokens,outputTokens:u.outputTokens,billingMode:u.billingMode,model:u.model};if(!u.ok||!u.resultText.trim()){let b=u.error??"Claude Code produced no output";s("error",`Run failed: ${b}`),await Et(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,b),xt(t.runId),i(u.timedOut?"timed_out":"failed",{error:b,...u.cancelled?{errorKind:"guard"}:{},...p});return}let f=Hs(u.resultText);if(f){if(t.rounds>=hd){await Rd(r.jiraFor(t.repoName??""),t,s,i,p);return}await Qi({kind:"plan",runId:t.runId,issueKey:t.issueKey,repoPath:t.repoPath,sessionId:t.sessionId,doneLabel:t.doneLabel,failedLabel:t.failedLabel,timeoutSeconds:t.timeoutSeconds,jira:r.jiraFor(t.repoName??""),nextLogSeq:l(),rounds:t.rounds+1,createdAt:t.createdAt,claudeConfigDir:t.claudeConfigDir,actorEmail:t.actorEmail,agent:t.agent,model:t.model},f,s,i,p);return}await gd({runId:t.runId,issueKey:t.issueKey,doneLabel:t.doneLabel,jira:r.jiraFor(t.repoName??""),resultText:u.resultText,costFields:p,emit:s,setStatus:i}),xt(t.runId)}catch(c){let u=c instanceof Error?c.message:String(c);s("error",`Run failed: ${u}`),await Et(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,u),xt(t.runId),i("failed",{error:u})}finally{an(t.repoPath)}}async function gd(t){let{runId:e,issueKey:n,doneLabel:r,jira:s,resultText:i,costFields:o,emit:l,setStatus:c}=t;c("posting",o),l("info",`Posting plan to ${n} (${i.length} chars)`);let u=`
651
723
 
652
724
  ---
653
- _Allwright plan-only run \`${e}\` \xB7 cost $${o.costUsd.toFixed(4)} \xB7 no code was written._`;await s.addComment(n,i+u),await s.editLabels(n,{add:[r],remove:[we.NEEDS_INPUT_LABEL]}),l("info",`Labeled ${n} with "${r}"`),c("succeeded",{...o,resultSummary:hr(i)}),l("info",`Run succeeded \xB7 $${o.costUsd.toFixed(4)}`)}async function jy(t){let{emit:e,setStatus:n,sendUsage:r}=dr(t.runId,t.transport),s=t.rule.action;if(s.type!=="respond")return;let i=pn(s.agent,s.type);if(i){e("error",i),await t.jira.addComment(t.issueKey,`**Allwright could not answer this question.**
725
+ _Allwright plan-only run \`${e}\` \xB7 cost $${o.costUsd.toFixed(4)} \xB7 no code was written._`;await s.addComment(n,i+u),await s.editLabels(n,{add:[r],remove:[we.NEEDS_INPUT_LABEL]}),l("info",`Labeled ${n} with "${r}"`),c("succeeded",{...o,resultSummary:br(i)}),l("info",`Run succeeded \xB7 $${o.costUsd.toFixed(4)}`)}async function tb(t){let{emit:e,setStatus:n,sendUsage:r}=yr(t.runId,t.transport),s=t.rule.action;if(s.type!=="respond")return;let i=bn(s.agent,s.type);if(i){e("error",i),await t.jira.addComment(t.issueKey,`**Allwright could not answer this question.**
654
726
 
655
- ${i}`).catch(()=>{}),n("failed",{error:i});return}try{n("running"),e("info",`Run started for ${t.issueKey} (rule "${t.rule.name}", respond`+(t.question?`, question from ${t.question.author}`:"")+")"),e("info",`Fetching ${t.issueKey} from Jira`);let o=await t.jira.getIssue(t.issueKey),l=qt(s.promptTemplate,{issueKey:o.key,summary:o.summary,description:o.description||"(no description)",comments:zs(o.comments),question:t.question?.body??"(see the latest comment on the ticket)",questionAuthor:t.question?.author??"the commenter"})+await Ur(t.jira,o.attachments,t.repoPath,e)+La(t.repoPath);e("info",`Starting Claude Code in ${t.repoPath} - read-only tools, path-jailed, timeout ${s.timeoutSeconds}s`);let c=await os(t.runId,Be(s.agent),{repoPath:t.repoPath,prompt:l,timeoutSeconds:s.timeoutSeconds,bin:Ue(t.cfg,s.agent),configDir:t.claudeConfigDir,mode:"read_only",model:s.model||void 0,sessionId:(0,Ki.randomUUID)(),onLog:(p,f)=>e(p,f),onUsage:r},e),u={costUsd:c.costUsd,inputTokens:c.inputTokens,outputTokens:c.outputTokens,billingMode:c.billingMode,model:c.model};if(!c.ok||!c.resultText.trim()){let p=c.error??"Claude Code produced no answer";e("error",`Run failed: ${p}`),await t.jira.addComment(t.issueKey,`**Allwright could not answer this question.**
727
+ ${i}`).catch(()=>{}),n("failed",{error:i});return}try{n("running"),e("info",`Run started for ${t.issueKey} (rule "${t.rule.name}", respond`+(t.question?`, question from ${t.question.author}`:"")+")"),e("info",`Fetching ${t.issueKey} from Jira`);let o=await t.jira.getIssue(t.issueKey),l=Ht(s.promptTemplate,{issueKey:o.key,summary:o.summary,description:o.description||"(no description)",comments:Ks(o.comments),question:t.question?.body??"(see the latest comment on the ticket)",questionAuthor:t.question?.author??"the commenter"})+await Gr(t.jira,o.attachments,t.repoPath,e)+Ya(t.repoPath);e("info",`Starting Claude Code in ${t.repoPath} - read-only tools, path-jailed, timeout ${s.timeoutSeconds}s`);let c=await hs(t.runId,Ke(s.agent),{repoPath:t.repoPath,prompt:l,timeoutSeconds:s.timeoutSeconds,bin:qe(t.cfg,s.agent),configDir:t.claudeConfigDir,mode:"read_only",model:s.model||void 0,sessionId:(0,Ji.randomUUID)(),onLog:(p,f)=>e(p,f),onUsage:r},e),u={costUsd:c.costUsd,inputTokens:c.inputTokens,outputTokens:c.outputTokens,billingMode:c.billingMode,model:c.model};if(!c.ok||!c.resultText.trim()){let p=c.error??"Claude Code produced no answer";e("error",`Run failed: ${p}`),await t.jira.addComment(t.issueKey,`**Allwright could not answer this question.**
656
728
 
657
729
  Error: ${p.slice(0,800)}
658
730
 
659
- Ask again in a new comment to retry. (run \`${t.runId}\`)`).catch(f=>y.error(`could not post answer failure to ${t.issueKey}: ${f}`)),n(c.timedOut?"timed_out":"failed",{error:p,...c.cancelled?{errorKind:"guard"}:{},...u});return}n("posting",u),e("info",`Posting answer to ${t.issueKey} (${c.resultText.length} chars)`),await t.jira.addComment(t.issueKey,c.resultText),n("succeeded",{...u,resultSummary:hr(c.resultText)}),e("info",`Run succeeded \xB7 $${c.costUsd.toFixed(4)}`)}catch(o){let l=o instanceof Error?o.message:String(o);e("error",`Run failed: ${l}`),n("failed",{error:l})}finally{tn(t.repoPath)}}async function od(t,e,n,r){let s=`${e}-wip`;try{return tn(t),await tr(t,`WIP: turn limit exhausted (Allwright run ${n})`),await Qo(t,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 ad(t){return`
731
+ Ask again in a new comment to retry. (run \`${t.runId}\`)`).catch(f=>y.error(`could not post answer failure to ${t.issueKey}: ${f}`)),n(c.timedOut?"timed_out":"failed",{error:p,...c.cancelled?{errorKind:"guard"}:{},...u});return}n("posting",u),e("info",`Posting answer to ${t.issueKey} (${c.resultText.length} chars)`),await t.jira.addComment(t.issueKey,c.resultText),n("succeeded",{...u,resultSummary:br(c.resultText)}),e("info",`Run succeeded \xB7 $${c.costUsd.toFixed(4)}`)}catch(o){let l=o instanceof Error?o.message:String(o);e("error",`Run failed: ${l}`),n("failed",{error:l})}finally{an(t.repoPath)}}async function yd(t,e,n,r){let s=`${e}-wip`;try{return an(t),await ar(t,`WIP: turn limit exhausted (Allwright run ${n})`),await ua(t,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 bd(t){return`
660
732
 
661
- Partial work from this run is saved on branch \`${t}\` - 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 Ny(t){let{emit:e,setStatus:n,sendUsage:r,nextSeq:s}=dr(t.runId,t.transport),{trigger:i}=t.rule,o=t.rule.action;if(o.type!=="implement")return;let l=pn(o.agent,o.type);if(l){e("error",l),await is(t,l),n("failed",{error:l});return}let c=Bi.default.join(Lt(),t.runId),u=qt(o.branchTemplate,{issueKey:t.issueKey}),p=(0,Ki.randomUUID)(),f=!1,b=!1;try{if(!$i(ye()??t.cfg,t.project.repoName,t.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(u===o.baseBranch&&!t.continueBranch)throw new Error(`rendered branch "${u}" equals the base branch - refusing (check the rule's branch template)`);if(n("running"),e("info",`Run started for ${t.issueKey} (rule "${t.rule.name}", implement)`),o.jiraTransitionOnStart)try{await t.jira.transitionByName(t.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(O){e("warn",`Jira start transition failed: ${O instanceof Error?O.message:O} - continuing anyway`)}let v=await rr(t.repoPath);if(e("info",`Repo origin: ${v}`),!lt(v))throw new Error(`origin "${v}" is not a GitHub remote - implement mode supports GitHub only`);e("info",`Fetching ${t.issueKey} from Jira`);let _=await t.jira.getIssue(t.issueKey),x=t.continueBranch?u:o.baseBranch;e("info",t.continueBranch?`Continuing branch "${u}" from origin/${u} (autopilot batch)`:`Preparing worktree on branch "${u}" from origin/${o.baseBranch}`),await un(t.repoPath,x),await ta(t.repoPath,u),await na(t.repoPath,c,u,x),f=!0;let $=qt(o.promptTemplate,{issueKey:_.key,summary:_.summary,description:_.description||"(no description)",comments:zs(_.comments)})+await Ur(t.jira,_.attachments,c,e)+La(c)+Ay(t.repoPath)+xy+we.NEEDS_INPUT_OPTIONS_PROMPT+Ey+(t.project.goLiveIssueKey?Ry:"")+(o.writeTests?ed.WRITE_TESTS_PROMPT:"")+(o.updateMemory?we.MEMORY_UPDATE_PROMPT:"");e("info",`Starting Claude Code in the worktree - edit tools enabled, path-jailed, no shell, timeout ${o.timeoutSeconds}s`);let j=await os(t.runId,Be(o.agent),{repoPath:c,prompt:$,timeoutSeconds:o.timeoutSeconds,bin:Ue(t.cfg,o.agent),configDir:t.claudeConfigDir,mode:"edit_no_shell",model:o.model||void 0,maxTurns:o.maxTurns,sessionId:p,onLog:(O,M)=>e(O,M),onUsage:r},e,()=>Ri(c)),S={costUsd:j.costUsd,inputTokens:j.inputTokens,outputTokens:j.outputTokens,billingMode:j.billingMode,model:j.model};if(!j.ok){let O=j.error??"Claude Code failed";e("error",`Run failed: ${O}`);let M=O;if(j.turnLimitHit){let W=await od(c,u,t.runId,e);W&&(M+=ad(W))}ct(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:"implement failed",detail:O.slice(0,500)}),await is(t,M),n(j.timedOut?"timed_out":"failed",{error:O,...j.cancelled?{errorKind:"guard"}:{},...S});return}let G=Ds(j.resultText);if(G){b=!0,await Gi({kind:"implement",runId:t.runId,issueKey:t.issueKey,repoPath:c,sessionId:p,doneLabel:i.doneLabel,failedLabel:i.failedLabel,timeoutSeconds:o.timeoutSeconds,jira:t.jira,nextLogSeq:s(),rounds:1,claudeConfigDir:t.claudeConfigDir,agent:o.agent,model:o.model,actorEmail:t.actorEmail,baseRepoPath:t.repoPath,repoName:t.project.repoName,branch:u,baseBranch:o.baseBranch,jiraTransition:o.jiraTransition,jiraTransitionOnMerge:o.jiraTransitionOnMerge,requireApproval:o.requireApproval,mergeOnApprove:o.mergeOnApprove,mergeMethod:o.mergeMethod,autoMerge:o.autoMerge,runTests:o.runTests,maxTurns:o.maxTurns,issueSummary:_.summary},G,e,n,S);return}tn(c),await ld({runId:t.runId,issueKey:t.issueKey,issueSummary:_.summary,worktreePath:c,agentConfigDir:t.claudeConfigDir,baseRepoPath:t.repoPath,branch:u,baseBranch:o.baseBranch,jiraTransition:o.jiraTransition,jiraTransitionOnMerge:o.jiraTransitionOnMerge,requireApproval:o.requireApproval,doneLabel:i.doneLabel,failedLabel:i.failedLabel,repoName:t.project.repoName,jira:t.jira,cfg:t.cfg,actorEmail:t.actorEmail,resultText:j.resultText,costFields:S,runTests:o.runTests,fixSession:{sessionId:p,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:n})}catch(v){let _=v instanceof Error?v.message:String(v);e("error",`Run failed: ${_}`),ct(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:"implement failed",detail:_.slice(0,500)}),await is(t,_),n("failed",{error:_})}finally{f&&!b&&await vt(t.repoPath,c).catch(()=>{})}}async function qa(t,e,n,r){let{emit:s,setStatus:i,sendUsage:o,nextSeq:l}=dr(t.runId,r.transport,t.nextLogSeq),c=t.repoPath,u=!1;try{if(!$i(ye()??r.cfg,t.repoName??"",t.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 ${t.issueKey} - continuing run \`${t.runId}\``);let p=md(e)+await Ur(r.jiraFor(t.repoName??""),n,c,s),f=await os(t.runId,Be(t.agent),{repoPath:c,prompt:p,timeoutSeconds:t.timeoutSeconds,bin:Ue(r.cfg,t.agent??""),configDir:t.claudeConfigDir,mode:"edit_no_shell",model:t.model||void 0,maxTurns:t.maxTurns??120,sessionId:t.sessionId,resume:!0,onLog:(_,x)=>s(_,x),onUsage:o},s,()=>Ri(c)),b={costUsd:f.costUsd,inputTokens:f.inputTokens,outputTokens:f.outputTokens,billingMode:f.billingMode,model:f.model};if(!f.ok){let _=f.error??"Claude Code failed";s("error",`Run failed: ${_}`);let x=_;if(f.turnLimitHit&&t.branch){let $=await od(c,t.branch,t.runId,s);$&&(x+=ad($))}await Tt(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,x),St(t.runId),i(f.timedOut?"timed_out":"failed",{error:_,...f.cancelled?{errorKind:"guard"}:{},...b});return}let v=Ds(f.resultText);if(v){if(t.rounds>=td){await gd(r.jiraFor(t.repoName??""),t,s,i,b);return}u=!0,await Gi({kind:"implement",runId:t.runId,issueKey:t.issueKey,repoPath:c,sessionId:t.sessionId,doneLabel:t.doneLabel,failedLabel:t.failedLabel,timeoutSeconds:t.timeoutSeconds,jira:r.jiraFor(t.repoName??""),nextLogSeq:l(),rounds:t.rounds+1,createdAt:t.createdAt,claudeConfigDir:t.claudeConfigDir,actorEmail:t.actorEmail,agent:t.agent,model:t.model,baseRepoPath:t.baseRepoPath,repoName:t.repoName,branch:t.branch,baseBranch:t.baseBranch,jiraTransition:t.jiraTransition,jiraTransitionOnMerge:t.jiraTransitionOnMerge,requireApproval:t.requireApproval,mergeOnApprove:t.mergeOnApprove,mergeMethod:t.mergeMethod,autoMerge:t.autoMerge,runTests:t.runTests,maxTurns:t.maxTurns,issueSummary:t.issueSummary},v,s,i,b);return}tn(c),await ld({runId:t.runId,issueKey:t.issueKey,issueSummary:t.issueSummary,worktreePath:c,agentConfigDir:t.claudeConfigDir,baseRepoPath:t.baseRepoPath??c,branch:t.branch,baseBranch:t.baseBranch,jiraTransition:t.jiraTransition,requireApproval:t.requireApproval??!0,doneLabel:t.doneLabel,failedLabel:t.failedLabel,repoName:t.repoName,jira:r.jiraFor(t.repoName??""),cfg:r.cfg,actorEmail:t.actorEmail,resultText:f.resultText,costFields:b,runTests:t.runTests,fixSession:{sessionId:t.sessionId,agent:t.agent??"",model:t.model,timeoutSeconds:t.timeoutSeconds,maxTurns:t.maxTurns},sendUsage:o,mergeOnApprove:t.mergeOnApprove,mergeMethod:t.mergeMethod,autoMerge:t.autoMerge??!1,emit:s,setStatus:i}),St(t.runId)}catch(p){let f=p instanceof Error?p.message:String(p);s("error",`Run failed: ${f}`),await Tt(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,f),St(t.runId),i("failed",{error:f})}finally{u||await vt(t.baseRepoPath??c,c).catch(()=>{})}}async function ld(t){let{runId:e,issueKey:n,issueSummary:r,worktreePath:s,baseRepoPath:i,branch:o,baseBranch:l,jiraTransition:c,jiraTransitionOnMerge:u,requireApproval:p,doneLabel:f,failedLabel:b,repoName:v,jira:_,cfg:x,actorEmail:$,runTests:j,mergeOnApprove:S,mergeMethod:G,autoMerge:O,resultText:M,costFields:W,emit:d,setStatus:m}=t,g=await Yr(s);g.deleted.length&&d("info",`Deleted ${g.deleted.length} file(s) listed in ${Dt}: `+g.deleted.slice(0,10).join(", ")+(g.deleted.length>10?", \u2026":""));for(let ve of g.refused)d("warn",`${Dt} entry refused: ${ve}`);d("info","Committing changes"),await tr(s,`${n}: ${r}
733
+ Partial work from this run is saved on branch \`${t}\` - 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 nb(t){let{emit:e,setStatus:n,sendUsage:r,nextSeq:s}=yr(t.runId,t.transport),{trigger:i}=t.rule,o=t.rule.action;if(o.type!=="implement")return;let l=bn(o.agent,o.type);if(l){e("error",l),await ds(t,l),n("failed",{error:l});return}let c=Yi.default.join(Ft(),t.runId),u=Ht(o.branchTemplate,{issueKey:t.issueKey}),p=(0,Ji.randomUUID)(),f=!1,b=!1;try{if(!Di(ye()??t.cfg,t.project.repoName,t.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(u===o.baseBranch&&!t.continueBranch)throw new Error(`rendered branch "${u}" equals the base branch - refusing (check the rule's branch template)`);if(n("running"),e("info",`Run started for ${t.issueKey} (rule "${t.rule.name}", implement)`),o.jiraTransitionOnStart)try{await t.jira.transitionByName(t.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(O){e("warn",`Jira start transition failed: ${O instanceof Error?O.message:O} - continuing anyway`)}let v=await cr(t.repoPath);if(e("info",`Repo origin: ${v}`),!ut(v))throw new Error(`origin "${v}" is not a GitHub remote - implement mode supports GitHub only`);e("info",`Fetching ${t.issueKey} from Jira`);let w=await t.jira.getIssue(t.issueKey),x=t.continueBranch?u:o.baseBranch;e("info",t.continueBranch?`Continuing branch "${u}" from origin/${u} (autopilot batch)`:`Preparing worktree on branch "${u}" from origin/${o.baseBranch}`),await mn(t.repoPath,x),await ha(t.repoPath,u),await pa(t.repoPath,c,u,x),f=!0;let $=Ht(o.promptTemplate,{issueKey:w.key,summary:w.summary,description:w.description||"(no description)",comments:Ks(w.comments)})+await Gr(t.jira,w.attachments,c,e)+Ya(c)+Jy(t.repoPath)+Zy+we.NEEDS_INPUT_OPTIONS_PROMPT+Vy+(t.project.goLiveIssueKey?Wy:"")+(o.writeTests?dd.WRITE_TESTS_PROMPT:"")+(o.updateMemory?we.MEMORY_UPDATE_PROMPT:"");e("info",`Starting Claude Code in the worktree - edit tools enabled, path-jailed, no shell, timeout ${o.timeoutSeconds}s`);let N=await hs(t.runId,Ke(o.agent),{repoPath:c,prompt:$,timeoutSeconds:o.timeoutSeconds,bin:qe(t.cfg,o.agent),configDir:t.claudeConfigDir,mode:"edit_no_shell",model:o.model||void 0,maxTurns:o.maxTurns,sessionId:p,onLog:(O,M)=>e(O,M),onUsage:r},e,()=>ji(c)),S={costUsd:N.costUsd,inputTokens:N.inputTokens,outputTokens:N.outputTokens,billingMode:N.billingMode,model:N.model};if(!N.ok){let O=N.error??"Claude Code failed";e("error",`Run failed: ${O}`);let M=O;if(N.turnLimitHit){let W=await yd(c,u,t.runId,e);W&&(M+=bd(W))}dt(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:"implement failed",detail:O.slice(0,500)}),await ds(t,M),n(N.timedOut?"timed_out":"failed",{error:O,...N.cancelled?{errorKind:"guard"}:{},...S});return}let G=Hs(N.resultText);if(G){b=!0,await Qi({kind:"implement",runId:t.runId,issueKey:t.issueKey,repoPath:c,sessionId:p,doneLabel:i.doneLabel,failedLabel:i.failedLabel,timeoutSeconds:o.timeoutSeconds,jira:t.jira,nextLogSeq:s(),rounds:1,claudeConfigDir:t.claudeConfigDir,agent:o.agent,model:o.model,actorEmail:t.actorEmail,baseRepoPath:t.repoPath,repoName:t.project.repoName,branch:u,baseBranch:o.baseBranch,jiraTransition:o.jiraTransition,jiraTransitionOnMerge:o.jiraTransitionOnMerge,requireApproval:o.requireApproval,mergeOnApprove:o.mergeOnApprove,mergeMethod:o.mergeMethod,autoMerge:o.autoMerge,runTests:o.runTests,maxTurns:o.maxTurns,issueSummary:w.summary},G,e,n,S);return}an(c),await vd({runId:t.runId,issueKey:t.issueKey,issueSummary:w.summary,worktreePath:c,agentConfigDir:t.claudeConfigDir,baseRepoPath:t.repoPath,branch:u,baseBranch:o.baseBranch,jiraTransition:o.jiraTransition,jiraTransitionOnMerge:o.jiraTransitionOnMerge,requireApproval:o.requireApproval,doneLabel:i.doneLabel,failedLabel:i.failedLabel,repoName:t.project.repoName,jira:t.jira,cfg:t.cfg,actorEmail:t.actorEmail,resultText:N.resultText,costFields:S,runTests:o.runTests,fixSession:{sessionId:p,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:n})}catch(v){let w=v instanceof Error?v.message:String(v);e("error",`Run failed: ${w}`),dt(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:"implement failed",detail:w.slice(0,500)}),await ds(t,w),n("failed",{error:w})}finally{f&&!b&&await kt(t.repoPath,c).catch(()=>{})}}async function Xa(t,e,n,r){let{emit:s,setStatus:i,sendUsage:o,nextSeq:l}=yr(t.runId,r.transport,t.nextLogSeq),c=t.repoPath,u=!1;try{if(!Di(ye()??r.cfg,t.repoName??"",t.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 ${t.issueKey} - continuing run \`${t.runId}\``);let p=Ed(e)+await Gr(r.jiraFor(t.repoName??""),n,c,s),f=await hs(t.runId,Ke(t.agent),{repoPath:c,prompt:p,timeoutSeconds:t.timeoutSeconds,bin:qe(r.cfg,t.agent??""),configDir:t.claudeConfigDir,mode:"edit_no_shell",model:t.model||void 0,maxTurns:t.maxTurns??120,sessionId:t.sessionId,resume:!0,onLog:(w,x)=>s(w,x),onUsage:o},s,()=>ji(c)),b={costUsd:f.costUsd,inputTokens:f.inputTokens,outputTokens:f.outputTokens,billingMode:f.billingMode,model:f.model};if(!f.ok){let w=f.error??"Claude Code failed";s("error",`Run failed: ${w}`);let x=w;if(f.turnLimitHit&&t.branch){let $=await yd(c,t.branch,t.runId,s);$&&(x+=bd($))}await Et(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,x),xt(t.runId),i(f.timedOut?"timed_out":"failed",{error:w,...f.cancelled?{errorKind:"guard"}:{},...b});return}let v=Hs(f.resultText);if(v){if(t.rounds>=hd){await Rd(r.jiraFor(t.repoName??""),t,s,i,b);return}u=!0,await Qi({kind:"implement",runId:t.runId,issueKey:t.issueKey,repoPath:c,sessionId:t.sessionId,doneLabel:t.doneLabel,failedLabel:t.failedLabel,timeoutSeconds:t.timeoutSeconds,jira:r.jiraFor(t.repoName??""),nextLogSeq:l(),rounds:t.rounds+1,createdAt:t.createdAt,claudeConfigDir:t.claudeConfigDir,actorEmail:t.actorEmail,agent:t.agent,model:t.model,baseRepoPath:t.baseRepoPath,repoName:t.repoName,branch:t.branch,baseBranch:t.baseBranch,jiraTransition:t.jiraTransition,jiraTransitionOnMerge:t.jiraTransitionOnMerge,requireApproval:t.requireApproval,mergeOnApprove:t.mergeOnApprove,mergeMethod:t.mergeMethod,autoMerge:t.autoMerge,runTests:t.runTests,maxTurns:t.maxTurns,issueSummary:t.issueSummary},v,s,i,b);return}an(c),await vd({runId:t.runId,issueKey:t.issueKey,issueSummary:t.issueSummary,worktreePath:c,agentConfigDir:t.claudeConfigDir,baseRepoPath:t.baseRepoPath??c,branch:t.branch,baseBranch:t.baseBranch,jiraTransition:t.jiraTransition,requireApproval:t.requireApproval??!0,doneLabel:t.doneLabel,failedLabel:t.failedLabel,repoName:t.repoName,jira:r.jiraFor(t.repoName??""),cfg:r.cfg,actorEmail:t.actorEmail,resultText:f.resultText,costFields:b,runTests:t.runTests,fixSession:{sessionId:t.sessionId,agent:t.agent??"",model:t.model,timeoutSeconds:t.timeoutSeconds,maxTurns:t.maxTurns},sendUsage:o,mergeOnApprove:t.mergeOnApprove,mergeMethod:t.mergeMethod,autoMerge:t.autoMerge??!1,emit:s,setStatus:i}),xt(t.runId)}catch(p){let f=p instanceof Error?p.message:String(p);s("error",`Run failed: ${f}`),await Et(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,f),xt(t.runId),i("failed",{error:f})}finally{u||await kt(t.baseRepoPath??c,c).catch(()=>{})}}async function vd(t){let{runId:e,issueKey:n,issueSummary:r,worktreePath:s,baseRepoPath:i,branch:o,baseBranch:l,jiraTransition:c,jiraTransitionOnMerge:u,requireApproval:p,doneLabel:f,failedLabel:b,repoName:v,jira:w,cfg:x,actorEmail:$,runTests:N,mergeOnApprove:S,mergeMethod:G,autoMerge:O,resultText:M,costFields:W,emit:d,setStatus:m}=t,g=await ns(s);g.deleted.length&&d("info",`Deleted ${g.deleted.length} file(s) listed in ${qt}: `+g.deleted.slice(0,10).join(", ")+(g.deleted.length>10?", \u2026":""));for(let ve of g.refused)d("warn",`${qt} entry refused: ${ve}`);d("info","Committing changes"),await ar(s,`${n}: ${r}
662
734
 
663
- Allwright run ${e}`);let E=await dn(s,l);if(!E.ok){let ve=E.forbidden.length?`refusing to push: changes touch protected paths (${E.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 (${E.files} files, ${E.insertions+E.deletions} lines; limits ${ln}/${cn})`;d("error",ve),await Tt(_,n,e,b,ve),m("failed",{error:ve,errorKind:"guard",...W});return}d("info",`Diff: ${E.files} file(s), +${E.insertions}/-${E.deletions}`);let P={...W},V="",ee="",Y,D,L;if(j){let ve=es(s);if(!ve)d("info","No TEST.md in this repo - skipping the test run (nothing documented to run)");else{let be=ts(Da.default.readFileSync(ve,"utf8"));if(!be.length)d("info",`${Bi.default.basename(ve)} lists no commands - nothing to run`);else{d("info",`Running ${be.length} documented test command(s) - no tokens, plain shell`);let de=await or(s,be,{perCommandTimeoutMs:15*6e4}),Re=de.filter(ce=>ce.exitCode!==0),ko=Re.length;for(let ce of de)d(ce.exitCode===0?"info":"warn",`${ce.exitCode===0?"PASS":"FAIL"} ${ce.command} (exit ${ce.exitCode})`+(ce.exitCode===0?"":`
664
- ${ce.tail.slice(-1500)}`));let Cr="";if(Re.length&&t.fixSession){let ce=await My({runId:e,issueKey:n,worktreePath:s,baseBranch:l,fixSession:t.fixSession,agentConfigDir:t.agentConfigDir,cfg:x,failed:Re,emit:d,sendUsage:t.sendUsage,baseCost:P});if(P.costUsd+=ce.cost.costUsd,P.inputTokens+=ce.cost.inputTokens,P.outputTokens+=ce.cost.outputTokens,ce.outcome==="cancelled"){let Ve="stopped by a person during the automatic test-fix attempt - nothing was pushed";d("warn",Ve),Di({runId:e,issueKey:n,issueSummary:r,mergeOnApprove:S,mergeMethod:G,autoMerge:O,repoName:v,baseRepoPath:i,branch:o,baseBranch:l,headSha:await nt(s),requireApproval:p,doneLabel:f,failedLabel:b,jiraTransition:c,jiraTransitionOnMerge:u,actorEmail:$,resultSummary:Qu(M),prSummary:za(M)??"",costUsd:P.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),await Tt(_,n,e,b,`${Ve}. The commit survived on the runner - "Retry push" on the run's dashboard page ships it without a new agent run.`),m("failed",{error:Ve,errorKind:"guard",retryAvailable:!0,...P});return}if(ce.outcome==="committed"){ee=ce.resultText,d("info",`Re-running ${be.length} documented test command(s) after the fix`),de=await or(s,be,{perCommandTimeoutMs:15*6e4}),Re=de.filter(Ve=>Ve.exitCode!==0);for(let Ve of de)d(Ve.exitCode===0?"info":"warn",`${Ve.exitCode===0?"PASS":"FAIL"} ${Ve.command} (exit ${Ve.exitCode})`+(Ve.exitCode===0?"":`
665
- ${Ve.tail.slice(-1500)}`));Cr=Re.length?`One automatic same-session fix attempt ran; the results above are AFTER it. First pass: ${ko} failure(s). ${ce.note}`:`The first pass had ${ko} failure(s); one automatic same-session fix attempt resolved them. ${ce.note}`}else Cr=ce.note}Y=Re.slice(0,20).map(ce=>({command:ce.command.slice(0,500),exitCode:ce.exitCode,tail:ce.tail.slice(-4e3)})),D=de.length-Re.length,L=de.length,V=`
735
+ Allwright run ${e}`);let E=await gn(s,l);if(!E.ok){let ve=E.forbidden.length?`refusing to push: changes touch protected paths (${E.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 (${E.files} files, ${E.insertions+E.deletions} lines; limits ${pn}/${fn})`;d("error",ve),await Et(w,n,e,b,ve),m("failed",{error:ve,errorKind:"guard",...W});return}d("info",`Diff: ${E.files} file(s), +${E.insertions}/-${E.deletions}`);let P={...W},V="",ee="",Y,D,L;if(N){let ve=os(s);if(!ve)d("info","No TEST.md in this repo - skipping the test run (nothing documented to run)");else{let be=as(Wa.default.readFileSync(ve,"utf8"));if(!be.length)d("info",`${Yi.default.basename(ve)} lists no commands - nothing to run`);else{d("info",`Running ${be.length} documented test command(s) - no tokens, plain shell`);let de=await hr(s,be,{perCommandTimeoutMs:15*6e4}),Ie=de.filter(ce=>ce.exitCode!==0),Po=Ie.length;for(let ce of de)d(ce.exitCode===0?"info":"warn",`${ce.exitCode===0?"PASS":"FAIL"} ${ce.command} (exit ${ce.exitCode})`+(ce.exitCode===0?"":`
736
+ ${ce.tail.slice(-1500)}`));let Mr="";if(Ie.length&&t.fixSession){let ce=await sb({runId:e,issueKey:n,worktreePath:s,baseBranch:l,fixSession:t.fixSession,agentConfigDir:t.agentConfigDir,cfg:x,failed:Ie,emit:d,sendUsage:t.sendUsage,baseCost:P});if(P.costUsd+=ce.cost.costUsd,P.inputTokens+=ce.cost.inputTokens,P.outputTokens+=ce.cost.outputTokens,ce.outcome==="cancelled"){let Ye="stopped by a person during the automatic test-fix attempt - nothing was pushed";d("warn",Ye),Hi({runId:e,issueKey:n,issueSummary:r,mergeOnApprove:S,mergeMethod:G,autoMerge:O,repoName:v,baseRepoPath:i,branch:o,baseBranch:l,headSha:await st(s),requireApproval:p,doneLabel:f,failedLabel:b,jiraTransition:c,jiraTransitionOnMerge:u,actorEmail:$,resultSummary:ud(M),prSummary:Va(M)??"",costUsd:P.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),await Et(w,n,e,b,`${Ye}. The commit survived on the runner - "Retry push" on the run's dashboard page ships it without a new agent run.`),m("failed",{error:Ye,errorKind:"guard",retryAvailable:!0,...P});return}if(ce.outcome==="committed"){ee=ce.resultText,d("info",`Re-running ${be.length} documented test command(s) after the fix`),de=await hr(s,be,{perCommandTimeoutMs:15*6e4}),Ie=de.filter(Ye=>Ye.exitCode!==0);for(let Ye of de)d(Ye.exitCode===0?"info":"warn",`${Ye.exitCode===0?"PASS":"FAIL"} ${Ye.command} (exit ${Ye.exitCode})`+(Ye.exitCode===0?"":`
737
+ ${Ye.tail.slice(-1500)}`));Mr=Ie.length?`One automatic same-session fix attempt ran; the results above are AFTER it. First pass: ${Po} failure(s). ${ce.note}`:`The first pass had ${Po} failure(s); one automatic same-session fix attempt resolved them. ${ce.note}`}else Mr=ce.note}Y=Ie.slice(0,20).map(ce=>({command:ce.command.slice(0,500),exitCode:ce.exitCode,tail:ce.tail.slice(-4e3)})),D=de.length-Ie.length,L=de.length,V=`
666
738
 
667
739
  ### Tests
668
740
  `+de.map(ce=>`- ${ce.exitCode===0?"PASS":"FAIL"} \`${ce.command}\``).join(`
669
- `)+(Re.length?`
741
+ `)+(Ie.length?`
670
742
 
671
- **${Re.length} of ${de.length} failed.** Output is in the run log.`:`
743
+ **${Ie.length} of ${de.length} failed.** Output is in the run log.`:`
672
744
 
673
- All ${de.length} passed.`)+(Cr?`
745
+ All ${de.length} passed.`)+(Mr?`
674
746
 
675
- ${Cr}`:""),Re.length&&d("warn",`${Re.length} test command(s) failed - the PR will say so; review before merging`),ko>0&&ct(i,{issueKey:n,runId:e,title:Re.length?`TEST.md commands failing at PR (${Re.length} of ${de.length})`:"TEST.md failures fixed by same-session retry",detail:de.map(ce=>`${ce.exitCode===0?"PASS":"FAIL"} ${ce.command}`).join(`
676
- `)+(Cr?`
677
- ${Cr}`:"")})}}}let re=await rr(s),B=lt(re);if(!B){let ve=`origin "${re}" is not a GitHub remote - implement mode supports GitHub only`;d("error",ve),await Tt(_,n,e,b,ve),m("failed",{error:ve,...W});return}let le=await nt(s),Oe=Qu(M),me=(ee?za(ee):null)??za(M);try{await cd({gitDir:s,ownerRepo:B,runId:e,issueKey:n,issueSummary:r,agentConfigDir:t.agentConfigDir,branch:o,baseBranch:l,jiraTransition:c,jiraTransitionOnMerge:u,requireApproval:p,doneLabel:f,failedLabel:b,repoName:v,jira:_,cfg:x,actorEmail:$,mergeOnApprove:S,mergeMethod:G,autoMerge:O,summary:Oe,prSummary:me??void 0,cost:P,testReport:V,failedTests:Y,testsPassed:D,testsTotal:L,goLiveDraft:(ee?Yu(ee):null)??Yu(M)??void 0,emit:d,setStatus:m})}catch(ve){let be=ve instanceof Error?ve.message:String(ve);Di({runId:e,issueKey:n,issueSummary:r,mergeOnApprove:S,mergeMethod:G,autoMerge:O,repoName:v,baseRepoPath:i,branch:o,baseBranch:l,headSha:le,requireApproval:p,doneLabel:f,failedLabel:b,jiraTransition:c,jiraTransitionOnMerge:u,actorEmail:$,resultSummary:Oe,prSummary:me??"",costUsd:P.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),d("error",`Run failed: ${be}`),d("info",`The commit itself survived on the runner (branch ${o}) - fix the cause, then use "Retry push" on this run's dashboard page.`),await Tt(_,n,e,b,`${be}
747
+ ${Mr}`:""),Ie.length&&d("warn",`${Ie.length} test command(s) failed - the PR will say so; review before merging`),Po>0&&dt(i,{issueKey:n,runId:e,title:Ie.length?`TEST.md commands failing at PR (${Ie.length} of ${de.length})`:"TEST.md failures fixed by same-session retry",detail:de.map(ce=>`${ce.exitCode===0?"PASS":"FAIL"} ${ce.command}`).join(`
748
+ `)+(Mr?`
749
+ ${Mr}`:"")})}}}let re=await cr(s),B=ut(re);if(!B){let ve=`origin "${re}" is not a GitHub remote - implement mode supports GitHub only`;d("error",ve),await Et(w,n,e,b,ve),m("failed",{error:ve,...W});return}let le=await st(s),Me=ud(M),me=(ee?Va(ee):null)??Va(M);try{await wd({gitDir:s,ownerRepo:B,runId:e,issueKey:n,issueSummary:r,agentConfigDir:t.agentConfigDir,branch:o,baseBranch:l,jiraTransition:c,jiraTransitionOnMerge:u,requireApproval:p,doneLabel:f,failedLabel:b,repoName:v,jira:w,cfg:x,actorEmail:$,mergeOnApprove:S,mergeMethod:G,autoMerge:O,summary:Me,prSummary:me??void 0,cost:P,testReport:V,failedTests:Y,testsPassed:D,testsTotal:L,goLiveDraft:(ee?ad(ee):null)??ad(M)??void 0,emit:d,setStatus:m})}catch(ve){let be=ve instanceof Error?ve.message:String(ve);Hi({runId:e,issueKey:n,issueSummary:r,mergeOnApprove:S,mergeMethod:G,autoMerge:O,repoName:v,baseRepoPath:i,branch:o,baseBranch:l,headSha:le,requireApproval:p,doneLabel:f,failedLabel:b,jiraTransition:c,jiraTransitionOnMerge:u,actorEmail:$,resultSummary:Me,prSummary:me??"",costUsd:P.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),d("error",`Run failed: ${be}`),d("info",`The commit itself survived on the runner (branch ${o}) - fix the cause, then use "Retry push" on this run's dashboard page.`),await Et(w,n,e,b,`${be}
678
750
 
679
- The agent's commit survived on the runner - "Retry push" on the dashboard's run page re-pushes it without a new agent run.`),m("failed",{error:be,retryAvailable:!0,...P})}}var Oy={costUsd:0,inputTokens:0,outputTokens:0};async function My(t){let{runId:e,issueKey:n,worktreePath:r,baseBranch:s,fixSession:i,cfg:o,failed:l,emit:c,sendUsage:u,baseCost:p}=t,f=Be(i.agent);if(!f?.capabilities.sessionResume){let j=`No automatic fix attempt: the ${i.agent||"configured"} adapter cannot resume sessions.`;return c("info",j),{outcome:"skipped",note:j,cost:Oy}}c("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 nt(r),v=await os(e,f,{repoPath:r,prompt:Iy(l),timeoutSeconds:i.timeoutSeconds,bin:Ue(o,i.agent),configDir:t.agentConfigDir,mode:"edit_no_shell",model:i.model||void 0,maxTurns:Math.min(i.maxTurns??120,60),sessionId:i.sessionId,resume:!0,onLog:(j,S)=>c(j,S),onUsage:u?j=>u({...j,inputTokens:p.inputTokens+j.inputTokens,outputTokens:p.outputTokens+j.outputTokens,costUsd:j.costUsd===void 0?void 0:p.costUsd+j.costUsd}):void 0},c),_={costUsd:v.costUsd,inputTokens:v.inputTokens,outputTokens:v.outputTokens};if(v.cancelled)return{outcome:"cancelled",cost:_};if(!v.ok){let j=`One automatic fix attempt did not complete (${v.error??"agent error"}) - the results above are from the original work.`;return c("warn",j),{outcome:"agent_failed",note:j,cost:_}}if(Ds(v.resultText)){let j="One automatic fix attempt asked for human input instead of fixing - the original commit ships unchanged; answer on the PR instead.";return c("warn",j),{outcome:"agent_failed",note:j,cost:_}}let x=await Yr(r);for(let j of x.refused)c("warn",`${Dt} entry refused: ${j}`);try{await tr(r,`${n}: fix failing TEST.md commands
751
+ The agent's commit survived on the runner - "Retry push" on the dashboard's run page re-pushes it without a new agent run.`),m("failed",{error:be,retryAvailable:!0,...P})}}var rb={costUsd:0,inputTokens:0,outputTokens:0};async function sb(t){let{runId:e,issueKey:n,worktreePath:r,baseBranch:s,fixSession:i,cfg:o,failed:l,emit:c,sendUsage:u,baseCost:p}=t,f=Ke(i.agent);if(!f?.capabilities.sessionResume){let N=`No automatic fix attempt: the ${i.agent||"configured"} adapter cannot resume sessions.`;return c("info",N),{outcome:"skipped",note:N,cost:rb}}c("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 st(r),v=await hs(e,f,{repoPath:r,prompt:Yy(l),timeoutSeconds:i.timeoutSeconds,bin:qe(o,i.agent),configDir:t.agentConfigDir,mode:"edit_no_shell",model:i.model||void 0,maxTurns:Math.min(i.maxTurns??120,60),sessionId:i.sessionId,resume:!0,onLog:(N,S)=>c(N,S),onUsage:u?N=>u({...N,inputTokens:p.inputTokens+N.inputTokens,outputTokens:p.outputTokens+N.outputTokens,costUsd:N.costUsd===void 0?void 0:p.costUsd+N.costUsd}):void 0},c),w={costUsd:v.costUsd,inputTokens:v.inputTokens,outputTokens:v.outputTokens};if(v.cancelled)return{outcome:"cancelled",cost:w};if(!v.ok){let N=`One automatic fix attempt did not complete (${v.error??"agent error"}) - the results above are from the original work.`;return c("warn",N),{outcome:"agent_failed",note:N,cost:w}}if(Hs(v.resultText)){let N="One automatic fix attempt asked for human input instead of fixing - the original commit ships unchanged; answer on the PR instead.";return c("warn",N),{outcome:"agent_failed",note:N,cost:w}}let x=await ns(r);for(let N of x.refused)c("warn",`${qt} entry refused: ${N}`);try{await ar(r,`${n}: fix failing TEST.md commands
680
752
 
681
- Allwright run ${e} (automatic test-fix attempt)`)}catch{let j=`An automatic fix attempt concluded no code change was warranted: ${hr(v.resultText)}`;return c("info",j),{outcome:"no_changes",note:j,cost:_}}let $=await dn(r,s);if(!$.ok){await Jr(r,b);let j=$.forbidden.length?`An automatic fix attempt touched protected paths (${$.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 c("warn",j),{outcome:"reverted",note:j,cost:_}}return{outcome:"committed",note:`Fix attempt: ${hr(v.resultText)}`,resultText:v.resultText,cost:_}}async function cd(t){let{gitDir:e,ownerRepo:n,runId:r,issueKey:s,issueSummary:i,mergeOnApprove:o,mergeMethod:l,autoMerge:c,branch:u,baseBranch:p,jiraTransition:f,jiraTransitionOnMerge:b,requireApproval:v,doneLabel:_,failedLabel:x,repoName:$,jira:j,cfg:S,actorEmail:G,summary:O,prSummary:M,cost:W,testReport:d,emit:m,setStatus:g}=t;m("info",`Pushing ${u} to origin`),await nr(e,u);let E=await Ii(e,u),V=`${M?.trim()?`${M.trim()}
753
+ Allwright run ${e} (automatic test-fix attempt)`)}catch{let N=`An automatic fix attempt concluded no code change was warranted: ${br(v.resultText)}`;return c("info",N),{outcome:"no_changes",note:N,cost:w}}let $=await gn(r,s);if(!$.ok){await rs(r,b);let N=$.forbidden.length?`An automatic fix attempt touched protected paths (${$.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 c("warn",N),{outcome:"reverted",note:N,cost:w}}return{outcome:"committed",note:`Fix attempt: ${br(v.resultText)}`,resultText:v.resultText,cost:w}}async function wd(t){let{gitDir:e,ownerRepo:n,runId:r,issueKey:s,issueSummary:i,mergeOnApprove:o,mergeMethod:l,autoMerge:c,branch:u,baseBranch:p,jiraTransition:f,jiraTransitionOnMerge:b,requireApproval:v,doneLabel:w,failedLabel:x,repoName:$,jira:N,cfg:S,actorEmail:G,summary:O,prSummary:M,cost:W,testReport:d,emit:m,setStatus:g}=t;m("info",`Pushing ${u} to origin`),await lr(e,u);let E=await Oi(e,u),V=`${M?.trim()?`${M.trim()}
682
754
 
683
755
  <details>
684
756
  <summary>Technical details</summary>
@@ -689,13 +761,13 @@ ${O}
689
761
 
690
762
  ---
691
763
  Jira: ${new URL(`/browse/${s}`,S.jira?.baseUrl??"").toString()}
692
- _Allwright implement run \`${r}\` \xB7 cost $${W.costUsd.toFixed(4)}. `+(d?"Tests were run by the runner, not the agent._":"The agent has no shell and no tests were run here - review accordingly._");m("info","Opening pull request");let ee=$i(ye()??S,$,G);ee.source==="user"&&m("info",`PR will be authored with ${G}'s own GitHub token`);let D=await new $e(ee.token).createPullRequest(n.owner,n.repo,{title:`${s}: ${i}`.slice(0,250),head:u,base:p,body:V});m("info",`PR ready: ${D.url}`),Hu({runId:r,issueKey:s,repoName:$,owner:n.owner,repo:n.repo,prNumber:D.number,prUrl:D.url,jiraTransitionOnMerge:b??"",createdAt:new Date().toISOString()}),g("posting",W);let L={nextDecisionSeq:1e5,runId:r,issueKey:s,repoName:$,owner:n.owner,repo:n.repo,prNumber:D.number,prUrl:D.url,branch:u,headSha:E,doneLabel:_,failedLabel:x,jiraTransition:f,mergeOnApprove:o,mergeMethod:l,autoMerge:c,agentConfigDir:t.agentConfigDir};if(v)dt(L),await j.addComment(s,`**Allwright opened a pull request for review.**
764
+ _Allwright implement run \`${r}\` \xB7 cost $${W.costUsd.toFixed(4)}. `+(d?"Tests were run by the runner, not the agent._":"The agent has no shell and no tests were run here - review accordingly._");m("info","Opening pull request");let ee=Di(ye()??S,$,G);ee.source==="user"&&m("info",`PR will be authored with ${G}'s own GitHub token`);let D=await new Pe(ee.token).createPullRequest(n.owner,n.repo,{title:`${s}: ${i}`.slice(0,250),head:u,base:p,body:V});m("info",`PR ready: ${D.url}`),nd({runId:r,issueKey:s,repoName:$,owner:n.owner,repo:n.repo,prNumber:D.number,prUrl:D.url,jiraTransitionOnMerge:b??"",createdAt:new Date().toISOString()}),g("posting",W);let L={nextDecisionSeq:1e5,runId:r,issueKey:s,repoName:$,owner:n.owner,repo:n.repo,prNumber:D.number,prUrl:D.url,branch:u,headSha:E,doneLabel:w,failedLabel:x,jiraTransition:f,mergeOnApprove:o,mergeMethod:l,autoMerge:c,agentConfigDir:t.agentConfigDir};if(v)pt(L),await N.addComment(s,`**Allwright opened a pull request for review.**
693
765
 
694
766
  PR: ${D.url}
695
767
 
696
- 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}\`)`),g("awaiting_approval",{...W,prUrl:D.url,headSha:E,resultSummary:hr(M?.trim()||O),retryAvailable:!1,...t.failedTests!==void 0?{failedTests:t.failedTests}:{},...t.testsPassed!==void 0?{testsPassed:t.testsPassed}:{},...t.testsTotal!==void 0?{testsTotal:t.testsTotal}:{},...t.goLiveDraft!==void 0?{goLiveDraft:t.goLiveDraft}:{}}),m("info",`Awaiting approval on the dashboard \xB7 $${W.costUsd.toFixed(4)}`);else{if(c){m("info",`Auto-merging PR #${D.number} (${l})`);let B=Ce(S,$),le=B?await new $e(B).mergePullRequest(n.owner,n.repo,D.number,l,{sha:E,title:`${s} (#${D.number})`}):{merged:!1,reason:"no GitHub token applies to this repo"};le.merged?m("info",`PR #${D.number} merged`):(m("warn",`Auto-merge did not go through - ${le.reason}. The PR stays open.`),await j.addComment(s,`**Allwright:** the work is done and the PR is open, but auto-merge did not go through - ${le.reason}
768
+ 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}\`)`),g("awaiting_approval",{...W,prUrl:D.url,headSha:E,resultSummary:br(M?.trim()||O),retryAvailable:!1,...t.failedTests!==void 0?{failedTests:t.failedTests}:{},...t.testsPassed!==void 0?{testsPassed:t.testsPassed}:{},...t.testsTotal!==void 0?{testsTotal:t.testsTotal}:{},...t.goLiveDraft!==void 0?{goLiveDraft:t.goLiveDraft}:{}}),m("info",`Awaiting approval on the dashboard \xB7 $${W.costUsd.toFixed(4)}`);else{if(c){m("info",`Auto-merging PR #${D.number} (${l})`);let B=$e(S,$),le=B?await new Pe(B).mergePullRequest(n.owner,n.repo,D.number,l,{sha:E,title:`${s} (#${D.number})`}):{merged:!1,reason:"no GitHub token applies to this repo"};le.merged?m("info",`PR #${D.number} merged`):(m("warn",`Auto-merge did not go through - ${le.reason}. The PR stays open.`),await N.addComment(s,`**Allwright:** the work is done and the PR is open, but auto-merge did not go through - ${le.reason}
697
769
 
698
- PR: ${D.url}`))}let re=(ye()??S).repos[$]?.path;re&&$s(re,s)&&ct(re,{issueKey:s,runId:r,title:"shipped after earlier failure",detail:`PR ${D.url} merged/opened straight-through.`}),await ud({jira:j,issueKey:s},L,m),g("succeeded",{...W,prUrl:D.url,headSha:E,resultSummary:hr(M?.trim()||O),retryAvailable:!1,...t.failedTests!==void 0?{failedTests:t.failedTests}:{},...t.testsPassed!==void 0?{testsPassed:t.testsPassed}:{},...t.testsTotal!==void 0?{testsTotal:t.testsTotal}:{},...t.goLiveDraft!==void 0?{goLiveDraft:t.goLiveDraft}:{}}),m("info",`Run succeeded \xB7 ${D.url} \xB7 $${W.costUsd.toFixed(4)}`)}}async function ud(t,e,n){let r=null;if(e.jiraTransition)try{await t.jira.transitionByName(e.issueKey,e.jiraTransition)?n("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`,n("warn",r))}catch(i){r=`Jira transition failed: ${i instanceof Error?i.message:i}`,n("warn",r)}let s=e.mergeOnApprove;return await t.jira.addComment(e.issueKey,(s?`**Allwright: implementation complete - the pull request was merged.**
770
+ PR: ${D.url}`))}let re=(ye()??S).repos[$]?.path;re&&Ds(re,s)&&dt(re,{issueKey:s,runId:r,title:"shipped after earlier failure",detail:`PR ${D.url} merged/opened straight-through.`}),await kd({jira:N,issueKey:s},L,m),g("succeeded",{...W,prUrl:D.url,headSha:E,resultSummary:br(M?.trim()||O),retryAvailable:!1,...t.failedTests!==void 0?{failedTests:t.failedTests}:{},...t.testsPassed!==void 0?{testsPassed:t.testsPassed}:{},...t.testsTotal!==void 0?{testsTotal:t.testsTotal}:{},...t.goLiveDraft!==void 0?{goLiveDraft:t.goLiveDraft}:{}}),m("info",`Run succeeded \xB7 ${D.url} \xB7 $${W.costUsd.toFixed(4)}`)}}async function kd(t,e,n){let r=null;if(e.jiraTransition)try{await t.jira.transitionByName(e.issueKey,e.jiraTransition)?n("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`,n("warn",r))}catch(i){r=`Jira transition failed: ${i instanceof Error?i.message:i}`,n("warn",r)}let s=e.mergeOnApprove;return await t.jira.addComment(e.issueKey,(s?`**Allwright: implementation complete - the pull request was merged.**
699
771
 
700
772
  PR: ${e.prUrl}`:`**Allwright: the change is approved, but NOT merged yet.**
701
773
 
@@ -705,66 +777,43 @@ This rule is set to "my team merges on GitHub", so Allwright deliberately did no
705
777
 
706
778
  Note: ${r}`:"")+`
707
779
 
708
- (run \`${e.runId}\`)`),await t.jira.editLabels(e.issueKey,{add:[e.doneLabel],remove:[we.NEEDS_INPUT_LABEL]}),r}async function Ms(t,e,n){let r=ss(e);if(!r){y.warn(`run.approved for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:s,setStatus:i}=pd(t,e);try{let o=Ce(ye()??t.cfg,r.repoName);if(!o)throw new Error("GitHub token missing on this runner");let l=new $e(o);s("info",`Approval received for ${r.issueKey} - verifying PR state`);let c=await l.getPullRequest(r.owner,r.repo,r.prNumber);if(!c)throw new Error(`PR #${r.prNumber} no longer exists on GitHub`);if(c.state==="closed"&&!c.merged)throw new Error(`PR #${r.prNumber} was closed on GitHub without merging`);let u=n??r.headSha;if(c.state==="open"&&c.headSha!==u){let p=`PR #${r.prNumber} changed since review started (${u.slice(0,7)} \u2192 ${c.headSha.slice(0,7)}) - approval not applied. Re-review the PR and approve again.`;s("warn",p),await t.jiraFor(r.repoName??"").addComment(r.issueKey,`**Allwright:** ${p}`),i("awaiting_approval",{prUrl:r.prUrl,headSha:c.headSha,resultSummary:p});return}if(r.mergeOnApprove&&c.state==="open"&&!c.merged){s("info",`Merging PR #${r.prNumber} (${r.mergeMethod})`);let p=await l.mergePullRequest(r.owner,r.repo,r.prNumber,r.mergeMethod,{sha:u,title:`${r.issueKey} (#${r.prNumber})`});if(!p.merged){let f=`Approved, but the merge did not go through - ${p.reason}`;s("warn",f),await t.jiraFor(r.repoName??"").addComment(r.issueKey,`**Allwright:** ${f}
780
+ (run \`${e.runId}\`)`),await t.jira.editLabels(e.issueKey,{add:[e.doneLabel],remove:[we.NEEDS_INPUT_LABEL]}),r}async function Bs(t,e,n){let r=us(e);if(!r){y.warn(`run.approved for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:s,setStatus:i}=Td(t,e);try{let o=$e(ye()??t.cfg,r.repoName);if(!o)throw new Error("GitHub token missing on this runner");let l=new Pe(o);s("info",`Approval received for ${r.issueKey} - verifying PR state`);let c=await l.getPullRequest(r.owner,r.repo,r.prNumber);if(!c)throw new Error(`PR #${r.prNumber} no longer exists on GitHub`);if(c.state==="closed"&&!c.merged)throw new Error(`PR #${r.prNumber} was closed on GitHub without merging`);let u=n??r.headSha;if(c.state==="open"&&c.headSha!==u){let p=`PR #${r.prNumber} changed since review started (${u.slice(0,7)} \u2192 ${c.headSha.slice(0,7)}) - approval not applied. Re-review the PR and approve again.`;s("warn",p),await t.jiraFor(r.repoName??"").addComment(r.issueKey,`**Allwright:** ${p}`),i("awaiting_approval",{prUrl:r.prUrl,headSha:c.headSha,resultSummary:p});return}if(r.mergeOnApprove&&c.state==="open"&&!c.merged){s("info",`Merging PR #${r.prNumber} (${r.mergeMethod})`);let p=await l.mergePullRequest(r.owner,r.repo,r.prNumber,r.mergeMethod,{sha:u,title:`${r.issueKey} (#${r.prNumber})`});if(!p.merged){let f=`Approved, but the merge did not go through - ${p.reason}`;s("warn",f),await t.jiraFor(r.repoName??"").addComment(r.issueKey,`**Allwright:** ${f}
709
781
 
710
- PR: ${r.prUrl}`),i("awaiting_approval",{prUrl:r.prUrl,headSha:c.headSha,resultSummary:f});return}s("info",`PR #${r.prNumber} merged`)}{let p=(ye()??t.cfg).repos[r.repoName??""]?.path;p&&$s(p,r.issueKey)&&ct(p,{issueKey:r.issueKey,runId:e,title:"shipped after earlier failure",detail:`PR ${r.prUrl} approved and completed.`})}await ud({jira:t.jiraFor(r.repoName??""),issueKey:r.issueKey},r,s),i("succeeded",{prUrl:r.prUrl,...r.mergeOnApprove?{}:{resultSummary:"Approved, but the PR was NOT merged - this rule leaves merging to your team on GitHub. Nothing ships until someone merges it."}}),s("info",r.mergeOnApprove?"Run completed after approval":'Run completed after approval - the PR is still OPEN because this rule does not merge on approval. Merge it on GitHub, or turn on "Merge the PR when I approve" in the rule.'),cr(e)}catch(o){let l=o instanceof Error?o.message:String(o);s("error",`Approval handling failed: ${l}`),await fd(t,r,l),i("failed",{error:l}),cr(e)}}async function dd(t,e){let n=ss(e);if(!n){y.warn(`run.rejected for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:r,setStatus:s}=pd(t,e);try{let i=Ce(ye()??t.cfg,n.repoName);if(!i)throw new Error("GitHub token missing on this runner");let o=new $e(i);r("info",`Rejection received for ${n.issueKey} - closing PR #${n.prNumber}`);let l=await o.getPullRequest(n.owner,n.repo,n.prNumber);l&&l.state==="open"&&await o.closePullRequest(n.owner,n.repo,n.prNumber),l?.merged||await o.deleteBranch(n.owner,n.repo,n.branch),await t.jiraFor(n.repoName??"").addComment(n.issueKey,`**Allwright: changes rejected.**
782
+ PR: ${r.prUrl}`),i("awaiting_approval",{prUrl:r.prUrl,headSha:c.headSha,resultSummary:f});return}s("info",`PR #${r.prNumber} merged`)}{let p=(ye()??t.cfg).repos[r.repoName??""]?.path;p&&Ds(p,r.issueKey)&&dt(p,{issueKey:r.issueKey,runId:e,title:"shipped after earlier failure",detail:`PR ${r.prUrl} approved and completed.`})}await kd({jira:t.jiraFor(r.repoName??""),issueKey:r.issueKey},r,s),i("succeeded",{prUrl:r.prUrl,...r.mergeOnApprove?{}:{resultSummary:"Approved, but the PR was NOT merged - this rule leaves merging to your team on GitHub. Nothing ships until someone merges it."}}),s("info",r.mergeOnApprove?"Run completed after approval":'Run completed after approval - the PR is still OPEN because this rule does not merge on approval. Merge it on GitHub, or turn on "Merge the PR when I approve" in the rule.'),mr(e)}catch(o){let l=o instanceof Error?o.message:String(o);s("error",`Approval handling failed: ${l}`),await xd(t,r,l),i("failed",{error:l}),mr(e)}}async function _d(t,e){let n=us(e);if(!n){y.warn(`run.rejected for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:r,setStatus:s}=Td(t,e);try{let i=$e(ye()??t.cfg,n.repoName);if(!i)throw new Error("GitHub token missing on this runner");let o=new Pe(i);r("info",`Rejection received for ${n.issueKey} - closing PR #${n.prNumber}`);let l=await o.getPullRequest(n.owner,n.repo,n.prNumber);l&&l.state==="open"&&await o.closePullRequest(n.owner,n.repo,n.prNumber),l?.merged||await o.deleteBranch(n.owner,n.repo,n.branch),await t.jiraFor(n.repoName??"").addComment(n.issueKey,`**Allwright: changes rejected.**
711
783
 
712
- The pull request was closed and the branch deleted. This ticket is labeled \`${n.failedLabel}\`; remove the label to try again. (run \`${n.runId}\`)`),await t.jiraFor(n.repoName??"").editLabels(n.issueKey,{add:[n.failedLabel]}),s("failed",{error:"rejected by user"}),r("info","PR closed, branch deleted, ticket labeled"),cr(e)}catch(i){let o=i instanceof Error?i.message:String(i);r("error",`Rejection handling failed: ${o}`),await fd(t,n,o),s("failed",{error:o}),cr(e)}}async function hd(t,e){let n=Li(e);if(!n){y.warn(`run.retryPush for ${e}: no retry record (already pushed, or invalidated?)`);let{emit:l,setStatus:c,sendUsage:u}=dr(e,t.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."),c("failed",{retryAvailable:!1});return}let{emit:r,setStatus:s,sendUsage:i,nextSeq:o}=dr(e,t.transport,n.nextLogSeq);try{let l=await Ii(n.baseRepoPath,n.branch);if(l!==n.headSha){r("error",`Retry push aborted: branch ${n.branch} no longer holds the commit this run produced (expected ${n.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.`),Oa(e),s("failed",{retryAvailable:!1});return}let c=await rr(n.baseRepoPath),u=lt(c);if(!u)throw new Error(`origin "${c}" is not a GitHub remote`);r("info",`Retry push for ${n.issueKey}: branch ${n.branch} at ${n.headSha.slice(0,7)}`);let p=t.jiraFor(n.repoName);await cd({gitDir:n.baseRepoPath,ownerRepo:u,runId:n.runId,issueKey:n.issueKey,issueSummary:n.issueSummary,branch:n.branch,baseBranch:n.baseBranch,jiraTransition:n.jiraTransition,jiraTransitionOnMerge:n.jiraTransitionOnMerge,requireApproval:n.requireApproval,mergeOnApprove:n.mergeOnApprove??!1,mergeMethod:n.mergeMethod??"squash",autoMerge:n.autoMerge??!1,doneLabel:n.doneLabel,failedLabel:n.failedLabel,repoName:n.repoName,jira:p,cfg:ye()??t.cfg,actorEmail:n.actorEmail,summary:n.resultSummary,prSummary:n.prSummary||void 0,cost:{costUsd:n.costUsd},emit:r,setStatus:s}),Oa(e),await p.editLabels(n.issueKey,{remove:[n.failedLabel]}).catch(()=>{})}catch(l){let c=l instanceof Error?l.message:String(l);r("error",`Retry push failed: ${c}`),Di({...n,nextLogSeq:o()}),s("failed",{error:c,retryAvailable:!0})}}function pd(t,e){let n=1e5;return{emit:(i,o)=>{t.transport.send({type:"run.log",runId:e,seq:n++,ts:new Date().toISOString(),level:i,message:o}),i!=="agent"&&y.info(`[run ${e}] ${o}`)},setStatus:(i,o={})=>{t.transport.send({type:"run.status",runId:e,status:i,...o})}}}async function fd(t,e,n){try{await t.jiraFor(e.repoName??"").addComment(e.issueKey,`**Allwright could not complete the approval decision.**
784
+ The pull request was closed and the branch deleted. This ticket is labeled \`${n.failedLabel}\`; remove the label to try again. (run \`${n.runId}\`)`),await t.jiraFor(n.repoName??"").editLabels(n.issueKey,{add:[n.failedLabel]}),s("failed",{error:"rejected by user"}),r("info","PR closed, branch deleted, ticket labeled"),mr(e)}catch(i){let o=i instanceof Error?i.message:String(i);r("error",`Rejection handling failed: ${o}`),await xd(t,n,o),s("failed",{error:o}),mr(e)}}async function Sd(t,e){let n=Gi(e);if(!n){y.warn(`run.retryPush for ${e}: no retry record (already pushed, or invalidated?)`);let{emit:l,setStatus:c,sendUsage:u}=yr(e,t.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."),c("failed",{retryAvailable:!1});return}let{emit:r,setStatus:s,sendUsage:i,nextSeq:o}=yr(e,t.transport,n.nextLogSeq);try{let l=await Oi(n.baseRepoPath,n.branch);if(l!==n.headSha){r("error",`Retry push aborted: branch ${n.branch} no longer holds the commit this run produced (expected ${n.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.`),Ga(e),s("failed",{retryAvailable:!1});return}let c=await cr(n.baseRepoPath),u=ut(c);if(!u)throw new Error(`origin "${c}" is not a GitHub remote`);r("info",`Retry push for ${n.issueKey}: branch ${n.branch} at ${n.headSha.slice(0,7)}`);let p=t.jiraFor(n.repoName);await wd({gitDir:n.baseRepoPath,ownerRepo:u,runId:n.runId,issueKey:n.issueKey,issueSummary:n.issueSummary,branch:n.branch,baseBranch:n.baseBranch,jiraTransition:n.jiraTransition,jiraTransitionOnMerge:n.jiraTransitionOnMerge,requireApproval:n.requireApproval,mergeOnApprove:n.mergeOnApprove??!1,mergeMethod:n.mergeMethod??"squash",autoMerge:n.autoMerge??!1,doneLabel:n.doneLabel,failedLabel:n.failedLabel,repoName:n.repoName,jira:p,cfg:ye()??t.cfg,actorEmail:n.actorEmail,summary:n.resultSummary,prSummary:n.prSummary||void 0,cost:{costUsd:n.costUsd},emit:r,setStatus:s}),Ga(e),await p.editLabels(n.issueKey,{remove:[n.failedLabel]}).catch(()=>{})}catch(l){let c=l instanceof Error?l.message:String(l);r("error",`Retry push failed: ${c}`),Hi({...n,nextLogSeq:o()}),s("failed",{error:c,retryAvailable:!0})}}function Td(t,e){let n=1e5;return{emit:(i,o)=>{t.transport.send({type:"run.log",runId:e,seq:n++,ts:new Date().toISOString(),level:i,message:o}),i!=="agent"&&y.info(`[run ${e}] ${o}`)},setStatus:(i,o={})=>{t.transport.send({type:"run.status",runId:e,status:i,...o})}}}async function xd(t,e,n){try{await t.jiraFor(e.repoName??"").addComment(e.issueKey,`**Allwright could not complete the approval decision.**
713
785
 
714
786
  Error: ${n.slice(0,800)}
715
787
 
716
788
  PR: ${e.prUrl}
717
- (run \`${e.runId}\`)`),await t.jiraFor(e.repoName??"").editLabels(e.issueKey,{add:[e.failedLabel]})}catch(r){y.error(`could not post decision failure to ${e.issueKey}: ${r}`)}}function zs(t){if(!t.length)return"(no comments)";let e=6e4,n=t.map(i=>`${i.author} (${i.created}):
789
+ (run \`${e.runId}\`)`),await t.jiraFor(e.repoName??"").editLabels(e.issueKey,{add:[e.failedLabel]})}catch(r){y.error(`could not post decision failure to ${e.issueKey}: ${r}`)}}function Ks(t){if(!t.length)return"(no comments)";let e=6e4,n=t.map(i=>`${i.author} (${i.created}):
718
790
  ${i.body}`),r=[],s=0;for(let i=n.length-1;i>=0;i--){if(s+=n[i].length+6,s>e){r.unshift(`(\u2026 ${i+1} earlier comment(s) omitted for length \u2026)`);break}r.unshift(n[i])}return r.join(`
719
791
  ---
720
- `)}function md(t){return`The ticket author replied:
792
+ `)}function Ed(t){return`The ticket author replied:
721
793
 
722
794
  ${t}
723
795
 
724
- 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 ${we.NEEDS_INPUT_MARKER} marker).`}function Ds(t){let e=t.trim(),n=e.split(`
796
+ 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 ${we.NEEDS_INPUT_MARKER} marker).`}function Hs(t){let e=t.trim(),n=e.split(`
725
797
  `,1)[0].trim(),r=o=>o.replace(/[^a-z]/gi,"").toUpperCase();if(r(n)!==r(we.NEEDS_INPUT_MARKER))return null;let s=e.indexOf(`
726
- `);return s<0?null:e.slice(s+1).trim()||null}function zy(t){let n=[...t.matchAll(new RegExp(`\`\`\`${we.NEEDS_INPUT_ASK_FENCE}\\s*\\n([\\s\\S]*?)\`\`\``,"g"))],r=[];for(let i=n.length-1;i>=0&&!r.length;i--)try{let o=JSON.parse(n[i][1]);r=(Array.isArray(o.options)?o.options:[]).filter(c=>typeof c=="string"&&!!c.trim()).slice(0,5).map(c=>c.trim().slice(0,200))}catch{}return{questions:t.replace(new RegExp(`\`\`\`${we.NEEDS_INPUT_ASK_FENCE}\\s*\\n[\\s\\S]*?\`\`\``,"g"),"").trim()||t.trim(),options:r}}async function Gi(t,e,n,r,s){let{questions:i,options:o}=zy(e);n("info",`Claude needs more information - posting questions to ${t.issueKey}`),await t.jira.addComment(t.issueKey,`**${we.NEEDS_INPUT_COMMENT_MARKER} before it can continue.**
798
+ `);return s<0?null:e.slice(s+1).trim()||null}function ib(t){let n=[...t.matchAll(new RegExp(`\`\`\`${we.NEEDS_INPUT_ASK_FENCE}\\s*\\n([\\s\\S]*?)\`\`\``,"g"))],r=[];for(let i=n.length-1;i>=0&&!r.length;i--)try{let o=JSON.parse(n[i][1]);r=(Array.isArray(o.options)?o.options:[]).filter(c=>typeof c=="string"&&!!c.trim()).slice(0,5).map(c=>c.trim().slice(0,200))}catch{}return{questions:t.replace(new RegExp(`\`\`\`${we.NEEDS_INPUT_ASK_FENCE}\\s*\\n[\\s\\S]*?\`\`\``,"g"),"").trim()||t.trim(),options:r}}async function Qi(t,e,n,r,s){let{questions:i,options:o}=ib(e);n("info",`Claude needs more information - posting questions to ${t.issueKey}`),await t.jira.addComment(t.issueKey,`**${we.NEEDS_INPUT_COMMENT_MARKER} before it can continue.**
727
799
 
728
800
  ${i}
729
801
 
730
- Reply with your answers in a comment on this ticket - or answer on the run page in the Allwright dashboard. Either way this run picks up right where it left off. (run \`${t.runId}\`)`);let l=new Date().toISOString();await t.jira.editLabels(t.issueKey,{add:[we.NEEDS_INPUT_LABEL]}),Vu({runId:t.runId,issueKey:t.issueKey,kind:t.kind,mergeOnApprove:t.mergeOnApprove??!1,mergeMethod:t.mergeMethod??"squash",autoMerge:t.autoMerge??!1,repoPath:t.repoPath,sessionId:t.sessionId,doneLabel:t.doneLabel,failedLabel:t.failedLabel,timeoutSeconds:t.timeoutSeconds,createdAt:t.createdAt??l,questionsPostedAt:l,rounds:t.rounds,nextLogSeq:t.nextLogSeq,baseRepoPath:t.baseRepoPath,repoName:t.repoName,branch:t.branch,baseBranch:t.baseBranch,jiraTransition:t.jiraTransition,jiraTransitionOnMerge:t.jiraTransitionOnMerge,requireApproval:t.requireApproval,maxTurns:t.maxTurns,runTests:t.runTests??!0,issueSummary:t.issueSummary??"",claudeConfigDir:t.claudeConfigDir,agent:t.agent,model:t.model,actorEmail:t.actorEmail}),r("needs_input",{...s,resultSummary:hr(i),inputQuestions:i.slice(0,4e3),inputOptions:o}),n("info",`Waiting for an answer on ${t.issueKey} (label "${we.NEEDS_INPUT_LABEL}") or on this run page`+(o.length?` - ${o.length} suggested answer(s) offered`:""))}async function gd(t,e,n,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.`;n("error",i),await Tt(t,e.issueKey,e.runId,e.failedLabel,i),St(e.runId),r("failed",{error:i,...s})}async function is(t,e){await Tt(t.jira,t.issueKey,t.runId,t.rule.trigger.failedLabel,e)}async function Tt(t,e,n,r,s){try{await t.addComment(e,`**Allwright run failed.**
802
+ Reply with your answers in a comment on this ticket - or answer on the run page in the Allwright dashboard. Either way this run picks up right where it left off. (run \`${t.runId}\`)`);let l=new Date().toISOString();await t.jira.editLabels(t.issueKey,{add:[we.NEEDS_INPUT_LABEL]}),id({runId:t.runId,issueKey:t.issueKey,kind:t.kind,mergeOnApprove:t.mergeOnApprove??!1,mergeMethod:t.mergeMethod??"squash",autoMerge:t.autoMerge??!1,repoPath:t.repoPath,sessionId:t.sessionId,doneLabel:t.doneLabel,failedLabel:t.failedLabel,timeoutSeconds:t.timeoutSeconds,createdAt:t.createdAt??l,questionsPostedAt:l,rounds:t.rounds,nextLogSeq:t.nextLogSeq,baseRepoPath:t.baseRepoPath,repoName:t.repoName,branch:t.branch,baseBranch:t.baseBranch,jiraTransition:t.jiraTransition,jiraTransitionOnMerge:t.jiraTransitionOnMerge,requireApproval:t.requireApproval,maxTurns:t.maxTurns,runTests:t.runTests??!0,issueSummary:t.issueSummary??"",claudeConfigDir:t.claudeConfigDir,agent:t.agent,model:t.model,actorEmail:t.actorEmail}),r("needs_input",{...s,resultSummary:br(i),inputQuestions:i.slice(0,4e3),inputOptions:o}),n("info",`Waiting for an answer on ${t.issueKey} (label "${we.NEEDS_INPUT_LABEL}") or on this run page`+(o.length?` - ${o.length} suggested answer(s) offered`:""))}async function Rd(t,e,n,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.`;n("error",i),await Et(t,e.issueKey,e.runId,e.failedLabel,i),xt(e.runId),r("failed",{error:i,...s})}async function ds(t,e){await Et(t.jira,t.issueKey,t.runId,t.rule.trigger.failedLabel,e)}async function Et(t,e,n,r,s){try{await t.addComment(e,`**Allwright run failed.**
731
803
 
732
804
  Error: ${s.slice(0,800)}
733
805
 
734
- This ticket has been labeled \`${r}\` and will not be retried automatically. To retry, fix the cause and remove the \`${r}\` label. (run \`${n}\`)`),await t.editLabels(e,{add:[r],remove:[we.NEEDS_INPUT_LABEL]})}catch(i){y.error(`could not post failure comment to ${e}: ${i}`)}}function Qu(t){let e=t.split(/\n##\s*(?:PR summary|Go-live draft)\s*\n/i)[0],n=/##\s*Summary of changes\s*\n([\s\S]*)$/i.exec(e);return(n?n[1]:e).trim().slice(0,8e3)||"(no summary provided)"}function za(t){let e=/##\s*PR summary\s*\n([\s\S]*?)(?=\n##\s|$)/i.exec(t),n=e?e[1].trim():"";return n?n.slice(0,2e3):null}function hr(t){for(let e of t.split(`
735
- `)){let n=e.replace(/^#+\s*/,"").trim();if(n.length>10)return n.slice(0,200)}return t.slice(0,200)}var gr=R(require("node:fs"),1);var pr=R(require("node:fs"),1),Fa=R(require("node:os"),1),fr=R(require("node:path"),1);function Dy(){try{return Fa.default.userInfo().username}catch{return"the user the runner service runs as"}}function Ly(t,e){let n=fr.default.join(t,"apps","api","prisma","manual"),r=fr.default.join(t,"prisma","manual");for(let s of[n,r]){let i;try{i=pr.default.readdirSync(s).filter(o=>o.endsWith(".sql")).sort()}catch{continue}for(let o of i.reverse())try{let l=pr.default.readFileSync(fr.default.join(s,o),"utf8");if(new RegExp(`"${e}"`,"i").test(l))return o}catch{}}return null}function Ba(t,e){let n=t.slice(-4e3),r=Dy(),s=e?.cwd?` -C ${e.cwd}`:"",i=/column "([^"]+)" of relation "([^"]+)" does not exist/i.exec(n)??/column ([\w.]+) does not exist/i.exec(n)??/The column `?([\w.]+)`? does not exist in the current database/i.exec(n)??/relation "([^"]+)" does not exist/i.exec(n);if(i){let u=(i[1]??"").split(".").pop()??"",p=e?.cwd?Ly(e.cwd,u):null;return{cause:`The code expects "${u}" in the database and the database does not have it. This is not a deploy-steps problem: a schema change shipped with the code, and the SQL that applies it is a HUMAN step by design`+(p?` - it is \`prisma/manual/${p}\`, checked in and not yet applied.`:"."),commands:p?[`cd apps/api && npx prisma db execute --file prisma/manual/${p} # dev/test database`,`cd apps/api && npx prisma db execute --url "$PROD_DATABASE_URL" --file prisma/manual/${p} # the live one`]:[`ls apps/api/prisma/manual/ # find the migration that adds "${u}"`,"cd apps/api && npx prisma db execute --file prisma/manual/<that file>"],note:"Apply it to EVERY database the code talks to - the test database and the live one are usually different, and applying only one turns a red build into a green build that breaks at runtime. Then re-run the deploy."}}let o=/\/usr\/bin\/env: ['\u2018]?(node|npm)['\u2019]?: No such file or directory/i.exec(n);if(o){let u="";try{let p=fr.default.join(Fa.default.homedir(),".nvm","versions","node"),f=pr.default.readdirSync(p).sort();f.length&&(u=fr.default.join(p,f[f.length-1],"bin"))}catch{}return{cause:`"${o[1]}" was not on the PATH of the process that ran this. npm's own first line is "#!/usr/bin/env node", so pointing at npm by absolute path does not help - npm still has to find node, and a systemd unit starts with a bare PATH that has never heard of nvm. It exits 127 immediately, and with Restart=always it does that forever while the start timestamp keeps moving, which is why a restart can look like it worked.`,commands:["sudo mkdir -p /etc/systemd/system/<your-unit>.service.d",`sudo tee /etc/systemd/system/<your-unit>.service.d/path.conf >/dev/null <<'EOF'
806
+ This ticket has been labeled \`${r}\` and will not be retried automatically. To retry, fix the cause and remove the \`${r}\` label. (run \`${n}\`)`),await t.editLabels(e,{add:[r],remove:[we.NEEDS_INPUT_LABEL]})}catch(i){y.error(`could not post failure comment to ${e}: ${i}`)}}function ud(t){let e=t.split(/\n##\s*(?:PR summary|Go-live draft)\s*\n/i)[0],n=/##\s*Summary of changes\s*\n([\s\S]*)$/i.exec(e);return(n?n[1]:e).trim().slice(0,8e3)||"(no summary provided)"}function Va(t){let e=/##\s*PR summary\s*\n([\s\S]*?)(?=\n##\s|$)/i.exec(t),n=e?e[1].trim():"";return n?n.slice(0,2e3):null}function br(t){for(let e of t.split(`
807
+ `)){let n=e.replace(/^#+\s*/,"").trim();if(n.length>10)return n.slice(0,200)}return t.slice(0,200)}var _r=R(require("node:fs"),1);var vr=R(require("node:fs"),1),Qa=R(require("node:os"),1),wr=R(require("node:path"),1);function ob(){try{return Qa.default.userInfo().username}catch{return"the user the runner service runs as"}}function ab(t,e){let n=wr.default.join(t,"apps","api","prisma","manual"),r=wr.default.join(t,"prisma","manual");for(let s of[n,r]){let i;try{i=vr.default.readdirSync(s).filter(o=>o.endsWith(".sql")).sort()}catch{continue}for(let o of i.reverse())try{let l=vr.default.readFileSync(wr.default.join(s,o),"utf8");if(new RegExp(`"${e}"`,"i").test(l))return o}catch{}}return null}function el(t,e){let n=t.slice(-4e3),r=ob(),s=e?.cwd?` -C ${e.cwd}`:"",i=/column "([^"]+)" of relation "([^"]+)" does not exist/i.exec(n)??/column ([\w.]+) does not exist/i.exec(n)??/The column `?([\w.]+)`? does not exist in the current database/i.exec(n)??/relation "([^"]+)" does not exist/i.exec(n);if(i){let u=(i[1]??"").split(".").pop()??"",p=e?.cwd?ab(e.cwd,u):null;return{cause:`The code expects "${u}" in the database and the database does not have it. This is not a deploy-steps problem: a schema change shipped with the code, and the SQL that applies it is a HUMAN step by design`+(p?` - it is \`prisma/manual/${p}\`, checked in and not yet applied.`:"."),commands:p?[`cd apps/api && npx prisma db execute --file prisma/manual/${p} # dev/test database`,`cd apps/api && npx prisma db execute --url "$PROD_DATABASE_URL" --file prisma/manual/${p} # the live one`]:[`ls apps/api/prisma/manual/ # find the migration that adds "${u}"`,"cd apps/api && npx prisma db execute --file prisma/manual/<that file>"],note:"Apply it to EVERY database the code talks to - the test database and the live one are usually different, and applying only one turns a red build into a green build that breaks at runtime. Then re-run the deploy."}}let o=/\/usr\/bin\/env: ['\u2018]?(node|npm)['\u2019]?: No such file or directory/i.exec(n);if(o){let u="";try{let p=wr.default.join(Qa.default.homedir(),".nvm","versions","node"),f=vr.default.readdirSync(p).sort();f.length&&(u=wr.default.join(p,f[f.length-1],"bin"))}catch{}return{cause:`"${o[1]}" was not on the PATH of the process that ran this. npm's own first line is "#!/usr/bin/env node", so pointing at npm by absolute path does not help - npm still has to find node, and a systemd unit starts with a bare PATH that has never heard of nvm. It exits 127 immediately, and with Restart=always it does that forever while the start timestamp keeps moving, which is why a restart can look like it worked.`,commands:["sudo mkdir -p /etc/systemd/system/<your-unit>.service.d",`sudo tee /etc/systemd/system/<your-unit>.service.d/path.conf >/dev/null <<'EOF'
736
808
  [Service]
737
809
  Environment=PATH=${u||"<the bin directory holding node>"}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
738
- EOF`,"sudo systemctl daemon-reload && sudo systemctl reset-failed <your-unit> && sudo systemctl restart <your-unit>"],note:"reset-failed because a crash loop leaves a restart counter behind. If you would rather not depend on a version-numbered nvm path, install Node system-wide instead - then /usr/bin/node exists and the bare PATH is enough."}}let l=/Failed to connect to ([\w.]+) port (\d+)|connect to ([\w.]+) port (\d+) failed|Connection refused/i.exec(n);if(l){let u=l[2]??l[4]??"",f=(pr.default.existsSync("/etc/systemd/system")?pr.default.readdirSync("/etc/systemd/system").filter(b=>b.endsWith(".service")).filter(b=>{try{let v=pr.default.readFileSync(fr.default.join("/etc/systemd/system",b),"utf8");return e?.cwd?v.includes(e.cwd):!1}catch{return!1}}).map(b=>b.replace(/\.service$/,"")):[])[0];return{cause:`Nothing is listening on ${l[1]??l[3]??"that address"}${u?`:${u}`:""}. `+(f?`The service that runs this checkout is "${f}" - a restart moves its start timestamp even when it dies a second later, so "a restart really happened" does not mean it stayed up. Either it is crash-looping, or it bound a DIFFERENT port than this check expects.`:"No systemd unit on this machine references this checkout, so nothing here is keeping the app alive between deploys."),commands:f?[`systemctl status ${f} --no-pager -l # active (running), or restarting in a loop?`,`journalctl -u ${f} -n 40 --no-pager # the crash itself`,`systemctl show ${f} -p Environment --value # the PORT it was actually given`,"ss -ltnp | grep -E 'node|next' # what it really bound, if anything"]:["ss -ltnp | grep -E 'node|next' # is anything serving this app at all?"],note:f?"If the port differs, change either the unit's PORT or this check - they must be the same number. If it crash-loops, the journal's last lines are the reason; a wrong ExecStart path shows up as status=203/EXEC.":"Until something supervises this app, a deploy has nothing to restart and nothing survives a reboot."}}if(/could not read (Username|Password) for/i.test(n)||/Authentication failed for .*https/i.test(n)||/fatal: Authentication failed/i.test(n))return{cause:`git needs a GitHub credential for the account this deploy runs as (${r}) and has none. It tried to ask, found no terminal, and gave up. Allwright's own GitHub token is NOT used here: deploy steps are plain shell, so they see only this machine's git config - which is why the same repo can push fine from Allwright and still fail this step.`,commands:[`sudo -u ${r} git${s} ls-remote origin >/dev/null && echo "AUTH OK" || echo "AUTH FAIL"`,`sudo -u ${r} gh auth setup-git # if you signed in with the gh CLI - its login does not reach git by itself`,`sudo -u ${r} git config --global credential.helper store # then one manual 'git fetch' to save the token`],note:`Or switch the checkout to SSH and give ${r} a deploy key: git${s} remote set-url origin git@github.com:OWNER/REPO.git. Never paste a token into a deploy step - it ends up in run logs and screenshots.`};if(/Permission denied \(publickey/i.test(n))return{cause:`SSH could not authenticate to the git host as ${r}. The key either does not exist for that account, or is not the one registered with the repository.`,commands:[`sudo -u ${r} ssh -T git@github.com # expect "successfully authenticated"`,`sudo -u ${r} ls -l ~/.ssh/`],note:"Add that account's public key as a deploy key on the repository (read-only is enough to fetch)."};if(/Host key verification failed/i.test(n))return{cause:`The git host is not in ${r}'s known_hosts, and ssh will not accept it unattended.`,commands:[`sudo -u ${r} ssh-keyscan github.com >> ~/.ssh/known_hosts`],note:"Run it as that user - a known_hosts entry under your own account does nothing for the service."};let c=/(?:^|\n)(?:bash: )?([\w.-]+): command not found/i.exec(n);return c?{cause:`"${c[1]}" is not on the PATH of the account this deploy runs as (${r}). A tool installed through nvm, asdf or a shell profile usually is not: the service starts with a bare environment, not your login shell.`,commands:[`sudo -u ${r} which ${c[1]} || echo "not on this account's PATH"`,`command -v ${c[1]} # where YOUR shell finds it`],note:"Either install it system-wide, or use the absolute path in the step - the path your own shell resolves is not the one the deploy gets."}:/EACCES|Permission denied(?!\s*\(publickey)/i.test(n)?{cause:`A path in this step is not writable by the account the deploy runs as (${r}).`,commands:[`sudo -u ${r} test -w ${e?.cwd??"<the path>"} && echo writable || echo "NOT writable"`],note:"Fix the ownership of that path rather than running the deploy as root - a root-owned build directory breaks the next deploy the other way."}:null}function yd(t){return t?`
810
+ EOF`,"sudo systemctl daemon-reload && sudo systemctl reset-failed <your-unit> && sudo systemctl restart <your-unit>"],note:"reset-failed because a crash loop leaves a restart counter behind. If you would rather not depend on a version-numbered nvm path, install Node system-wide instead - then /usr/bin/node exists and the bare PATH is enough."}}let l=/Failed to connect to ([\w.]+) port (\d+)|connect to ([\w.]+) port (\d+) failed|Connection refused/i.exec(n);if(l){let u=l[2]??l[4]??"",f=(vr.default.existsSync("/etc/systemd/system")?vr.default.readdirSync("/etc/systemd/system").filter(b=>b.endsWith(".service")).filter(b=>{try{let v=vr.default.readFileSync(wr.default.join("/etc/systemd/system",b),"utf8");return e?.cwd?v.includes(e.cwd):!1}catch{return!1}}).map(b=>b.replace(/\.service$/,"")):[])[0];return{cause:`Nothing is listening on ${l[1]??l[3]??"that address"}${u?`:${u}`:""}. `+(f?`The service that runs this checkout is "${f}" - a restart moves its start timestamp even when it dies a second later, so "a restart really happened" does not mean it stayed up. Either it is crash-looping, or it bound a DIFFERENT port than this check expects.`:"No systemd unit on this machine references this checkout, so nothing here is keeping the app alive between deploys."),commands:f?[`systemctl status ${f} --no-pager -l # active (running), or restarting in a loop?`,`journalctl -u ${f} -n 40 --no-pager # the crash itself`,`systemctl show ${f} -p Environment --value # the PORT it was actually given`,"ss -ltnp | grep -E 'node|next' # what it really bound, if anything"]:["ss -ltnp | grep -E 'node|next' # is anything serving this app at all?"],note:f?"If the port differs, change either the unit's PORT or this check - they must be the same number. If it crash-loops, the journal's last lines are the reason; a wrong ExecStart path shows up as status=203/EXEC.":"Until something supervises this app, a deploy has nothing to restart and nothing survives a reboot."}}if(/could not read (Username|Password) for/i.test(n)||/Authentication failed for .*https/i.test(n)||/fatal: Authentication failed/i.test(n))return{cause:`git needs a GitHub credential for the account this deploy runs as (${r}) and has none. It tried to ask, found no terminal, and gave up. Allwright's own GitHub token is NOT used here: deploy steps are plain shell, so they see only this machine's git config - which is why the same repo can push fine from Allwright and still fail this step.`,commands:[`sudo -u ${r} git${s} ls-remote origin >/dev/null && echo "AUTH OK" || echo "AUTH FAIL"`,`sudo -u ${r} gh auth setup-git # if you signed in with the gh CLI - its login does not reach git by itself`,`sudo -u ${r} git config --global credential.helper store # then one manual 'git fetch' to save the token`],note:`Or switch the checkout to SSH and give ${r} a deploy key: git${s} remote set-url origin git@github.com:OWNER/REPO.git. Never paste a token into a deploy step - it ends up in run logs and screenshots.`};if(/Permission denied \(publickey/i.test(n))return{cause:`SSH could not authenticate to the git host as ${r}. The key either does not exist for that account, or is not the one registered with the repository.`,commands:[`sudo -u ${r} ssh -T git@github.com # expect "successfully authenticated"`,`sudo -u ${r} ls -l ~/.ssh/`],note:"Add that account's public key as a deploy key on the repository (read-only is enough to fetch)."};if(/Host key verification failed/i.test(n))return{cause:`The git host is not in ${r}'s known_hosts, and ssh will not accept it unattended.`,commands:[`sudo -u ${r} ssh-keyscan github.com >> ~/.ssh/known_hosts`],note:"Run it as that user - a known_hosts entry under your own account does nothing for the service."};let c=/(?:^|\n)(?:bash: )?([\w.-]+): command not found/i.exec(n);return c?{cause:`"${c[1]}" is not on the PATH of the account this deploy runs as (${r}). A tool installed through nvm, asdf or a shell profile usually is not: the service starts with a bare environment, not your login shell.`,commands:[`sudo -u ${r} which ${c[1]} || echo "not on this account's PATH"`,`command -v ${c[1]} # where YOUR shell finds it`],note:"Either install it system-wide, or use the absolute path in the step - the path your own shell resolves is not the one the deploy gets."}:/EACCES|Permission denied(?!\s*\(publickey)/i.test(n)?{cause:`A path in this step is not writable by the account the deploy runs as (${r}).`,commands:[`sudo -u ${r} test -w ${e?.cwd??"<the path>"} && echo writable || echo "NOT writable"`],note:"Fix the ownership of that path rather than running the deploy as root - a root-owned build directory breaks the next deploy the other way."}:null}function Id(t){return t?`
739
811
 
740
812
  What this means: ${t.cause}
741
813
  Run these ON THE DEPLOY MACHINE:
742
814
  `+t.commands.map(e=>` ${e}`).join(`
743
815
  `)+`
744
- ${t.note}`:""}var mr=R(require("node:path"),1),yr=require("node:child_process"),Va=R(require("node:readline"),1),Wa=require("node:crypto"),br=R(ke(),1);var jd=R(ke(),1);wt();ut();sr();var Zi=require("node:child_process"),Ls=R(require("node:fs"),1),Ka=R(require("node:path"),1),Uy=["/etc/systemd/system","/lib/systemd/system","/usr/lib/systemd/system"],qy=["/etc/caddy/Caddyfile","/usr/local/etc/caddy/Caddyfile","/etc/nginx/nginx.conf"],Fy=["/etc/nginx/sites-enabled","/etc/nginx/conf.d","/etc/caddy/conf.d","/etc/caddy/sites-enabled"];function bd(t,e=512e3){try{let n=Ls.default.statSync(t);return!n.isFile()||n.size>e?null:Ls.default.readFileSync(t,"utf8")}catch{return null}}function vd(t,e=60){try{return Ls.default.readdirSync(t).slice(0,e).map(n=>Ka.default.join(t,n)).filter(n=>{try{return Ls.default.statSync(n).isFile()}catch{return!1}})}catch{return[]}}function wd(t,e=Uy){let n=t.replace(/\/+$/,"");if(!n)return[];let r=[];for(let s of e)for(let i of vd(s)){if(!i.endsWith(".service"))continue;let o=bd(i);if(!o||!o.includes(n))continue;let l=/^\s*ExecStart\s*=\s*(.+)$/m.exec(o)?.[1]?.trim()??"",c=/^\s*User\s*=\s*(.+)$/m.exec(o)?.[1]?.trim()??"root (no User= line)";r.push(`${Ka.default.basename(i,".service")} (User=${c})`+(l?` runs: ${l}`:""))}return r}function kd(t,e=qy,n=Fy){let r=t.map(o=>o.trim().toLowerCase()).filter(Boolean);if(!r.length)return[];let s=[...e,...n.flatMap(o=>vd(o))],i=[];for(let o of s){let l=bd(o);if(!l)continue;let c=l.toLowerCase(),u=r.find(f=>c.includes(f));if(!u)continue;let p=l.split(`
745
- `).filter(f=>/reverse_proxy|proxy_pass|root\s+\*?\s*\//i.test(f)).map(f=>f.trim()).slice(0,8);i.push(`${o} mentions ${u}`+(p.length?` - routing lines: ${p.join(" | ")}`:" - no routing line found"))}return i}function as(t){let e=l=>{try{return(0,Zi.execFileSync)("git",l,{cwd:t,encoding:"utf8",timeout:2e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"true"},stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}},n=e(["ls-remote","--heads","origin"]),r=e(["branch","--format=%(refname:short)"]),s=e(["branch","-r","--format=%(refname:short)"]),i=n?n.split(`
746
- `).map(l=>l.split(/\s+/)[1]??"").map(l=>l.replace(/^refs\/heads\//,"")).filter(Boolean):null,o=[`
747
-
748
- BRANCHES - asked of git just now by the runner, which has a shell. Do NOT conclude a branch is missing from what is under .git/refs: that only says what this checkout has fetched, and a branch pushed from somewhere else is invisible there until someone runs git fetch.`];if(o.push(i?`- on origin: ${i.join(", ")||"(none)"}`:"- origin could not be reached (no credentials for this account, or the network refused). Say the branch could not be VERIFIED - do not say it does not exist."),r&&o.push(`- local branches in this checkout: ${r.split(`
749
- `).join(", ")}`),s&&o.push(`- remote-tracking refs already fetched here: ${s.split(`
750
- `).join(", ")}`),i&&s){let l=new Set(s.split(`
751
- `).map(u=>u.replace(/^origin\//,""))),c=i.filter(u=>!l.has(u));c.length&&o.push(`- exists on origin but NOT fetched here yet: ${c.join(", ")}. This is a \`git fetch\`, not a missing branch - never report it as a blocker.`)}return o.join(`
752
- `)}function By(){let t=o=>{try{return(0,Zi.execFileSync)("bash",["-lc",`command -v ${JSON.stringify(o)}`],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}),!0}catch{return!1}},e=o=>{try{return(0,Zi.execFileSync)("systemctl",["is-active",o],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim()==="active"}catch{return!1}},n=["caddy","nginx","apache2","haproxy","docker","pm2","systemctl","certbot"],r=n.filter(t),s=n.filter(o=>!r.includes(o)),i=["caddy","nginx","apache2","haproxy"].filter(o=>e(o));return`
753
-
754
- WHAT THIS MACHINE ALREADY RUNS - build the answer on these, never on a tool that is not here:
755
- - installed: ${r.join(", ")||"(none of the usual ones)"}
756
- - NOT installed: ${s.join(", ")||"(none missing)"}
757
- - reverse proxy currently running: ${i.join(", ")||"(none)"}
758
- A proxy that is already running is almost certainly serving something else on this box. EXTEND its configuration; never introduce a second one. Two cannot hold port 80, so the best case is that yours refuses to start and the worst is that someone stops the running one to make room and takes an unrelated site down. Same for supervisors: if units already exist here, write one in that style rather than proposing docker or pm2 because they are more familiar.`}function Ky(t){try{return new URL(t).hostname}catch{return""}}function Ha(t){let e=t.urls.map(Ky).filter(Boolean),n=wd(t.repoPath),r=kd(e),s=[`
759
-
760
- ABOUT THE MACHINE THIS RUNS ON - gathered by the runner just now, read-only. Trust these over anything you infer from the repository: the repo is exactly where supervision and proxying are NOT configured, so "the repo has no systemd unit" says nothing about whether a unit exists.`];return s.push(n.length?`- systemd units pointing at this checkout (${t.repoPath}):
761
- `+n.map(i=>` - ${i}`).join(`
762
- `)+`
763
- Use the real unit name in the restart step. Do NOT write a bare foreground start command - it dies with the deploy session.`:`- NO systemd unit on this machine references ${t.repoPath}. If this project is served by something else (pm2, docker, a proxy serving static files), say which in the document; if nothing supervises it, that is a BLOCKER, not a detail.`),s.push(r.length?`- reverse-proxy configuration mentioning this environment's hostname:
764
- `+r.map(i=>` - ${i}`).join(`
765
- `)+`
766
- Public checks must go through the public URL; a check against localhost only proves the app started, not that visitors can reach it.`:e.length?`- NO reverse-proxy file on this machine mentions ${e.join(", ")}. Either the site is served another way, or the public URL does not reach this machine at all - flag it, do not assume it works.`:"- no public URL was declared for these environments, so nothing could be checked against a proxy configuration."),s.join(`
767
- `)+By()}function _d(t){let e=[],n=o=>o.workdir.trim()||t.repoPath,r=as(t.repoPath),s=t.environments.map(o=>({name:o.name,dir:n(o)})),i=s.filter((o,l)=>s.findIndex(c=>c.dir===o.dir)!==l);t.environments.length>1&&e.push({environment:"",question:"Each environment has a working directory of its own",ok:i.length===0,blocking:!0,detail:i.length===0?s.map(o=>`${o.name}: ${o.dir}`).join(" \xB7 "):`${s.map(o=>`${o.name}: ${o.dir}`).join(" \xB7 ")} - a deploy of one replaces the other's checkout and build. Set the Working directory on the environment; creating the directory on the machine is not enough on its own.`});for(let o of t.environments){let l=n(o),c=wd(l);if(e.push({environment:o.name,question:`Something supervises the app in ${l}`,ok:c.length>0,blocking:!0,detail:c.length?c.join(" \xB7 "):`no systemd unit on this machine references ${l}`}),o.publicUrl){let u="";try{u=new URL(o.publicUrl).hostname}catch{u=""}let p=u?kd([u]):[];e.push({environment:o.name,question:`A reverse proxy here serves ${u||o.publicUrl}`,ok:p.length>0,blocking:!1,detail:p.length?p.join(" \xB7 "):`no proxy configuration on this machine mentions ${u||o.publicUrl}`})}if(o.branch){let u=new RegExp(`(^|[\\s,])${o.branch}([\\s,]|$)`,"m").test(/- on origin: (.*)/.exec(r)?.[1]??"");e.push({environment:o.name,question:`Branch "${o.branch}" exists on origin`,ok:u,blocking:!0,detail:u?"":`origin has no branch called ${o.branch} (or it could not be reached)`})}}return e}var Td=require("node:child_process"),Ga=R(require("node:fs"),1),xd=R(require("node:path"),1),Sd=4e3,Hy=/(TOKEN|KEY|SECRET|PASSWORD|PASSWD|CREDENTIAL|AUTH|COOKIE|SESSION)/i;function Gy(t){return t.replace(/([A-Za-z_][A-Za-z0-9_]*)=(\S+)/g,(e,n,r)=>Hy.test(n)?`${n}=<redacted>`:e)}function Bt(t,e){try{let r=(0,Td.execFileSync)(t,e,{encoding:"utf8",timeout:1e4,maxBuffer:2e6,stdio:["ignore","pipe","pipe"]}).trim();return r?r.slice(0,Sd):null}catch(n){let r=n,s=`${r?.stdout??""}${r?.stderr??""}`.trim();return s?s.slice(0,Sd):null}}function Zy(t){let e=["/etc/systemd/system","/lib/systemd/system"],n=[];for(let r of e){let s;try{s=Ga.default.readdirSync(r)}catch{continue}for(let i of s)if(i.endsWith(".service"))try{let o=Ga.default.readFileSync(xd.default.join(r,i),"utf8");t&&o.includes(t)&&n.push(i.replace(/\.service$/,""))}catch{}}return[...new Set(n)].slice(0,3)}function Ed(t){let e=t.errorText.slice(-6e3),n=[],r=(o,l)=>{l&&n.push({command:o,output:Gy(l)})},s=Zy(t.repoPath);for(let o of s)r(`systemctl status ${o}`,Bt("systemctl",["status",o,"--no-pager","-l"])),r(`journalctl -u ${o} -n 40`,Bt("journalctl",["-u",o,"-n","40","--no-pager"])),r(`systemctl show ${o} -p ExecStart -p Environment -p WorkingDirectory -p User`,Bt("systemctl",["show",o,"-p","ExecStart","-p","Environment","-p","WorkingDirectory","-p","User"]));/refused|Failed to connect|Couldn't connect|ECONNREFUSED/i.test(e)&&r("ss -ltnp",Bt("bash",["-lc","ss -ltnp 2>/dev/null | head -40"]));let i=/(?:^|\s)(?:bash: )?['"\u2018]?([\w.-]+)['"\u2019]?: (?:command not found|No such file or directory)/i.exec(e);if(i){let o=i[1];r(`which ${o} (in the runner's PATH)`,Bt("bash",["-lc",`command -v ${JSON.stringify(o)} || echo "not on this PATH"`])),r("ls of the usual system locations",Bt("bash",["-lc",`ls -l /usr/bin/${o} /usr/local/bin/${o} 2>&1 | head -5`]))}return/ENOSPC|No space left|write error/i.test(e)&&r("df -h",Bt("bash",["-lc","df -h | head -10"])),/EACCES|Permission denied|Operation not permitted/i.test(e)&&(r("id",Bt("id",[])),r(`ls -ld ${t.repoPath}`,Bt("bash",["-lc",`ls -ld ${JSON.stringify(t.repoPath)} 2>&1`]))),n}function Rd(t){return t.length?`
816
+ ${t.note}`:""}var kr=R(require("node:path"),1),Sr=require("node:child_process"),il=R(require("node:readline"),1),ol=require("node:crypto"),Tr=R(_e(),1);var Bd=R(_e(),1);_t();ht();ur();no();var jd=require("node:child_process"),rl=R(require("node:fs"),1),Od=R(require("node:path"),1),Nd=4e3,pb=/(TOKEN|KEY|SECRET|PASSWORD|PASSWD|CREDENTIAL|AUTH|COOKIE|SESSION)/i;function fb(t){return t.replace(/([A-Za-z_][A-Za-z0-9_]*)=(\S+)/g,(e,n,r)=>pb.test(n)?`${n}=<redacted>`:e)}function Zt(t,e){try{let r=(0,jd.execFileSync)(t,e,{encoding:"utf8",timeout:1e4,maxBuffer:2e6,stdio:["ignore","pipe","pipe"]}).trim();return r?r.slice(0,Nd):null}catch(n){let r=n,s=`${r?.stdout??""}${r?.stderr??""}`.trim();return s?s.slice(0,Nd):null}}function mb(t){let e=["/etc/systemd/system","/lib/systemd/system"],n=[];for(let r of e){let s;try{s=rl.default.readdirSync(r)}catch{continue}for(let i of s)if(i.endsWith(".service"))try{let o=rl.default.readFileSync(Od.default.join(r,i),"utf8");t&&o.includes(t)&&n.push(i.replace(/\.service$/,""))}catch{}}return[...new Set(n)].slice(0,3)}function Md(t){let e=t.errorText.slice(-6e3),n=[],r=(o,l)=>{l&&n.push({command:o,output:fb(l)})},s=mb(t.repoPath);for(let o of s)r(`systemctl status ${o}`,Zt("systemctl",["status",o,"--no-pager","-l"])),r(`journalctl -u ${o} -n 40`,Zt("journalctl",["-u",o,"-n","40","--no-pager"])),r(`systemctl show ${o} -p ExecStart -p Environment -p WorkingDirectory -p User`,Zt("systemctl",["show",o,"-p","ExecStart","-p","Environment","-p","WorkingDirectory","-p","User"]));/refused|Failed to connect|Couldn't connect|ECONNREFUSED/i.test(e)&&r("ss -ltnp",Zt("bash",["-lc","ss -ltnp 2>/dev/null | head -40"]));let i=/(?:^|\s)(?:bash: )?['"\u2018]?([\w.-]+)['"\u2019]?: (?:command not found|No such file or directory)/i.exec(e);if(i){let o=i[1];r(`which ${o} (in the runner's PATH)`,Zt("bash",["-lc",`command -v ${JSON.stringify(o)} || echo "not on this PATH"`])),r("ls of the usual system locations",Zt("bash",["-lc",`ls -l /usr/bin/${o} /usr/local/bin/${o} 2>&1 | head -5`]))}return/ENOSPC|No space left|write error/i.test(e)&&r("df -h",Zt("bash",["-lc","df -h | head -10"])),/EACCES|Permission denied|Operation not permitted/i.test(e)&&(r("id",Zt("id",[])),r(`ls -ld ${t.repoPath}`,Zt("bash",["-lc",`ls -ld ${JSON.stringify(t.repoPath)} 2>&1`]))),n}function zd(t){return t.length?`
768
817
 
769
818
  EVIDENCE FROM THE MACHINE - gathered by the runner just now, read-only, because you cannot run commands yourself. This is the part of the system the repository cannot tell you about, and it is usually where the answer is. Values that looked like credentials were redacted before you saw them.
770
819
 
@@ -773,32 +822,32 @@ ${e.output}`).join(`
773
822
 
774
823
  `)+`
775
824
 
776
- Reason from THIS. If it does not contain the answer, say what you would need to look at and why - naming a command someone can run beats inventing a cause that fits the little you were shown.`:""}var Id=4e3,Vy=4e3;function Ad(t,e){t("warn",`${e.length} step(s) still need YOU - Allwright deliberately did not run these:
825
+ Reason from THIS. If it does not contain the answer, say what you would need to look at and why - naming a command someone can run beats inventing a cause that fits the little you were shown.`:""}Kt();var Dd=4e3,gb=4e3;function Ld(t,e){t("warn",`${e.length} step(s) still need YOU - Allwright deliberately did not run these:
777
826
  `+e.map(n=>` ${n.command}${n.why?` # ${n.why}`:""}`).join(`
778
- `))}function Ya(t){let e=0;return{emit:(s,i)=>{t.transport.send({type:"run.log",runId:t.runId,seq:e++,ts:new Date().toISOString(),level:s,message:i.slice(0,Vy)}),s!=="agent"&&y.info(`[deploy ${t.runId}] ${i}`)},setStatus:(s,i={})=>{t.transport.send({type:"run.status",runId:t.runId,status:s,...i})}}}var Wy=/^\s*(?:ALLWRIGHT|TICKETPILOT)[-\s]MANUAL:\s*(.+)$/i;function Yy(t){let e=Wy.exec(t);if(!e)return null;let[n,...r]=e[1].split(/\s+#\s+/),s=n.trim();return s?{command:s.slice(0,500),why:r.join(" # ").trim().slice(0,300)}:null}async function Wi(t){let{emit:e,setStatus:n}=Ya(t),r=t.environment;try{let s=Jy(t);if(s){e("error",s),await ht(t,`**Allwright could not deploy to \`${r.name}\`.**
827
+ `))}function al(t){let e=0;return{emit:(s,i)=>{t.transport.send({type:"run.log",runId:t.runId,seq:e++,ts:new Date().toISOString(),level:s,message:i.slice(0,gb)}),s!=="agent"&&y.info(`[deploy ${t.runId}] ${i}`)},setStatus:(s,i={})=>{t.transport.send({type:"run.status",runId:t.runId,status:s,...i})}}}var yb=/^\s*(?:ALLWRIGHT|TICKETPILOT)[-\s]MANUAL:\s*(.+)$/i;function bb(t){let e=yb.exec(t);if(!e)return null;let[n,...r]=e[1].split(/\s+#\s+/),s=n.trim();return s?{command:s.slice(0,500),why:r.join(" # ").trim().slice(0,300)}:null}async function so(t){let{emit:e,setStatus:n}=al(t),r=t.environment;try{let s=vb(t);if(s){e("error",s),await ft(t,`**Allwright could not deploy to \`${r.name}\`.**
779
828
 
780
- ${s}`),n("failed",{error:s});return}if(r.requireApproval){Zu({runId:t.runId,issueKey:t.issueKey,issueSummary:t.issueSummary,projectId:t.project.id,repoName:t.project.repoName,environmentName:r.name,requestedBy:t.requestedBy,createdAt:new Date().toISOString()}),e("info",`Deploy to "${r.name}" is waiting for approval on the dashboard - no step has run yet`),await ht(t,`**Allwright: deploy to \`${r.name}\` needs approval.**
829
+ ${s}`),n("failed",{error:s});return}if(r.requireApproval){sd({runId:t.runId,issueKey:t.issueKey,issueSummary:t.issueSummary,projectId:t.project.id,repoName:t.project.repoName,environmentName:r.name,requestedBy:t.requestedBy,createdAt:new Date().toISOString()}),e("info",`Deploy to "${r.name}" is waiting for approval on the dashboard - no step has run yet`),await ft(t,`**Allwright: deploy to \`${r.name}\` needs approval.**
781
830
 
782
- ${t.requestedBy?`Requested by ${t.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 \`${t.runId}\`)`),n("awaiting_approval",{resultSummary:`Awaiting approval to deploy ${t.issueKey} to ${r.name}`});return}await Nd(t,e,n)}catch(s){let i=s instanceof Error?s.message:String(s);e("error",`Deploy failed: ${i}`),await ht(t,`**Allwright deploy to \`${r.name}\` failed.**
831
+ ${t.requestedBy?`Requested by ${t.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 \`${t.runId}\`)`),n("awaiting_approval",{resultSummary:`Awaiting approval to deploy ${t.issueKey} to ${r.name}`});return}await Kd(t,e,n)}catch(s){let i=s instanceof Error?s.message:String(s);e("error",`Deploy failed: ${i}`),await ft(t,`**Allwright deploy to \`${r.name}\` failed.**
783
832
 
784
833
  ${i.slice(0,800)}
785
834
 
786
- (run \`${t.runId}\`)`),n("failed",{error:i})}}function Jy(t){let e=t.environment;if(!t.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 n=Nt(t.cfg,t.project.repoName,e.name),r=new Set,s=new Set;for(let l of e.steps){for(let c of l.run.matchAll(/(?:^|[\s;&|(])([A-Za-z_][A-Za-z0-9_]*)=/g))r.add(c[1]);for(let c of l.run.matchAll(/\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/g))s.add(c[1])}let i=e.requiredSecrets.filter(l=>!s.has(l));i.length&&y.warn(`environment "${e.name}" lists ${i.join(", ")} under required secrets, but no step uses ${i.length===1?"it":"them"} - ignoring. Remove ${i.length===1?"it":"them"} from "Needs secrets" on the environment to silence this.`);let o=e.requiredSecrets.filter(l=>s.has(l)&&!r.has(l)&&!n[l]&&!process.env[l]);return o.length?`missing deploy secret(s) on this runner: ${o.join(", ")}. Set them with: allwright env set "${t.project.repoName}" "${e.name}" ${o[0]}=...`:null}async function Nd(t,e,n){let r=t.environment,s=Nt(t.cfg,t.project.repoName,r.name),i=Ja(Object.values(s)),o=Date.now(),l=[];if(n("running"),e("info",`Deploying ${t.issueKey} to "${r.name}"`+(t.requestedBy?` (requested by ${t.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 O=Ke(t.cfg,t.project,"assist"),M="error"in O?{ok:!1,error:O.error}:await ns({projectId:t.project.id,repoPath:t.repoPath,role:r.auditBeforeDeploy,scope:{kind:"repo",ref:""},model:"",agent:O,jira:t.jira});if(!M.ok)e("warn",`Pre-deploy audit could not run: ${M.error} - deploying anyway (advisory)`);else if(!M.audit.findings.length)e("info","Pre-deploy audit: no findings \u2713");else{let W={};for(let d of M.audit.findings)W[d.severity]=(W[d.severity]??0)+1;e("warn",`Pre-deploy audit: ${M.audit.findings.length} finding(s) (`+Object.entries(W).map(([d,m])=>`${m} ${d}`).join(", ")+") - full report on the Audits page. Deploying anyway (advisory).");for(let d of M.audit.findings.slice(0,5))e("warn",` [${d.severity}] ${d.title} - ${d.evidence[0]?.file??""}`)}}catch(O){e("warn",`Pre-deploy audit crashed: ${O instanceof Error?O.message:String(O)} - deploying anyway`)}}if(r.requireSyncCheck){if(!r.previousEnvBranch||!r.branch){let M=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",M),await ht(t,`**Allwright refused to deploy to \`${r.name}\`.**
835
+ (run \`${t.runId}\`)`),n("failed",{error:i})}}function vb(t){let e=t.environment;if(!t.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 n=zt(t.cfg,t.project.repoName,e.name),r=new Set,s=new Set;for(let l of e.steps){for(let c of l.run.matchAll(/(?:^|[\s;&|(])([A-Za-z_][A-Za-z0-9_]*)=/g))r.add(c[1]);for(let c of l.run.matchAll(/\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/g))s.add(c[1])}let i=e.requiredSecrets.filter(l=>!s.has(l));i.length&&y.warn(`environment "${e.name}" lists ${i.join(", ")} under required secrets, but no step uses ${i.length===1?"it":"them"} - ignoring. Remove ${i.length===1?"it":"them"} from "Needs secrets" on the environment to silence this.`);let o=e.requiredSecrets.filter(l=>s.has(l)&&!r.has(l)&&!n[l]&&!process.env[l]);return o.length?`missing deploy secret(s) on this runner: ${o.join(", ")}. Set them with: allwright env set "${t.project.repoName}" "${e.name}" ${o[0]}=...`:null}async function Kd(t,e,n){let r=t.environment,s=zt(t.cfg,t.project.repoName,r.name),i=ll(Object.values(s)),o=Date.now(),l=[];if(n("running"),e("info",`Deploying ${t.issueKey} to "${r.name}"`+(t.requestedBy?` (requested by ${t.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 O=He(t.cfg,t.project,"assist"),M="error"in O?{ok:!1,error:O.error}:await ls({projectId:t.project.id,repoPath:t.repoPath,role:r.auditBeforeDeploy,scope:{kind:"repo",ref:""},model:"",agent:O,jira:t.jira});if(!M.ok)e("warn",`Pre-deploy audit could not run: ${M.error} - deploying anyway (advisory)`);else if(!M.audit.findings.length)e("info","Pre-deploy audit: no findings \u2713");else{let W={};for(let d of M.audit.findings)W[d.severity]=(W[d.severity]??0)+1;e("warn",`Pre-deploy audit: ${M.audit.findings.length} finding(s) (`+Object.entries(W).map(([d,m])=>`${m} ${d}`).join(", ")+") - full report on the Audits page. Deploying anyway (advisory).");for(let d of M.audit.findings.slice(0,5))e("warn",` [${d.severity}] ${d.title} - ${d.evidence[0]?.file??""}`)}}catch(O){e("warn",`Pre-deploy audit crashed: ${O instanceof Error?O.message:String(O)} - deploying anyway`)}}if(r.requireSyncCheck){if(!r.previousEnvBranch||!r.branch){let M=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",M),await ft(t,`**Allwright refused to deploy to \`${r.name}\`.**
787
836
 
788
837
  ${M}
789
838
 
790
- (run \`${t.runId}\`)`),n("failed",{error:M,errorKind:"guard"});return}let O=await Qy(t,e);if(O){await ht(t,O.comment),n("failed",{error:O.error,...O.guard?{errorKind:"guard"}:{}});return}}let c=t.repoPath;if(r.useDedicatedCheckout||r.promotionMode==="merge_and_deploy"?(e("info",`Preparing ${r.name} checkout at origin/${r.branch}`),c=await ia({repoPath:t.repoPath,repoName:t.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 O=qt(r.ticketBranchTemplate,{issueKey:t.issueKey});e("info",`Merging "${O}" into "${r.branch}"`);let M=await oa(c,O,`Deploy ${t.issueKey} to ${r.name}
839
+ (run \`${t.runId}\`)`),n("failed",{error:M,errorKind:"guard"});return}let O=await kb(t,e);if(O){await ft(t,O.comment),n("failed",{error:O.error,...O.guard?{errorKind:"guard"}:{}});return}}let c=t.repoPath;if(r.useDedicatedCheckout||r.promotionMode==="merge_and_deploy"?(e("info",`Preparing ${r.name} checkout at origin/${r.branch}`),c=await ga({repoPath:t.repoPath,repoName:t.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 O=Ht(r.ticketBranchTemplate,{issueKey:t.issueKey});e("info",`Merging "${O}" into "${r.branch}"`);let M=await ya(c,O,`Deploy ${t.issueKey} to ${r.name}
791
840
 
792
- Allwright run ${t.runId}`);if(!M.ok){e("error",M.reason??"merge failed"),await ht(t,`**Allwright deploy to \`${r.name}\` failed before running anything.**
841
+ Allwright run ${t.runId}`);if(!M.ok){e("error",M.reason??"merge failed"),await ft(t,`**Allwright deploy to \`${r.name}\` failed before running anything.**
793
842
 
794
- ${M.reason}`),n("failed",{error:M.reason});return}M.alreadyMerged?e("info",`"${O}" is already in "${r.branch}" - nothing to merge`):(e("info",`Pushing "${r.branch}" to origin`),await ua(c,r.branch))}let p=await nt(c).catch(()=>"");p&&e("info",`Deploying commit ${p.slice(0,10)}`);let f=eb(c,r.workdir),b={...process.env,...s,ALLWRIGHT_ENVIRONMENT:r.name,ALLWRIGHT_ISSUE_KEY:t.issueKey,ALLWRIGHT_RUN_ID:t.runId,ALLWRIGHT_DEPLOY_REF:p,ALLWRIGHT_BRANCH:r.branch,TICKETPILOT_ENVIRONMENT:r.name,TICKETPILOT_ISSUE_KEY:t.issueKey,TICKETPILOT_RUN_ID:t.runId,TICKETPILOT_DEPLOY_REF:p,TICKETPILOT_BRANCH:r.branch},v=0,_=r.timeoutSeconds*1e3,x=rd(t.runId),$=()=>x.signal.aborted;try{for(let[O,M]of r.steps.entries()){if($()){let m=`stopped from the dashboard during step ${O+1} - nothing further ran`;e("error",m),n("failed",{error:m,errorKind:"guard",deployedRef:p});return}let W=_-(Date.now()-o);if(W<=0){let m=`deploy exceeded its ${r.timeoutSeconds}s budget before step ${O+1}`;e("error",m),await ht(t,`**Allwright deploy to \`${r.name}\` timed out.**
843
+ ${M.reason}`),n("failed",{error:M.reason});return}M.alreadyMerged?e("info",`"${O}" is already in "${r.branch}" - nothing to merge`):(e("info",`Pushing "${r.branch}" to origin`),await ka(c,r.branch))}let p=await st(c).catch(()=>"");p&&e("info",`Deploying commit ${p.slice(0,10)}`);let f=_b(c,r.workdir),b={...process.env,...s,ALLWRIGHT_ENVIRONMENT:r.name,ALLWRIGHT_ISSUE_KEY:t.issueKey,ALLWRIGHT_RUN_ID:t.runId,ALLWRIGHT_DEPLOY_REF:p,ALLWRIGHT_BRANCH:r.branch,TICKETPILOT_ENVIRONMENT:r.name,TICKETPILOT_ISSUE_KEY:t.issueKey,TICKETPILOT_RUN_ID:t.runId,TICKETPILOT_DEPLOY_REF:p,TICKETPILOT_BRANCH:r.branch},v=0,w=r.timeoutSeconds*1e3,x=fd(t.runId),$=()=>x.signal.aborted;try{for(let[O,M]of r.steps.entries()){if($()){let m=`stopped from the dashboard during step ${O+1} - nothing further ran`;e("error",m),n("failed",{error:m,errorKind:"guard",deployedRef:p});return}let W=w-(Date.now()-o);if(W<=0){let m=`deploy exceeded its ${r.timeoutSeconds}s budget before step ${O+1}`;e("error",m),await ft(t,`**Allwright deploy to \`${r.name}\` timed out.**
795
844
 
796
- ${m}`),n("timed_out",{error:m,deployedRef:p});return}e("info",`\u25B6 step ${O+1}/${r.steps.length}: ${M.name}`);let d=await tb({command:M.run,cwd:f,env:b,timeoutMs:W,signal:x.signal,onLine:(m,g)=>{v++;let E=Yy(g);E&&l.length<20&&l.push(E),v===Id&&e("warn","(output truncated - deploy log limit reached)"),!(v>=Id)&&e(m,i(g))}});if(d.timedOut){let m=`step "${M.name}" hit the ${r.timeoutSeconds}s deploy budget and was killed`;e("error",m),await ht(t,`**Allwright deploy to \`${r.name}\` timed out.**
845
+ ${m}`),n("timed_out",{error:m,deployedRef:p});return}e("info",`\u25B6 step ${O+1}/${r.steps.length}: ${M.name}`);let d=await Sb({command:M.run,cwd:f,env:b,timeoutMs:W,signal:x.signal,onLine:(m,g)=>{v++;let E=bb(g);E&&l.length<20&&l.push(E),v===Dd&&e("warn","(output truncated - deploy log limit reached)"),!(v>=Dd)&&e(m,i(g))}});if(d.timedOut){let m=`step "${M.name}" hit the ${r.timeoutSeconds}s deploy budget and was killed`;e("error",m),await ft(t,`**Allwright deploy to \`${r.name}\` timed out.**
797
846
 
798
- ${m}`),n("timed_out",{error:m,deployedRef:p});return}if(d.code!==0){if(M.continueOnError){e("warn",`step "${M.name}" exited ${d.code} - continuing (marked continue-on-error)`);continue}let m="";try{m=i(await ea(c))}catch{}let g=yd(Ba(d.tail??"",{cwd:c})),E=`step ${O+1} "${M.name}" failed with exit code ${d.code}`+(d.tail?`: ${i(d.tail)}`:"")+g+(m?`
847
+ ${m}`),n("timed_out",{error:m,deployedRef:p});return}if(d.code!==0){if(M.continueOnError){e("warn",`step "${M.name}" exited ${d.code} - continuing (marked continue-on-error)`);continue}let m="";try{m=i(await da(c))}catch{}let g=Id(el(d.tail??"",{cwd:c})),E=`step ${O+1} "${M.name}" failed with exit code ${d.code}`+(d.tail?`: ${i(d.tail)}`:"")+g+(m?`
799
848
 
800
849
  Checkout at failure:
801
- ${m}`:"");e("error",E),await ht(t,`**Allwright deploy to \`${r.name}\` failed.**
850
+ ${m}`:"");e("error",E),await ft(t,`**Allwright deploy to \`${r.name}\` failed.**
802
851
 
803
852
  Step ${O+1} \`${M.name}\` exited ${d.code}.
804
853
 
@@ -817,8 +866,8 @@ ${m.slice(0,800)}
817
866
  `+l.map(P=>`- \`${P.command}\`${P.why?` - ${P.why}`:""}`).join(`
818
867
  `)+`
819
868
 
820
- `:"")+`Nothing after it ran. Full log is on the Allwright dashboard. (run \`${t.runId}\`)`),ct(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.name} failed`,detail:`step ${O+1} "${M.name}" exit ${d.code}`+(d.tail?`
821
- ${i(d.tail).slice(0,500)}`:"")}),l.length&&Ad(e,l),n("failed",{error:E.slice(0,1600),deployedRef:p,...l.length?{manualSteps:l}:{}});return}e("info",`\u2713 step ${O+1}/${r.steps.length}: ${M.name}`)}}finally{sd(t.runId)}n("posting");let j=Math.round((Date.now()-o)/1e3),S=null;r.publicUrl?.trim()&&(S=await sb(r.publicUrl.trim()),e(S?"warn":"info",S??`${r.publicUrl.trim()} points at this machine - the deploy is live there`)),t.issueKey!==br.BRANCH_DEPLOY_ISSUE_KEY&&await ht(t,`**Allwright deployed \`${t.issueKey}\` to \`${r.name}\`.**
869
+ `:"")+`Nothing after it ran. Full log is on the Allwright dashboard. (run \`${t.runId}\`)`),dt(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.name} failed`,detail:`step ${O+1} "${M.name}" exit ${d.code}`+(d.tail?`
870
+ ${i(d.tail).slice(0,500)}`:"")}),l.length&&Ld(e,l),n("failed",{error:E.slice(0,1600),deployedRef:p,...l.length?{manualSteps:l}:{}});return}e("info",`\u2713 step ${O+1}/${r.steps.length}: ${M.name}`)}}finally{md(t.runId)}n("posting");let N=Math.round((Date.now()-o)/1e3),S=null;r.publicUrl?.trim()&&(S=await Eb(r.publicUrl.trim()),e(S?"warn":"info",S??`${r.publicUrl.trim()} points at this machine - the deploy is live there`)),t.issueKey!==Tr.BRANCH_DEPLOY_ISSUE_KEY&&await ft(t,`**Allwright deployed \`${t.issueKey}\` to \`${r.name}\`.**
822
871
 
823
872
  `+(S?`> **Live where?** ${S}
824
873
 
@@ -827,56 +876,56 @@ ${i(d.tail).slice(0,500)}`:"")}),l.length&&Ad(e,l),n("failed",{error:E.slice(0,1
827
876
  `)+`
828
877
 
829
878
  `:"")+(p?`Commit: \`${p.slice(0,10)}\`${r.branch?` on \`${r.branch}\``:""}
830
- `:"")+`${r.steps.length} step(s) in ${j}s.`+(t.requestedBy?` Requested by ${t.requestedBy}.`:"")+`
879
+ `:"")+`${r.steps.length} step(s) in ${N}s.`+(t.requestedBy?` Requested by ${t.requestedBy}.`:"")+`
831
880
 
832
- (run \`${t.runId}\`)`);let G=await Xy(t,e,p);t.project.goLiveIssueKey&&e("info",`Go-live checklist: this project keeps one on ${t.project.goLiveIssueKey} - review it before shipping to production`),$s(t.repoPath,t.issueKey)&&ct(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.name} succeeded after earlier failure`,detail:p?`commit ${p.slice(0,10)}`:void 0}),l.length&&Ad(e,l),n("succeeded",{resultSummary:`Deployed to ${r.name}${p?` at ${p.slice(0,10)}`:""} in ${j}s`+(G!==null?` \xB7 ${G} ticket(s) moved to "${r.deployToColumn}"`:"")+(l.length?` \xB7 ${l.length} manual step(s) left for you`:"")+(S?` \xB7 NOT reachable at ${r.publicUrl} yet`:""),deployedRef:p,...l.length?{manualSteps:l}:{}}),e("info",`Deploy to "${r.name}" succeeded in ${j}s`)}async function Xy(t,e,n){let r=t.environment;if(!r.deployFromColumn||!r.deployToColumn)return null;let s=new Date().toISOString().slice(0,10),i;try{i=await t.jira.search(`project = "${t.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 t.jira.addComment(l.key,`**Allwright: deployed to \`${r.name}\` on ${s}.**
881
+ (run \`${t.runId}\`)`);let G=await wb(t,e,p);t.project.goLiveIssueKey&&e("info",`Go-live checklist: this project keeps one on ${t.project.goLiveIssueKey} - review it before shipping to production`),Ds(t.repoPath,t.issueKey)&&dt(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.name} succeeded after earlier failure`,detail:p?`commit ${p.slice(0,10)}`:void 0}),l.length&&Ld(e,l),n("succeeded",{resultSummary:`Deployed to ${r.name}${p?` at ${p.slice(0,10)}`:""} in ${N}s`+(G!==null?` \xB7 ${G} ticket(s) moved to "${r.deployToColumn}"`:"")+(l.length?` \xB7 ${l.length} manual step(s) left for you`:"")+(S?` \xB7 NOT reachable at ${r.publicUrl} yet`:""),deployedRef:p,...l.length?{manualSteps:l}:{}}),e("info",`Deploy to "${r.name}" succeeded in ${N}s`)}async function wb(t,e,n){let r=t.environment;if(!r.deployFromColumn||!r.deployToColumn)return null;let s=new Date().toISOString().slice(0,10),i;try{i=await t.jira.search(`project = "${t.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 t.jira.addComment(l.key,`**Allwright: deployed to \`${r.name}\` on ${s}.**
833
882
 
834
883
  `+(n?`Commit: \`${n.slice(0,10)}\`${r.branch?` on \`${r.branch}\``:""}
835
- `:"")+(t.requestedBy?`Requested by ${t.requestedBy}. `:"")+`(run \`${t.runId}\`)`),!await t.jira.transitionByName(l.key,r.deployToColumn)){e("warn",`${l.key}: no workflow transition to "${r.deployToColumn}" from its current status - left in place`),await t.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 \`${t.runId}\`)`).catch(()=>{});continue}o++,e("info",`\u2713 ${l.key} \u2192 "${r.deployToColumn}"`)}catch(c){e("warn",`${l.key}: sweep failed (${c instanceof Error?c.message:c}) - left in "${r.deployFromColumn}"`)}return e("info",`Moved ${o}/${i.length} ticket(s) to "${r.deployToColumn}"`),o}async function Qy(t,e){let n=t.environment,r=n.previousEnvBranch,s=(l,c=!1)=>({error:l,guard:c,comment:`**Allwright could not deploy \`${t.issueKey}\` to \`${n.name}\`.**
884
+ `:"")+(t.requestedBy?`Requested by ${t.requestedBy}. `:"")+`(run \`${t.runId}\`)`),!await t.jira.transitionByName(l.key,r.deployToColumn)){e("warn",`${l.key}: no workflow transition to "${r.deployToColumn}" from its current status - left in place`),await t.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 \`${t.runId}\`)`).catch(()=>{});continue}o++,e("info",`\u2713 ${l.key} \u2192 "${r.deployToColumn}"`)}catch(c){e("warn",`${l.key}: sweep failed (${c instanceof Error?c.message:c}) - left in "${r.deployFromColumn}"`)}return e("info",`Moved ${o}/${i.length} ticket(s) to "${r.deployToColumn}"`),o}async function kb(t,e){let n=t.environment,r=n.previousEnvBranch,s=(l,c=!1)=>({error:l,guard:c,comment:`**Allwright could not deploy \`${t.issueKey}\` to \`${n.name}\`.**
836
885
 
837
886
  ${l}
838
887
 
839
- (run \`${t.runId}\`)`});e("info",`Checking "${n.branch}" is in sync with "${r}" before deploying`);try{await un(t.repoPath,r),await un(t.repoPath,n.branch)}catch(l){return s(`sync check could not fetch branches: ${l instanceof Error?l.message:String(l)}`)}let i;try{i=await da(t.repoPath,`origin/${r}`,`origin/${n.branch}`)}catch(l){return s(`sync check failed: ${l instanceof Error?l.message:String(l)}`)}if(!i)return e("info",`"${n.branch}" already matches "${r}" - continuing`),null;e("warn",`"${n.branch}" and "${r}" have diverged - opening a PR instead of deploying`);let o=Ce(ye()??t.cfg,t.project.repoName);if(!o)return s(`"${n.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 rr(t.repoPath),c=lt(l);if(!c)throw new Error(`could not parse a GitHub owner/repo from origin "${l}"`);let p=await new $e(o).createPullRequest(c.owner,c.repo,{title:`Sync ${n.name} (${n.branch}) with ${r}`,head:r,base:n.branch,body:`Allwright opened this automatically while trying to deploy \`${t.issueKey}\` to \`${n.name}\`: \`${n.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.
888
+ (run \`${t.runId}\`)`});e("info",`Checking "${n.branch}" is in sync with "${r}" before deploying`);try{await mn(t.repoPath,r),await mn(t.repoPath,n.branch)}catch(l){return s(`sync check could not fetch branches: ${l instanceof Error?l.message:String(l)}`)}let i;try{i=await _a(t.repoPath,`origin/${r}`,`origin/${n.branch}`)}catch(l){return s(`sync check failed: ${l instanceof Error?l.message:String(l)}`)}if(!i)return e("info",`"${n.branch}" already matches "${r}" - continuing`),null;e("warn",`"${n.branch}" and "${r}" have diverged - opening a PR instead of deploying`);let o=$e(ye()??t.cfg,t.project.repoName);if(!o)return s(`"${n.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 cr(t.repoPath),c=ut(l);if(!c)throw new Error(`could not parse a GitHub owner/repo from origin "${l}"`);let p=await new Pe(o).createPullRequest(c.owner,c.repo,{title:`Sync ${n.name} (${n.branch}) with ${r}`,head:r,base:n.branch,body:`Allwright opened this automatically while trying to deploy \`${t.issueKey}\` to \`${n.name}\`: \`${n.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.
840
889
 
841
- (run \`${t.runId}\`)`});return s(`"${n.branch}" is not in sync with "${r}" - opened ${p.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 eb(t,e){if(!e.trim())return t;let n=mr.default.resolve(t,e),r=mr.default.relative(t,n);if(r.startsWith("..")||mr.default.isAbsolute(r))throw new Error(`working directory "${e}" is outside the repository checkout`);return n}function tb(t){return new Promise(e=>{let n=(0,yr.spawn)("bash",["-lc",t.command],{cwd:t.cwd,env:t.env,detached:!0,stdio:["ignore","pipe","pipe"]}),r=[],s=p=>{r.push(p),r.length>20&&r.shift()},i=!1,o=!1,l=p=>{i||(i=!0,clearTimeout(c),t.signal?.removeEventListener("abort",u),e({code:p,timedOut:o,tail:r.join(`
842
- `)}))},c=setTimeout(()=>{o=!0,Vi(n.pid,"SIGTERM"),setTimeout(()=>Vi(n.pid,"SIGKILL"),1e4).unref()},t.timeoutMs),u=()=>{t.onLine("warn","stop requested - killing this step"),Vi(n.pid,"SIGTERM"),setTimeout(()=>Vi(n.pid,"SIGKILL"),5e3).unref()};t.signal&&(t.signal.aborted?u():t.signal.addEventListener("abort",u,{once:!0})),Va.default.createInterface({input:n.stdout}).on("line",p=>{s(p),t.onLine("info",p)}),Va.default.createInterface({input:n.stderr}).on("line",p=>{s(p),t.onLine("warn",p)}),n.on("error",p=>{s(`failed to start: ${p.message}`),l(127)}),n.on("close",p=>l(p??1))})}function Vi(t,e){if(t)try{process.kill(-t,e)}catch{try{process.kill(t,e)}catch{}}}function Ja(t){let e=t.filter(n=>n&&n.length>=6).sort((n,r)=>r.length-n.length);return e.length?n=>{let r=n;for(let s of e)r=r.split(s).join("***");return r}:n=>n}async function ht(t,e){if(t.issueKey!==br.BRANCH_DEPLOY_ISSUE_KEY)try{await t.jira.addComment(t.issueKey,e)}catch(n){y.error(`could not post deploy comment to ${t.issueKey}: ${n}`)}}function Xa(t){return qi(t)!==null}async function Od(t,e){let n=qi(e);if(!n)return;let{emit:r,setStatus:s}=Ya({runId:e,transport:t.transport}),i=t.lookup(n.projectId,n.environmentName);if(!i){let l=`approved, but environment "${n.environmentName}" is no longer in this runner's config (deleted or renamed?) - nothing was deployed`;r("error",l),s("failed",{error:l}),Fi(e);return}Fi(e);let o={runId:e,project:i.project,environment:i.environment,issueKey:n.issueKey,issueSummary:n.issueSummary,repoPath:i.repoPath,cfg:t.cfg,jira:t.jiraFor(i.project.repoName),transport:t.transport,requestedBy:n.requestedBy};r("info",`Approved - running the ${i.environment.steps.length} deploy step(s) now`);try{await Nd(o,r,s)}catch(l){let c=l instanceof Error?l.message:String(l);r("error",`Deploy failed: ${c}`),await ht(o,`**Allwright deploy failed.**
890
+ (run \`${t.runId}\`)`});return s(`"${n.branch}" is not in sync with "${r}" - opened ${p.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 _b(t,e){if(!e.trim())return t;let n=kr.default.resolve(t,e),r=kr.default.relative(t,n);if(r.startsWith("..")||kr.default.isAbsolute(r))throw new Error(`working directory "${e}" is outside the repository checkout`);return n}function Sb(t){return new Promise(e=>{let n=(0,Sr.spawn)("bash",["-lc",t.command],{cwd:t.cwd,env:t.env,detached:!0,stdio:["ignore","pipe","pipe"]}),r=[],s=p=>{r.push(p),r.length>20&&r.shift()},i=!1,o=!1,l=p=>{i||(i=!0,clearTimeout(c),t.signal?.removeEventListener("abort",u),e({code:p,timedOut:o,tail:r.join(`
891
+ `)}))},c=setTimeout(()=>{o=!0,ro(n.pid,"SIGTERM"),setTimeout(()=>ro(n.pid,"SIGKILL"),1e4).unref()},t.timeoutMs),u=()=>{t.onLine("warn","stop requested - killing this step"),ro(n.pid,"SIGTERM"),setTimeout(()=>ro(n.pid,"SIGKILL"),5e3).unref()};t.signal&&(t.signal.aborted?u():t.signal.addEventListener("abort",u,{once:!0})),il.default.createInterface({input:n.stdout}).on("line",p=>{s(p),t.onLine("info",p)}),il.default.createInterface({input:n.stderr}).on("line",p=>{s(p),t.onLine("warn",p)}),n.on("error",p=>{s(`failed to start: ${p.message}`),l(127)}),n.on("close",p=>l(p??1))})}function ro(t,e){if(t)try{process.kill(-t,e)}catch{try{process.kill(t,e)}catch{}}}function ll(t){let e=t.filter(n=>n&&n.length>=6).sort((n,r)=>r.length-n.length);return e.length?n=>{let r=n;for(let s of e)r=r.split(s).join("***");return r}:n=>n}async function ft(t,e){if(t.issueKey!==Tr.BRANCH_DEPLOY_ISSUE_KEY)try{await t.jira.addComment(t.issueKey,e)}catch(n){y.error(`could not post deploy comment to ${t.issueKey}: ${n}`)}}function cl(t){return Vi(t)!==null}async function Hd(t,e){let n=Vi(e);if(!n)return;let{emit:r,setStatus:s}=al({runId:e,transport:t.transport}),i=t.lookup(n.projectId,n.environmentName);if(!i){let l=`approved, but environment "${n.environmentName}" is no longer in this runner's config (deleted or renamed?) - nothing was deployed`;r("error",l),s("failed",{error:l}),Wi(e);return}Wi(e);let o={runId:e,project:i.project,environment:i.environment,issueKey:n.issueKey,issueSummary:n.issueSummary,repoPath:i.repoPath,cfg:t.cfg,jira:t.jiraFor(i.project.repoName),transport:t.transport,requestedBy:n.requestedBy};r("info",`Approved - running the ${i.environment.steps.length} deploy step(s) now`);try{await Kd(o,r,s)}catch(l){let c=l instanceof Error?l.message:String(l);r("error",`Deploy failed: ${c}`),await ft(o,`**Allwright deploy failed.**
843
892
 
844
- ${c.slice(0,800)}`),s("failed",{error:c})}}async function Md(t,e){let n=qi(e);if(!n)return;let{emit:r,setStatus:s}=Ya({runId:e,transport:t.transport});Fi(e),r("info",`Deploy to "${n.environmentName}" was rejected - nothing ran`);let i=t.lookup(n.projectId,n.environmentName);try{await t.jiraFor(i?.project.repoName??"").addComment(n.issueKey,`**Allwright: deploy to \`${n.environmentName}\` was rejected.**
893
+ ${c.slice(0,800)}`),s("failed",{error:c})}}async function Gd(t,e){let n=Vi(e);if(!n)return;let{emit:r,setStatus:s}=al({runId:e,transport:t.transport});Wi(e),r("info",`Deploy to "${n.environmentName}" was rejected - nothing ran`);let i=t.lookup(n.projectId,n.environmentName);try{await t.jiraFor(i?.project.repoName??"").addComment(n.issueKey,`**Allwright: deploy to \`${n.environmentName}\` was rejected.**
845
894
 
846
- No deploy step was executed. (run \`${e}\`)`)}catch(o){y.error(`could not post rejection comment to ${n.issueKey}: ${o}`)}s("failed",{error:"deploy rejected by a reviewer"})}var nb=w.object({steps:w.array(br.DeployStep).max(50).default([]),requiredSecrets:w.array(w.string()).max(50).default([]),notes:w.string().default("")}),rb=[".ticketpilot/deploy.md","DEPLOY.md","DEPLOYMENT.md","docs/DEPLOY.md","docs/deploy.md","docs/deployment.md"],Cd=24e3;function Yi(t){for(let e of rb){let n=mr.default.join(t,e);try{if(!gr.default.existsSync(n))continue;let r=gr.default.readFileSync(n,"utf8");if(!r.trim())continue;return{path:e,content:r.length>Cd?r.slice(0,Cd)+`
895
+ No deploy step was executed. (run \`${e}\`)`)}catch(o){y.error(`could not post rejection comment to ${n.issueKey}: ${o}`)}s("failed",{error:"deploy rejected by a reviewer"})}var Tb=k.object({steps:k.array(Tr.DeployStep).max(50).default([]),requiredSecrets:k.array(k.string()).max(50).default([]),notes:k.string().default("")}),xb=[".ticketpilot/deploy.md","DEPLOY.md","DEPLOYMENT.md","docs/DEPLOY.md","docs/deploy.md","docs/deployment.md"],Ud=24e3;function io(t){for(let e of xb){let n=kr.default.join(t,e);try{if(!_r.default.existsSync(n))continue;let r=_r.default.readFileSync(n,"utf8");if(!r.trim())continue;return{path:e,content:r.length>Ud?r.slice(0,Ud)+`
847
896
 
848
- [\u2026document truncated\u2026]`:r}}catch{continue}}return null}var $d=["docker","docker-compose","pm2","systemctl","node","pnpm","npm","yarn","make","python3","pip","rsync","ssh","caddy","nginx"];function zd(t){return Dd("bash",["-lc",`command -v ${JSON.stringify(t)}`]).trim().length>0}function Dd(t,e){try{let n=(0,yr.spawnSync)(t,e,{encoding:"utf8",timeout:5e3});return n.status===0?n.stdout??"":""}catch{return""}}async function sb(t){let e;try{e=new URL(t)}catch{return null}let n=[];try{let{resolve4:i,resolve6:o}=await import("node:dns/promises"),[l,c]=await Promise.all([i(e.hostname).catch(()=>[]),o(e.hostname).catch(()=>[])]);n=[...l,...c]}catch{n=[]}if(!n.length)return`${e.hostname} does not resolve yet - this build is on THIS machine, but nothing points at it. Users see whatever your DNS points at today.`;let r=await import("node:os"),s=new Set(Object.values(r.networkInterfaces()).flatMap(i=>i??[]).filter(i=>!i.internal).map(i=>i.address));return n.some(i=>s.has(i))?null:`${e.hostname} resolves to ${n.slice(0,3).join(", ")}, which is not an address of this machine. If you front it with a CDN or load balancer that is expected; otherwise this deploy changed nothing for users - they are still being served by the old server until the DNS record moves.`}async function ib(t,e){let n;try{n=new URL(t)}catch{e.push({name:"public-url",ok:!1,detail:`not a valid URL: ${t}`});return}try{let{lookup:r}=await import("node:dns/promises"),s=await r(n.hostname);e.push({name:"public-url-dns",ok:!0,detail:`${n.hostname} \u2192 ${s.address}`})}catch{e.push({name:"public-url-dns",ok:!1,detail:`${n.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(n.protocol==="https:"){let r=await import("node:tls");await new Promise(s=>{let i=r.connect({host:n.hostname,port:Number(n.port||443),servername:n.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(n.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 ob(t){let e=t.match(/\/(?:var|home|opt|srv)\/[\w./-]+/g)??[],n=[...new Set(e.map(s=>s.replace(/[.,;:)\]'"`]+$/,"")))].slice(0,12);return n.length?`
897
+ [\u2026document truncated\u2026]`:r}}catch{continue}}return null}var qd=["docker","docker-compose","pm2","systemctl","node","pnpm","npm","yarn","make","python3","pip","rsync","ssh","caddy","nginx"];function Zd(t){return Vd("bash",["-lc",`command -v ${JSON.stringify(t)}`]).trim().length>0}function Vd(t,e){try{let n=(0,Sr.spawnSync)(t,e,{encoding:"utf8",timeout:5e3});return n.status===0?n.stdout??"":""}catch{return""}}async function Eb(t){let e;try{e=new URL(t)}catch{return null}let n=[];try{let{resolve4:i,resolve6:o}=await import("node:dns/promises"),[l,c]=await Promise.all([i(e.hostname).catch(()=>[]),o(e.hostname).catch(()=>[])]);n=[...l,...c]}catch{n=[]}if(!n.length)return`${e.hostname} does not resolve yet - this build is on THIS machine, but nothing points at it. Users see whatever your DNS points at today.`;let r=await import("node:os"),s=new Set(Object.values(r.networkInterfaces()).flatMap(i=>i??[]).filter(i=>!i.internal).map(i=>i.address));return n.some(i=>s.has(i))?null:`${e.hostname} resolves to ${n.slice(0,3).join(", ")}, which is not an address of this machine. If you front it with a CDN or load balancer that is expected; otherwise this deploy changed nothing for users - they are still being served by the old server until the DNS record moves.`}async function Rb(t,e){let n;try{n=new URL(t)}catch{e.push({name:"public-url",ok:!1,detail:`not a valid URL: ${t}`});return}try{let{lookup:r}=await import("node:dns/promises"),s=await r(n.hostname);e.push({name:"public-url-dns",ok:!0,detail:`${n.hostname} \u2192 ${s.address}`})}catch{e.push({name:"public-url-dns",ok:!1,detail:`${n.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(n.protocol==="https:"){let r=await import("node:tls");await new Promise(s=>{let i=r.connect({host:n.hostname,port:Number(n.port||443),servername:n.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(n.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 Ib(t){let e=t.match(/\/(?:var|home|opt|srv)\/[\w./-]+/g)??[],n=[...new Set(e.map(s=>s.replace(/[.,;:)\]'"`]+$/,"")))].slice(0,12);return n.length?`
849
898
  - absolute paths the document mentions, checked on THIS machine:
850
- ${n.map(s=>` - ${s}: ${gr.default.existsSync(s)?"EXISTS on this machine":"not found on this machine"}`).join(`
851
- `)}`:""}function ab(){let t=[],e=(n,r)=>{try{let s=(0,yr.execFileSync)(r,["--version"],{encoding:"utf8",timeout:5e3}).trim();t.push(`- ${n}: ${s}`)}catch{}};for(let n of["node","npm","python3"]){let r="";try{r=(0,yr.execFileSync)("which",[n],{encoding:"utf8",timeout:5e3}).trim()}catch{continue}e(`${n} in the RUNNER's PATH (${r}) - deploy steps run with THIS`,r);for(let s of[`/usr/bin/${n}`,`/usr/local/bin/${n}`])s!==r&&gr.default.existsSync(s)&&e(`${n} at ${s}`,s)}return t.length?`
899
+ ${n.map(s=>` - ${s}: ${_r.default.existsSync(s)?"EXISTS on this machine":"not found on this machine"}`).join(`
900
+ `)}`:""}function Ab(){let t=[],e=(n,r)=>{try{let s=(0,Sr.execFileSync)(r,["--version"],{encoding:"utf8",timeout:5e3}).trim();t.push(`- ${n}: ${s}`)}catch{}};for(let n of["node","npm","python3"]){let r="";try{r=(0,Sr.execFileSync)("which",[n],{encoding:"utf8",timeout:5e3}).trim()}catch{continue}e(`${n} in the RUNNER's PATH (${r}) - deploy steps run with THIS`,r);for(let s of[`/usr/bin/${n}`,`/usr/local/bin/${n}`])s!==r&&_r.default.existsSync(s)&&e(`${n} at ${s}`,s)}return t.length?`
852
901
  - runtime versions (a MISMATCH between the runner's PATH and the system install is a common root cause):
853
902
  ${t.map(n=>` ${n}`).join(`
854
- `)}`:""}function Ld(t,e,n,r="",s="."){let i=$d.filter(c=>zd(c)),o=$d.filter(c=>!i.includes(c)),l=Object.keys(Nt(t,e,n));return`About the machine these steps will run on (gathered by the runner, trust it):
903
+ `)}`:""}function Wd(t,e,n,r="",s="."){let i=qd.filter(c=>Zd(c)),o=qd.filter(c=>!i.includes(c)),l=Object.keys(zt(t,e,n));return`About the machine these steps will run on (gathered by the runner, trust it):
855
904
  - available tools: ${i.join(", ")||"(none of the common ones)"}
856
905
  - NOT installed: ${o.join(", ")||"(none missing)"}
857
- - secrets already stored for this environment (names only): ${l.join(", ")||"(none yet)"}`+ab()+ob(r)+as(s)}async function Ud(t){let e=[];if(t.publicUrl?.trim()&&await ib(t.publicUrl.trim(),e),e.push(gr.default.existsSync(t.repoPath)?{name:"repo-path",ok:!0,detail:t.repoPath}:{name:"repo-path",ok:!1,detail:`checkout missing: ${t.repoPath}`}),e.push({name:"deploys-enabled",ok:t.cfg.deploy.enabled,detail:t.cfg.deploy.enabled?"enabled on this runner":"disabled - run: allwright deploy enable (then restart the runner)"}),t.workdir){let l=mr.default.isAbsolute(t.workdir)?t.workdir:mr.default.join(t.repoPath,t.workdir);e.push(gr.default.existsSync(l)?{name:"workdir",ok:!0,detail:l}:{name:"workdir",ok:!1,detail:`does not exist: ${l}`})}if(t.branch){let l=Dd("git",["-C",t.repoPath,"ls-remote","--heads","origin",t.branch]);e.push(l.trim()?{name:"branch",ok:!0,detail:`origin/${t.branch} exists`}:{name:"branch",ok:!1,detail:`origin has no branch "${t.branch}" (or the remote is unreachable)`})}let n=Nt(t.cfg,t.repoName,t.environmentName),r=new Set(t.requiredSecrets);for(let l of t.steps)for(let c of l.run.matchAll(/\$\{?([A-Z][A-Z0-9_]{2,})\}?/g))r.add(c[1]);let s=[...r].filter(l=>!n[l]&&!process.env[l]);e.push({name:"secrets",ok:s.length===0,detail:s.length?`missing: ${s.join(", ")} - set with: allwright env set "${t.repoName}" "${t.environmentName}" ${s[0]}=...`:`${r.size} present`});let i=new Set;for(let l of t.steps)for(let c of l.run.split(/&&|\|\||;|\|/)){let u=c.trim().split(/\s+/),p=u.shift();for(;p&&(/^[A-Za-z_][A-Za-z0-9_]*=/.test(p)||p==="sudo"||p==="env"||p==="nohup");)p=u.shift();!p||p.startsWith("$")||p.startsWith("#")||p.startsWith("(")||i.add(p)}let o=[...i].filter(l=>!zd(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 qd(t){let e=Ld(t.cfg,t.repoName,t.environmentName,"",t.repoPath),n=qt(jd.DEPLOY_FIX_PROMPT_TEMPLATE,{envName:t.environmentName,steps:t.steps.map((p,f)=>`${f+1}. [${p.name}]${p.continueOnError?" (continues on error)":""}
906
+ - secrets already stored for this environment (names only): ${l.join(", ")||"(none yet)"}`+Ab()+Ib(r)+ps(s)}async function Yd(t){let e=[];if(t.publicUrl?.trim()&&await Rb(t.publicUrl.trim(),e),e.push(_r.default.existsSync(t.repoPath)?{name:"repo-path",ok:!0,detail:t.repoPath}:{name:"repo-path",ok:!1,detail:`checkout missing: ${t.repoPath}`}),e.push({name:"deploys-enabled",ok:t.cfg.deploy.enabled,detail:t.cfg.deploy.enabled?"enabled on this runner":"disabled - run: allwright deploy enable (then restart the runner)"}),t.workdir){let l=kr.default.isAbsolute(t.workdir)?t.workdir:kr.default.join(t.repoPath,t.workdir);e.push(_r.default.existsSync(l)?{name:"workdir",ok:!0,detail:l}:{name:"workdir",ok:!1,detail:`does not exist: ${l}`})}if(t.branch){let l=Vd("git",["-C",t.repoPath,"ls-remote","--heads","origin",t.branch]);e.push(l.trim()?{name:"branch",ok:!0,detail:`origin/${t.branch} exists`}:{name:"branch",ok:!1,detail:`origin has no branch "${t.branch}" (or the remote is unreachable)`})}let n=zt(t.cfg,t.repoName,t.environmentName),r=new Set(t.requiredSecrets);for(let l of t.steps)for(let c of l.run.matchAll(/\$\{?([A-Z][A-Z0-9_]{2,})\}?/g))r.add(c[1]);let s=[...r].filter(l=>!n[l]&&!process.env[l]);e.push({name:"secrets",ok:s.length===0,detail:s.length?`missing: ${s.join(", ")} - set with: allwright env set "${t.repoName}" "${t.environmentName}" ${s[0]}=...`:`${r.size} present`});let i=new Set;for(let l of t.steps)for(let c of l.run.split(/&&|\|\||;|\|/)){let u=c.trim().split(/\s+/),p=u.shift();for(;p&&(/^[A-Za-z_][A-Za-z0-9_]*=/.test(p)||p==="sudo"||p==="env"||p==="nohup");)p=u.shift();!p||p.startsWith("$")||p.startsWith("#")||p.startsWith("(")||i.add(p)}let o=[...i].filter(l=>!Zd(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 Jd(t){let e=Wd(t.cfg,t.repoName,t.environmentName,"",t.repoPath),n=Ht(Bd.DEPLOY_FIX_PROMPT_TEMPLATE,{envName:t.environmentName,steps:t.steps.map((p,f)=>`${f+1}. [${p.name}]${p.continueOnError?" (continues on error)":""}
858
907
  ${p.run}`).join(`
859
- `),failedStep:t.failedStep||"(unknown)",errorText:t.errorText||"(no error text recorded)",knownCause:(()=>{let p=Ba(t.errorText,{cwd:t.repoPath});return p?`
908
+ `),failedStep:t.failedStep||"(unknown)",errorText:t.errorText||"(no error text recorded)",knownCause:(()=>{let p=el(t.errorText,{cwd:t.repoPath});return p?`
860
909
 
861
910
  THE RUNNER ALREADY RECOGNISES THIS FAILURE, and told the operator so:
862
911
  - what it means: ${p.cause}
863
912
  - what closes it: ${p.commands.join(" ; ")}
864
913
  - ${p.note}
865
- Start from this. If your own reading of the evidence agrees, say so in one line and turn it into steps; if it does NOT, say which evidence contradicts it - do not quietly produce a second, different answer to the same failure.`:""})(),evidence:Rd(Ed({errorText:t.errorText,repoPath:t.repoPath})),machineContext:e}),r=await t.agent.adapter.run({repoPath:t.repoPath,prompt:n,timeoutSeconds:240,bin:t.agent.bin,mode:"read_only",maxTurns:40,sessionId:(0,Wa.randomUUID)(),onLog:()=>{}});if(!r.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:r.error??"the agent produced no output"};let s=Bd(r.resultText),i=(r.resultText.split(/```/)[0]??"").replace(/^\s*CAUSE TYPE:.*$/im,"").trim(),l=/```(?:markdown|md)\s*\n([\s\S]*?)```/i.exec(r.resultText)?.[1]?.trim()??"",c=l?Yi(t.repoPath):null;if(!s)return{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"`};let u=/^\s*CAUSE TYPE:\s*(CODE|MACHINE)\b/im.exec(r.resultText)?.[1]?.toUpperCase();return u?{ok:!1,steps:[],requiredSecrets:[],notes:i,error:u==="MACHINE"?'this is not a steps problem - the steps are right, but something on this machine is missing or misconfigured. The commands to fix it are under "WHAT A HUMAN MUST RUN" above; run them on that server, then retry the deploy. Allwright will not paste a credential into a deploy recipe to work around it.':"this is not a steps problem - the deploy failed because the code or the database is not ready (a build error, a failing test, or a migration that was never applied). Changing deploy steps cannot fix it; the diagnosis above says what a person has to change."}:{ok:!0,...s,notes:i||s.notes,docPath:c?.path??(l?"DEPLOY.md":""),docContent:l}}async function Fd(t){let e=Yi(t.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 n=Ld(t.cfg,t.repoName,t.environmentName,e.content,t.repoPath),r=qt(br.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE,{envName:t.environmentName,docPath:e.path,docContent:e.content,notes:t.notes.trim()||"(nothing specified)",machineContext:n}),s=await t.agent.adapter.run({repoPath:t.repoPath,prompt:r,timeoutSeconds:t.timeoutSeconds,bin:t.agent.bin,mode:"read_only",maxTurns:30,sessionId:(0,Wa.randomUUID)(),onLog:()=>{}});if(!s.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:s.error??"Claude Code produced no output"};let i=Bd(s.resultText);return i?{ok:!0,...i}:(y.warn(`deploy step suggestion could not be parsed. Claude's raw answer follows:
866
- `+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 Bd(t){for(let e of lb(t)){let n;try{n=JSON.parse(e)}catch{continue}let r=nb.safeParse(cb(n));if(r.success&&r.data.steps.length||r.success&&r.data.notes.trim())return r.data}return null}function lb(t){let e=[];for(let s of t.matchAll(/```[a-zA-Z0-9_-]*[ \t]*\r?\n([\s\S]*?)```/g))s[1].trim()&&e.push(s[1]);let n=t.indexOf("{"),r=t.lastIndexOf("}");return n>=0&&r>n&&e.push(t.slice(n,r+1)),e}function cb(t){if(!t||typeof t!="object")return t;let e=t,r=(Array.isArray(t)?t: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:Pd(o,l),run:o.trim()}:null;if(!o||typeof o!="object")return null;let c=o,u=Za(c.run,c.command,c.cmd,c.script,c.shell);return u?{name:(Za(c.name,c.title,c.description)??Pd(u,l)).slice(0,120),run:u,continueOnError:c.continueOnError===!0||c.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:Za(e.notes,e.note,e.explanation)??""}}function Za(...t){for(let e of t)if(typeof e=="string"&&e.trim())return e.trim()}function Pd(t,e){return(t.split(`
867
- `)[0].trim()||`Step ${e+1}`).slice(0,120)}wt();ut();sr();function Ji(t,e){if(!t.componentRoutes.length)return{project:t};let n=e.filter(Boolean);if(!n.length)return{error:`no Jira component set - project "${t.name}" routes by component (${t.componentRoutes.map(i=>i.component).join(", ")}); set one on the ticket`};let r=t.componentRoutes.filter(i=>n.includes(i.component));if(!r.length)return{error:`component(s) [${n.join(", ")}] not mapped - known: `+t.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:{...t,repoName:r[0].repoName}}}var Kd=24*3600*1e3,Xi=14,ub=Xi*24*3600*1e3,db=new Set(["to","on","this","the","a","an","env","environment","please","now","it"]),Qi=class{constructor(e,n,r){this.cfg=e;this.jiraFor=n;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,n){this.routingWarned.has(e)||(this.routingWarned.add(e),y.warn(`Component routing refused - ${n}`))}resolveClaudeProfile(e,n){if(!n)return;let r=this.cfg.claudeProfiles[n]?.configDir;return!r&&e&&(this.transport.send({type:"run.log",runId:e,seq:99e3,ts:new Date().toISOString(),level:"warn",message:`Claude profile "${n}" is not set up on this runner (allwright claude login "${n}") - using the runner's own login instead.`}),y.warn(`run ${e}: claude profile "${n}" missing locally - using default login`)),r}setConfig(e,n,r=!1,s=[]){this.projects=e,this.rules=n,this.environments=s;let i=n.filter(o=>o.enabled).length;y.info(`config synced: ${e.length} project(s), ${n.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 n=this.projects.find(s=>s.repoName===e.repoName);if(!n)continue;let r=ku(n.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=Ke(this.cfg,n,"assist");if("error"in s){y.warn(`Scheduled audit skipped: ${s.error}`);continue}let i=await ns({projectId:n.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 n of this.rules){if(!n.enabled)continue;let r=this.projects.find(i=>i.id===n.projectId);if(!r)continue;let s=this.cfg.repos[r.repoName];if(!s){y.warn(`rule "${n.name}": no local path for repo "${r.repoName}" - run: allwright repo add "${r.repoName}" /path/to/checkout`);continue}n.action.type==="deploy"?await this.pollDeployRule(n,r,s.path):n.action.type==="respond"?await this.pollRespondRule(n,r,s.path):(e.has(r.id)||(e.add(r.id),await this.sweepNeedsInput(r)),n.trigger.type==="comment_keyword"&&await this.sweepRevisions(n,r),await this.pollRule(n,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 _=Date.parse(e.pausedUntil);Number.isFinite(_)&&(this.autopilotPausedUntil=_);return}let n=e.item;if(!n)return;let r=this.rules.find(_=>_.id===n.ruleId&&_.enabled),s=this.projects.find(_=>_.id===n.projectId);if(!r||!s){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:"the rule or project this item was queued against no longer exists"});return}let i=Ji(s,[]),o="project"in i?i.project:s,l=this.cfg.repos[o.repoName];if(!l){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:`no local checkout mapped for "${o.repoName}" on this machine`});return}let c=n.baseOverride||n.branchOverride||n.autoMerge?{...r,action:r.action.type==="implement"?{...r.action,...n.baseOverride?{baseBranch:n.baseOverride}:{},...n.branchOverride?{branchTemplate:n.branchOverride}:{},...n.autoMerge?{requireApproval:!1,autoMerge:!0}:{}}:r.action}:r;y.info(`autopilot: taking ${n.issueKey} (${r.name})`+(n.branchOverride?` -> shared branch ${n.branchOverride}`:"")+(n.baseOverride?` -> stacked on ${n.baseOverride}`:""));let u=this.jiraOf(o),p="";try{p=(await u.getIssue(n.issueKey))?.summary??""}catch(_){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:`could not read ${n.issueKey} from Jira: ${_ instanceof Error?_.message:String(_)}`});return}let f=await this.transport.claimRun({ruleId:r.id,issueKey:n.issueKey,issueSummary:p,triggerFingerprint:`autopilot:${n.id}`,dedupKey:`autopilot:${n.id}`});if(!f.accepted||!f.runId){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:f.reason??"the control plane refused the run"});return}this.transport.sendAutopilotReport({itemId:n.id,outcome:"claimed",runId:f.runId});let b=`${r.id}:${n.issueKey}`;this.inFlight.add(b);let v=this.resolveClaudeProfile(f.runId,f.claudeProfile);this.enqueueForRepo(l.path,async()=>{try{await Hi({runId:f.runId,rule:c,project:o,issueKey:n.issueKey,repoPath:l.path,cfg:this.cfg,jira:u,transport:this.transport,claudeConfigDir:v,actorEmail:f.actorEmail,continueBranch:n.continueBranch})}finally{this.inFlight.delete(b)}})}async sweepGitHubApprovals(){let e=Object.values(js());if(!e.length)return;let n=ye()??this.cfg,r=new Map,s=i=>{let o=Ce(n,i);if(!o)return null;let l=r.get(o);return l||r.set(o,l=new $e(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 c,u;try{[c,u]=await Promise.all([o.getReviews(i.owner,i.repo,i.prNumber),o.getPullRequest(i.owner,i.repo,i.prNumber)])}catch(v){y.warn(`review check failed for ${i.owner}/${i.repo}#${i.prNumber}: ${v instanceof Error?v.message:v}`);continue}if(!u)continue;let p={cfg:this.cfg,jiraFor:this.jiraFor,transport:this.transport};if(u.merged){y.info(`PR #${i.prNumber} for ${i.issueKey} was merged on GitHub - completing the run`),this.inFlight.add(l);try{await Ms(p,i.runId,u.headSha)}finally{this.inFlight.delete(l)}continue}if(u.state==="closed"){y.info(`PR #${i.prNumber} for ${i.issueKey} was closed unmerged on GitHub - failing the run`);let v=this.jiraFor(i.repoName),_=`PR #${i.prNumber} was closed on GitHub without merging`;await v.addComment(i.issueKey,`**Allwright: the pull request for this ticket was closed on GitHub without merging.**
914
+ Start from this. If your own reading of the evidence agrees, say so in one line and turn it into steps; if it does NOT, say which evidence contradicts it - do not quietly produce a second, different answer to the same failure.`:""})(),evidence:zd(Md({errorText:t.errorText,repoPath:t.repoPath})),machineContext:e}),r=await t.agent.adapter.run({repoPath:t.repoPath,prompt:n,timeoutSeconds:240,bin:t.agent.bin,mode:"read_only",maxTurns:40,sessionId:(0,ol.randomUUID)(),onLog:()=>{}});if(!r.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:r.error??"the agent produced no output"};let s=Qd(r.resultText),i=(r.resultText.split(/```/)[0]??"").replace(/^\s*CAUSE TYPE:.*$/im,"").trim(),l=/```(?:markdown|md)\s*\n([\s\S]*?)```/i.exec(r.resultText)?.[1]?.trim()??"",c=l?io(t.repoPath):null;if(!s)return{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"`};let u=/^\s*CAUSE TYPE:\s*(CODE|MACHINE)\b/im.exec(r.resultText)?.[1]?.toUpperCase();return u?{ok:!1,steps:[],requiredSecrets:[],notes:i,error:u==="MACHINE"?'this is not a steps problem - the steps are right, but something on this machine is missing or misconfigured. The commands to fix it are under "WHAT A HUMAN MUST RUN" above; run them on that server, then retry the deploy. Allwright will not paste a credential into a deploy recipe to work around it.':"this is not a steps problem - the deploy failed because the code or the database is not ready (a build error, a failing test, or a migration that was never applied). Changing deploy steps cannot fix it; the diagnosis above says what a person has to change."}:{ok:!0,...s,notes:i||s.notes,docPath:c?.path??(l?"DEPLOY.md":""),docContent:l}}async function Xd(t){let e=io(t.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 n=Wd(t.cfg,t.repoName,t.environmentName,e.content,t.repoPath),r=Ht(Tr.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE,{envName:t.environmentName,docPath:e.path,docContent:e.content,notes:t.notes.trim()||"(nothing specified)",machineContext:n}),s=await t.agent.adapter.run({repoPath:t.repoPath,prompt:r,timeoutSeconds:t.timeoutSeconds,bin:t.agent.bin,mode:"read_only",maxTurns:30,sessionId:(0,ol.randomUUID)(),onLog:()=>{}});if(!s.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:s.error??"Claude Code produced no output"};let i=Qd(s.resultText);return i?{ok:!0,...i}:(y.warn(`deploy step suggestion could not be parsed. Claude's raw answer follows:
915
+ `+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 Qd(t){for(let e of Cb(t)){let n;try{n=JSON.parse(e)}catch{continue}let r=Tb.safeParse($b(n));if(r.success&&r.data.steps.length||r.success&&r.data.notes.trim())return r.data}return null}function Cb(t){let e=[];for(let s of t.matchAll(/```[a-zA-Z0-9_-]*[ \t]*\r?\n([\s\S]*?)```/g))s[1].trim()&&e.push(s[1]);let n=t.indexOf("{"),r=t.lastIndexOf("}");return n>=0&&r>n&&e.push(t.slice(n,r+1)),e}function $b(t){if(!t||typeof t!="object")return t;let e=t,r=(Array.isArray(t)?t: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:Fd(o,l),run:o.trim()}:null;if(!o||typeof o!="object")return null;let c=o,u=sl(c.run,c.command,c.cmd,c.script,c.shell);return u?{name:(sl(c.name,c.title,c.description)??Fd(u,l)).slice(0,120),run:u,continueOnError:c.continueOnError===!0||c.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:sl(e.notes,e.note,e.explanation)??""}}function sl(...t){for(let e of t)if(typeof e=="string"&&e.trim())return e.trim()}function Fd(t,e){return(t.split(`
916
+ `)[0].trim()||`Step ${e+1}`).slice(0,120)}_t();ht();ur();function oo(t,e){if(!t.componentRoutes.length)return{project:t};let n=e.filter(Boolean);if(!n.length)return{error:`no Jira component set - project "${t.name}" routes by component (${t.componentRoutes.map(i=>i.component).join(", ")}); set one on the ticket`};let r=t.componentRoutes.filter(i=>n.includes(i.component));if(!r.length)return{error:`component(s) [${n.join(", ")}] not mapped - known: `+t.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:{...t,repoName:r[0].repoName}}}Kt();var eh=24*3600*1e3,ao=14,Pb=ao*24*3600*1e3,Nb=new Set(["to","on","this","the","a","an","env","environment","please","now","it"]),lo=class{constructor(e,n,r){this.cfg=e;this.jiraFor=n;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,n){this.routingWarned.has(e)||(this.routingWarned.add(e),y.warn(`Component routing refused - ${n}`))}resolveClaudeProfile(e,n){if(!n)return;let r=this.cfg.claudeProfiles[n]?.configDir;return!r&&e&&(this.transport.send({type:"run.log",runId:e,seq:99e3,ts:new Date().toISOString(),level:"warn",message:`Claude profile "${n}" is not set up on this runner (allwright claude login "${n}") - using the runner's own login instead.`}),y.warn(`run ${e}: claude profile "${n}" missing locally - using default login`)),r}setConfig(e,n,r=!1,s=[]){this.projects=e,this.rules=n,this.environments=s;let i=n.filter(o=>o.enabled).length;y.info(`config synced: ${e.length} project(s), ${n.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 n=this.projects.find(s=>s.repoName===e.repoName);if(!n)continue;let r=Pu(n.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=He(this.cfg,n,"assist");if("error"in s){y.warn(`Scheduled audit skipped: ${s.error}`);continue}let i=await ls({projectId:n.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 n of this.rules){if(!n.enabled)continue;let r=this.projects.find(i=>i.id===n.projectId);if(!r)continue;let s=this.cfg.repos[r.repoName];if(!s){y.warn(`rule "${n.name}": no local path for repo "${r.repoName}" - run: allwright repo add "${r.repoName}" /path/to/checkout`);continue}n.action.type==="deploy"?await this.pollDeployRule(n,r,s.path):n.action.type==="respond"?await this.pollRespondRule(n,r,s.path):(e.has(r.id)||(e.add(r.id),await this.sweepNeedsInput(r)),n.trigger.type==="comment_keyword"&&await this.sweepRevisions(n,r),await this.pollRule(n,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 w=Date.parse(e.pausedUntil);Number.isFinite(w)&&(this.autopilotPausedUntil=w);return}let n=e.item;if(!n)return;let r=this.rules.find(w=>w.id===n.ruleId&&w.enabled),s=this.projects.find(w=>w.id===n.projectId);if(!r||!s){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:"the rule or project this item was queued against no longer exists"});return}let i=oo(s,[]),o="project"in i?i.project:s,l=this.cfg.repos[o.repoName];if(!l){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:`no local checkout mapped for "${o.repoName}" on this machine`});return}let c=n.baseOverride||n.branchOverride||n.autoMerge?{...r,action:r.action.type==="implement"?{...r.action,...n.baseOverride?{baseBranch:n.baseOverride}:{},...n.branchOverride?{branchTemplate:n.branchOverride}:{},...n.autoMerge?{requireApproval:!1,autoMerge:!0}:{}}:r.action}:r;y.info(`autopilot: taking ${n.issueKey} (${r.name})`+(n.branchOverride?` -> shared branch ${n.branchOverride}`:"")+(n.baseOverride?` -> stacked on ${n.baseOverride}`:""));let u=this.jiraOf(o),p="";try{p=(await u.getIssue(n.issueKey))?.summary??""}catch(w){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:`could not read ${n.issueKey} from Jira: ${w instanceof Error?w.message:String(w)}`});return}let f=await this.transport.claimRun({ruleId:r.id,issueKey:n.issueKey,issueSummary:p,triggerFingerprint:`autopilot:${n.id}`,dedupKey:`autopilot:${n.id}`});if(!f.accepted||!f.runId){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:f.reason??"the control plane refused the run"});return}this.transport.sendAutopilotReport({itemId:n.id,outcome:"claimed",runId:f.runId});let b=`${r.id}:${n.issueKey}`;this.inFlight.add(b);let v=this.resolveClaudeProfile(f.runId,f.claudeProfile);this.enqueueForRepo(l.path,async()=>{try{await Xi({runId:f.runId,rule:c,project:o,issueKey:n.issueKey,repoPath:l.path,cfg:this.cfg,jira:u,transport:this.transport,claudeConfigDir:v,actorEmail:f.actorEmail,continueBranch:n.continueBranch})}finally{this.inFlight.delete(b)}})}async sweepGitHubApprovals(){let e=Object.values(Us());if(!e.length)return;let n=ye()??this.cfg,r=new Map,s=i=>{let o=$e(n,i);if(!o)return null;let l=r.get(o);return l||r.set(o,l=new Pe(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 c,u;try{[c,u]=await Promise.all([o.getReviews(i.owner,i.repo,i.prNumber),o.getPullRequest(i.owner,i.repo,i.prNumber)])}catch(v){y.warn(`review check failed for ${i.owner}/${i.repo}#${i.prNumber}: ${v instanceof Error?v.message:v}`);continue}if(!u)continue;let p={cfg:this.cfg,jiraFor:this.jiraFor,transport:this.transport};if(u.merged){y.info(`PR #${i.prNumber} for ${i.issueKey} was merged on GitHub - completing the run`),this.inFlight.add(l);try{await Bs(p,i.runId,u.headSha)}finally{this.inFlight.delete(l)}continue}if(u.state==="closed"){y.info(`PR #${i.prNumber} for ${i.issueKey} was closed unmerged on GitHub - failing the run`);let v=this.jiraFor(i.repoName),w=`PR #${i.prNumber} was closed on GitHub without merging`;await v.addComment(i.issueKey,`**Allwright: the pull request for this ticket was closed on GitHub without merging.**
868
917
 
869
918
  PR: ${i.prUrl}
870
919
 
871
- 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 v.editLabels(i.issueKey,{add:[i.failedLabel]}).catch(()=>{}),this.transport.send({type:"run.status",runId:i.runId,status:"failed",error:_}),cr(i.runId);continue}u.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.
920
+ 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 v.editLabels(i.issueKey,{add:[i.failedLabel]}).catch(()=>{}),this.transport.send({type:"run.status",runId:i.runId,status:"failed",error:w}),mr(i.runId);continue}u.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.
872
921
 
873
922
  PR: ${i.prUrl}
874
923
 
875
- 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,dt(i),y.info(`merge conflicts on PR #${i.prNumber} for ${i.issueKey} - ticket notified`))):u.mergeableState!==null&&u.mergeableState!=="unknown"&&(this.transport.send({type:"run.pr.conflict",runId:i.runId,conflicted:!1}),i.conflictNotified&&(i.conflictNotified=!1,dt(i)));let f=c.filter(v=>v.state==="APPROVED"||v.state==="CHANGES_REQUESTED").sort((v,_)=>v.submittedAt.localeCompare(_.submittedAt)),b=f[f.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}).
924
+ 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,pt(i),y.info(`merge conflicts on PR #${i.prNumber} for ${i.issueKey} - ticket notified`))):u.mergeableState!==null&&u.mergeableState!=="unknown"&&(this.transport.send({type:"run.pr.conflict",runId:i.runId,conflicted:!1}),i.conflictNotified&&(i.conflictNotified=!1,pt(i)));let f=c.filter(v=>v.state==="APPROVED"||v.state==="CHANGES_REQUESTED").sort((v,w)=>v.submittedAt.localeCompare(w.submittedAt)),b=f[f.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}).
876
925
 
877
926
  PR: ${i.prUrl}
878
927
 
879
- Reply to the review on GitHub, or reject the run on the Allwright dashboard and re-trigger with new instructions. (run \`${i.runId}\`)`).catch(()=>{}),dt({...i,changesRequestedNotified:!0}),y.info(`changes requested on PR #${i.prNumber} for ${i.issueKey} - ticket notified`));continue}if(b.commitId===u.headSha){y.info(`PR #${i.prNumber} for ${i.issueKey} approved on GitHub by ${b.user} - completing the run`),this.inFlight.add(l);try{await Ms(p,i.runId,b.commitId)}catch(v){y.warn(`github-approval completion failed for ${i.runId}: ${v instanceof Error?v.message:v}`)}finally{this.inFlight.delete(l)}}}}}async sweepMergedPRs(){let e=Object.values(Ui());if(!e.length)return;let n=ye()??this.cfg,r=new Map,s=l=>{let c=Ce(n,l);if(!c)return null;let u=r.get(c);return u||r.set(c,u=new $e(c)),u},i=20,o=720*3600*1e3;for(let l of e.slice(0,i)){let c=s(l.repoName);if(!c)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`),Ps(l.runId);continue}let u;try{u=await c.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(!u){Ps(l.runId);continue}if(u.state==="open")continue;if(!u.merged){Ps(l.runId);continue}let p=this.jiraFor(l.repoName),f="";if(l.jiraTransitionOnMerge)try{f=await p.transitionByName(l.issueKey,l.jiraTransitionOnMerge)?`
928
+ Reply to the review on GitHub, or reject the run on the Allwright dashboard and re-trigger with new instructions. (run \`${i.runId}\`)`).catch(()=>{}),pt({...i,changesRequestedNotified:!0}),y.info(`changes requested on PR #${i.prNumber} for ${i.issueKey} - ticket notified`));continue}if(b.commitId===u.headSha){y.info(`PR #${i.prNumber} for ${i.issueKey} approved on GitHub by ${b.user} - completing the run`),this.inFlight.add(l);try{await Bs(p,i.runId,b.commitId)}catch(v){y.warn(`github-approval completion failed for ${i.runId}: ${v instanceof Error?v.message:v}`)}finally{this.inFlight.delete(l)}}}}}async sweepMergedPRs(){let e=Object.values(Zi());if(!e.length)return;let n=ye()??this.cfg,r=new Map,s=l=>{let c=$e(n,l);if(!c)return null;let u=r.get(c);return u||r.set(c,u=new Pe(c)),u},i=20,o=720*3600*1e3;for(let l of e.slice(0,i)){let c=s(l.repoName);if(!c)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`),Ls(l.runId);continue}let u;try{u=await c.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(!u){Ls(l.runId);continue}if(u.state==="open")continue;if(!u.merged){Ls(l.runId);continue}let p=this.jiraFor(l.repoName),f="";if(l.jiraTransitionOnMerge)try{f=await p.transitionByName(l.issueKey,l.jiraTransitionOnMerge)?`
880
929
 
881
930
  Ticket moved to **${l.jiraTransitionOnMerge}**.`:`
882
931
 
@@ -886,19 +935,19 @@ Note: the "${l.jiraTransitionOnMerge}" transition failed: ${b instanceof Error?b
886
935
 
887
936
  PR: ${l.prUrl} (merged at \`${u.headSha.slice(0,10)}\`)${f}
888
937
 
889
- (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`),Ps(l.runId)}}async sweepNeedsInput(e){let n;try{n=await this.jiraOf(e).search(`project = "${e.jiraProjectKey}" AND labels = "${fn.NEEDS_INPUT_LABEL}"`,10)}catch(s){y.warn(`needs-input sweep failed for ${e.jiraProjectKey}: ${s instanceof Error?s.message:s}`);return}if(!n.length)return;let r=ur();for(let s of n){let i=Object.values(r).filter(l=>l.issueKey===s.key);if(!i.length){await this.jiraOf(e).editLabels(s.key,{remove:[fn.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 c=`resume:${l.runId}`;if(this.inFlight.has(c))continue;if(Date.now()-new Date(l.createdAt).getTime()>ub){this.inFlight.add(c),this.abandonStaleInput(l,e).finally(()=>this.inFlight.delete(c));continue}try{o=o??await this.jiraOf(e).getIssue(s.key)}catch(_){y.warn(`needs-input check failed for ${s.key}: ${_ instanceof Error?_.message:_}`);continue}let u=new Date(l.questionsPostedAt).getTime(),p=o.comments.filter(_=>!kt(_.body)&&new Date(_.created).getTime()>u);if(!p.length)continue;let f=zs(p),b=o.attachments;this.inFlight.add(c),y.info(`reply received on ${s.key} - resuming run ${l.runId}`),await this.jiraOf(e).editLabels(s.key,{remove:[fn.NEEDS_INPUT_LABEL]}).catch(_=>{y.warn(`could not remove needs-input label on ${s.key}: ${_}`)});let v={jiraFor:this.jiraFor,transport:this.transport,cfg:this.cfg};l.kind==="implement"?this.enqueueForRepo(l.baseRepoPath??l.repoPath,async()=>{try{await qa(l,f,b,v)}finally{this.inFlight.delete(c)}}):this.enqueueForRepo(l.repoPath,async()=>{try{await Ua(l,f,b,v)}finally{this.inFlight.delete(c)}})}}}async answerPendingInput(e,n,r){let s=Wu(e);if(!s)return{ok:!1,note:"",error:"this run is not waiting for an answer on this server - it may have been answered already, or abandoned after 14 days without a reply"};let i=`resume:${e}`;if(this.inFlight.has(i))return{ok:!1,note:"",error:"an answer for this run is already being applied"};this.inFlight.add(i);let o=this.jiraFor(s.repoName??""),l=[];try{l=(await o.getIssue(s.issueKey)).attachments,await o.addComment(s.issueKey,`**Answered on the Allwright dashboard${r?` by ${r}`:""}.**
938
+ (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`),Ls(l.runId)}}async sweepNeedsInput(e){let n;try{n=await this.jiraOf(e).search(`project = "${e.jiraProjectKey}" AND labels = "${vn.NEEDS_INPUT_LABEL}"`,10)}catch(s){y.warn(`needs-input sweep failed for ${e.jiraProjectKey}: ${s instanceof Error?s.message:s}`);return}if(!n.length)return;let r=gr();for(let s of n){let i=Object.values(r).filter(l=>l.issueKey===s.key);if(!i.length){await this.jiraOf(e).editLabels(s.key,{remove:[vn.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 c=`resume:${l.runId}`;if(this.inFlight.has(c))continue;if(Date.now()-new Date(l.createdAt).getTime()>Pb){this.inFlight.add(c),this.abandonStaleInput(l,e).finally(()=>this.inFlight.delete(c));continue}try{o=o??await this.jiraOf(e).getIssue(s.key)}catch(w){y.warn(`needs-input check failed for ${s.key}: ${w instanceof Error?w.message:w}`);continue}let u=new Date(l.questionsPostedAt).getTime(),p=o.comments.filter(w=>!St(w.body)&&new Date(w.created).getTime()>u);if(!p.length)continue;let f=Ks(p),b=o.attachments;this.inFlight.add(c),y.info(`reply received on ${s.key} - resuming run ${l.runId}`),await this.jiraOf(e).editLabels(s.key,{remove:[vn.NEEDS_INPUT_LABEL]}).catch(w=>{y.warn(`could not remove needs-input label on ${s.key}: ${w}`)});let v={jiraFor:this.jiraFor,transport:this.transport,cfg:this.cfg};l.kind==="implement"?this.enqueueForRepo(l.baseRepoPath??l.repoPath,async()=>{try{await Xa(l,f,b,v)}finally{this.inFlight.delete(c)}}):this.enqueueForRepo(l.repoPath,async()=>{try{await Ja(l,f,b,v)}finally{this.inFlight.delete(c)}})}}}async answerPendingInput(e,n,r){let s=od(e);if(!s)return{ok:!1,note:"",error:"this run is not waiting for an answer on this server - it may have been answered already, or abandoned after 14 days without a reply"};let i=`resume:${e}`;if(this.inFlight.has(i))return{ok:!1,note:"",error:"an answer for this run is already being applied"};this.inFlight.add(i);let o=this.jiraFor(s.repoName??""),l=[];try{l=(await o.getIssue(s.issueKey)).attachments,await o.addComment(s.issueKey,`**Answered on the Allwright dashboard${r?` by ${r}`:""}.**
890
939
 
891
940
  ${n}
892
941
 
893
- This run is continuing from where it left off. (run \`${e}\`)`),await o.editLabels(s.issueKey,{remove:[fn.NEEDS_INPUT_LABEL]})}catch(f){this.inFlight.delete(i);let b=f instanceof Error?f.message:String(f);return{ok:!1,note:"",error:`could not write the answer to ${s.issueKey}: ${b}`}}y.info(`answer received from the dashboard for ${s.issueKey} - resuming run ${e}`);let c=r?`${r}: ${n}`:n,u={jiraFor:this.jiraFor,transport:this.transport,cfg:this.cfg},p=s.kind==="implement"?s.baseRepoPath??s.repoPath:s.repoPath;return this.enqueueForRepo(p,async()=>{try{s.kind==="implement"?await qa(s,c,l,u):await Ua(s,c,l,u)}finally{this.inFlight.delete(i)}}),{ok:!0,note:`Answer sent - the run is continuing, and it was posted to ${s.issueKey} too.`}}async abandonStaleInput(e,n){y.warn(`${e.issueKey}: needs-input unanswered for over ${Xi}d - abandoning run ${e.runId}`);try{await this.jiraOf(n).addComment(e.issueKey,`**Allwright gave up waiting for an answer.**
942
+ This run is continuing from where it left off. (run \`${e}\`)`),await o.editLabels(s.issueKey,{remove:[vn.NEEDS_INPUT_LABEL]})}catch(f){this.inFlight.delete(i);let b=f instanceof Error?f.message:String(f);return{ok:!1,note:"",error:`could not write the answer to ${s.issueKey}: ${b}`}}y.info(`answer received from the dashboard for ${s.issueKey} - resuming run ${e}`);let c=r?`${r}: ${n}`:n,u={jiraFor:this.jiraFor,transport:this.transport,cfg:this.cfg},p=s.kind==="implement"?s.baseRepoPath??s.repoPath:s.repoPath;return this.enqueueForRepo(p,async()=>{try{s.kind==="implement"?await Xa(s,c,l,u):await Ja(s,c,l,u)}finally{this.inFlight.delete(i)}}),{ok:!0,note:`Answer sent - the run is continuing, and it was posted to ${s.issueKey} too.`}}async abandonStaleInput(e,n){y.warn(`${e.issueKey}: needs-input unanswered for over ${ao}d - abandoning run ${e.runId}`);try{await this.jiraOf(n).addComment(e.issueKey,`**Allwright gave up waiting for an answer.**
894
943
 
895
- No reply arrived within ${Xi} 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(n).editLabels(e.issueKey,{add:[e.failedLabel],remove:[fn.NEEDS_INPUT_LABEL]})}catch(r){y.warn(`could not post staleness notice for ${e.issueKey}: ${r}`)}e.kind==="implement"&&await vt(e.baseRepoPath??e.repoPath,e.repoPath).catch(()=>{}),St(e.runId),this.transport.send({type:"run.status",runId:e.runId,status:"failed",error:`no reply within ${Xi} days`})}async pollRule(e,n,r){let s=e.trigger.type==="label_added"?await this.matchLabelTrigger(e,n):await this.matchCommentTrigger(e,n);for(let i of s){let o=`${e.id}:${i.issueKey}`;if(this.inFlight.has(o))continue;let l=Ji(n,i.components??[]);if("error"in l){this.warnRoutingOnce(`${e.id}:${i.issueKey}`,`${i.issueKey}: ${l.error}`);continue}let c=l.project,u=c.repoName===n.repoName?r:this.cfg.repos[c.repoName]?.path;if(!u){this.warnRoutingOnce(`${e.id}:${i.issueKey}:path`,`${i.issueKey}: routed to repo "${c.repoName}" but it has no local checkout - run: allwright repo add "${c.repoName}" /path/to/checkout`);continue}let p=await this.transport.claimRun({ruleId:e.id,issueKey:i.issueKey,issueSummary:i.summary,triggerFingerprint:i.fingerprint,triggeredByAccountId:i.triggeredByAccountId});if(!p.accepted||!p.runId){p.reason!=="duplicate"&&y.warn(`claim rejected for ${i.issueKey}: ${p.reason??"unknown"}`);continue}this.inFlight.add(o),y.info(`claimed run ${p.runId} for ${i.issueKey}`+(c.repoName!==n.repoName?` (routed \u2192 ${c.repoName})`:"")+(p.claudeProfile?` (claude profile "${p.claudeProfile}")`:""));let f=this.resolveClaudeProfile(p.runId,p.claudeProfile);this.enqueueForRepo(u,async()=>{try{await Hi({runId:p.runId,rule:e,project:c,issueKey:i.issueKey,repoPath:u,cfg:this.cfg,jira:this.jiraOf(c),transport:this.transport,claudeConfigDir:f,actorEmail:p.actorEmail})}finally{this.inFlight.delete(o)}})}}async pollRespondRule(e,n,r){let s=e.trigger;if(s.type!=="comment_keyword"||e.action.type!=="respond")return;let i=await this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=s.keyword.toLowerCase(),l=Date.now()-Kd;for(let c of i){let u=await this.jiraOf(n).getIssue(c.key);for(let p of u.comments){if(!p.body.toLowerCase().includes(o)||kt(p.body)||new Date(p.created).getTime()<l||!p.id)continue;let f=`respond:${p.id}`;if(this.inFlight.has(f))continue;let b=Ji(n,c.components??[]);if("error"in b){this.warnRoutingOnce(`${e.id}:${c.key}`,`${c.key}: ${b.error}`);continue}let v=b.project,_=v.repoName===n.repoName?r:this.cfg.repos[v.repoName]?.path;if(!_){this.warnRoutingOnce(`${e.id}:${c.key}:path`,`${c.key}: routed to repo "${v.repoName}" but it has no local checkout - run: allwright repo add "${v.repoName}" /path/to/checkout`);continue}let x=await this.transport.claimRun({ruleId:e.id,issueKey:c.key,issueSummary:c.summary,triggerFingerprint:`question by ${p.author} at ${p.created}`,dedupKey:`respond:comment:${p.id}`,triggeredByAccountId:p.authorAccountId??void 0});if(!x.accepted||!x.runId){x.reason!=="duplicate"&&y.warn(`respond claim rejected for ${c.key}: ${x.reason??"unknown"}`);continue}this.inFlight.add(f),y.info(`claimed respond run ${x.runId}: ${c.key} (comment ${p.id})`+(v.repoName!==n.repoName?` (routed \u2192 ${v.repoName})`:"")+(x.claudeProfile?` (claude profile "${x.claudeProfile}")`:""));let $={author:p.author,body:p.body},j=this.resolveClaudeProfile(x.runId,x.claudeProfile);this.enqueueForRepo(_,async()=>{try{await Hi({runId:x.runId,rule:e,project:v,issueKey:c.key,repoPath:_,cfg:this.cfg,jira:this.jiraOf(v),transport:this.transport,question:$,claudeConfigDir:j,actorEmail:x.actorEmail})}finally{this.inFlight.delete(f)}})}}}async sweepRevisions(e,n){let r=e.trigger;if(r.type!=="comment_keyword")return;let s;try{s=await this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND labels = "${r.doneLabel}" AND updated >= "-2d"`,10)}catch(o){y.warn(`revision sweep failed for ${n.jiraProjectKey}: ${o instanceof Error?o.message:o}`);return}let i=r.keyword.toLowerCase();for(let o of s)try{let l=await this.jiraOf(n).getIssue(o.key),c=null;for(let p of l.comments)kt(p.body)&&(c=Math.max(c??0,new Date(p.created).getTime()));if(c===null||!l.comments.some(p=>!kt(p.body)&&p.body.toLowerCase().includes(i)&&new Date(p.created).getTime()>c))continue;await this.jiraOf(n).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,n,r){if(e.action.type!=="deploy")return;let s=e.trigger.type==="status_changed"?await this.matchStatusDeploys(e,n):await this.matchCommentDeploys(e,n);for(let i of s){let o=`deploy:${i.dedupKey}`;if(this.inFlight.has(o))continue;let l=await this.transport.claimDeploy({projectId:n.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(n).addComment(i.issueKey,`**Allwright did not deploy this ticket.**
944
+ No reply arrived within ${ao} 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(n).editLabels(e.issueKey,{add:[e.failedLabel],remove:[vn.NEEDS_INPUT_LABEL]})}catch(r){y.warn(`could not post staleness notice for ${e.issueKey}: ${r}`)}e.kind==="implement"&&await kt(e.baseRepoPath??e.repoPath,e.repoPath).catch(()=>{}),xt(e.runId),this.transport.send({type:"run.status",runId:e.runId,status:"failed",error:`no reply within ${ao} days`})}async pollRule(e,n,r){let s=e.trigger.type==="label_added"?await this.matchLabelTrigger(e,n):await this.matchCommentTrigger(e,n);for(let i of s){let o=`${e.id}:${i.issueKey}`;if(this.inFlight.has(o))continue;let l=oo(n,i.components??[]);if("error"in l){this.warnRoutingOnce(`${e.id}:${i.issueKey}`,`${i.issueKey}: ${l.error}`);continue}let c=l.project,u=c.repoName===n.repoName?r:this.cfg.repos[c.repoName]?.path;if(!u){this.warnRoutingOnce(`${e.id}:${i.issueKey}:path`,`${i.issueKey}: routed to repo "${c.repoName}" but it has no local checkout - run: allwright repo add "${c.repoName}" /path/to/checkout`);continue}let p=await this.transport.claimRun({ruleId:e.id,issueKey:i.issueKey,issueSummary:i.summary,triggerFingerprint:i.fingerprint,triggeredByAccountId:i.triggeredByAccountId});if(!p.accepted||!p.runId){p.reason!=="duplicate"&&y.warn(`claim rejected for ${i.issueKey}: ${p.reason??"unknown"}`);continue}this.inFlight.add(o),y.info(`claimed run ${p.runId} for ${i.issueKey}`+(c.repoName!==n.repoName?` (routed \u2192 ${c.repoName})`:"")+(p.claudeProfile?` (claude profile "${p.claudeProfile}")`:""));let f=this.resolveClaudeProfile(p.runId,p.claudeProfile);this.enqueueForRepo(u,async()=>{try{await Xi({runId:p.runId,rule:e,project:c,issueKey:i.issueKey,repoPath:u,cfg:this.cfg,jira:this.jiraOf(c),transport:this.transport,claudeConfigDir:f,actorEmail:p.actorEmail})}finally{this.inFlight.delete(o)}})}}async pollRespondRule(e,n,r){let s=e.trigger;if(s.type!=="comment_keyword"||e.action.type!=="respond")return;let i=await this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=s.keyword.toLowerCase(),l=Date.now()-eh;for(let c of i){let u=await this.jiraOf(n).getIssue(c.key);for(let p of u.comments){if(!p.body.toLowerCase().includes(o)||St(p.body)||new Date(p.created).getTime()<l||!p.id)continue;let f=`respond:${p.id}`;if(this.inFlight.has(f))continue;let b=oo(n,c.components??[]);if("error"in b){this.warnRoutingOnce(`${e.id}:${c.key}`,`${c.key}: ${b.error}`);continue}let v=b.project,w=v.repoName===n.repoName?r:this.cfg.repos[v.repoName]?.path;if(!w){this.warnRoutingOnce(`${e.id}:${c.key}:path`,`${c.key}: routed to repo "${v.repoName}" but it has no local checkout - run: allwright repo add "${v.repoName}" /path/to/checkout`);continue}let x=await this.transport.claimRun({ruleId:e.id,issueKey:c.key,issueSummary:c.summary,triggerFingerprint:`question by ${p.author} at ${p.created}`,dedupKey:`respond:comment:${p.id}`,triggeredByAccountId:p.authorAccountId??void 0});if(!x.accepted||!x.runId){x.reason!=="duplicate"&&y.warn(`respond claim rejected for ${c.key}: ${x.reason??"unknown"}`);continue}this.inFlight.add(f),y.info(`claimed respond run ${x.runId}: ${c.key} (comment ${p.id})`+(v.repoName!==n.repoName?` (routed \u2192 ${v.repoName})`:"")+(x.claudeProfile?` (claude profile "${x.claudeProfile}")`:""));let $={author:p.author,body:p.body},N=this.resolveClaudeProfile(x.runId,x.claudeProfile);this.enqueueForRepo(w,async()=>{try{await Xi({runId:x.runId,rule:e,project:v,issueKey:c.key,repoPath:w,cfg:this.cfg,jira:this.jiraOf(v),transport:this.transport,question:$,claudeConfigDir:N,actorEmail:x.actorEmail})}finally{this.inFlight.delete(f)}})}}}async sweepRevisions(e,n){let r=e.trigger;if(r.type!=="comment_keyword")return;let s;try{s=await this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND labels = "${r.doneLabel}" AND updated >= "-2d"`,10)}catch(o){y.warn(`revision sweep failed for ${n.jiraProjectKey}: ${o instanceof Error?o.message:o}`);return}let i=r.keyword.toLowerCase();for(let o of s)try{let l=await this.jiraOf(n).getIssue(o.key),c=null;for(let p of l.comments)St(p.body)&&(c=Math.max(c??0,new Date(p.created).getTime()));if(c===null||!l.comments.some(p=>!St(p.body)&&p.body.toLowerCase().includes(i)&&new Date(p.created).getTime()>c))continue;await this.jiraOf(n).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,n,r){if(e.action.type!=="deploy")return;let s=e.trigger.type==="status_changed"?await this.matchStatusDeploys(e,n):await this.matchCommentDeploys(e,n);for(let i of s){let o=`deploy:${i.dedupKey}`;if(this.inFlight.has(o))continue;let l=await this.transport.claimDeploy({projectId:n.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(n).addComment(i.issueKey,`**Allwright did not deploy this ticket.**
896
945
 
897
946
  ${l.reason}`+(i.requestedByAccountId?`
898
947
 
899
948
  Jira account id: \`${i.requestedByAccountId}\``:"")+`
900
949
 
901
- (run \`${l.runId}\`)`).catch(u=>y.warn(`could not post refusal to ${i.issueKey}: ${u}`)),y.warn(`deploy refused for ${i.issueKey}: ${l.reason}`)):l.reason&&y.warn(`deploy claim rejected for ${i.issueKey}: ${l.reason}`);continue}let c=l.environment;this.inFlight.add(o),y.info(`claimed deploy ${l.runId}: ${i.issueKey} \u2192 ${c.name}`),this.enqueue(this.envQueues,c.id,async()=>{try{await Wi({runId:l.runId,project:n,environment:c,issueKey:i.issueKey,issueSummary:i.summary,repoPath:r,cfg:this.cfg,jira:this.jiraOf(n),transport:this.transport,requestedBy:i.requestedByDisplayName})}finally{this.inFlight.delete(o)}})}}async matchCommentDeploys(e,n){let r=e.trigger,s=e.action;if(r.type!=="comment_keyword"||s.type!=="deploy")return[];let i=await this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=r.keyword.toLowerCase(),l=Date.now()-Kd,c=this.environments.filter(f=>f.projectId===n.id).map(f=>f.name),u=this.fixedEnvironmentName(s.environmentId),p=[];for(let f of i){let b=await this.jiraOf(n).getIssue(f.key);if(!(s.requireStatus&&b.status.toLowerCase()!==s.requireStatus.toLowerCase()))for(let v of b.comments){if(!v.body.toLowerCase().includes(o)||kt(v.body)||new Date(v.created).getTime()<l||!v.id)continue;let _=s.envSelection==="fixed"?u:hb(v.body,r.keyword,c);p.push({issueKey:f.key,summary:f.summary,environmentName:_,requestedByAccountId:v.authorAccountId??void 0,requestedByDisplayName:v.author,dedupKey:`deploy:comment:${v.id}`,fingerprint:`comment "${r.keyword}" by ${v.author} at ${v.created}`+(_?` \u2192 ${_}`:"")})}}return p}async matchStatusDeploys(e,n){let r=e.trigger,s=e.action;if(r.type!=="status_changed"||s.type!=="deploy")return[];let i=await this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND status = "${r.status}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=this.fixedEnvironmentName(s.environmentId),l=[];for(let c of i){let u=await this.jiraOf(n).lastEnteredStatus(c.key,r.status);u&&l.push({issueKey:c.key,summary:c.summary,environmentName:o,requestedByAccountId:u.authorAccountId??void 0,requestedByDisplayName:u.author,dedupKey:`deploy:status:${e.id}:${c.key}:${u.at}`,fingerprint:`moved to "${r.status}" by ${u.author} at ${u.at}`})}return l}fixedEnvironmentName(e){return e?this.environments.find(n=>n.id===e)?.name??"":""}async matchLabelTrigger(e,n){let r=e.trigger;if(r.type!=="label_added")return[];let s=`project = "${n.jiraProjectKey}" AND labels = "${r.label}" AND labels not in ("${r.doneLabel}", "${r.failedLabel}", "${fn.NEEDS_INPUT_LABEL}") ORDER BY updated ASC`;return(await this.jiraOf(n).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,n){let r=e.trigger;if(r.type!=="comment_keyword")return[];let s=`project = "${n.jiraProjectKey}" AND updated >= "-2d" AND (labels IS EMPTY OR labels not in ("${r.doneLabel}", "${r.failedLabel}", "${fn.NEEDS_INPUT_LABEL}")) ORDER BY updated DESC`,i=await this.jiraOf(n).search(s,10),o=r.keyword.toLowerCase(),l=[];for(let c of i){let p=[...(await this.jiraOf(n).getIssue(c.key)).comments].reverse().find(f=>f.body.toLowerCase().includes(o)&&!kt(f.body));p&&l.push({issueKey:c.key,components:c.components,summary:c.summary,fingerprint:`comment keyword "${r.keyword}" by ${p.author} at ${p.created}`,triggeredByAccountId:p.authorAccountId??void 0})}return l}async diagnoseRule(e,n){let r=e.trigger;if(e.action.type==="deploy"){let c=r.type==="status_changed"?await this.matchStatusDeploys(e,n):await this.matchCommentDeploys(e,n),u=c.filter(p=>p.environmentName);return{matchedCount:u.length,excludedCount:c.length-u.length,excludedSample:c.filter(p=>!p.environmentName).slice(0,5).map(p=>p.issueKey)}}if(r.type==="status_changed")return{matchedCount:(await this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND status = "${r.status}"`,50)).length,excludedCount:0,excludedSample:[]};if(r.type==="label_added"){let[c,u]=await Promise.all([this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND labels = "${r.label}" AND labels not in ("${r.doneLabel}", "${r.failedLabel}")`,50),this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND labels = "${r.label}" AND labels in ("${r.doneLabel}", "${r.failedLabel}")`,50)]);return{matchedCount:c.length,excludedCount:u.length,excludedSample:u.slice(0,5).map(p=>p.key)}}let s=r.keyword.toLowerCase(),[i,o]=await Promise.all([this.matchCommentTrigger(e,n),this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND updated >= "-2d" AND labels in ("${r.doneLabel}", "${r.failedLabel}")`,50)]),l=[];for(let c of o)(await this.jiraOf(n).getIssue(c.key)).comments.some(p=>p.body.toLowerCase().includes(s))&&l.push(c.key);return{matchedCount:i.length,excludedCount:l.length,excludedSample:l.slice(0,5)}}enqueueForRepo(e,n){this.enqueue(this.repoQueues,e,n)}runOnRepoQueue(e,n){this.enqueue(this.repoQueues,e,n)}runOnEnvironmentQueue(e,n){this.enqueue(this.envQueues,e,n)}enqueue(e,n,r){let i=(e.get(n)??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(n,i)}};function hb(t,e,n){let r=t.toLowerCase().indexOf(e.toLowerCase());if(r<0)return"";let i=t.slice(r+e.length).split(/[^\w.-]+/).filter(Boolean);for(let o of i){let l=n.find(c=>c.toLowerCase()===o.toLowerCase());if(l)return l}for(let o of i)if(!db.has(o.toLowerCase()))return o;return""}var Hd=R(require("node:fs"),1),Gd=R(require("node:path"),1),Qa=require("node:crypto");wt();var pb=`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.
950
+ (run \`${l.runId}\`)`).catch(u=>y.warn(`could not post refusal to ${i.issueKey}: ${u}`)),y.warn(`deploy refused for ${i.issueKey}: ${l.reason}`)):l.reason&&y.warn(`deploy claim rejected for ${i.issueKey}: ${l.reason}`);continue}let c=l.environment;this.inFlight.add(o),y.info(`claimed deploy ${l.runId}: ${i.issueKey} \u2192 ${c.name}`),this.enqueue(this.envQueues,c.id,async()=>{try{await so({runId:l.runId,project:n,environment:c,issueKey:i.issueKey,issueSummary:i.summary,repoPath:r,cfg:this.cfg,jira:this.jiraOf(n),transport:this.transport,requestedBy:i.requestedByDisplayName})}finally{this.inFlight.delete(o)}})}}async matchCommentDeploys(e,n){let r=e.trigger,s=e.action;if(r.type!=="comment_keyword"||s.type!=="deploy")return[];let i=await this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=r.keyword.toLowerCase(),l=Date.now()-eh,c=this.environments.filter(f=>f.projectId===n.id).map(f=>f.name),u=this.fixedEnvironmentName(s.environmentId),p=[];for(let f of i){let b=await this.jiraOf(n).getIssue(f.key);if(!(s.requireStatus&&b.status.toLowerCase()!==s.requireStatus.toLowerCase()))for(let v of b.comments){if(!v.body.toLowerCase().includes(o)||St(v.body)||new Date(v.created).getTime()<l||!v.id)continue;let w=s.envSelection==="fixed"?u:jb(v.body,r.keyword,c);p.push({issueKey:f.key,summary:f.summary,environmentName:w,requestedByAccountId:v.authorAccountId??void 0,requestedByDisplayName:v.author,dedupKey:`deploy:comment:${v.id}`,fingerprint:`comment "${r.keyword}" by ${v.author} at ${v.created}`+(w?` \u2192 ${w}`:"")})}}return p}async matchStatusDeploys(e,n){let r=e.trigger,s=e.action;if(r.type!=="status_changed"||s.type!=="deploy")return[];let i=await this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND status = "${r.status}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=this.fixedEnvironmentName(s.environmentId),l=[];for(let c of i){let u=await this.jiraOf(n).lastEnteredStatus(c.key,r.status);u&&l.push({issueKey:c.key,summary:c.summary,environmentName:o,requestedByAccountId:u.authorAccountId??void 0,requestedByDisplayName:u.author,dedupKey:`deploy:status:${e.id}:${c.key}:${u.at}`,fingerprint:`moved to "${r.status}" by ${u.author} at ${u.at}`})}return l}fixedEnvironmentName(e){return e?this.environments.find(n=>n.id===e)?.name??"":""}async matchLabelTrigger(e,n){let r=e.trigger;if(r.type!=="label_added")return[];let s=`project = "${n.jiraProjectKey}" AND labels = "${r.label}" AND labels not in ("${r.doneLabel}", "${r.failedLabel}", "${vn.NEEDS_INPUT_LABEL}") ORDER BY updated ASC`;return(await this.jiraOf(n).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,n){let r=e.trigger;if(r.type!=="comment_keyword")return[];let s=`project = "${n.jiraProjectKey}" AND updated >= "-2d" AND (labels IS EMPTY OR labels not in ("${r.doneLabel}", "${r.failedLabel}", "${vn.NEEDS_INPUT_LABEL}")) ORDER BY updated DESC`,i=await this.jiraOf(n).search(s,10),o=r.keyword.toLowerCase(),l=[];for(let c of i){let p=[...(await this.jiraOf(n).getIssue(c.key)).comments].reverse().find(f=>f.body.toLowerCase().includes(o)&&!St(f.body));p&&l.push({issueKey:c.key,components:c.components,summary:c.summary,fingerprint:`comment keyword "${r.keyword}" by ${p.author} at ${p.created}`,triggeredByAccountId:p.authorAccountId??void 0})}return l}async diagnoseRule(e,n){let r=e.trigger;if(e.action.type==="deploy"){let c=r.type==="status_changed"?await this.matchStatusDeploys(e,n):await this.matchCommentDeploys(e,n),u=c.filter(p=>p.environmentName);return{matchedCount:u.length,excludedCount:c.length-u.length,excludedSample:c.filter(p=>!p.environmentName).slice(0,5).map(p=>p.issueKey)}}if(r.type==="status_changed")return{matchedCount:(await this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND status = "${r.status}"`,50)).length,excludedCount:0,excludedSample:[]};if(r.type==="label_added"){let[c,u]=await Promise.all([this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND labels = "${r.label}" AND labels not in ("${r.doneLabel}", "${r.failedLabel}")`,50),this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND labels = "${r.label}" AND labels in ("${r.doneLabel}", "${r.failedLabel}")`,50)]);return{matchedCount:c.length,excludedCount:u.length,excludedSample:u.slice(0,5).map(p=>p.key)}}let s=r.keyword.toLowerCase(),[i,o]=await Promise.all([this.matchCommentTrigger(e,n),this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND updated >= "-2d" AND labels in ("${r.doneLabel}", "${r.failedLabel}")`,50)]),l=[];for(let c of o)(await this.jiraOf(n).getIssue(c.key)).comments.some(p=>p.body.toLowerCase().includes(s))&&l.push(c.key);return{matchedCount:i.length,excludedCount:l.length,excludedSample:l.slice(0,5)}}enqueueForRepo(e,n){this.enqueue(this.repoQueues,e,n)}runOnRepoQueue(e,n){this.enqueue(this.repoQueues,e,n)}runOnEnvironmentQueue(e,n){this.enqueue(this.envQueues,e,n)}enqueue(e,n,r){let i=(e.get(n)??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(n,i)}};function jb(t,e,n){let r=t.toLowerCase().indexOf(e.toLowerCase());if(r<0)return"";let i=t.slice(r+e.length).split(/[^\w.-]+/).filter(Boolean);for(let o of i){let l=n.find(c=>c.toLowerCase()===o.toLowerCase());if(l)return l}for(let o of i)if(!Nb.has(o.toLowerCase()))return o;return""}var th=R(require("node:fs"),1),nh=R(require("node:path"),1),ul=require("node:crypto");_t();var Ob=`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.
902
951
 
903
952
  Rules:
904
953
  - Edit ONLY the conflicted files listed below. Do not touch anything else, do not refactor, do not "improve" surrounding code.
@@ -907,10 +956,10 @@ Rules:
907
956
  - When you are done, every listed file must contain no conflict markers and must be syntactically valid.
908
957
 
909
958
  Conflicted files:
910
- `;async function Zd(t){let{cfg:e,repoPath:n,branch:r,baseBranch:s,issueKey:i,onLog:o}=t,l=Gd.default.join(Lt(),`conflict-${(0,Qa.randomUUID)().slice(0,8)}`),c=!1;try{o("info",`Preparing a worktree for ${r} to merge ${s} into it`),await Is(n,l,r),c=!0;let u=await aa(l,s);if(u.ok&&u.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(!u.ok&&u.conflicts===null)return{ok:!1,note:`The merge could not even be started: ${u.reason}`};let p={},f=!1;if(!u.ok){let _=u.conflicts;o("info",`git merged everything except ${_.length} file(s): ${_.slice(0,20).join(", ")}`+(_.length>20?", \u2026":""));let x=Be(t.agentId);if(!x)return await hn(l),{ok:!1,note:`no adapter for agent "${t.agentId}" on this runner`};let $=pn(t.agentId,"edit_no_shell");if($)return await hn(l),{ok:!1,note:`${$} Resolve the conflicts yourself on branch ${r}, or use Rebuild on current base.`};o("info",`Asking ${x.displayName} to resolve only those files`);let j=-1,S=setInterval(()=>{ca(l,_).then(M=>{let W=_.filter(d=>!M.includes(d));W.length!==j&&(j=W.length,o("info",`Conflict progress: ${W.length}/${_.length} resolved`+(W.length?` \xB7 clean: ${W.join(", ")}`:"")+(M.length?` \xB7 still conflicted: ${M.join(", ")}`:"")))}).catch(()=>{})},12e3),G=await Os(x,{repoPath:l,prompt:pb+_.map(M=>`- ${M}`).join(`
911
- `),timeoutSeconds:t.timeoutSeconds,bin:Ue(e,t.agentId),configDir:t.configDir,mode:"edit_no_shell",sessionId:(0,Qa.randomUUID)(),onLog:(M,W)=>o(M,W)},(M,W)=>o(M==="warn"?"warn":M,W));if(clearInterval(S),p={costUsd:G.costUsd,inputTokens:G.inputTokens,outputTokens:G.outputTokens},!G.ok)return await hn(l),{ok:!1,...p,note:`The agent could not do the resolution: ${G.error??"it produced no output"}. Nothing was changed - the merge was rolled back. Fix that first, then Resolve again.`};f=!0;let O=await Ci(l);if(O.length)return await hn(l),{ok:!1,...p,note:`The agent left conflict markers in ${O.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 la(l,`${i}: merge ${s}, conflicts resolved by the agent
959
+ `;async function rh(t){let{cfg:e,repoPath:n,branch:r,baseBranch:s,issueKey:i,onLog:o}=t,l=nh.default.join(Ft(),`conflict-${(0,ul.randomUUID)().slice(0,8)}`),c=!1;try{o("info",`Preparing a worktree for ${r} to merge ${s} into it`),await Os(n,l,r),c=!0;let u=await ba(l,s);if(u.ok&&u.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(!u.ok&&u.conflicts===null)return{ok:!1,note:`The merge could not even be started: ${u.reason}`};let p={},f=!1;if(!u.ok){let w=u.conflicts;o("info",`git merged everything except ${w.length} file(s): ${w.slice(0,20).join(", ")}`+(w.length>20?", \u2026":""));let x=Ke(t.agentId);if(!x)return await yn(l),{ok:!1,note:`no adapter for agent "${t.agentId}" on this runner`};let $=bn(t.agentId,"edit_no_shell");if($)return await yn(l),{ok:!1,note:`${$} Resolve the conflicts yourself on branch ${r}, or use Rebuild on current base.`};o("info",`Asking ${x.displayName} to resolve only those files`);let N=-1,S=setInterval(()=>{wa(l,w).then(M=>{let W=w.filter(d=>!M.includes(d));W.length!==N&&(N=W.length,o("info",`Conflict progress: ${W.length}/${w.length} resolved`+(W.length?` \xB7 clean: ${W.join(", ")}`:"")+(M.length?` \xB7 still conflicted: ${M.join(", ")}`:"")))}).catch(()=>{})},12e3),G=await Fs(x,{repoPath:l,prompt:Ob+w.map(M=>`- ${M}`).join(`
960
+ `),timeoutSeconds:t.timeoutSeconds,bin:qe(e,t.agentId),configDir:t.configDir,mode:"edit_no_shell",sessionId:(0,ul.randomUUID)(),onLog:(M,W)=>o(M,W)},(M,W)=>o(M==="warn"?"warn":M,W));if(clearInterval(S),p={costUsd:G.costUsd,inputTokens:G.inputTokens,outputTokens:G.outputTokens},!G.ok)return await yn(l),{ok:!1,...p,note:`The agent could not do the resolution: ${G.error??"it produced no output"}. Nothing was changed - the merge was rolled back. Fix that first, then Resolve again.`};f=!0;let O=await zi(l);if(O.length)return await yn(l),{ok:!1,...p,note:`The agent left conflict markers in ${O.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 va(l,`${i}: merge ${s}, conflicts resolved by the agent
912
961
 
913
- Resolved via Allwright`)}let b=await dn(l,s);if(!b.ok){let _=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 ${ln}/${cn})`;return await hn(l),{ok:!1,...p,note:`Nothing was pushed: ${_}. The merge was rolled back.`}}await nr(l,r);let v=await nt(l);return o("info",`Pushed the merge to ${r} (${v.slice(0,7)})`),{ok:!0,...p,freeOfCharge:!f,headSha:v,note:f?`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(u){return await hn(l).catch(()=>{}),{ok:!1,note:`Could not resolve the conflict: ${u instanceof Error?u.message.slice(0,300):String(u)}`}}finally{c&&(await vt(n,l).catch(()=>{}),Hd.default.rmSync(l,{recursive:!0,force:!0}))}}var el=R(require("node:fs"),1),Vd=R(require("node:path"),1),tl=require("node:crypto");wt();function fb(t,e){let n=e.map(r=>`$ ${r.command} (exit ${r.exitCode})
962
+ Resolved via Allwright`)}let b=await gn(l,s);if(!b.ok){let w=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 ${pn}/${fn})`;return await yn(l),{ok:!1,...p,note:`Nothing was pushed: ${w}. The merge was rolled back.`}}await lr(l,r);let v=await st(l);return o("info",`Pushed the merge to ${r} (${v.slice(0,7)})`),{ok:!0,...p,freeOfCharge:!f,headSha:v,note:f?`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(u){return await yn(l).catch(()=>{}),{ok:!1,note:`Could not resolve the conflict: ${u instanceof Error?u.message.slice(0,300):String(u)}`}}finally{c&&(await kt(n,l).catch(()=>{}),th.default.rmSync(l,{recursive:!0,force:!0}))}}var dl=R(require("node:fs"),1),sh=R(require("node:path"),1),hl=require("node:crypto");_t();function Mb(t,e){let n=e.map(r=>`$ ${r.command} (exit ${r.exitCode})
914
963
  ${r.tail.slice(-2e3)}`).join(`
915
964
 
916
965
  `);return`You are on the pull-request branch for ticket ${t}. 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:
@@ -923,17 +972,17 @@ Your ONLY job is to make these commands pass, with the smallest change possible.
923
972
  - 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.
924
973
  - Do not ask questions; if you cannot fix something safely, say what you found and stop.
925
974
  - You have no shell; the runner re-runs every documented command after you finish.
926
- End with one short paragraph stating exactly what you changed, or why you changed nothing.`}async function Wd(t){let{cfg:e,repoPath:n,branch:r,baseBranch:s,issueKey:i,failedTests:o,onLog:l}=t,c=Vd.default.join(Lt(),`testfix-${(0,tl.randomUUID)().slice(0,8)}`),u=!1;try{let p=Be(t.agentId);if(!p)return{ok:!1,note:`no adapter for agent "${t.agentId}" on this runner`};let f=pn(t.agentId,"edit_no_shell");if(f)return{ok:!1,note:f};l("info",`Preparing a worktree on ${r} for the test fix`),await un(n,r),await Is(n,c,r),u=!0,await Jr(c,`origin/${r}`);let b=await nt(c);l("info",`Asking ${p.displayName} to fix ${o.length} failing test command(s) - narrow prompt, failure output included, no re-exploration`);let v=await Os(p,{repoPath:c,prompt:fb(i,o),timeoutSeconds:t.timeoutSeconds,bin:Ue(e,t.agentId),configDir:t.configDir,mode:"edit_no_shell",maxTurns:60,sessionId:(0,tl.randomUUID)(),onLog:(d,m)=>l(d,m)},(d,m)=>l(d==="warn"?"warn":d,m)),_={costUsd:v.costUsd,inputTokens:v.inputTokens,outputTokens:v.outputTokens};if(!v.ok)return{ok:!1,..._,note:`The fix agent could not run: ${v.error??"it produced no output"}. Nothing was changed or pushed.`};let x=await Yr(c);for(let d of x.refused)l("warn",`${Dt} entry refused: ${d}`);let $=!0;try{await tr(c,`${i}: fix failing TEST.md commands
975
+ End with one short paragraph stating exactly what you changed, or why you changed nothing.`}async function ih(t){let{cfg:e,repoPath:n,branch:r,baseBranch:s,issueKey:i,failedTests:o,onLog:l}=t,c=sh.default.join(Ft(),`testfix-${(0,hl.randomUUID)().slice(0,8)}`),u=!1;try{let p=Ke(t.agentId);if(!p)return{ok:!1,note:`no adapter for agent "${t.agentId}" on this runner`};let f=bn(t.agentId,"edit_no_shell");if(f)return{ok:!1,note:f};l("info",`Preparing a worktree on ${r} for the test fix`),await mn(n,r),await Os(n,c,r),u=!0,await rs(c,`origin/${r}`);let b=await st(c);l("info",`Asking ${p.displayName} to fix ${o.length} failing test command(s) - narrow prompt, failure output included, no re-exploration`);let v=await Fs(p,{repoPath:c,prompt:Mb(i,o),timeoutSeconds:t.timeoutSeconds,bin:qe(e,t.agentId),configDir:t.configDir,mode:"edit_no_shell",maxTurns:60,sessionId:(0,hl.randomUUID)(),onLog:(d,m)=>l(d,m)},(d,m)=>l(d==="warn"?"warn":d,m)),w={costUsd:v.costUsd,inputTokens:v.inputTokens,outputTokens:v.outputTokens};if(!v.ok)return{ok:!1,...w,note:`The fix agent could not run: ${v.error??"it produced no output"}. Nothing was changed or pushed.`};let x=await ns(c);for(let d of x.refused)l("warn",`${qt} entry refused: ${d}`);let $=!0;try{await ar(c,`${i}: fix failing TEST.md commands
927
976
 
928
- Allwright test-fix run`)}catch{$=!1}if(!$){let d=`The agent changed nothing - its own conclusion: ${v.resultText.trim().slice(0,400)||"(no explanation given)"}`;return l("info",d),{ok:!0,..._,remaining:o,note:d}}let j=await dn(c,s);if(!j.ok){await Jr(c,b);let d=j.forbidden.length?`the fixed result touches protected paths (${j.forbidden.slice(0,5).join(", ")})`:`the fixed result is too large (${j.files} files, ${j.insertions+j.deletions} lines; limits ${ln}/${cn})`;return{ok:!1,..._,note:`Nothing was pushed: ${d}. The fix commit was discarded; the PR is unchanged.`}}let S=o,G,O,M=es(c);if(M){let d=ts(el.default.readFileSync(M,"utf8"));if(d.length){l("info",`Re-running ${d.length} documented test command(s)`);let m=await or(c,d,{perCommandTimeoutMs:15*6e4});for(let g of m)l(g.exitCode===0?"info":"warn",`${g.exitCode===0?"PASS":"FAIL"} ${g.command} (exit ${g.exitCode})`+(g.exitCode===0?"":`
929
- ${g.tail.slice(-1500)}`));S=m.filter(g=>g.exitCode!==0).slice(0,20).map(g=>({command:g.command.slice(0,500),exitCode:g.exitCode,tail:g.tail.slice(-4e3)})),O=m.length,G=m.length-S.length}}await nr(c,r);let W=await nt(c);return l("info",`Pushed the fix to ${r} (${W.slice(0,7)})`),{ok:!0,..._,headSha:W,remaining:S,testsPassed:G,testsTotal:O,note:S.length?`The fix was pushed, but ${S.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(p){return{ok:!1,note:`Could not fix the tests: ${p instanceof Error?p.message.slice(0,300):String(p)}`}}finally{u&&(await vt(n,c).catch(()=>{}),el.default.rmSync(c,{recursive:!0,force:!0}))}}ut();var vr=R(require("node:fs"),1),Jd=R(require("node:path"),1);var mb=w.object({role:w.enum(["user","agent"]),text:w.string(),steps:w.array(w.string()).default([]),files:w.array(w.string()).default([])}),gb=w.object({sessionId:w.string(),projectId:w.string(),title:w.string().default(""),updatedAt:w.string(),messages:w.array(mb).default([])}),yb=w.record(gb),bb=10,vb=200,Yd=2e4,wb=30,kb=2e3,_b=8,Sb=255;function Xd(){return Jd.default.join(ie(),"chat-sessions.json")}function nl(){let t=Xd();if(!vr.default.existsSync(t))return{};try{return yb.parse(JSON.parse(vr.default.readFileSync(t,"utf8")))}catch{return{}}}function Tb(t){vr.default.mkdirSync(ie(),{recursive:!0,mode:448});let e=Xd(),n=e+".tmp";vr.default.writeFileSync(n,JSON.stringify(t,null,2)+`
930
- `,{mode:384}),vr.default.renameSync(n,e),vr.default.chmodSync(e,384)}function Qd(t,e,n,r,s=[],i=[]){let o=nl(),c=o[e]??{sessionId:e,projectId:t,title:n.slice(0,80),updatedAt:new Date().toISOString(),messages:[]};c.messages.push({role:"user",text:n.slice(0,Yd),steps:[],files:i.slice(0,_b).map(p=>p.slice(0,Sb))},{role:"agent",text:r.slice(0,Yd),steps:s.slice(0,wb).map(p=>p.slice(0,kb)),files:[]}),c.messages=c.messages.slice(-vb),c.updatedAt=new Date().toISOString(),o[e]=c;let u=Object.values(o).filter(p=>p.projectId===c.projectId).sort((p,f)=>f.updatedAt.localeCompare(p.updatedAt));for(let p of u.slice(bb))delete o[p.sessionId];Tb(o)}function eh(t){return Object.values(nl()).filter(e=>e.projectId===t).sort((e,n)=>n.updatedAt.localeCompare(e.updatedAt)).map(e=>({sessionId:e.sessionId,title:e.title,updatedAt:e.updatedAt,messageCount:e.messages.length}))}function Us(t){return nl()[t]??null}var th=36,nh=60;function rh(t){let e=t.toLowerCase();return e?e.includes("[1m]")||e.includes("-1m")?1e6:e.includes("haiku")||e.includes("sonnet")||e.includes("opus")||e.includes("fable")?2e5:0:0}var xb=`This conversation is being COMPACTED: it continues in a fresh window that will only have your summary, so anything you leave out is gone. Summarize it now under these headings, in under 500 words total:
977
+ Allwright test-fix run`)}catch{$=!1}if(!$){let d=`The agent changed nothing - its own conclusion: ${v.resultText.trim().slice(0,400)||"(no explanation given)"}`;return l("info",d),{ok:!0,...w,remaining:o,note:d}}let N=await gn(c,s);if(!N.ok){await rs(c,b);let d=N.forbidden.length?`the fixed result touches protected paths (${N.forbidden.slice(0,5).join(", ")})`:`the fixed result is too large (${N.files} files, ${N.insertions+N.deletions} lines; limits ${pn}/${fn})`;return{ok:!1,...w,note:`Nothing was pushed: ${d}. The fix commit was discarded; the PR is unchanged.`}}let S=o,G,O,M=os(c);if(M){let d=as(dl.default.readFileSync(M,"utf8"));if(d.length){l("info",`Re-running ${d.length} documented test command(s)`);let m=await hr(c,d,{perCommandTimeoutMs:15*6e4});for(let g of m)l(g.exitCode===0?"info":"warn",`${g.exitCode===0?"PASS":"FAIL"} ${g.command} (exit ${g.exitCode})`+(g.exitCode===0?"":`
978
+ ${g.tail.slice(-1500)}`));S=m.filter(g=>g.exitCode!==0).slice(0,20).map(g=>({command:g.command.slice(0,500),exitCode:g.exitCode,tail:g.tail.slice(-4e3)})),O=m.length,G=m.length-S.length}}await lr(c,r);let W=await st(c);return l("info",`Pushed the fix to ${r} (${W.slice(0,7)})`),{ok:!0,...w,headSha:W,remaining:S,testsPassed:G,testsTotal:O,note:S.length?`The fix was pushed, but ${S.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(p){return{ok:!1,note:`Could not fix the tests: ${p instanceof Error?p.message.slice(0,300):String(p)}`}}finally{u&&(await kt(n,c).catch(()=>{}),dl.default.rmSync(c,{recursive:!0,force:!0}))}}ht();var xr=R(require("node:fs"),1),ah=R(require("node:path"),1);var zb=k.object({role:k.enum(["user","agent"]),text:k.string(),steps:k.array(k.string()).default([]),files:k.array(k.string()).default([])}),Db=k.object({sessionId:k.string(),projectId:k.string(),title:k.string().default(""),updatedAt:k.string(),messages:k.array(zb).default([])}),Lb=k.record(Db),Ub=10,qb=200,oh=2e4,Fb=30,Bb=2e3,Kb=8,Hb=255;function lh(){return ah.default.join(ie(),"chat-sessions.json")}function pl(){let t=lh();if(!xr.default.existsSync(t))return{};try{return Lb.parse(JSON.parse(xr.default.readFileSync(t,"utf8")))}catch{return{}}}function Gb(t){xr.default.mkdirSync(ie(),{recursive:!0,mode:448});let e=lh(),n=e+".tmp";xr.default.writeFileSync(n,JSON.stringify(t,null,2)+`
979
+ `,{mode:384}),xr.default.renameSync(n,e),xr.default.chmodSync(e,384)}function ch(t,e,n,r,s=[],i=[]){let o=pl(),c=o[e]??{sessionId:e,projectId:t,title:n.slice(0,80),updatedAt:new Date().toISOString(),messages:[]};c.messages.push({role:"user",text:n.slice(0,oh),steps:[],files:i.slice(0,Kb).map(p=>p.slice(0,Hb))},{role:"agent",text:r.slice(0,oh),steps:s.slice(0,Fb).map(p=>p.slice(0,Bb)),files:[]}),c.messages=c.messages.slice(-qb),c.updatedAt=new Date().toISOString(),o[e]=c;let u=Object.values(o).filter(p=>p.projectId===c.projectId).sort((p,f)=>f.updatedAt.localeCompare(p.updatedAt));for(let p of u.slice(Ub))delete o[p.sessionId];Gb(o)}function uh(t){return Object.values(pl()).filter(e=>e.projectId===t).sort((e,n)=>n.updatedAt.localeCompare(e.updatedAt)).map(e=>({sessionId:e.sessionId,title:e.title,updatedAt:e.updatedAt,messageCount:e.messages.length}))}function Zs(t){return pl()[t]??null}Kt();var dh=36,hh=60;function ph(t){let e=t.toLowerCase();return e?e.includes("[1m]")||e.includes("-1m")?1e6:e.includes("haiku")||e.includes("sonnet")||e.includes("opus")||e.includes("fable")?2e5:0:0}var Zb=`This conversation is being COMPACTED: it continues in a fresh window that will only have your summary, so anything you leave out is gone. Summarize it now under these headings, in under 500 words total:
931
980
  Goal: what the user is trying to achieve.
932
981
  Decided: choices already made, including ones you talked them out of - each as one line.
933
982
  Constraints: rules, preferences and corrections the user gave you.
934
983
  Repo facts: what you learned about this codebase that is worth not re-reading.
935
984
  Open: what is still unresolved right now.
936
- Write plain statements, no preamble, no closing offer of help. Do NOT emit a ticket block.`;async function sh(t,e,n){if(!Us(e))return null;let s=Ke(n,t.project,"chat");if("error"in s)return null;try{let i=await s.adapter.run({repoPath:t.repoPath,prompt:xb,timeoutSeconds:60,bin:s.bin,mode:"read_only",maxTurns:3,model:s.adapter.fastModel,sessionId:e,resume:!0,onLog:()=>{}}),o=i.ok?i.resultText.trim():"";return o?o.slice(0,6e3):null}catch(i){return y.warn(`chat compaction failed: ${i instanceof Error?i.message:i}`),null}}var ih=`
985
+ Write plain statements, no preamble, no closing offer of help. Do NOT emit a ticket block.`;async function fh(t,e,n){if(!Zs(e))return null;let s=He(n,t.project,"chat");if("error"in s)return null;try{let i=await s.adapter.run({repoPath:t.repoPath,prompt:Zb,timeoutSeconds:60,bin:s.bin,mode:"read_only",maxTurns:3,model:s.adapter.fastModel,sessionId:e,resume:!0,onLog:()=>{}}),o=i.ok?i.resultText.trim():"";return o?o.slice(0,6e3):null}catch(i){return y.warn(`chat compaction failed: ${i instanceof Error?i.message:i}`),null}}var mh=`
937
986
 
938
987
  TWO OPTIONAL BLOCKS, for the dashboard's benefit. Never mention them in your prose.
939
988
  1. When you ASK the user something and the sensible answers are countable, end with:
@@ -946,11 +995,11 @@ TWO OPTIONAL BLOCKS, for the dashboard's benefit. Never mention them in your pro
946
995
  ["\u2026", "\u2026"]
947
996
  \`\`\`
948
997
  1 to 3 short suggestions, written AS THE USER (first person, imperative) - they are typed into the user's box, not yours. Skip the block entirely when nothing obvious follows; a wrong guess costs the user more than no guess.
949
- Never emit both blocks in one reply, and never let either replace the actual answer.`;var wr=R(require("node:fs"),1),rt=R(require("node:path"),1),rl=300,Eb=4,oh=512*1024,Rb=new Set([".git","node_modules","dist","build","out",".next","vendor","coverage",".venv","venv","__pycache__",".turbo",".cache"]),ah=/\.mdx?$/i;function lh(t){let e=rt.default.resolve(t),n=[],r=(s,i)=>{if(i>Eb||n.length>=rl)return;let o;try{o=wr.default.readdirSync(s,{withFileTypes:!0})}catch{return}for(let l of o){if(n.length>=rl)return;if(!l.isFile()||!ah.test(l.name))continue;let c=rt.default.join(s,l.name);try{let u=wr.default.statSync(c);n.push({path:rt.default.relative(e,c).split(rt.default.sep).join("/"),sizeBytes:u.size,updatedAt:u.mtime.toISOString()})}catch{}}for(let l of o){if(n.length>=rl)return;!l.isDirectory()||l.isSymbolicLink()||Rb.has(l.name)||l.name.startsWith(".")||r(rt.default.join(s,l.name),i+1)}};return r(e,0),n}function ch(t,e){let n=rt.default.resolve(t);if(!ah.test(e))return{ok:!1,error:"only markdown files can be opened here"};let r=rt.default.resolve(n,e);if(r!==n&&!r.startsWith(n+rt.default.sep))return{ok:!1,error:"that path is outside the project checkout"};let s;try{s=wr.default.realpathSync(r)}catch{return{ok:!1,error:"file not found in this checkout"}}let i=(()=>{try{return wr.default.realpathSync(n)}catch{return n}})();if(s!==i&&!s.startsWith(i+rt.default.sep))return{ok:!1,error:"that path links outside the project checkout"};let o;try{o=wr.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=wr.default.readFileSync(s,"utf8"),c=Buffer.byteLength(l,"utf8")>oh;return{ok:!0,path:rt.default.relative(i,s).split(rt.default.sep).join("/"),content:c?l.slice(0,oh):l,truncated:c}}catch(l){return{ok:!1,error:l instanceof Error?l.message:"could not read the file"}}}var Ze=R(ke(),1);var eo=R(require("node:fs"),1),uh=R(require("node:path"),1);var Ib=w.object({id:w.string(),name:w.string().default(""),jiraProjectKey:w.string().default(""),repoName:w.string().default(""),jiraSiteUrl:w.string().default("")}),Ab=w.array(Ib);function dh(){return uh.default.join(ie(),"synced-projects.json")}function hh(t){try{let e=t.map(n=>({id:n.id,name:n.name,jiraProjectKey:n.jiraProjectKey,repoName:n.repoName,jiraSiteUrl:n.jiraSiteUrl??""}));eo.default.mkdirSync(ie(),{recursive:!0}),eo.default.writeFileSync(dh(),JSON.stringify(e,null,2),{mode:384})}catch{}}function Cb(){try{let t=Ab.safeParse(JSON.parse(eo.default.readFileSync(dh(),"utf8")));return t.success?t.data:[]}catch{return[]}}function ph(t){return Cb().find(e=>e.repoName===t)??null}var il=R(require("node:fs"),1),kr=R(require("node:path"),1),fh=require("node:child_process"),_r=R(ke(),1);var $b=15e4,sl=(t,e,n,r="")=>({ok:!1,file:t,checks:[e],output:r,error:n});function Pb(t){let e=kr.default.join(t,"node_modules",".bin","prisma");return il.default.existsSync(e)?{bin:e,prefix:[]}:{bin:"npx",prefix:["--yes","prisma"]}}function jb(t,e){if(!(0,_r.isSelfMigrationFilename)(e))return null;let n=kr.default.join(t,_r.SELF_MIGRATION_DIR),r=kr.default.resolve(n,e),s=kr.default.relative(n,r);return s!==e||s.startsWith("..")||kr.default.isAbsolute(s)?null:r}async function mh(t){let{file:e}=t,n=jb(t.repoPath,e);if(!n)return sl(e,{name:"file",ok:!1,detail:`"${e}" is not a migration filename`,fix:[]},`"${e}" is not a migration filename`);if(!il.default.existsSync(n))return sl(e,{name:"file",ok:!1,detail:`${_r.SELF_MIGRATION_DIR}/${e} does not exist in this checkout`,fix:[`cd ${t.repoPath} && git pull`]},`${_r.SELF_MIGRATION_DIR}/${e} is not in this checkout - it may be newer than the code here`);let s=Nt(t.cfg,t.repoName,t.environmentName)[t.urlSecret]?.trim();if(!s)return sl(e,{name:"database url",ok:!1,detail:`no ${t.urlSecret} in this runner's secret store for "${t.repoName}:${t.environmentName}" - the value stays on this machine`,fix:[`allwright env set ${t.repoName} ${t.environmentName} "${t.urlSecret}=postgresql://\u2026"`]},`this runner has no ${t.urlSecret} for "${t.environmentName}"`);let i=kr.default.join(t.repoPath,"apps","api"),{bin:o,prefix:l}=Pb(i),c=Ja([s]),u=await Nb(o,[...l,"db","execute","--url",s,"--file",n],i),p=c(u.output).slice(-8e3);return u.code!==0?{ok:!1,file:e,checks:[{name:"apply",ok:!1,detail:`prisma db execute exited ${u.code}`,fix:[`cd apps/api && npx prisma db execute --url "$DATABASE_URL" --file prisma/manual/${e}`]}],output:p,error:`applying ${e} failed (exit ${u.code})`}:{ok:!0,file:e,checks:[{name:"apply",ok:!0,detail:`${_r.SELF_MIGRATION_DIR}/${e} applied`,fix:[]}],output:p,error:""}}function Nb(t,e,n){return new Promise(r=>{(0,fh.execFile)(t,e,{cwd:n,timeout:$b,maxBuffer:4*1024*1024,encoding:"utf8"},(s,i,o)=>{let l=[i,o].filter(Boolean).join(`
950
- `).trim();if(!s)return r({code:0,output:l});let c=typeof s.code=="number"?s.code:1;r({code:c||1,output:l||s.message})})})}var tw=R(up(),1),nw=R(co(),1),rw=R(us(),1),sw=R(gl(),1),iw=R(vl(),1),ow=R(xl(),1),vp=R(fo(),1),aw=R(bp(),1);var Rl=vp.default;var Vs=R(require("node:crypto"),1),Et=R(ke(),1);function lw(t){let e=t&&typeof t=="object"&&"name"in t?String(t.name):null;return e?`"${e}"`:"(unnamed)"}function Il(t,e,n,r){t.push(`dropped ${e} ${n} - 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 cw(t){if(!t||typeof t!="object"||t.type!=="config")return null;let e=t,n=[],r=[];for(let l of Array.isArray(e.projects)?e.projects:[]){let c=Et.ProjectConfig.safeParse(l);c.success?r.push(c.data):Il(n,"project","",c.error.issues[0]?.message??"invalid shape")}let s=[];for(let l of Array.isArray(e.rules)?e.rules:[]){let c=Et.RuleConfig.safeParse(l);c.success?s.push(c.data):Il(n,"rule",lw(l),c.error.issues[0]?.message??"invalid shape")}let i=[];for(let l of Array.isArray(e.environments)?e.environments:[]){let c=Et.EnvironmentConfig.safeParse(l);c.success?i.push(c.data):Il(n,"environment","",c.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:n}}var uw=2e4,dw=6e4,hw=5e3,go=class{constructor(e,n,r,s){this.wsUrl=e;this.runnerToken=n;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===Rl.OPEN}connect(){if(this.closed)return;y.info(`connecting to control plane at ${this.wsUrl}`);let e=new Rl(this.wsUrl,{headers:{authorization:`Bearer ${this.runnerToken}`}});this.ws=e,e.on("open",()=>{this.backoffMs=1e3,this.sendNow({type:"hello",protocolVersion:Et.PROTOCOL_VERSION,runnerVersion:this.meta.runnerVersion,platform:`${process.platform}/${process.arch} node${process.versions.node}`,justBooted:!this.bootAnnounced});let n=this.queue.splice(0,this.queue.length);for(let r of n)this.sendNow(r);this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=setInterval(()=>{this.send({type:"heartbeat",ts:new Date().toISOString()})},uw)}),e.on("message",n=>{let r;try{r=JSON.parse(n.toString())}catch(i){y.warn(`ignoring malformed server message (bad JSON): ${i}`);return}let s;try{s=(0,Et.parseServerMsg)(r)}catch(i){let o=cw(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",n=>{if(this.heartbeat&&clearInterval(this.heartbeat),n===4001)y.error("control plane rejected this runner version (protocol mismatch). Update with: npm install -g @ticketpilot/runner");else if(n===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 ${n}); reconnecting in ${Math.round(s/1e3)}s`),setTimeout(()=>this.connect(),s),this.backoffMs=Math.min(this.backoffMs*2,dw)}),e.on("error",n=>{y.warn(`websocket error: ${n.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 n=this.pending.get(e.requestId);n&&(clearTimeout(n.timer),this.pending.delete(e.requestId),n.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==="selfmigration.apply")return this.events.onSelfMigrationApply(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.recheck")return this.events.onSetupRecheck(e);if(e.type==="repo.unmap")return this.events.onRepoUnmap(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==="run.answer")return this.events.onRunAnswer(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>=hw){let n=this.queue.findIndex(r=>r.type==="run.log");n>=0?this.queue.splice(n,1):this.queue.shift()}this.queue.push(e)}async claimRun(e){if(!this.connected)return{accepted:!1,reason:"control plane offline"};let n=Vs.default.randomUUID(),r=await new Promise(s=>{let i=setTimeout(()=>{this.pending.delete(n),s(null)},15e3);this.pending.set(n,{resolve:s,timer:i}),this.sendNow({type:"run.claim",requestId:n,...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=Vs.default.randomUUID(),n=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!n||n.type!=="autopilot.next.result"?null:{ok:n.ok,item:n.item,pausedUntil:n.pausedUntil}}sendAutopilotReport(e){this.send({type:"autopilot.report",requestId:Vs.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 n=Vs.default.randomUUID(),r=await new Promise(s=>{let i=setTimeout(()=>{this.pending.delete(n),s(null)},15e3);this.pending.set(n,{resolve:s,timer:i}),this.sendNow({type:"deploy.claim",requestId:n,...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,n){this.send({type:"deploy.suggest.result",requestId:e,...n,docPath:n.docPath??"",docContent:n.docContent??""})}sendChatTurnResult(e,n){this.send({type:"chat.turn.result",requestId:e,...n,inputTokens:n.inputTokens??0,outputTokens:n.outputTokens??0,cacheReadTokens:n.cacheReadTokens??0,costUsd:n.costUsd??0,model:n.model??"",contextTokens:n.contextTokens??0,contextLimit:n.contextLimit??0,compacted:n.compacted??!1,compactedMessages:n.compactedMessages??0})}sendChatCreateTicketResult(e,n){this.send({type:"chat.create.ticket.result",requestId:e,...n,childKeys:n.childKeys??[]})}sendChatListResult(e,n){this.send({type:"chat.list.result",requestId:e,sessions:n})}sendRepoDocsResult(e,n){this.send({type:"repo.docs.result",requestId:e,...n})}sendRepoDocReadResult(e,n){this.send({type:"repo.doc.read.result",requestId:e,...n})}sendChatLoadResult(e,n){this.send({type:"chat.load.result",requestId:e,...n,messages:n.messages.map(r=>({...r,steps:r.steps??[],files:r.files??[]}))})}sendBoardFetchResult(e,n){this.send({type:"board.fetch.result",requestId:e,...n,browseBaseUrl:n.browseBaseUrl??""})}sendAuditStartResult(e,n){this.send({type:"audit.start.result",requestId:e,...n})}sendAuditListResult(e,n){this.send({type:"audit.list.result",requestId:e,ok:n.ok,error:n.error,audits:(n.audits??[]).map(r=>({...r,detailLevel:r.detailLevel??"technical"}))})}sendAuditGetResult(e,n){this.send({type:"audit.get.result",requestId:e,...n})}sendAuditReviewResult(e,n){this.send({type:"audit.review.result",requestId:e,...n})}sendKnowledgeListResult(e,n){this.send({type:"knowledge.list.result",requestId:e,ok:n.ok,error:n.error,files:n.files??[]})}sendKnowledgeSaveResult(e,n){this.send({type:"knowledge.save.result",requestId:e,...n})}sendEpicListResult(e,n){this.send({type:"epic.list.result",requestId:e,ok:n.ok,error:n.error,epics:n.epics??[],children:n.children??[]})}sendEpicSuggestResult(e,n){this.send({type:"epic.suggest.result",requestId:e,ok:n.ok,error:n.error,issueKey:n.issueKey??"",reason:n.reason??"",considered:n.considered??0})}sendTeamCredsResult(e,n){this.send({type:"team.creds.result",requestId:e,ok:n.ok,error:n.error,githubShared:n.githubShared??!1,sharedGithubLogin:n.sharedGithubLogin??"",entries:n.entries??[]})}sendBoardTriggerResult(e,n){this.send({type:"board.trigger.result",requestId:e,...n})}sendAuditStatsResult(e,n){this.send({type:"audit.stats.result",requestId:e,ok:n.ok,error:n.error,byProject:n.byProject??{}})}sendRunnerUpdateResult(e,n){this.send({type:"runner.update.result",requestId:e,ok:n.ok,error:n.error,note:n.note??"",scheduled:n.scheduled??!1})}sendSetupClaudeMdGenerateResult(e,n){this.send({type:"setup.claudemd.generate.result",requestId:e,ok:n.ok,error:n.error,content:n.content??""})}sendRepoUnmapResult(e,n){this.send({type:"repo.unmap.result",requestId:e,ok:n.ok,error:n.error??"",removedPath:n.removedPath??""})}sendSetupRecheckResult(e,n){this.send({type:"setup.recheck.result",requestId:e,ok:n.ok,error:n.error??"",checks:(n.checks??[]).map(r=>({environment:r.environment??"",question:r.question,ok:r.ok,detail:r.detail??"",blocking:r.blocking??!0}))})}sendSetupClaudeMdSaveResult(e,n){this.send({type:"setup.claudemd.save.result",requestId:e,ok:n.ok,error:n.error,note:n.note??""})}sendResolveConflictResult(e,n){this.send({type:"run.resolve.conflict.result",requestId:e,ok:n.ok,note:n.note??"",freeOfCharge:n.freeOfCharge??!1,headSha:n.headSha??"",costUsd:n.costUsd,inputTokens:n.inputTokens,outputTokens:n.outputTokens})}sendTestFixResult(e,n){this.send({type:"run.testfix.result",requestId:e,ok:n.ok,note:n.note??"",headSha:n.headSha??"",remaining:n.remaining??[],costUsd:n.costUsd,inputTokens:n.inputTokens,outputTokens:n.outputTokens})}sendRunAnswerResult(e,n){this.send({type:"run.answer.result",requestId:e,ok:n.ok,note:n.note??"",error:n.error})}sendAgentProfilesResult(e,n){this.send({type:"agent.profiles.result",requestId:e,ok:n.ok,error:n.error,profiles:n.profiles??[],defaultLoggedIn:n.defaultLoggedIn??!1,agentsWithoutProfiles:n.agentsWithoutProfiles??[]})}sendRepoDocSaveResult(e,n){this.send({type:"repo.doc.save.result",requestId:e,ok:n.ok,error:n.error,note:n.note??""})}sendSetupStatusResult(e,n){this.send({type:"setup.status.result",requestId:e,ok:n.ok,error:n.error,jiraConfigured:n.jiraConfigured??!1,jiraEmail:n.jiraEmail??"",claude:n.claude,githubTokenSet:n.githubTokenSet??!1,githubLogin:n.githubLogin??"",deploysEnabled:n.deploysEnabled??!1,jiraUserCount:n.jiraUserCount??0,repos:n.repos??[]})}sendEnvPreflightResult(e,n){this.send({type:"env.preflight.result",requestId:e,...n,checks:this.withFixDefaults(n.checks)})}sendSelfMigrationApplyResult(e,n){this.send({type:"selfmigration.apply.result",requestId:e,...n})}sendJiraUsersResult(e,n){this.send({type:"jira.users.result",requestId:e,...n})}withFixDefaults(e){return e.map(n=>({...n,kind:n.kind??"connection",fix:n.fix??[],fixNote:n.fixNote??""}))}sendProjectTestResult(e,n,r){this.send({type:"project.test.result",requestId:e,ok:n,checks:this.withFixDefaults(r)})}sendRuleDiagnoseResult(e,n){this.send({type:"rule.diagnose.result",requestId:e,...n,checks:this.withFixDefaults(n.checks)})}};var yo=R(require("node:fs"),1),gs=R(require("node:path"),1),Al=require("node:child_process"),pw=/\.mdx?$/i,wp=6,fw=/^[\w.\- ()]+$/;function mw(t,e){let n=e.trim().replace(/\\/g,"/").replace(/^\.\//,"");if(!n)return{ok:!1,error:"empty path"};if(gs.default.isAbsolute(n))return{ok:!1,error:"path must be repo-relative"};if(!pw.test(n))return{ok:!1,error:"only markdown files (.md) can be saved"};let r=n.split("/");if(r.length>wp)return{ok:!1,error:`path deeper than ${wp} levels`};for(let o of r)if(o==="."||o===".."||!fw.test(o))return{ok:!1,error:`invalid path segment "${o}"`};if(r[0]===".git")return{ok:!1,error:"cannot write under .git"};let s=gs.default.resolve(t),i=gs.default.resolve(s,n);return i!==s&&!i.startsWith(s+gs.default.sep)?{ok:!1,error:"path escapes the checkout"}:{ok:!0,abs:i,rel:n}}async function Cl(t){let e=mw(t.repoPath,t.relPath);if(!e.ok)return{ok:!1,error:e.error};if(yo.default.existsSync(e.abs)&&!t.overwrite)return{ok:!1,error:`${e.rel} already exists in this checkout`};yo.default.mkdirSync(gs.default.dirname(e.abs),{recursive:!0}),yo.default.writeFileSync(e.abs,t.content.endsWith(`
998
+ Never emit both blocks in one reply, and never let either replace the actual answer.`;var Er=R(require("node:fs"),1),it=R(require("node:path"),1),fl=300,Vb=4,gh=512*1024,Wb=new Set([".git","node_modules","dist","build","out",".next","vendor","coverage",".venv","venv","__pycache__",".turbo",".cache"]),yh=/\.mdx?$/i;function bh(t){let e=it.default.resolve(t),n=[],r=(s,i)=>{if(i>Vb||n.length>=fl)return;let o;try{o=Er.default.readdirSync(s,{withFileTypes:!0})}catch{return}for(let l of o){if(n.length>=fl)return;if(!l.isFile()||!yh.test(l.name))continue;let c=it.default.join(s,l.name);try{let u=Er.default.statSync(c);n.push({path:it.default.relative(e,c).split(it.default.sep).join("/"),sizeBytes:u.size,updatedAt:u.mtime.toISOString()})}catch{}}for(let l of o){if(n.length>=fl)return;!l.isDirectory()||l.isSymbolicLink()||Wb.has(l.name)||l.name.startsWith(".")||r(it.default.join(s,l.name),i+1)}};return r(e,0),n}function vh(t,e){let n=it.default.resolve(t);if(!yh.test(e))return{ok:!1,error:"only markdown files can be opened here"};let r=it.default.resolve(n,e);if(r!==n&&!r.startsWith(n+it.default.sep))return{ok:!1,error:"that path is outside the project checkout"};let s;try{s=Er.default.realpathSync(r)}catch{return{ok:!1,error:"file not found in this checkout"}}let i=(()=>{try{return Er.default.realpathSync(n)}catch{return n}})();if(s!==i&&!s.startsWith(i+it.default.sep))return{ok:!1,error:"that path links outside the project checkout"};let o;try{o=Er.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=Er.default.readFileSync(s,"utf8"),c=Buffer.byteLength(l,"utf8")>gh;return{ok:!0,path:it.default.relative(i,s).split(it.default.sep).join("/"),content:c?l.slice(0,gh):l,truncated:c}}catch(l){return{ok:!1,error:l instanceof Error?l.message:"could not read the file"}}}var We=R(_e(),1);var co=R(require("node:fs"),1),wh=R(require("node:path"),1);var Yb=k.object({id:k.string(),name:k.string().default(""),jiraProjectKey:k.string().default(""),repoName:k.string().default(""),jiraSiteUrl:k.string().default("")}),Jb=k.array(Yb);function kh(){return wh.default.join(ie(),"synced-projects.json")}function _h(t){try{let e=t.map(n=>({id:n.id,name:n.name,jiraProjectKey:n.jiraProjectKey,repoName:n.repoName,jiraSiteUrl:n.jiraSiteUrl??""}));co.default.mkdirSync(ie(),{recursive:!0}),co.default.writeFileSync(kh(),JSON.stringify(e,null,2),{mode:384})}catch{}}function Xb(){try{let t=Jb.safeParse(JSON.parse(co.default.readFileSync(kh(),"utf8")));return t.success?t.data:[]}catch{return[]}}function Sh(t){return Xb().find(e=>e.repoName===t)??null}var gl=R(require("node:fs"),1),Rr=R(require("node:path"),1),Th=require("node:child_process"),Ir=R(_e(),1);var Qb=15e4,ml=(t,e,n,r="")=>({ok:!1,file:t,checks:[e],output:r,error:n});function ev(t){let e=Rr.default.join(t,"node_modules",".bin","prisma");return gl.default.existsSync(e)?{bin:e,prefix:[]}:{bin:"npx",prefix:["--yes","prisma"]}}function tv(t,e){if(!(0,Ir.isSelfMigrationFilename)(e))return null;let n=Rr.default.join(t,Ir.SELF_MIGRATION_DIR),r=Rr.default.resolve(n,e),s=Rr.default.relative(n,r);return s!==e||s.startsWith("..")||Rr.default.isAbsolute(s)?null:r}async function xh(t){let{file:e}=t,n=tv(t.repoPath,e);if(!n)return ml(e,{name:"file",ok:!1,detail:`"${e}" is not a migration filename`,fix:[]},`"${e}" is not a migration filename`);if(!gl.default.existsSync(n))return ml(e,{name:"file",ok:!1,detail:`${Ir.SELF_MIGRATION_DIR}/${e} does not exist in this checkout`,fix:[`cd ${t.repoPath} && git pull`]},`${Ir.SELF_MIGRATION_DIR}/${e} is not in this checkout - it may be newer than the code here`);let s=zt(t.cfg,t.repoName,t.environmentName)[t.urlSecret]?.trim();if(!s)return ml(e,{name:"database url",ok:!1,detail:`no ${t.urlSecret} in this runner's secret store for "${t.repoName}:${t.environmentName}" - the value stays on this machine`,fix:[`allwright env set ${t.repoName} ${t.environmentName} "${t.urlSecret}=postgresql://\u2026"`]},`this runner has no ${t.urlSecret} for "${t.environmentName}"`);let i=Rr.default.join(t.repoPath,"apps","api"),{bin:o,prefix:l}=ev(i),c=ll([s]),u=await nv(o,[...l,"db","execute","--url",s,"--file",n],i),p=c(u.output).slice(-8e3);return u.code!==0?{ok:!1,file:e,checks:[{name:"apply",ok:!1,detail:`prisma db execute exited ${u.code}`,fix:[`cd apps/api && npx prisma db execute --url "$DATABASE_URL" --file prisma/manual/${e}`]}],output:p,error:`applying ${e} failed (exit ${u.code})`}:{ok:!0,file:e,checks:[{name:"apply",ok:!0,detail:`${Ir.SELF_MIGRATION_DIR}/${e} applied`,fix:[]}],output:p,error:""}}function nv(t,e,n){return new Promise(r=>{(0,Th.execFile)(t,e,{cwd:n,timeout:Qb,maxBuffer:4*1024*1024,encoding:"utf8"},(s,i,o)=>{let l=[i,o].filter(Boolean).join(`
999
+ `).trim();if(!s)return r({code:0,output:l});let c=typeof s.code=="number"?s.code:1;r({code:c||1,output:l||s.message})})})}var Sw=R(wp(),1),Tw=R(vo(),1),xw=R(gs(),1),Ew=R(Rl(),1),Rw=R(Cl(),1),Iw=R(Ml(),1),Ap=R(So(),1),Aw=R(Ip(),1);var Dl=Ap.default;var ti=R(require("node:crypto"),1),It=R(_e(),1);Kt();function Cw(t){let e=t&&typeof t=="object"&&"name"in t?String(t.name):null;return e?`"${e}"`:"(unnamed)"}function Ll(t,e,n,r){t.push(`dropped ${e} ${n} - 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 $w(t){if(!t||typeof t!="object"||t.type!=="config")return null;let e=t,n=[],r=[];for(let l of Array.isArray(e.projects)?e.projects:[]){let c=It.ProjectConfig.safeParse(l);c.success?r.push(c.data):Ll(n,"project","",c.error.issues[0]?.message??"invalid shape")}let s=[];for(let l of Array.isArray(e.rules)?e.rules:[]){let c=It.RuleConfig.safeParse(l);c.success?s.push(c.data):Ll(n,"rule",Cw(l),c.error.issues[0]?.message??"invalid shape")}let i=[];for(let l of Array.isArray(e.environments)?e.environments:[]){let c=It.EnvironmentConfig.safeParse(l);c.success?i.push(c.data):Ll(n,"environment","",c.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:n}}var Pw=2e4,Nw=6e4,jw=5e3,xo=class{constructor(e,n,r,s){this.wsUrl=e;this.runnerToken=n;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===Dl.OPEN}connect(){if(this.closed)return;y.info(`connecting to control plane at ${this.wsUrl}`);let e=new Dl(this.wsUrl,{headers:{authorization:`Bearer ${this.runnerToken}`}});this.ws=e,e.on("open",()=>{this.backoffMs=1e3,this.sendNow({type:"hello",protocolVersion:It.PROTOCOL_VERSION,runnerVersion:this.meta.runnerVersion,platform:`${process.platform}/${process.arch} node${process.versions.node}`,justBooted:!this.bootAnnounced});let n=this.queue.splice(0,this.queue.length);for(let r of n)this.sendNow(r);this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=setInterval(()=>{this.send({type:"heartbeat",ts:new Date().toISOString()})},Pw)}),e.on("message",n=>{let r;try{r=JSON.parse(n.toString())}catch(i){y.warn(`ignoring malformed server message (bad JSON): ${i}`);return}let s;try{s=(0,It.parseServerMsg)(r)}catch(i){let o=$w(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",n=>{if(this.heartbeat&&clearInterval(this.heartbeat),n===4001)y.error("control plane rejected this runner version (protocol mismatch). Update with: npm install -g @ticketpilot/runner");else if(n===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 ${n}); reconnecting in ${Math.round(s/1e3)}s`),setTimeout(()=>this.connect(),s),this.backoffMs=Math.min(this.backoffMs*2,Nw)}),e.on("error",n=>{y.warn(`websocket error: ${n.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 n=this.pending.get(e.requestId);n&&(clearTimeout(n.timer),this.pending.delete(e.requestId),n.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==="selfmigration.apply")return this.events.onSelfMigrationApply(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.recheck")return this.events.onSetupRecheck(e);if(e.type==="repo.unmap")return this.events.onRepoUnmap(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==="run.answer")return this.events.onRunAnswer(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>=jw){let n=this.queue.findIndex(r=>r.type==="run.log");n>=0?this.queue.splice(n,1):this.queue.shift()}this.queue.push(e)}async claimRun(e){if(!this.connected)return{accepted:!1,reason:"control plane offline"};let n=ti.default.randomUUID(),r=await new Promise(s=>{let i=setTimeout(()=>{this.pending.delete(n),s(null)},15e3);this.pending.set(n,{resolve:s,timer:i}),this.sendNow({type:"run.claim",requestId:n,...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=ti.default.randomUUID(),n=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!n||n.type!=="autopilot.next.result"?null:{ok:n.ok,item:n.item,pausedUntil:n.pausedUntil}}sendAutopilotReport(e){this.send({type:"autopilot.report",requestId:ti.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 n=ti.default.randomUUID(),r=await new Promise(s=>{let i=setTimeout(()=>{this.pending.delete(n),s(null)},15e3);this.pending.set(n,{resolve:s,timer:i}),this.sendNow({type:"deploy.claim",requestId:n,...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,n){this.send({type:"deploy.suggest.result",requestId:e,...n,docPath:n.docPath??"",docContent:n.docContent??""})}sendChatTurnResult(e,n){this.send({type:"chat.turn.result",requestId:e,...n,inputTokens:n.inputTokens??0,outputTokens:n.outputTokens??0,cacheReadTokens:n.cacheReadTokens??0,costUsd:n.costUsd??0,model:n.model??"",contextTokens:n.contextTokens??0,contextLimit:n.contextLimit??0,compacted:n.compacted??!1,compactedMessages:n.compactedMessages??0})}sendChatCreateTicketResult(e,n){this.send({type:"chat.create.ticket.result",requestId:e,...n,childKeys:n.childKeys??[]})}sendChatListResult(e,n){this.send({type:"chat.list.result",requestId:e,sessions:n})}sendRepoDocsResult(e,n){this.send({type:"repo.docs.result",requestId:e,...n})}sendRepoDocReadResult(e,n){this.send({type:"repo.doc.read.result",requestId:e,...n})}sendChatLoadResult(e,n){this.send({type:"chat.load.result",requestId:e,...n,messages:n.messages.map(r=>({...r,steps:r.steps??[],files:r.files??[]}))})}sendBoardFetchResult(e,n){this.send({type:"board.fetch.result",requestId:e,...n,browseBaseUrl:n.browseBaseUrl??""})}sendAuditStartResult(e,n){this.send({type:"audit.start.result",requestId:e,...n})}sendAuditListResult(e,n){this.send({type:"audit.list.result",requestId:e,ok:n.ok,error:n.error,audits:(n.audits??[]).map(r=>({...r,detailLevel:r.detailLevel??"technical"}))})}sendAuditGetResult(e,n){this.send({type:"audit.get.result",requestId:e,...n})}sendAuditReviewResult(e,n){this.send({type:"audit.review.result",requestId:e,...n})}sendKnowledgeListResult(e,n){this.send({type:"knowledge.list.result",requestId:e,ok:n.ok,error:n.error,files:n.files??[]})}sendKnowledgeSaveResult(e,n){this.send({type:"knowledge.save.result",requestId:e,...n})}sendEpicListResult(e,n){this.send({type:"epic.list.result",requestId:e,ok:n.ok,error:n.error,epics:n.epics??[],children:n.children??[]})}sendEpicSuggestResult(e,n){this.send({type:"epic.suggest.result",requestId:e,ok:n.ok,error:n.error,issueKey:n.issueKey??"",reason:n.reason??"",considered:n.considered??0})}sendTeamCredsResult(e,n){this.send({type:"team.creds.result",requestId:e,ok:n.ok,error:n.error,githubShared:n.githubShared??!1,sharedGithubLogin:n.sharedGithubLogin??"",entries:n.entries??[]})}sendBoardTriggerResult(e,n){this.send({type:"board.trigger.result",requestId:e,...n})}sendAuditStatsResult(e,n){this.send({type:"audit.stats.result",requestId:e,ok:n.ok,error:n.error,byProject:n.byProject??{}})}sendRunnerUpdateResult(e,n){this.send({type:"runner.update.result",requestId:e,ok:n.ok,error:n.error,note:n.note??"",scheduled:n.scheduled??!1})}sendSetupClaudeMdGenerateResult(e,n){this.send({type:"setup.claudemd.generate.result",requestId:e,ok:n.ok,error:n.error,content:n.content??""})}sendRepoUnmapResult(e,n){this.send({type:"repo.unmap.result",requestId:e,ok:n.ok,error:n.error??"",removedPath:n.removedPath??""})}sendSetupRecheckResult(e,n){this.send({type:"setup.recheck.result",requestId:e,ok:n.ok,error:n.error??"",checks:(n.checks??[]).map(r=>({environment:r.environment??"",question:r.question,ok:r.ok,detail:r.detail??"",blocking:r.blocking??!0}))})}sendSetupClaudeMdSaveResult(e,n){this.send({type:"setup.claudemd.save.result",requestId:e,ok:n.ok,error:n.error,note:n.note??""})}sendResolveConflictResult(e,n){this.send({type:"run.resolve.conflict.result",requestId:e,ok:n.ok,note:n.note??"",freeOfCharge:n.freeOfCharge??!1,headSha:n.headSha??"",costUsd:n.costUsd,inputTokens:n.inputTokens,outputTokens:n.outputTokens})}sendTestFixResult(e,n){this.send({type:"run.testfix.result",requestId:e,ok:n.ok,note:n.note??"",headSha:n.headSha??"",remaining:n.remaining??[],costUsd:n.costUsd,inputTokens:n.inputTokens,outputTokens:n.outputTokens})}sendRunAnswerResult(e,n){this.send({type:"run.answer.result",requestId:e,ok:n.ok,note:n.note??"",error:n.error})}sendAgentProfilesResult(e,n){this.send({type:"agent.profiles.result",requestId:e,ok:n.ok,error:n.error,profiles:n.profiles??[],defaultLoggedIn:n.defaultLoggedIn??!1,agentsWithoutProfiles:n.agentsWithoutProfiles??[]})}sendRepoDocSaveResult(e,n){this.send({type:"repo.doc.save.result",requestId:e,ok:n.ok,error:n.error,note:n.note??""})}sendSetupStatusResult(e,n){this.send({type:"setup.status.result",requestId:e,ok:n.ok,error:n.error,jiraConfigured:n.jiraConfigured??!1,jiraEmail:n.jiraEmail??"",claude:n.claude,githubTokenSet:n.githubTokenSet??!1,githubLogin:n.githubLogin??"",deploysEnabled:n.deploysEnabled??!1,jiraUserCount:n.jiraUserCount??0,repos:n.repos??[]})}sendEnvPreflightResult(e,n){this.send({type:"env.preflight.result",requestId:e,...n,checks:this.withFixDefaults(n.checks)})}sendSelfMigrationApplyResult(e,n){this.send({type:"selfmigration.apply.result",requestId:e,...n})}sendJiraUsersResult(e,n){this.send({type:"jira.users.result",requestId:e,...n})}withFixDefaults(e){return e.map(n=>({...n,kind:n.kind??"connection",fix:n.fix??[],fixNote:n.fixNote??""}))}sendProjectTestResult(e,n,r){this.send({type:"project.test.result",requestId:e,ok:n,checks:this.withFixDefaults(r)})}sendRuleDiagnoseResult(e,n){this.send({type:"rule.diagnose.result",requestId:e,...n,checks:this.withFixDefaults(n.checks)})}};var Eo=R(require("node:fs"),1),_s=R(require("node:path"),1),Ul=require("node:child_process"),Ow=/\.mdx?$/i,Cp=6,Mw=/^[\w.\- ()]+$/;function zw(t,e){let n=e.trim().replace(/\\/g,"/").replace(/^\.\//,"");if(!n)return{ok:!1,error:"empty path"};if(_s.default.isAbsolute(n))return{ok:!1,error:"path must be repo-relative"};if(!Ow.test(n))return{ok:!1,error:"only markdown files (.md) can be saved"};let r=n.split("/");if(r.length>Cp)return{ok:!1,error:`path deeper than ${Cp} levels`};for(let o of r)if(o==="."||o===".."||!Mw.test(o))return{ok:!1,error:`invalid path segment "${o}"`};if(r[0]===".git")return{ok:!1,error:"cannot write under .git"};let s=_s.default.resolve(t),i=_s.default.resolve(s,n);return i!==s&&!i.startsWith(s+_s.default.sep)?{ok:!1,error:"path escapes the checkout"}:{ok:!0,abs:i,rel:n}}async function ql(t){let e=zw(t.repoPath,t.relPath);if(!e.ok)return{ok:!1,error:e.error};if(Eo.default.existsSync(e.abs)&&!t.overwrite)return{ok:!1,error:`${e.rel} already exists in this checkout`};Eo.default.mkdirSync(_s.default.dirname(e.abs),{recursive:!0}),Eo.default.writeFileSync(e.abs,t.content.endsWith(`
951
1000
  `)?t.content:t.content+`
952
- `);let n=i=>new Promise((o,l)=>{(0,Al.execFile)("git",["-C",t.repoPath,...i],{timeout:12e4},(c,u,p)=>c?l(new Error(p||c.message)):o())}),r="";try{r=await new Promise((i,o)=>(0,Al.execFile)("git",["-C",t.repoPath,"rev-parse","--abbrev-ref","HEAD"],{timeout:2e4},(l,c,u)=>l?o(new Error(u||l.message)):i(c.trim())))}catch{}let s="";try{await n(["add",e.rel]),await n(["-c","user.name=Allwright","-c","user.email=runner@allwright.local","commit","-m",t.commitMessage]);try{await n(["push"]),s=`committed and pushed to ${r||"the current branch"}`}catch(i){s=`committed locally to ${r||"the current branch"}, but push failed: `+(i instanceof Error?i.message.slice(0,200):"unknown")+" - push it from the server when convenient"}}catch(i){s="file written, but commit failed: "+(i instanceof Error?i.message.slice(0,200):"unknown")+" - commit it from the server when convenient"}return{ok:!0,note:s}}var Ir=R(require("node:fs"),1),$l=R(require("node:path"),1),bo=require("node:child_process"),_p=require("node:util");sr();wt();var Sp=R(ke(),1),kp=(0,_p.promisify)(bo.execFile);function gw(t){try{return new URL(t).host}catch{return t}}function yw(t){try{return(0,bo.execFileSync)("git",["-C",t,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim()}catch{return null}}async function vo(t,e,n=[],r){let s=[],i=t.repos[e.repoName]?.jira,o=i??t.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 f=gw(o.baseUrl),b=i?"this repo's own Jira credential":"the runner-wide Jira credential";if(f!==l)s.push({name:"jira-site",ok:!1,detail:`this project is on ${l}, but ${b} is for ${f}.`,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 v=new Pe(o);try{let _=await v.myself();s.push({name:"jira-auth",ok:!0,detail:`authenticated as ${_.displayName} on ${f} (${b})`});try{await v.search(`project = "${e.jiraProjectKey}" ORDER BY created DESC`,1),s.push({name:"jira-project",ok:!0,detail:`project ${e.jiraProjectKey} is readable on ${f}`})}catch(x){s.push({name:"jira-project",ok:!1,detail:`cannot read project ${e.jiraProjectKey} on ${f}: ${Ws(x)}`})}}catch(_){s.push({name:"jira-auth",ok:!1,detail:`Jira auth failed on ${f}: ${Ws(_)}`})}}}let c=t.repos[e.repoName];if(c&&Ir.default.existsSync(c.path)){let f=$l.default.join(c.path,"CLAUDE.md"),b=Ir.default.existsSync(f)&&Ir.default.readFileSync(f,"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 v=Yi(c.path);s.push({name:"deploy-doc",kind:"content",ok:v!==null,detail:v?`${v.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.",...v?{}:{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(!c)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(!Ir.default.existsSync(c.path))s.push({name:"repo-path",ok:!1,detail:`path does not exist: ${c.path}`});else{let f=Ir.default.existsSync($l.default.join(c.path,".git"));s.push({name:"repo-path",ok:!0,detail:`${c.path}${f?" (git checkout)":" (warning: not a git checkout)"}`})}let u=[...new Set([e.defaultAgent||"claude-code",...r??[]])];for(let f of u){let b=Ue(t,f),v=f==="claude-code"?"claude-code":`agent:${f}`;try{let{stdout:_}=await kp(b,["--version"],{timeout:15e3});s.push({name:v,ok:!0,detail:_.trim().slice(0,100)})}catch(_){s.push({name:v,ok:!1,detail:`cannot run "${b}" for agent "${f}": ${Ws(_)}`,fixNote:f==="claude-code"?"Install Claude Code on this server (npm install -g @anthropic-ai/claude-code) and log it in.":`Install the "${f}" CLI on this server, or point the runner at its binary in the config's agents section.`})}}try{let{stdout:f}=await kp("git",["--version"],{timeout:15e3});s.push({name:"git",ok:!0,detail:f.trim().slice(0,100)})}catch(f){s.push({name:"git",ok:!1,detail:`cannot run git: ${Ws(f)}`})}let p=Ce(t,e.repoName);if(!p)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 ${Sp.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:f}=await Promise.resolve().then(()=>(ut(),lr)),b=new f(p),v=await b.whoami(),_=c&&Ir.default.existsSync(c.path)?yw(c.path):null,x=_?lt(_):null;if(!x)s.push({name:"github-token",ok:!0,detail:`authenticated as ${v} - repo access not checked (no local checkout yet)`});else{let $=await b.repoAccess(x.owner,x.repo);s.push({name:"github-token",ok:$.ok&&$.canPush,detail:$.ok?$.canPush?`${v} has push access to ${x.owner}/${x.repo}`:`${v} can read ${x.owner}/${x.repo} but NOT push to it - implement rules will fail at the push`:`${v} cannot see ${x.owner}/${x.repo}: ${$.error}`,...$.ok&&$.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(f){s.push({name:"github-token",ok:!1,detail:Ws(f)})}if(n.length){t.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 f of n){let b=Nt(t,e.repoName,f.name),v=f.requiredSecrets.filter(_=>!b[_]&&!process.env[_]);s.push({name:`env:${f.name}`,ok:v.length===0,detail:v.length?`missing secret(s): ${v.join(", ")} - allwright env set "${e.repoName}" "${f.name}" ${v[0]}=...`:`${f.steps.length} step(s), ${f.requiredSecrets.length} secret(s) present`+(f.branch?`, deploys origin/${f.branch}`:"")})}}return s}function Ws(t){return(t instanceof Error?t.message:String(t)).slice(0,300)}var Te=new Yl;Te.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(Ti);function $p(t){y.info(`Create the token at ${Ze.GITHUB_TOKEN_PERMISSIONS.where}`);for(let e of Ze.GITHUB_TOKEN_PERMISSIONS.steps)y.info(` - ${e}`);y.info(Ze.GITHUB_TOKEN_PERMISSIONS.note),y.info(`Then paste it below for ${t}.`)}Te.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",wo.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 t=>{let e=vn.default.createInterface({input:process.stdin,output:process.stdout}),n=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 n("Control plane URL",t.cpUrl),s=await n("Enrolment token (from the web UI)",t.enrollToken),i=await n("Jira base URL (https://yourorg.atlassian.net)",t.jiraUrl),o=await n("Jira account email",t.jiraEmail),l=await n("Jira API token (create at id.atlassian.com/manage-profile/security/api-tokens)",t.jiraToken,!0),c=qo.parse({controlPlaneUrl:r,runnerName:t.name,jira:{baseUrl:i,email:o,apiToken:l}}),u=await new Pe(c.jira).myself();y.info(`Jira credential OK - authenticated as ${u.displayName}`),c=await Kc(c,s),y.info(`Enrolled as runner "${c.runnerName}" (${c.runnerId})`),y.info(`Credentials saved to ${jt()} (mode 600, this machine only)`),y.info("Next: map your repo with `allwright repo add <repoName> <localPath>`, then `allwright start`")}finally{e.close()}});var Pl=Te.command("repo").description("Map control-plane repo names to local checkouts");Pl.command("add <repoName> <localPath>").description("Map a repo name (as configured in the web UI) to a local checkout path").option("--force","map it even though there is no git checkout there yet").action(async(t,e,n)=>{let r=oe(),s=bn.default.resolve(e.replace(/^~(?=\/|$)/,wo.default.homedir()));if(!n.force){if(!Ge.default.existsSync(s))throw new Error(`${s} does not exist - nothing was mapped. The clone before this command probably failed; scroll up and read its error. Map it anyway with --force if you are going to clone it in a moment.`);if(!Ge.default.existsSync(bn.default.join(s,".git")))throw new Error(`${s} exists but is not a git checkout (no .git) - nothing was mapped. If the clone landed one level deeper, the path you want probably ends in the repo name. Map it anyway with --force if you know what you are doing.`)}r.repos[t]={path:s},fe(r),y.info(`mapped repo "${t}" -> ${s}`);try{let{originUrl:i}=await Promise.resolve().then(()=>(wt(),Xc));y.info(` origin remote: ${await i(s)} - make sure this is the repo you meant`)}catch{y.warn(` could not read an origin remote at ${s} - is it a git checkout?`)}Vt()||y.warn(`"${t}" is saved but NOT live yet - the running runner still does not know about it, and runs will keep saying it is not mapped until it reloads.`)});Pl.command("list").description("Show configured repo mappings").action(()=>{let t=oe(),e=Object.entries(t.repos);if(!e.length)return y.info("no repos mapped yet");for(let[n,r]of e)y.info(`${n} -> ${r.path}`)});var Pp=Te.command("claude").description("Per-user Claude login profiles - each teammate's runs bill their OWN Claude account");Pp.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 t=>{if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new Error("profile name: letters, digits, dots, dashes and underscores only");let e=oe(),n=e.claudeProfiles[t]?.configDir??`${jt().replace(/runner\.json$/,"")}claude-profiles/${t}`;Ge.default.mkdirSync(n,{recursive:!0,mode:448}),e.claudeProfiles[t]={configDir:n},fe(e),y.info(`profile "${t}" -> ${n}`),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,Wt.spawn)(e.claudeBin,[],{env:{...process.env,CLAUDE_CONFIG_DIR:n},stdio:"inherit"});await new Promise(s=>r.on("exit",()=>s())),y.info(`Done. Assign it on the dashboard: Team -> the user -> Claude profile = "${t}".`),Vt()});Pp.command("list").description("Show configured Claude profiles and whether each looks logged in").action(()=>{let t=oe(),e=Object.entries(t.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[n,r]of e){let s=Ge.default.existsSync(r.configDir)&&Ge.default.readdirSync(r.configDir).length>0;y.info(`${n} -> ${r.configDir} ${s?"(logged in)":"(NOT logged in yet)"}`)}});Pl.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(t=>{let e=oe();if(!e.repos[t]){let i=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${t}" - mapped repos: ${i}`)}let n=e.repos[t].path;delete e.repos[t];let r=Object.keys(e.environments).filter(i=>i.startsWith(`${t}:`));for(let i of r)delete e.environments[i];let s=e.auditSchedules.length;e.auditSchedules=e.auditSchedules.filter(i=>i.repoName!==t),fe(e),y.info(`Removed "${t}" (was ${n})`),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 jl=Te.command("service").description("Run the runner as a system service (starts on boot, restarts on crash)");jl.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(t=>{if(t.print){y.info(`
953
- `+ya(ga()));return}iu(y)});jl.command("uninstall").description("Stop and remove the systemd service (config/credentials untouched)").action(()=>ou(y));jl.command("status").description("systemctl status for the runner service").action(()=>{(0,Wt.spawn)("systemctl",["status","allwright","--no-pager"],{stdio:"inherit"}).on("exit",e=>process.exit(e??0))});Te.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 t=(0,Wt.spawn)("npm",["install","-g","allwright@latest"],{stdio:"inherit"});await new Promise((e,n)=>{t.on("exit",r=>r===0?e():n(new Error(`npm exited with code ${r}`))),t.on("error",n)}),y.info("Updated. Restart the runner service to load the new version (check active runs first).")});var ys=Te.command("jira").description("Per-repo Jira site overrides - for projects living on a different Atlassian site");ys.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 t=>{let e=oe();if(!e.repos[t]){let l=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${t}" - mapped repos: ${l}. Run \`allwright repo add\` first.`)}let n=ph(t),r=(n?.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 c=await new Pe(l).myself();if(e.repos[t].jira=l,fe(e),y.info(`The token already on this server works on ${r} - authenticated as ${c.displayName}. Saved it for "${t}"; nothing to type.`),n?.jiraProjectKey)try{await new Pe(l).search(`project = "${n.jiraProjectKey}"`,1),y.info(`Project ${n.jiraProjectKey} is readable with it.`)}catch{y.warn(`Authenticated, but project ${n.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.`)}Vt();return}catch{y.info(`The token already on this server does not work on ${r} - asking for one that does.`)}}let o=vn.default.createInterface({input:process.stdin,output:process.stdout});try{let c=(await o.question(s?`Jira base URL [${s}]: `:"Jira base URL for this repo (https://yourorg.atlassian.net): ")).trim()||s,p=(await o.question(i?`Jira account email [${i}]: `:"Jira account email: ")).trim()||i,f=(await o.question("Jira API token (id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!c||!p||!f)throw new Error("all three values are required");let b={baseUrl:c,email:p,apiToken:f},v=await new Pe(b).myself();y.info(`Jira credential OK - authenticated as ${v.displayName} on ${c}`),e.repos[t].jira=b,fe(e),y.info(`Saved: repo "${t}" now polls ${c} (other repos keep the runner-wide credential)`),Vt()}finally{o.close()}});ys.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 t=oe(),e=vn.default.createInterface({input:process.stdin,output:process.stdout});try{let n=t.jira?.baseUrl??"",r=t.jira?.email??"",s=(await e.question(n?`Jira base URL [${n}]: `:"Jira base URL (https://yourorg.atlassian.net): ")).trim()||n,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},c=await new Pe(l).myself();t.jira=l,fe(t),y.info(`Jira credential OK - authenticated as ${c.displayName} on ${s}`),y.info(`Saved to ${jt()} (mode 600, this machine only). Repo overrides are untouched.`),Vt()}finally{e.close()}});ys.command("show").description("Show which Jira site each repo uses (never prints tokens)").action(()=>{let t=oe();y.info(`runner-wide: ${t.jira?`${t.jira.baseUrl} (${t.jira.email})`:"(not configured)"}`);for(let[e,n]of Object.entries(t.repos))y.info(`${e} -> ${n.jira?`${n.jira.baseUrl} (${n.jira.email})`:"(runner-wide credential)"}`)});ys.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 t=>{let e=oe(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=vn.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await r.question(`Their ATLASSIAN account email [${n}]: `)).trim()||n,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(u=>u.jira)].filter(u=>!!u),l=new Set,c=!1;for(let u of o)if(!l.has(u.baseUrl)){l.add(u.baseUrl);try{let p=await new Pe({baseUrl:u.baseUrl,email:s,apiToken:i}).myself();y.info(`${u.baseUrl}: OK - authenticated as ${p.displayName}`),c=!0}catch{y.warn(`${u.baseUrl}: this credential does NOT work there (fine if they don't use that site)`)}}if(!c)throw new Error("credential failed on every configured Jira site - nothing saved");e.jiraUsers[n]={email:s,apiToken:i},fe(e),y.info(`Saved. Dashboard actions by ${n} now post to Jira as ${s}. No restart needed.`)}finally{r.close()}});ys.command("user-list").description("Show which Allwright users have their own Jira credential here (never prints tokens)").action(()=>{let t=oe(),e=Object.entries(t.jiraUsers);if(!e.length)return y.info("none yet - everyone's dashboard clicks require one: allwright jira user-add <their-ticketpilot-email>");for(let[n,r]of e)y.info(`${n} -> posts to Jira as ${r.email}`)});ys.command("user-remove <ticketpilotEmail>").description("Delete a person's stored Jira credential").action(t=>{let e=oe(),n=t.trim().toLowerCase();if(!e.jiraUsers[n])throw new Error(`no credential stored for ${n}`);delete e.jiraUsers[n],fe(e),y.info(`Removed. Dashboard actions by ${n} will now be refused until a new credential is added.`)});var bs=Te.command("github").description("GitHub credential for implement-mode rules");bs.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 t=>{let e=vn.default.createInterface({input:process.stdin,output:process.stdout});try{let n=t.token??void $p("every repo on this server")??(await e.question("GitHub token: ")).trim();if(!n)throw new Error("token is required");let{GitHubClient:r}=await Promise.resolve().then(()=>(ut(),lr)),s=await new r(n).whoami(),i=oe();i.github={token:n,login:s},fe(i),y.info(`GitHub token OK - authenticated as ${s}`),y.info(`Saved to ${jt()} (mode 600, this machine only)`)}finally{e.close()}});bs.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 t=>{let e=oe();if(!e.repos[t]){let i=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${t}" - mapped repos: ${i}. Run \`allwright repo add\` first.`)}let n=e.github?.token,r=e.repos[t]?.path;if(n&&r&&Ge.default.existsSync(r))try{let i=(0,Wt.execFileSync)("git",["-C",r,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim(),o=lt(i);if(o){let{GitHubClient:l}=await Promise.resolve().then(()=>(ut(),lr)),c=new l(n),u=await c.repoAccess(o.owner,o.repo);if(u.ok&&u.canPush){let p=await c.whoami();y.info(`The shared token on this server already has push access to ${o.owner}/${o.repo} as ${p} - "${t}" 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=vn.default.createInterface({input:process.stdin,output:process.stdout});try{$p(`"${t}"`);let i=(await s.question(`GitHub token for "${t}": `)).trim();if(!i&&n){y.info(`Nothing changed - "${t}" keeps using the shared token.`);return}if(!i)throw new Error("token is required");let{GitHubClient:o}=await Promise.resolve().then(()=>(ut(),lr)),l=await new o(i).whoami();e.repos[t].github={token:i,login:l},fe(e),y.info(`GitHub token OK - authenticated as ${l}`),y.info(`Saved: repo "${t}" now uses its own token (other repos keep the runner-wide one)`)}finally{s.close()}});bs.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 t=>{let e=oe(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=vn.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await r.question(`GitHub token for ${n}: `)).trim();if(!s)throw new Error("token is required");let{GitHubClient:i}=await Promise.resolve().then(()=>(ut(),lr)),o=await new i(s).whoami();e.githubUsers[n]={token:s,login:o},fe(e),y.info(`GitHub token OK - authenticated as ${o}`),y.info(`Saved. Implement runs triggered by ${n} now open PRs as ${o}. No restart needed.`)}finally{r.close()}});bs.command("user-list").description("Show which Allwright users have their own GitHub token here (never prints tokens)").action(()=>{let t=oe(),e=Object.entries(t.githubUsers);if(!e.length)return y.info("no per-user GitHub tokens - everyone's PRs use the repo/runner-wide token");for(let[n]of e)y.info(`${n} -> own GitHub token stored`)});bs.command("user-remove <ticketpilotEmail>").description("Delete a person's stored GitHub token (their runs fall back to the shared token)").action(t=>{let e=oe(),n=t.trim().toLowerCase();if(!e.githubUsers[n])throw new Error(`no GitHub token stored for ${n}`);delete e.githubUsers[n],fe(e),y.info(`Removed. ${n}'s runs use the repo/runner-wide token again.`)});bs.command("show").description("Show which GitHub token each repo and person would use (never prints tokens)").action(()=>{let t=oe();y.info(`runner-wide: ${t.github?.token?"token set":"(not configured)"}`);for(let[n,r]of Object.entries(t.repos))y.info(`${n} -> ${r.github?.token?"own repo token":"runner-wide token"}`);let e=Object.keys(t.githubUsers);y.info(e.length?`per-user tokens: ${e.join(", ")}`:"per-user tokens: (none)")});var Nl=Te.command("audit").description("Recurring specialist audits on this runner");Nl.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((t,e,n)=>{let r=oe();if(!r.repos[t]){let i=Object.keys(r.repos).join(", ")||"(none)";throw new Error(`unknown repo "${t}" - mapped repos: ${i}`)}if(e!=="security"&&e!=="testing")throw new Error('role must be "security" or "testing"');let s=parseInt(n,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===t&&i.role===e)),{repoName:t,role:e,intervalHours:s}],fe(r),y.info(`Scheduled: ${e} audit of "${t}" every ${s}h. Restart the runner to apply.`)});Nl.command("schedules").description("List scheduled audits").action(()=>{let t=oe();if(!t.auditSchedules.length)return y.info("no scheduled audits - allwright audit schedule <repo> <role> <hours>");for(let e of t.auditSchedules)y.info(`${e.repoName} \xB7 ${e.role} \xB7 every ${e.intervalHours}h`)});Nl.command("unschedule <repoName> <role>").description("Remove a scheduled audit").action((t,e)=>{let n=oe(),r=n.auditSchedules.length;if(n.auditSchedules=n.auditSchedules.filter(s=>!(s.repoName===t&&s.role===e)),n.auditSchedules.length===r)throw new Error("no such schedule");fe(n),y.info("Removed. Restart the runner to apply.")});var Ol=Te.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 t=oe();t.deploy={enabled:!0},fe(t),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."),Vt()});Ol.command("disable").description("Stop this runner from executing any deploy steps").action(()=>{let t=oe();t.deploy={enabled:!1},fe(t),y.info("deployments DISABLED on this runner"),Vt()});Ol.command("status").description("Show whether deployments are enabled here, and which env secrets are stored").action(()=>{let t=oe();y.info(`deployments: ${t.deploy.enabled?"enabled":"disabled"}`);let e=Object.entries(t.environments);if(!e.length)return y.info("no environment secrets stored");for(let[n,r]of e){let s=Object.keys(r.secrets);y.info(`${n}: ${s.length?s.join(", "):"(no secrets)"}`)}});var Ml=Te.command("env").description("Per-environment deploy secrets. Values stay on this machine, like your Jira token.");Ml.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((t,e,n)=>{let r=oe(),s=ui(t,e),i=r.environments[s]??{secrets:{}},o=[];for(let l of n){let c=l.indexOf("=");if(c<=0)throw new Error(`expected KEY=VALUE, got "${l}"`);let u=l.slice(0,c).trim();i.secrets[u]=l.slice(c+1),o.push(u)}r.environments[s]=i,fe(r),y.info(`stored ${o.length} secret(s) for ${s}: ${o.join(", ")}`),y.info(`Saved to ${jt()} (mode 600, this machine only)`),Vt()});Ml.command("unset <repoName> <envName> <names...>").description("Remove stored secrets for an environment").action((t,e,n)=>{let r=oe(),s=ui(t,e),i=r.environments[s];if(!i)return y.info(`nothing stored for ${s}`);for(let o of n)delete i.secrets[o];r.environments[s]=i,fe(r),y.info(`removed ${n.join(", ")} from ${s}`)});Ml.command("list").description("Show which environments have secrets stored here (names only, never values)").action(()=>{let t=oe(),e=Object.entries(t.environments);if(!e.length)return y.info("no environment secrets stored");for(let[n,r]of e)y.info(`${n}: ${Object.keys(r.secrets).join(", ")||"(none)"}`)});Te.command("export [file]").description("Back up ALL runner state (config+secrets, knowledge, audits, chats) to one tarball").action(t=>{try{let e=cc(t);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 ${bn.default.basename(e.file)}`)}catch(e){y.error(e instanceof Error?e.message:String(e)),process.exitCode=1}});Te.command("import <file>").description("Restore runner state from an `export` tarball (existing config is kept as a .bak dir)").action(t=>{let e=Mn();if(e&&zn(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 n=uc(t);y.info(`Restored ${n.restored.length} entries into ${ie()}`),n.previousDir&&y.info(`Previous config kept at ${n.previousDir}`),y.info("Start the runner and it will reconnect with the restored identity.")}catch(n){y.error(n instanceof Error?n.message:String(n)),process.exitCode=1}});Te.command("test").description("Check local setup: Jira auth, repo mappings, Claude Code binary").action(async()=>{let t=oe(),e=Object.keys(t.repos);if(!t.jira){y.error("no Jira credentials configured - run `allwright init`"),process.exitCode=1;return}let n=e.length?e.map(s=>({jiraProjectKey:"*",repoName:s})):[{jiraProjectKey:"*",repoName:"(none mapped)"}],r=!0;for(let s of n){let i=await vo(t,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 Vt(){let t=Mn()??Fr();if(t&&zn(t)&&process.platform!=="win32")try{return process.kill(t,"SIGHUP"),y.info("running runner reloaded its config live - no restart needed"),!0}catch{}let e=t?bc(t):null;return y.info(e?`No background runner found to reload, but a service named "${e}" exists here: sudo systemctl kill -s HUP ${e} - otherwise it applies on the next start.`:"Could not signal the running runner - it may run as another user (the service usually runs as root, and `sudo` is what lets you signal it). Under systemd: sudo systemctl kill -s HUP <your allwright service> (allwright service install names it 'allwright'; installs predating the rename use 'ticketpilot-runner') - otherwise it applies on the next allwright start."),!1}function ww(t){if(!t.runnerToken)throw new Error("runner not enrolled - run `allwright init`");if(!t.jira)throw new Error("no Jira credentials - run `allwright init`");let e=yc();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",Ko);let n=new Pe(t.jira),r=new Map,s=d=>{let m=t.repos[d]?.jira;if(!m)return n;let g=r.get(d);return g||(g=new Pe(m),r.set(d,g)),g},i=new Map,o=(d,m)=>{let g=tu(ye()??t,d,m);switch(g.kind){case"legacy":return{jira:s(d),authored:!1};case"self":return{jira:s(d),authored:!0};case"missing":return{error:g.error};case"user":{let E=`${g.creds.baseUrl}:${g.creds.email}:${g.creds.apiToken.slice(-6)}`,P=i.get(E);return P||(P=new Pe(g.creds),i.set(E,P)),{jira:P,authored:!0}}}},l=new URL("/api/runner/ws",t.controlPlaneUrl);l.protocol=l.protocol==="https:"?"wss:":"ws:";let c=[],u=[],p=[],f,b=null,v={cfg:t,jiraFor:s,transport:null},_=new Set,x=d=>{let m=c.find(E=>E.id===d),g=m&&t.repos[m.repoName];return m&&g?{project:m,repoPath:g.path}:null},$=d=>{let m=c.find(P=>P.id===d),g=t.runnerName?`This runner ("${t.runnerName}")`:"This runner";if(!m)return`${g} does not know that project at all - it may have been deleted, or this runner has not synced yet.`;let E=Object.keys(t.repos).join(", ")||"(none)";return`${g} has no local checkout for "${m.name}" (repo "${m.repoName}"). Repos mapped here: ${E}. Either pin the project to the runner that HAS that repo (Dashboard \u2192 the project \u2192 Edit \u2192 Runner) - do this when several runners are online and the project is unpinned, because then the request goes to whichever one answers first - or map the repo on this machine: allwright repo add ${m.repoName} /path/to/checkout`},j={cfg:t,jiraFor:s,get transport(){return v.transport},lookup:(d,m)=>{let g=x(d),E=p.find(P=>P.projectId===d&&P.name===m);return g&&E?{...g,environment:E}:null}},S=new go(l.toString(),t.runnerToken,{runnerVersion:Ti},{onConfig:d=>{c=d.projects,hh(d.projects),u=d.rules,p=d.environments,f.setConfig(d.projects,d.rules,d.pollingPaused,d.environments)},onDeployFix:async d=>{let m=x(d.projectId);if(!m){S.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:$(d.projectId)});return}let g=Ke(t,m.project,"assist");if("error"in g){S.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:g.error});return}y.info(`investigating failed deploy of "${d.environmentName}" (step: ${d.failedStep||"?"})`);let E=await qd({agent:g,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,steps:d.steps,failedStep:d.failedStep,errorText:d.errorText,cfg:t});S.sendDeploySuggestResult(d.requestId,E)},onProjectTest:async d=>{let m=c.find(E=>E.id===d.projectId);if(!m){S.sendProjectTestResult(d.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 vo(ye()??t,m,p.filter(E=>E.projectId===m.id),u.filter(E=>E.projectId===m.id).map(E=>"agent"in E.action?E.action.agent:"").filter(Boolean));S.sendProjectTestResult(d.requestId,g.every(E=>E.ok),g)},onRuleDiagnose:async d=>{let m=u.find(D=>D.id===d.ruleId),g=m&&c.find(D=>D.id===m.projectId);if(!m||!g){S.sendRuleDiagnoseResult(d.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 E=await vo(ye()??t,g,m.action.type==="deploy"?p.filter(D=>D.projectId===g.id):[]),P=m.action.type==="implement"?E:E.filter(D=>D.name!=="github-token"),{matchedCount:V,excludedCount:ee,excludedSample:Y}=await f.diagnoseRule(m,g);S.sendRuleDiagnoseResult(d.requestId,{checks:P,matchedCount:V,excludedCount:ee,excludedSample:Y})},onCancel:d=>{nd(d)?y.info(`run ${d} stopped from the dashboard`):y.warn(`cancel requested for run ${d}, but nothing is running under that id here - it likely finished already`)},onApproved:(d,m)=>{if(Xa(d)){Od(j,d).catch(g=>y.error(`deploy approval crashed for ${d}: ${g instanceof Error?g.stack:g}`));return}Ms(v,d,m).catch(g=>y.error(`approval handling crashed for ${d}: ${g instanceof Error?g.stack:g}`))},onRetryPush:d=>{let m=Li(d),g=()=>hd(v,d).catch(E=>y.error(`retry push crashed for ${d}: ${E instanceof Error?E.stack:E}`));m?f.runOnRepoQueue(m.baseRepoPath,g):g()},onRejected:d=>{if(Xa(d)){Md(j,d).catch(m=>y.error(`deploy rejection crashed for ${d}: ${m instanceof Error?m.stack:m}`));return}dd(v,d).catch(m=>y.error(`rejection handling crashed for ${d}: ${m instanceof Error?m.stack:m}`))},onDeployStart:d=>{let m=`${d.runId}#${d.attempt}`;if(_.has(m))return;_.add(m);let g=x(d.projectId);if(!g){let E=$(d.projectId);y.error(`deploy ${d.runId}: ${E}`),S.send({type:"run.status",runId:d.runId,status:"failed",error:E});return}y.info(`deploy ${d.runId} requested from the dashboard: ${d.issueKey} \u2192 ${d.environment.name}`),f.runOnEnvironmentQueue(d.environment.id,()=>Wi({runId:d.runId,project:g.project,environment:d.environment,issueKey:d.issueKey,issueSummary:d.issueSummary,repoPath:g.repoPath,cfg:t,jira:s(g.project.repoName),transport:S,requestedBy:d.requestedBy}).catch(E=>y.error(`deploy crashed for ${d.runId}: ${E instanceof Error?E.stack:E}`)))},onDeploySuggest:async d=>{let m=x(d.projectId);if(!m){S.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:$(d.projectId)});return}let g=Ke(t,m.project,"assist");if("error"in g){S.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:g.error});return}y.info(`asking ${g.adapter.displayName} for "${d.environmentName}" deploy steps in ${m.repoPath}`);let E=await Fd({agent:g,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,notes:d.notes,timeoutSeconds:d.timeoutSeconds,cfg:t});S.sendDeploySuggestResult(d.requestId,E)},onEnvPreflight:async d=>{let m=x(d.projectId);if(!m){S.sendEnvPreflightResult(d.requestId,{ok:!1,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project"}]});return}let g=await Ud({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,steps:d.steps,requiredSecrets:d.requiredSecrets,workdir:d.workdir,branch:d.branch,publicUrl:d.publicUrl,cfg:t});S.sendEnvPreflightResult(d.requestId,g)},onSelfMigrationApply:async d=>{let m=x(d.projectId);if(!m){S.sendSelfMigrationApplyResult(d.requestId,{ok:!1,file:d.file,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project",fix:[]}],output:"",error:$(d.projectId)});return}y.info(`applying migration ${d.file} for "${d.environmentName}"`);let g=await mh({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,file:d.file,urlSecret:d.urlSecret,cfg:t});y.info(g.ok?`migration ${d.file} applied`:`migration ${d.file} failed: ${g.error}`),S.sendSelfMigrationApplyResult(d.requestId,g)},onChatTurn:async d=>{let m=x(d.projectId);if(!m){S.sendChatTurnResult(d.requestId,{ok:!1,sessionId:d.sessionId??"",reply:"",error:$(d.projectId)});return}let g=d.sessionId||(0,Xs.randomUUID)(),E=!d.sessionId,P=E?0:Us(g)?.messages.length??0,V=!1,ee=0,Y="";if(!E&&P>=th){let be=await sh(m,g,t);if(be)V=!0,ee=P,Y=be,g=(0,Xs.randomUUID)(),E=!0,y.info(`chat compacted: ${P} message(s) summarized into a fresh session`);else if(P>=nh){S.sendChatTurnResult(d.requestId,{ok:!1,sessionId:g,reply:"",error:"this chat is very long and could not be compacted automatically - start a new chat (it keeps the repo knowledge; only the conversation resets)."});return}}let D=d.files.length?pc(m.repoPath,d.requestId,d.files):null,L=(0,Ze.replyPreferenceAppendix)({language:d.replyLanguage,languageInstruction:d.replyLanguageInstruction,style:d.replyStyle})+(0,Ze.pendingMigrationsAppendix)(d.pendingMigrations),re="```",B=E?`You are the project assistant for "${m.project.name}" - this working directory is its repository, and you have read-only access.
1001
+ `);let n=i=>new Promise((o,l)=>{(0,Ul.execFile)("git",["-C",t.repoPath,...i],{timeout:12e4},(c,u,p)=>c?l(new Error(p||c.message)):o())}),r="";try{r=await new Promise((i,o)=>(0,Ul.execFile)("git",["-C",t.repoPath,"rev-parse","--abbrev-ref","HEAD"],{timeout:2e4},(l,c,u)=>l?o(new Error(u||l.message)):i(c.trim())))}catch{}let s="";try{await n(["add",e.rel]),await n(["-c","user.name=Allwright","-c","user.email=runner@allwright.local","commit","-m",t.commitMessage]);try{await n(["push"]),s=`committed and pushed to ${r||"the current branch"}`}catch(i){s=`committed locally to ${r||"the current branch"}, but push failed: `+(i instanceof Error?i.message.slice(0,200):"unknown")+" - push it from the server when convenient"}}catch(i){s="file written, but commit failed: "+(i instanceof Error?i.message.slice(0,200):"unknown")+" - commit it from the server when convenient"}return{ok:!0,note:s}}var jr=R(require("node:fs"),1),Fl=R(require("node:path"),1),Ro=require("node:child_process"),Pp=require("node:util");ur();_t();var Np=R(_e(),1),$p=(0,Pp.promisify)(Ro.execFile);function Dw(t){try{return new URL(t).host}catch{return t}}function Lw(t){try{return(0,Ro.execFileSync)("git",["-C",t,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim()}catch{return null}}async function Io(t,e,n=[],r){let s=[],i=t.repos[e.repoName]?.jira,o=i??t.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 f=Dw(o.baseUrl),b=i?"this repo's own Jira credential":"the runner-wide Jira credential";if(f!==l)s.push({name:"jira-site",ok:!1,detail:`this project is on ${l}, but ${b} is for ${f}.`,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 v=new Ne(o);try{let w=await v.myself();s.push({name:"jira-auth",ok:!0,detail:`authenticated as ${w.displayName} on ${f} (${b})`});try{await v.search(`project = "${e.jiraProjectKey}" ORDER BY created DESC`,1),s.push({name:"jira-project",ok:!0,detail:`project ${e.jiraProjectKey} is readable on ${f}`})}catch(x){s.push({name:"jira-project",ok:!1,detail:`cannot read project ${e.jiraProjectKey} on ${f}: ${ni(x)}`})}}catch(w){s.push({name:"jira-auth",ok:!1,detail:`Jira auth failed on ${f}: ${ni(w)}`})}}}let c=t.repos[e.repoName];if(c&&jr.default.existsSync(c.path)){let f=Fl.default.join(c.path,"CLAUDE.md"),b=jr.default.existsSync(f)&&jr.default.readFileSync(f,"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 v=io(c.path);s.push({name:"deploy-doc",kind:"content",ok:v!==null,detail:v?`${v.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.",...v?{}:{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(!c)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(!jr.default.existsSync(c.path))s.push({name:"repo-path",ok:!1,detail:`path does not exist: ${c.path}`});else{let f=jr.default.existsSync(Fl.default.join(c.path,".git"));s.push({name:"repo-path",ok:!0,detail:`${c.path}${f?" (git checkout)":" (warning: not a git checkout)"}`})}let u=[...new Set([e.defaultAgent||"claude-code",...r??[]])];for(let f of u){let b=qe(t,f),v=f==="claude-code"?"claude-code":`agent:${f}`;try{let{stdout:w}=await $p(b,["--version"],{timeout:15e3});s.push({name:v,ok:!0,detail:w.trim().slice(0,100)})}catch(w){s.push({name:v,ok:!1,detail:`cannot run "${b}" for agent "${f}": ${ni(w)}`,fixNote:f==="claude-code"?"Install Claude Code on this server (npm install -g @anthropic-ai/claude-code) and log it in.":`Install the "${f}" CLI on this server, or point the runner at its binary in the config's agents section.`})}}try{let{stdout:f}=await $p("git",["--version"],{timeout:15e3});s.push({name:"git",ok:!0,detail:f.trim().slice(0,100)})}catch(f){s.push({name:"git",ok:!1,detail:`cannot run git: ${ni(f)}`})}let p=$e(t,e.repoName);if(!p)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 ${Np.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:f}=await Promise.resolve().then(()=>(ht(),fr)),b=new f(p),v=await b.whoami(),w=c&&jr.default.existsSync(c.path)?Lw(c.path):null,x=w?ut(w):null;if(!x)s.push({name:"github-token",ok:!0,detail:`authenticated as ${v} - repo access not checked (no local checkout yet)`});else{let $=await b.repoAccess(x.owner,x.repo);s.push({name:"github-token",ok:$.ok&&$.canPush,detail:$.ok?$.canPush?`${v} has push access to ${x.owner}/${x.repo}`:`${v} can read ${x.owner}/${x.repo} but NOT push to it - implement rules will fail at the push`:`${v} cannot see ${x.owner}/${x.repo}: ${$.error}`,...$.ok&&$.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(f){s.push({name:"github-token",ok:!1,detail:ni(f)})}if(n.length){t.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 f of n){let b=zt(t,e.repoName,f.name),v=f.requiredSecrets.filter(w=>!b[w]&&!process.env[w]);s.push({name:`env:${f.name}`,ok:v.length===0,detail:v.length?`missing secret(s): ${v.join(", ")} - allwright env set "${e.repoName}" "${f.name}" ${v[0]}=...`:`${f.steps.length} step(s), ${f.requiredSecrets.length} secret(s) present`+(f.branch?`, deploys origin/${f.branch}`:"")})}}return s}function ni(t){return(t instanceof Error?t.message:String(t)).slice(0,300)}Kt();no();var xe=new ac;xe.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($i);function Qp(t){y.info(`Create the token at ${We.GITHUB_TOKEN_PERMISSIONS.where}`);for(let e of We.GITHUB_TOKEN_PERMISSIONS.steps)y.info(` - ${e}`);y.info(We.GITHUB_TOKEN_PERMISSIONS.note),y.info(`Then paste it below for ${t}.`)}xe.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",ai.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 t=>{let e=Tn.default.createInterface({input:process.stdin,output:process.stdout}),n=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 n("Control plane URL",t.cpUrl),s=await n("Enrolment token (from the web UI)",t.enrollToken),i=await n("Jira base URL (https://yourorg.atlassian.net)",t.jiraUrl),o=await n("Jira account email",t.jiraEmail),l=await n("Jira API token (create at id.atlassian.com/manage-profile/security/api-tokens)",t.jiraToken,!0),c=Xo.parse({controlPlaneUrl:r,runnerName:t.name,jira:{baseUrl:i,email:o,apiToken:l}}),u=await new Ne(c.jira).myself();y.info(`Jira credential OK - authenticated as ${u.displayName}`),c=await tu(c,s),y.info(`Enrolled as runner "${c.runnerName}" (${c.runnerId})`),y.info(`Credentials saved to ${Mt()} (mode 600, this machine only)`),y.info("Next: map your repo with `allwright repo add <repoName> <localPath>`, then `allwright start`")}finally{e.close()}});var Kl=xe.command("repo").description("Map control-plane repo names to local checkouts");Kl.command("add <repoName> <localPath>").description("Map a repo name (as configured in the web UI) to a local checkout path").option("--force","map it even though there is no git checkout there yet").action(async(t,e,n)=>{let r=oe(),s=Xt.default.resolve(e.replace(/^~(?=\/|$)/,ai.default.homedir()));if(!n.force){if(!Ve.default.existsSync(s))throw new Error(`${s} does not exist - nothing was mapped. The clone before this command probably failed; scroll up and read its error. Map it anyway with --force if you are going to clone it in a moment.`);if(!Ve.default.existsSync(Xt.default.join(s,".git")))throw new Error(`${s} exists but is not a git checkout (no .git) - nothing was mapped. If the clone landed one level deeper, the path you want probably ends in the repo name. Map it anyway with --force if you know what you are doing.`)}r.repos[t]={path:s},fe(r),y.info(`mapped repo "${t}" -> ${s}`);try{let{originUrl:i}=await Promise.resolve().then(()=>(_t(),cu));y.info(` origin remote: ${await i(s)} - make sure this is the repo you meant`)}catch{y.warn(` could not read an origin remote at ${s} - is it a git checkout?`)}Qt()||y.warn(`"${t}" is saved but NOT live yet - the running runner still does not know about it, and runs will keep saying it is not mapped until it reloads.`)});Kl.command("list").description("Show configured repo mappings").action(()=>{let t=oe(),e=Object.entries(t.repos);if(!e.length)return y.info("no repos mapped yet");for(let[n,r]of e)y.info(`${n} -> ${r.path}`)});var ef=xe.command("claude").description("Per-user Claude login profiles - each teammate's runs bill their OWN Claude account");ef.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 t=>{if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new Error("profile name: letters, digits, dots, dashes and underscores only");let e=oe(),n=e.claudeProfiles[t]?.configDir??`${Mt().replace(/runner\.json$/,"")}claude-profiles/${t}`;Ve.default.mkdirSync(n,{recursive:!0,mode:448}),e.claudeProfiles[t]={configDir:n},fe(e),y.info(`profile "${t}" -> ${n}`),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,en.spawn)(e.claudeBin,[],{env:{...process.env,CLAUDE_CONFIG_DIR:n},stdio:"inherit"});await new Promise(s=>r.on("exit",()=>s())),y.info(`Done. Assign it on the dashboard: Team -> the user -> Claude profile = "${t}".`),Qt()});ef.command("list").description("Show configured Claude profiles and whether each looks logged in").action(()=>{let t=oe(),e=Object.entries(t.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[n,r]of e){let s=Ve.default.existsSync(r.configDir)&&Ve.default.readdirSync(r.configDir).length>0;y.info(`${n} -> ${r.configDir} ${s?"(logged in)":"(NOT logged in yet)"}`)}});Kl.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(t=>{let e=oe();if(!e.repos[t]){let i=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${t}" - mapped repos: ${i}`)}let n=e.repos[t].path;delete e.repos[t];let r=Object.keys(e.environments).filter(i=>i.startsWith(`${t}:`));for(let i of r)delete e.environments[i];let s=e.auditSchedules.length;e.auditSchedules=e.auditSchedules.filter(i=>i.repoName!==t),fe(e),y.info(`Removed "${t}" (was ${n})`),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 Hl=xe.command("service").description("Run the runner as a system service (starts on boot, restarts on crash)");Hl.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(t=>{if(t.print){y.info(`
1002
+ `+Ia(Ra()));return}gu(y)});Hl.command("uninstall").description("Stop and remove the systemd service (config/credentials untouched)").action(()=>yu(y));Hl.command("status").description("systemctl status for the runner service").action(()=>{(0,en.spawn)("systemctl",["status","allwright","--no-pager"],{stdio:"inherit"}).on("exit",e=>process.exit(e??0))});xe.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 t=(0,en.spawn)("npm",["install","-g","allwright@latest"],{stdio:"inherit"});await new Promise((e,n)=>{t.on("exit",r=>r===0?e():n(new Error(`npm exited with code ${r}`))),t.on("error",n)}),y.info("Updated. Restart the runner service to load the new version (check active runs first).")});var Ss=xe.command("jira").description("Per-repo Jira site overrides - for projects living on a different Atlassian site");Ss.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 t=>{let e=oe();if(!e.repos[t]){let l=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${t}" - mapped repos: ${l}. Run \`allwright repo add\` first.`)}let n=Sh(t),r=(n?.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 c=await new Ne(l).myself();if(e.repos[t].jira=l,fe(e),y.info(`The token already on this server works on ${r} - authenticated as ${c.displayName}. Saved it for "${t}"; nothing to type.`),n?.jiraProjectKey)try{await new Ne(l).search(`project = "${n.jiraProjectKey}"`,1),y.info(`Project ${n.jiraProjectKey} is readable with it.`)}catch{y.warn(`Authenticated, but project ${n.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.`)}Qt();return}catch{y.info(`The token already on this server does not work on ${r} - asking for one that does.`)}}let o=Tn.default.createInterface({input:process.stdin,output:process.stdout});try{let c=(await o.question(s?`Jira base URL [${s}]: `:"Jira base URL for this repo (https://yourorg.atlassian.net): ")).trim()||s,p=(await o.question(i?`Jira account email [${i}]: `:"Jira account email: ")).trim()||i,f=(await o.question("Jira API token (id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!c||!p||!f)throw new Error("all three values are required");let b={baseUrl:c,email:p,apiToken:f},v=await new Ne(b).myself();y.info(`Jira credential OK - authenticated as ${v.displayName} on ${c}`),e.repos[t].jira=b,fe(e),y.info(`Saved: repo "${t}" now polls ${c} (other repos keep the runner-wide credential)`),Qt()}finally{o.close()}});Ss.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 t=oe(),e=Tn.default.createInterface({input:process.stdin,output:process.stdout});try{let n=t.jira?.baseUrl??"",r=t.jira?.email??"",s=(await e.question(n?`Jira base URL [${n}]: `:"Jira base URL (https://yourorg.atlassian.net): ")).trim()||n,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},c=await new Ne(l).myself();t.jira=l,fe(t),y.info(`Jira credential OK - authenticated as ${c.displayName} on ${s}`),y.info(`Saved to ${Mt()} (mode 600, this machine only). Repo overrides are untouched.`),Qt()}finally{e.close()}});Ss.command("show").description("Show which Jira site each repo uses (never prints tokens)").action(()=>{let t=oe();y.info(`runner-wide: ${t.jira?`${t.jira.baseUrl} (${t.jira.email})`:"(not configured)"}`);for(let[e,n]of Object.entries(t.repos))y.info(`${e} -> ${n.jira?`${n.jira.baseUrl} (${n.jira.email})`:"(runner-wide credential)"}`)});Ss.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 t=>{let e=oe(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=Tn.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await r.question(`Their ATLASSIAN account email [${n}]: `)).trim()||n,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(u=>u.jira)].filter(u=>!!u),l=new Set,c=!1;for(let u of o)if(!l.has(u.baseUrl)){l.add(u.baseUrl);try{let p=await new Ne({baseUrl:u.baseUrl,email:s,apiToken:i}).myself();y.info(`${u.baseUrl}: OK - authenticated as ${p.displayName}`),c=!0}catch{y.warn(`${u.baseUrl}: this credential does NOT work there (fine if they don't use that site)`)}}if(!c)throw new Error("credential failed on every configured Jira site - nothing saved");e.jiraUsers[n]={email:s,apiToken:i},fe(e),y.info(`Saved. Dashboard actions by ${n} now post to Jira as ${s}. No restart needed.`)}finally{r.close()}});Ss.command("user-list").description("Show which Allwright users have their own Jira credential here (never prints tokens)").action(()=>{let t=oe(),e=Object.entries(t.jiraUsers);if(!e.length)return y.info("none yet - everyone's dashboard clicks require one: allwright jira user-add <their-ticketpilot-email>");for(let[n,r]of e)y.info(`${n} -> posts to Jira as ${r.email}`)});Ss.command("user-remove <ticketpilotEmail>").description("Delete a person's stored Jira credential").action(t=>{let e=oe(),n=t.trim().toLowerCase();if(!e.jiraUsers[n])throw new Error(`no credential stored for ${n}`);delete e.jiraUsers[n],fe(e),y.info(`Removed. Dashboard actions by ${n} will now be refused until a new credential is added.`)});var Ts=xe.command("github").description("GitHub credential for implement-mode rules");Ts.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 t=>{let e=Tn.default.createInterface({input:process.stdin,output:process.stdout});try{let n=t.token??void Qp("every repo on this server")??(await e.question("GitHub token: ")).trim();if(!n)throw new Error("token is required");let{GitHubClient:r}=await Promise.resolve().then(()=>(ht(),fr)),s=await new r(n).whoami(),i=oe();i.github={token:n,login:s},fe(i),y.info(`GitHub token OK - authenticated as ${s}`),y.info(`Saved to ${Mt()} (mode 600, this machine only)`)}finally{e.close()}});Ts.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 t=>{let e=oe();if(!e.repos[t]){let i=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${t}" - mapped repos: ${i}. Run \`allwright repo add\` first.`)}let n=e.github?.token,r=e.repos[t]?.path;if(n&&r&&Ve.default.existsSync(r))try{let i=(0,en.execFileSync)("git",["-C",r,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim(),o=ut(i);if(o){let{GitHubClient:l}=await Promise.resolve().then(()=>(ht(),fr)),c=new l(n),u=await c.repoAccess(o.owner,o.repo);if(u.ok&&u.canPush){let p=await c.whoami();y.info(`The shared token on this server already has push access to ${o.owner}/${o.repo} as ${p} - "${t}" 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=Tn.default.createInterface({input:process.stdin,output:process.stdout});try{Qp(`"${t}"`);let i=(await s.question(`GitHub token for "${t}": `)).trim();if(!i&&n){y.info(`Nothing changed - "${t}" keeps using the shared token.`);return}if(!i)throw new Error("token is required");let{GitHubClient:o}=await Promise.resolve().then(()=>(ht(),fr)),l=await new o(i).whoami();e.repos[t].github={token:i,login:l},fe(e),y.info(`GitHub token OK - authenticated as ${l}`),y.info(`Saved: repo "${t}" now uses its own token (other repos keep the runner-wide one)`)}finally{s.close()}});Ts.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 t=>{let e=oe(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=Tn.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await r.question(`GitHub token for ${n}: `)).trim();if(!s)throw new Error("token is required");let{GitHubClient:i}=await Promise.resolve().then(()=>(ht(),fr)),o=await new i(s).whoami();e.githubUsers[n]={token:s,login:o},fe(e),y.info(`GitHub token OK - authenticated as ${o}`),y.info(`Saved. Implement runs triggered by ${n} now open PRs as ${o}. No restart needed.`)}finally{r.close()}});Ts.command("user-list").description("Show which Allwright users have their own GitHub token here (never prints tokens)").action(()=>{let t=oe(),e=Object.entries(t.githubUsers);if(!e.length)return y.info("no per-user GitHub tokens - everyone's PRs use the repo/runner-wide token");for(let[n]of e)y.info(`${n} -> own GitHub token stored`)});Ts.command("user-remove <ticketpilotEmail>").description("Delete a person's stored GitHub token (their runs fall back to the shared token)").action(t=>{let e=oe(),n=t.trim().toLowerCase();if(!e.githubUsers[n])throw new Error(`no GitHub token stored for ${n}`);delete e.githubUsers[n],fe(e),y.info(`Removed. ${n}'s runs use the repo/runner-wide token again.`)});Ts.command("show").description("Show which GitHub token each repo and person would use (never prints tokens)").action(()=>{let t=oe();y.info(`runner-wide: ${t.github?.token?"token set":"(not configured)"}`);for(let[n,r]of Object.entries(t.repos))y.info(`${n} -> ${r.github?.token?"own repo token":"runner-wide token"}`);let e=Object.keys(t.githubUsers);y.info(e.length?`per-user tokens: ${e.join(", ")}`:"per-user tokens: (none)")});var Gl=xe.command("audit").description("Recurring specialist audits on this runner");Gl.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((t,e,n)=>{let r=oe();if(!r.repos[t]){let i=Object.keys(r.repos).join(", ")||"(none)";throw new Error(`unknown repo "${t}" - mapped repos: ${i}`)}if(e!=="security"&&e!=="testing")throw new Error('role must be "security" or "testing"');let s=parseInt(n,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===t&&i.role===e)),{repoName:t,role:e,intervalHours:s}],fe(r),y.info(`Scheduled: ${e} audit of "${t}" every ${s}h. Restart the runner to apply.`)});Gl.command("schedules").description("List scheduled audits").action(()=>{let t=oe();if(!t.auditSchedules.length)return y.info("no scheduled audits - allwright audit schedule <repo> <role> <hours>");for(let e of t.auditSchedules)y.info(`${e.repoName} \xB7 ${e.role} \xB7 every ${e.intervalHours}h`)});Gl.command("unschedule <repoName> <role>").description("Remove a scheduled audit").action((t,e)=>{let n=oe(),r=n.auditSchedules.length;if(n.auditSchedules=n.auditSchedules.filter(s=>!(s.repoName===t&&s.role===e)),n.auditSchedules.length===r)throw new Error("no such schedule");fe(n),y.info("Removed. Restart the runner to apply.")});var Zl=xe.command("deploy").description("Deployment settings for this machine");Zl.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 t=oe();t.deploy={enabled:!0},fe(t),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."),Qt()});Zl.command("disable").description("Stop this runner from executing any deploy steps").action(()=>{let t=oe();t.deploy={enabled:!1},fe(t),y.info("deployments DISABLED on this runner"),Qt()});Zl.command("status").description("Show whether deployments are enabled here, and which env secrets are stored").action(()=>{let t=oe();y.info(`deployments: ${t.deploy.enabled?"enabled":"disabled"}`);let e=Object.entries(t.environments);if(!e.length)return y.info("no environment secrets stored");for(let[n,r]of e){let s=Object.keys(r.secrets);y.info(`${n}: ${s.length?s.join(", "):"(no secrets)"}`)}});var $o=xe.command("env").description("Per-environment deploy secrets. Values stay on this machine, like your Jira token.");$o.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((t,e,n)=>{let r=oe(),s=yi(t,e),i=r.environments[s]??{secrets:{}},o=[];for(let l of n){let c=l.indexOf("=");if(c<=0)throw new Error(`expected KEY=VALUE, got "${l}"`);let u=l.slice(0,c).trim();i.secrets[u]=l.slice(c+1),o.push(u)}r.environments[s]=i,fe(r),y.info(`stored ${o.length} secret(s) for ${s}: ${o.join(", ")}`),y.info(`Saved to ${Mt()} (mode 600, this machine only)`),Qt()});$o.command("prepare <repoName> <envName>").description("Stand the environment up: systemd unit (nvm-aware PATH, crash-loop limit), scoped passwordless restart for deploys, and a Caddy site block when --url is given. Fixed templates, no AI anywhere; runs with YOUR sudo, in YOUR terminal, and only ever overwrites files it wrote itself. --dry-run prints everything without touching anything.").option("--port <n>","port the app should bind (default: first free from 3000)").option("--url <publicUrl>","public URL this environment serves - wires the running Caddy").option("--workdir <dir>","checkout to run from (default: the mapped repo path)").option("--dry-run","print every file this would write, write nothing").action(async(t,e,n)=>{let s=oe().repos[t]?.path,i=n.workdir??s;if(!i)throw new Error(`"${t}" is not mapped on this runner and no --workdir was given. Map it first: allwright repo add "${t}" <path>`);let{envPrepare:o}=await Promise.resolve().then(()=>(Hp(),Kp));await o({repoName:t,envName:e,dir:Xt.default.resolve(i.replace(/^~(?=\/|$)/,ai.default.homedir())),port:n.port?Number(n.port):void 0,publicUrl:n.url,dryRun:!!n.dryRun})});$o.command("unset <repoName> <envName> <names...>").description("Remove stored secrets for an environment").action((t,e,n)=>{let r=oe(),s=yi(t,e),i=r.environments[s];if(!i)return y.info(`nothing stored for ${s}`);for(let o of n)delete i.secrets[o];r.environments[s]=i,fe(r),y.info(`removed ${n.join(", ")} from ${s}`)});$o.command("list").description("Show which environments have secrets stored here (names only, never values)").action(()=>{let t=oe(),e=Object.entries(t.environments);if(!e.length)return y.info("no environment secrets stored");for(let[n,r]of e)y.info(`${n}: ${Object.keys(r.secrets).join(", ")||"(none)"}`)});xe.command("export [file]").description("Back up ALL runner state (config+secrets, knowledge, audits, chats) to one tarball").action(t=>{try{let e=wc(t);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 ${Xt.default.basename(e.file)}`)}catch(e){y.error(e instanceof Error?e.message:String(e)),process.exitCode=1}});xe.command("import <file>").description("Restore runner state from an `export` tarball (existing config is kept as a .bak dir)").action(t=>{let e=Fn();if(e&&Bn(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 n=kc(t);y.info(`Restored ${n.restored.length} entries into ${ie()}`),n.previousDir&&y.info(`Previous config kept at ${n.previousDir}`),y.info("Start the runner and it will reconnect with the restored identity.")}catch(n){y.error(n instanceof Error?n.message:String(n)),process.exitCode=1}});xe.command("test").description("Check local setup: Jira auth, repo mappings, Claude Code binary").action(async()=>{let t=oe(),e=Object.keys(t.repos);if(!t.jira){y.error("no Jira credentials configured - run `allwright init`"),process.exitCode=1;return}let n=e.length?e.map(s=>({jiraProjectKey:"*",repoName:s})):[{jiraProjectKey:"*",repoName:"(none mapped)"}],r=!0;for(let s of n){let i=await Io(t,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 Qt(){let t=Fn()??Vr();if(t&&Bn(t)&&process.platform!=="win32")try{return process.kill(t,"SIGHUP"),y.info("running runner reloaded its config live - no restart needed"),!0}catch{}let e=t?Ac(t):null;return y.info(e?`No background runner found to reload, but a service named "${e}" exists here: sudo systemctl kill -s HUP ${e} - otherwise it applies on the next start.`:"Could not signal the running runner - it may run as another user (the service usually runs as root, and `sudo` is what lets you signal it). Under systemd: sudo systemctl kill -s HUP <your allwright service> (allwright service install names it 'allwright'; installs predating the rename use 'ticketpilot-runner') - otherwise it applies on the next allwright start."),!1}function Vw(t){if(!t.runnerToken)throw new Error("runner not enrolled - run `allwright init`");if(!t.jira)throw new Error("no Jira credentials - run `allwright init`");let e=Ic();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",ta);let n=new Ne(t.jira),r=new Map,s=d=>{let m=t.repos[d]?.jira;if(!m)return n;let g=r.get(d);return g||(g=new Ne(m),r.set(d,g)),g},i=new Map,o=(d,m)=>{let g=hu(ye()??t,d,m);switch(g.kind){case"legacy":return{jira:s(d),authored:!1};case"self":return{jira:s(d),authored:!0};case"missing":return{error:g.error};case"user":{let E=`${g.creds.baseUrl}:${g.creds.email}:${g.creds.apiToken.slice(-6)}`,P=i.get(E);return P||(P=new Ne(g.creds),i.set(E,P)),{jira:P,authored:!0}}}},l=new URL("/api/runner/ws",t.controlPlaneUrl);l.protocol=l.protocol==="https:"?"wss:":"ws:";let c=[],u=[],p=[],f,b=null,v={cfg:t,jiraFor:s,transport:null},w=new Set,x=d=>{let m=c.find(E=>E.id===d),g=m&&t.repos[m.repoName];return m&&g?{project:m,repoPath:g.path}:null},$=d=>{let m=c.find(P=>P.id===d),g=t.runnerName?`This runner ("${t.runnerName}")`:"This runner";if(!m)return`${g} does not know that project at all - it may have been deleted, or this runner has not synced yet.`;let E=Object.keys(t.repos).join(", ")||"(none)";return`${g} has no local checkout for "${m.name}" (repo "${m.repoName}"). Repos mapped here: ${E}. Either pin the project to the runner that HAS that repo (Dashboard \u2192 the project \u2192 Edit \u2192 Runner) - do this when several runners are online and the project is unpinned, because then the request goes to whichever one answers first - or map the repo on this machine: allwright repo add ${m.repoName} /path/to/checkout`},N={cfg:t,jiraFor:s,get transport(){return v.transport},lookup:(d,m)=>{let g=x(d),E=p.find(P=>P.projectId===d&&P.name===m);return g&&E?{...g,environment:E}:null}},S=new xo(l.toString(),t.runnerToken,{runnerVersion:$i},{onConfig:d=>{c=d.projects,_h(d.projects),u=d.rules,p=d.environments,f.setConfig(d.projects,d.rules,d.pollingPaused,d.environments)},onDeployFix:async d=>{let m=x(d.projectId);if(!m){S.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:$(d.projectId)});return}let g=He(t,m.project,"assist");if("error"in g){S.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:g.error});return}y.info(`investigating failed deploy of "${d.environmentName}" (step: ${d.failedStep||"?"})`);let E=await Jd({agent:g,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,steps:d.steps,failedStep:d.failedStep,errorText:d.errorText,cfg:t});S.sendDeploySuggestResult(d.requestId,E)},onProjectTest:async d=>{let m=c.find(E=>E.id===d.projectId);if(!m){S.sendProjectTestResult(d.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 Io(ye()??t,m,p.filter(E=>E.projectId===m.id),u.filter(E=>E.projectId===m.id).map(E=>"agent"in E.action?E.action.agent:"").filter(Boolean));S.sendProjectTestResult(d.requestId,g.every(E=>E.ok),g)},onRuleDiagnose:async d=>{let m=u.find(D=>D.id===d.ruleId),g=m&&c.find(D=>D.id===m.projectId);if(!m||!g){S.sendRuleDiagnoseResult(d.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 E=await Io(ye()??t,g,m.action.type==="deploy"?p.filter(D=>D.projectId===g.id):[]),P=m.action.type==="implement"?E:E.filter(D=>D.name!=="github-token"),{matchedCount:V,excludedCount:ee,excludedSample:Y}=await f.diagnoseRule(m,g);S.sendRuleDiagnoseResult(d.requestId,{checks:P,matchedCount:V,excludedCount:ee,excludedSample:Y})},onCancel:d=>{pd(d)?y.info(`run ${d} stopped from the dashboard`):y.warn(`cancel requested for run ${d}, but nothing is running under that id here - it likely finished already`)},onApproved:(d,m)=>{if(cl(d)){Hd(N,d).catch(g=>y.error(`deploy approval crashed for ${d}: ${g instanceof Error?g.stack:g}`));return}Bs(v,d,m).catch(g=>y.error(`approval handling crashed for ${d}: ${g instanceof Error?g.stack:g}`))},onRetryPush:d=>{let m=Gi(d),g=()=>Sd(v,d).catch(E=>y.error(`retry push crashed for ${d}: ${E instanceof Error?E.stack:E}`));m?f.runOnRepoQueue(m.baseRepoPath,g):g()},onRejected:d=>{if(cl(d)){Gd(N,d).catch(m=>y.error(`deploy rejection crashed for ${d}: ${m instanceof Error?m.stack:m}`));return}_d(v,d).catch(m=>y.error(`rejection handling crashed for ${d}: ${m instanceof Error?m.stack:m}`))},onDeployStart:d=>{let m=`${d.runId}#${d.attempt}`;if(w.has(m))return;w.add(m);let g=x(d.projectId);if(!g){let E=$(d.projectId);y.error(`deploy ${d.runId}: ${E}`),S.send({type:"run.status",runId:d.runId,status:"failed",error:E});return}y.info(`deploy ${d.runId} requested from the dashboard: ${d.issueKey} \u2192 ${d.environment.name}`),f.runOnEnvironmentQueue(d.environment.id,()=>so({runId:d.runId,project:g.project,environment:d.environment,issueKey:d.issueKey,issueSummary:d.issueSummary,repoPath:g.repoPath,cfg:t,jira:s(g.project.repoName),transport:S,requestedBy:d.requestedBy}).catch(E=>y.error(`deploy crashed for ${d.runId}: ${E instanceof Error?E.stack:E}`)))},onDeploySuggest:async d=>{let m=x(d.projectId);if(!m){S.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:$(d.projectId)});return}let g=He(t,m.project,"assist");if("error"in g){S.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:g.error});return}y.info(`asking ${g.adapter.displayName} for "${d.environmentName}" deploy steps in ${m.repoPath}`);let E=await Xd({agent:g,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,notes:d.notes,timeoutSeconds:d.timeoutSeconds,cfg:t});S.sendDeploySuggestResult(d.requestId,E)},onEnvPreflight:async d=>{let m=x(d.projectId);if(!m){S.sendEnvPreflightResult(d.requestId,{ok:!1,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project"}]});return}let g=await Yd({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,steps:d.steps,requiredSecrets:d.requiredSecrets,workdir:d.workdir,branch:d.branch,publicUrl:d.publicUrl,cfg:t});S.sendEnvPreflightResult(d.requestId,g)},onSelfMigrationApply:async d=>{let m=x(d.projectId);if(!m){S.sendSelfMigrationApplyResult(d.requestId,{ok:!1,file:d.file,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project",fix:[]}],output:"",error:$(d.projectId)});return}y.info(`applying migration ${d.file} for "${d.environmentName}"`);let g=await xh({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,file:d.file,urlSecret:d.urlSecret,cfg:t});y.info(g.ok?`migration ${d.file} applied`:`migration ${d.file} failed: ${g.error}`),S.sendSelfMigrationApplyResult(d.requestId,g)},onChatTurn:async d=>{let m=x(d.projectId);if(!m){S.sendChatTurnResult(d.requestId,{ok:!1,sessionId:d.sessionId??"",reply:"",error:$(d.projectId)});return}let g=d.sessionId||(0,oi.randomUUID)(),E=!d.sessionId,P=E?0:Zs(g)?.messages.length??0,V=!1,ee=0,Y="";if(!E&&P>=dh){let be=await fh(m,g,t);if(be)V=!0,ee=P,Y=be,g=(0,oi.randomUUID)(),E=!0,y.info(`chat compacted: ${P} message(s) summarized into a fresh session`);else if(P>=hh){S.sendChatTurnResult(d.requestId,{ok:!1,sessionId:g,reply:"",error:"this chat is very long and could not be compacted automatically - start a new chat (it keeps the repo knowledge; only the conversation resets)."});return}}let D=d.files.length?Tc(m.repoPath,d.requestId,d.files):null,L=(0,We.replyPreferenceAppendix)({language:d.replyLanguage,languageInstruction:d.replyLanguageInstruction,style:d.replyStyle})+(0,We.pendingMigrationsAppendix)(d.pendingMigrations),re="```",B=E?`You are the project assistant for "${m.project.name}" - this working directory is its repository, and you have read-only access.
954
1003
 
955
1004
  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.
956
1005
  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.
@@ -972,19 +1021,19 @@ EXCEPTION - big requirements: when the user asks for an epic with sub-tickets, o
972
1021
  {"epic": {"summary": "\u2026", "description": "\u2026"}, "tickets": [{"summary": "\u2026", "description": "\u2026"}, \u2026]}
973
1022
  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.
974
1023
 
975
- `+ih+(Y?`
1024
+ `+mh+(Y?`
976
1025
 
977
1026
  This conversation was already running and has been compacted. Everything agreed so far, in summary form - treat it as established, do not re-ask:
978
1027
  ${Y}
979
1028
  `:"")+L+`
980
- ${d.userName||"The user"} says: ${d.message}`+(D?.section??""):L+`${d.userName||"The user"} says: ${d.message}`+(D?.section??""),le=0,Oe=[],me;try{let be=Ke(t,m.project,"chat");if("error"in be){S.sendChatTurnResult(d.requestId,{ok:!1,sessionId:g,reply:"",error:be.error});return}me=await be.adapter.run({repoPath:m.repoPath,prompt:B,timeoutSeconds:180,bin:be.bin,mode:"read_only",maxTurns:25,model:d.model||be.adapter.fastModel,sessionId:g,resume:!E,onLog:(de,Re)=>{de==="agent"&&(Oe.push(Re.slice(0,4e3)),S.send({type:"chat.stream",requestId:d.requestId,seq:le++,text:Re.slice(0,8e3)}))},onUsage:de=>{S.send({type:"chat.usage",requestId:d.requestId,inputTokens:Math.round(de.inputTokens),outputTokens:Math.round(de.outputTokens),cacheReadTokens:de.cacheReadTokens===void 0?void 0:Math.round(de.cacheReadTokens),turns:de.turns})}})}finally{D&&Ge.default.rmSync(D.dir,{recursive:!0,force:!0})}if(me.ok){let be=Oe.filter(de=>de.trim()&&!me.resultText.trim().startsWith(de.trim()));Qd(d.projectId,g,d.message,me.resultText,be,d.files.map(de=>de.name))}let ve=(me.inputTokens??0)+(me.cacheReadTokens??0);S.sendChatTurnResult(d.requestId,{contextTokens:ve,contextLimit:rh(me.model||d.model||""),compacted:V,compactedMessages:ee,ok:me.ok,sessionId:g,reply:me.resultText,error:me.ok?void 0:me.error??"the agent produced no reply",inputTokens:me.inputTokens,outputTokens:me.outputTokens,cacheReadTokens:me.cacheReadTokens,costUsd:me.costUsd,model:me.model??""})},onChatList:d=>{S.sendChatListResult(d.requestId,eh(d.projectId))},onRepoDocs:d=>{let m=x(d.projectId);if(!m){S.sendRepoDocsResult(d.requestId,{ok:!1,docs:[],error:$(d.projectId)});return}S.sendRepoDocsResult(d.requestId,{ok:!0,docs:lh(m.repoPath)})},onRepoDocRead:d=>{let m=x(d.projectId);if(!m){S.sendRepoDocReadResult(d.requestId,{ok:!1,path:d.path,content:"",truncated:!1,error:$(d.projectId)});return}let g=ch(m.repoPath,d.path);S.sendRepoDocReadResult(d.requestId,{ok:g.ok,path:g.ok?g.path:d.path,content:g.ok?g.content:"",truncated:g.ok?g.truncated:!1,error:g.ok?void 0:g.error})},onChatLoad:d=>{let m=Us(d.sessionId);S.sendChatLoadResult(d.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 d=>{let m=x(d.projectId);if(!m){S.sendBoardFetchResult(d.requestId,{ok:!1,columns:[],error:$(d.projectId)});return}try{let g=s(m.project.repoName),E;try{E=await g.searchBoard(`project = "${m.project.jiraProjectKey}" ORDER BY Rank ASC`,100)}catch{E=await g.searchBoard(`project = "${m.project.jiraProjectKey}" ORDER BY updated DESC`,100)}let P=await g.boardColumns(m.project.jiraProjectKey),V;if(P){V=P.map(D=>({name:D.name,issues:[]}));let Y=new Map;for(let D of E){let L=P.findIndex(B=>B.statusIds.includes(D.statusId)),re={key:D.key,summary:D.summary,labels:D.labels};if(L>=0)V[L].issues.push(re);else{let B=Y.get(D.status)??[];B.push(re),Y.set(D.status,B)}}for(let[D,L]of Y)V.push({name:D,issues:L})}else{let Y=le=>le.trim().toLowerCase(),D=new Map,L=new Map;for(let le of E){let Oe=Y(le.status);D.has(Oe)||D.set(Oe,le.status.trim());let me=L.get(Oe)??[];me.push({key:le.key,summary:le.summary,labels:le.labels}),L.set(Oe,me)}let re=[];try{re=await g.projectStatuses(m.project.jiraProjectKey)}catch{}let B=[];for(let le of re){let Oe=Y(le);!B.includes(Oe)&&L.has(Oe)&&B.push(Oe)}for(let le of L.keys())B.includes(le)||B.push(le);V=B.map(le=>({name:D.get(le)??le,issues:L.get(le)??[]}))}let ee=t.repos[m.project.repoName]?.jira??t.jira;S.sendBoardFetchResult(d.requestId,{ok:!0,browseBaseUrl:(ee?.baseUrl??"").replace(/\/+$/,""),columns:V})}catch(g){S.sendBoardFetchResult(d.requestId,{ok:!1,columns:[],error:g instanceof Error?g.message:String(g)})}},onBoardTrigger:async d=>{let m=x(d.projectId);if(!m){S.sendBoardTriggerResult(d.requestId,{ok:!1,error:$(d.projectId)});return}try{let g=s(m.project.repoName),E=d.comment.trim()?o(m.project.repoName,d.requestedByEmail):{jira:g,authored:!1};if(E.error!==void 0){S.sendBoardTriggerResult(d.requestId,{ok:!1,error:E.error});return}if(d.reimplement){let P=await g.getIssue(d.issueKey),V=P.comments.filter(D=>kt(D.body)),ee=V.length?Math.max(...V.map(D=>new Date(D.created).getTime())):0;if(!P.comments.some(D=>!kt(D.body)&&new Date(D.created).getTime()>ee)){S.sendBoardTriggerResult(d.requestId,{ok:!1,error:`${d.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(d.issueKey,{remove:["agent-implemented"]})}d.removeLabel.trim()&&await g.editLabels(d.issueKey,{remove:[d.removeLabel.trim()]}),d.comment.trim()&&await E.jira.addTriggerComment(d.issueKey,`${d.comment.trim()}`+(!E.authored&&d.requestedBy?`
1029
+ ${d.userName||"The user"} says: ${d.message}`+(D?.section??""):L+`${d.userName||"The user"} says: ${d.message}`+(D?.section??""),le=0,Me=[],me;try{let be=He(t,m.project,"chat");if("error"in be){S.sendChatTurnResult(d.requestId,{ok:!1,sessionId:g,reply:"",error:be.error});return}me=await be.adapter.run({repoPath:m.repoPath,prompt:B,timeoutSeconds:180,bin:be.bin,mode:"read_only",maxTurns:25,model:d.model||be.adapter.fastModel,sessionId:g,resume:!E,onLog:(de,Ie)=>{de==="agent"&&(Me.push(Ie.slice(0,4e3)),S.send({type:"chat.stream",requestId:d.requestId,seq:le++,text:Ie.slice(0,8e3)}))},onUsage:de=>{S.send({type:"chat.usage",requestId:d.requestId,inputTokens:Math.round(de.inputTokens),outputTokens:Math.round(de.outputTokens),cacheReadTokens:de.cacheReadTokens===void 0?void 0:Math.round(de.cacheReadTokens),turns:de.turns})}})}finally{D&&Ve.default.rmSync(D.dir,{recursive:!0,force:!0})}if(me.ok){let be=Me.filter(de=>de.trim()&&!me.resultText.trim().startsWith(de.trim()));ch(d.projectId,g,d.message,me.resultText,be,d.files.map(de=>de.name))}let ve=(me.inputTokens??0)+(me.cacheReadTokens??0);S.sendChatTurnResult(d.requestId,{contextTokens:ve,contextLimit:ph(me.model||d.model||""),compacted:V,compactedMessages:ee,ok:me.ok,sessionId:g,reply:me.resultText,error:me.ok?void 0:me.error??"the agent produced no reply",inputTokens:me.inputTokens,outputTokens:me.outputTokens,cacheReadTokens:me.cacheReadTokens,costUsd:me.costUsd,model:me.model??""})},onChatList:d=>{S.sendChatListResult(d.requestId,uh(d.projectId))},onRepoDocs:d=>{let m=x(d.projectId);if(!m){S.sendRepoDocsResult(d.requestId,{ok:!1,docs:[],error:$(d.projectId)});return}S.sendRepoDocsResult(d.requestId,{ok:!0,docs:bh(m.repoPath)})},onRepoDocRead:d=>{let m=x(d.projectId);if(!m){S.sendRepoDocReadResult(d.requestId,{ok:!1,path:d.path,content:"",truncated:!1,error:$(d.projectId)});return}let g=vh(m.repoPath,d.path);S.sendRepoDocReadResult(d.requestId,{ok:g.ok,path:g.ok?g.path:d.path,content:g.ok?g.content:"",truncated:g.ok?g.truncated:!1,error:g.ok?void 0:g.error})},onChatLoad:d=>{let m=Zs(d.sessionId);S.sendChatLoadResult(d.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 d=>{let m=x(d.projectId);if(!m){S.sendBoardFetchResult(d.requestId,{ok:!1,columns:[],error:$(d.projectId)});return}try{let g=s(m.project.repoName),E;try{E=await g.searchBoard(`project = "${m.project.jiraProjectKey}" ORDER BY Rank ASC`,100)}catch{E=await g.searchBoard(`project = "${m.project.jiraProjectKey}" ORDER BY updated DESC`,100)}let P=await g.boardColumns(m.project.jiraProjectKey),V;if(P){V=P.map(D=>({name:D.name,issues:[]}));let Y=new Map;for(let D of E){let L=P.findIndex(B=>B.statusIds.includes(D.statusId)),re={key:D.key,summary:D.summary,labels:D.labels};if(L>=0)V[L].issues.push(re);else{let B=Y.get(D.status)??[];B.push(re),Y.set(D.status,B)}}for(let[D,L]of Y)V.push({name:D,issues:L})}else{let Y=le=>le.trim().toLowerCase(),D=new Map,L=new Map;for(let le of E){let Me=Y(le.status);D.has(Me)||D.set(Me,le.status.trim());let me=L.get(Me)??[];me.push({key:le.key,summary:le.summary,labels:le.labels}),L.set(Me,me)}let re=[];try{re=await g.projectStatuses(m.project.jiraProjectKey)}catch{}let B=[];for(let le of re){let Me=Y(le);!B.includes(Me)&&L.has(Me)&&B.push(Me)}for(let le of L.keys())B.includes(le)||B.push(le);V=B.map(le=>({name:D.get(le)??le,issues:L.get(le)??[]}))}let ee=t.repos[m.project.repoName]?.jira??t.jira;S.sendBoardFetchResult(d.requestId,{ok:!0,browseBaseUrl:(ee?.baseUrl??"").replace(/\/+$/,""),columns:V})}catch(g){S.sendBoardFetchResult(d.requestId,{ok:!1,columns:[],error:g instanceof Error?g.message:String(g)})}},onBoardTrigger:async d=>{let m=x(d.projectId);if(!m){S.sendBoardTriggerResult(d.requestId,{ok:!1,error:$(d.projectId)});return}try{let g=s(m.project.repoName),E=d.comment.trim()?o(m.project.repoName,d.requestedByEmail):{jira:g,authored:!1};if(E.error!==void 0){S.sendBoardTriggerResult(d.requestId,{ok:!1,error:E.error});return}if(d.reimplement){let P=await g.getIssue(d.issueKey),V=P.comments.filter(D=>St(D.body)),ee=V.length?Math.max(...V.map(D=>new Date(D.created).getTime())):0;if(!P.comments.some(D=>!St(D.body)&&new Date(D.created).getTime()>ee)){S.sendBoardTriggerResult(d.requestId,{ok:!1,error:`${d.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(d.issueKey,{remove:["agent-implemented"]})}d.removeLabel.trim()&&await g.editLabels(d.issueKey,{remove:[d.removeLabel.trim()]}),d.comment.trim()&&await E.jira.addTriggerComment(d.issueKey,`${d.comment.trim()}`+(!E.authored&&d.requestedBy?`
981
1030
 
982
1031
  _(requested by ${d.requestedBy} via Allwright)_`:"")),y.info(`Board action on ${d.issueKey}`+(d.comment?` comment "${d.comment.trim()}"`:"")+(d.removeLabel?` -label ${d.removeLabel}`:"")+(d.requestedBy?` by ${d.requestedBy}`:"")),S.sendBoardTriggerResult(d.requestId,{ok:!0})}catch(g){S.sendBoardTriggerResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onChatCreateTicket:async d=>{let m=x(d.projectId);if(!m){S.sendChatCreateTicketResult(d.requestId,{ok:!1,issueKey:"",error:$(d.projectId)});return}try{let g=o(m.project.repoName,d.requestedByEmail);if(g.error!==void 0){S.sendChatCreateTicketResult(d.requestId,{ok:!1,issueKey:"",error:g.error});return}let E=`
983
1032
 
984
1033
  ---
985
1034
  _Created via Allwright Compose`+(!g.authored&&d.requestedBy?` by ${d.requestedBy}`:"")+", drafted with the project agent._";if(d.asEpic&&d.createAs!=="epic_with_children"&&d.children.length){let ee=d.createAs==="separate_epics"?"Epic":"Task",Y=[];for(let D of d.children){let L=await g.jira.createIssue(m.project.jiraProjectKey,D.summary,(D.description||"(no description)")+E,ee);Y.push(L.key)}y.info(`Compose created ${Y.length} standalone ${ee.toLowerCase()}(s)`),S.sendChatCreateTicketResult(d.requestId,{ok:!0,issueKey:Y[0]??"",childKeys:Y});return}let{key:P}=await g.jira.createIssue(m.project.jiraProjectKey,d.summary,(d.description||"(no description)")+E,d.asEpic?"Epic":"Task");d.files.length&&await g.jira.addAttachments(P,d.files.map(ee=>({name:ee.name,content:Buffer.from(ee.contentBase64,"base64")}))).then(()=>y.info(`Compose attached ${d.files.length} file(s) to ${P}`)).catch(ee=>y.warn(`Compose could not attach files to ${P}: ${ee instanceof Error?ee.message:ee}`));let V=[];if(d.asEpic){for(let ee of d.children){let Y=await g.jira.createIssue(m.project.jiraProjectKey,ee.summary,ee.description||"(no description)","Task",P);V.push(Y.key)}y.info(`Compose created epic ${P} with ${V.length} child ticket(s)`),S.sendChatCreateTicketResult(d.requestId,{ok:!0,issueKey:P,childKeys:V});return}d.triggerComment.trim()&&await g.jira.addTriggerComment(P,`${d.triggerComment.trim()}`+(!g.authored&&d.requestedBy?`
986
1035
 
987
- _(requested by ${d.requestedBy} via Allwright)_`:"")),y.info(`Compose created ${P}`+(d.requestedBy?` for ${d.requestedBy}`:"")+(d.triggerComment?` with trigger "${d.triggerComment.trim()}"`:"")),S.sendChatCreateTicketResult(d.requestId,{ok:!0,issueKey:P})}catch(g){S.sendChatCreateTicketResult(d.requestId,{ok:!1,issueKey:"",error:g instanceof Error?g.message:String(g)})}},onAuditStart:async d=>{let m=x(d.projectId);if(!m){S.sendAuditStartResult(d.requestId,{ok:!1,error:$(d.projectId)});return}try{y.info(`Audit (${d.role}) starting on ${m.project.repoName}`+(d.scope.kind!=="repo"?` scoped to ${d.scope.kind}:${d.scope.ref}`:""));let g=Ke(t,m.project,"assist");if("error"in g){S.sendAuditStartResult(d.requestId,{ok:!1,error:g.error});return}let E=await ns({projectId:d.projectId,repoPath:m.repoPath,role:d.role,scope:d.scope,detailLevel:d.detailLevel,model:d.model,agent:g,jira:s(m.project.repoName)});if(!E.ok){S.sendAuditStartResult(d.requestId,{ok:!1,error:E.error});return}S.sendAuditStartResult(d.requestId,{ok:!0,audit:E.audit})}catch(g){S.sendAuditStartResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onAuditList:async d=>{try{S.sendAuditListResult(d.requestId,{ok:!0,audits:vu(d.projectId)})}catch(m){S.sendAuditListResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditGet:async d=>{try{let m=_u(d.projectId,d.auditId);if(!m){S.sendAuditGetResult(d.requestId,{ok:!1,error:"audit not found on this runner"});return}S.sendAuditGetResult(d.requestId,{ok:!0,audit:m})}catch(m){S.sendAuditGetResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditReview:async d=>{try{let m=wa(d.projectId,d.auditId,{selected:d.selected,ticketed:d.ticketed,verdicts:d.verdicts,verdictBy:d.verdictBy});if(!m){S.sendAuditReviewResult(d.requestId,{ok:!1,error:"audit not found on this runner"});return}let g=x(d.projectId);if(g&&d.verdicts.length){let E=[];for(let P of d.verdicts){if(P.verdict==="valid"||m.lessonsWritten.includes(P.findingId))continue;let V=m.findings.find(ee=>ee.id===P.findingId);V&&(xa(g.repoPath,m.role,Au(V,P.verdict,P.note,d.verdictBy)),E.push(P.findingId),y.info(`Lesson written (${m.role}): ${P.verdict} - ${V.title.slice(0,60)}`))}E.length&&(m=wa(d.projectId,d.auditId,{markLessonsWritten:E})??m)}S.sendAuditReviewResult(d.requestId,{ok:!0,audit:m})}catch(m){S.sendAuditReviewResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onKnowledgeList:async d=>{let m=x(d.projectId);if(!m){S.sendKnowledgeListResult(d.requestId,{ok:!1,error:$(d.projectId)});return}try{S.sendKnowledgeListResult(d.requestId,{ok:!0,files:$u(m.repoPath)})}catch(g){S.sendKnowledgeListResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onKnowledgeSave:async d=>{let m=x(d.projectId);if(!m){S.sendKnowledgeSaveResult(d.requestId,{ok:!1,error:$(d.projectId)});return}try{d.append?xa(m.repoPath,d.role,Cu(d.content,d.by),d.level):Pu(m.repoPath,d.role,d.level,d.source,d.name,d.content),y.info(`Knowledge ${d.append?"taught":"saved"}: ${d.role}/${d.level}/${d.name}`),S.sendKnowledgeSaveResult(d.requestId,{ok:!0})}catch(g){S.sendKnowledgeSaveResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onEpicList:async d=>{let m=x(d.projectId);if(!m){S.sendEpicListResult(d.requestId,{ok:!1,error:$(d.projectId)});return}try{let g=s(m.project.repoName);if(d.epicKey){let E=await g.epicChildren(d.epicKey);S.sendEpicListResult(d.requestId,{ok:!0,children:E})}else{let E=await g.searchEpics(m.project.jiraProjectKey);S.sendEpicListResult(d.requestId,{ok:!0,epics:E})}}catch(g){S.sendEpicListResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onEpicSuggest:async d=>{let m=x(d.projectId);if(!m){S.sendEpicSuggestResult(d.requestId,{ok:!1,error:$(d.projectId)});return}try{let g=s(m.project.repoName),E=await g.epicChildren(d.epicKey),P=lu(E);if(!P.length){S.sendEpicSuggestResult(d.requestId,{ok:!1,error:`every child of ${d.epicKey} is already done or in an agent's hands - nothing to sequence`});return}if(P.length===1){S.sendEpicSuggestResult(d.requestId,{ok:!0,issueKey:P[0].key,reason:"It's the only pending ticket left in this epic.",considered:1});return}let V=await Promise.all(P.slice(0,12).map(async re=>{try{let B=await g.getIssue(re.key);return{...re,description:B.description}}catch{return{...re,description:""}}})),ee=(await g.getIssue(d.epicKey).catch(()=>null))?.summary??"";y.info(`Epic suggest: weighing ${V.length} pending children of ${d.epicKey}`);let Y=Ke(t,m.project,"assist");if("error"in Y){S.sendEpicSuggestResult(d.requestId,{ok:!1,error:Y.error});return}let D=await Y.adapter.run({repoPath:m.repoPath,prompt:cu(d.epicKey,ee,V),timeoutSeconds:150,bin:Y.bin,mode:"read_only",maxTurns:20,sessionId:(0,Xs.randomUUID)(),model:d.model||"claude-sonnet-5",onLog:()=>{}}),L=uu(D.resultText,V.map(re=>re.key));if("error"in L){S.sendEpicSuggestResult(d.requestId,{ok:!1,error:L.error});return}y.info(`Epic suggest: ${d.epicKey} -> do ${L.issueKey} first`),S.sendEpicSuggestResult(d.requestId,{ok:!0,issueKey:L.issueKey,reason:L.reason,considered:V.length})}catch(g){S.sendEpicSuggestResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onTeamCreds:async d=>{try{let m=ye()??t;if(m.github?.token&&!m.github.login)try{let{GitHubClient:E}=await Promise.resolve().then(()=>(ut(),lr));m.github.login=await new E(m.github.token).whoami(),fe(m)}catch{}let g=nu(m,d.emails);S.sendTeamCredsResult(d.requestId,{ok:!0,...g})}catch(m){S.sendTeamCredsResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRepoUnmap:d=>{try{let m=ye();if(!m){S.sendRepoUnmapResult(d.requestId,{ok:!1,error:"this runner has no config file"});return}let g=m.repos[d.repoName];if(!g){S.sendRepoUnmapResult(d.requestId,{ok:!0,removedPath:""});return}let E=g.path;delete m.repos[d.repoName];for(let P of Object.keys(m.environments).filter(V=>V.startsWith(`${d.repoName}:`)))delete m.environments[P];m.auditSchedules=m.auditSchedules.filter(P=>P.repoName!==d.repoName),fe(m),Vt(),y.info(`Unmapped "${d.repoName}" (was ${E}) - its project was deleted on the dashboard. The checkout on disk was NOT touched.`),S.sendRepoUnmapResult(d.requestId,{ok:!0,removedPath:E})}catch(m){S.sendRepoUnmapResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupRecheck:d=>{try{let m=x(d.projectId);if(!m){S.sendSetupRecheckResult(d.requestId,{ok:!1,error:$(d.projectId)});return}S.sendSetupRecheckResult(d.requestId,{ok:!0,checks:_d({repoPath:m.repoPath,environments:d.environments})})}catch(m){S.sendSetupRecheckResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupStatus:async d=>{try{let m=ye()??t,{buildSetupReport:g}=await Promise.resolve().then(()=>(Cp(),Ap)),E=await g(m,d.repoNames,t);S.sendSetupStatusResult(d.requestId,{ok:!0,...E})}catch(m){S.sendSetupStatusResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdGenerate:async d=>{try{let m=x(d.projectId);if(!m){S.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=d.kind==="deploy"?"DEPLOY.md":d.kind==="design"?"DESIGN.md":"CLAUDE.md";y.info(`Setup: drafting ${g} for ${m.project.repoName}`);let E="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.",P=`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.
1036
+ _(requested by ${d.requestedBy} via Allwright)_`:"")),y.info(`Compose created ${P}`+(d.requestedBy?` for ${d.requestedBy}`:"")+(d.triggerComment?` with trigger "${d.triggerComment.trim()}"`:"")),S.sendChatCreateTicketResult(d.requestId,{ok:!0,issueKey:P})}catch(g){S.sendChatCreateTicketResult(d.requestId,{ok:!1,issueKey:"",error:g instanceof Error?g.message:String(g)})}},onAuditStart:async d=>{let m=x(d.projectId);if(!m){S.sendAuditStartResult(d.requestId,{ok:!1,error:$(d.projectId)});return}try{y.info(`Audit (${d.role}) starting on ${m.project.repoName}`+(d.scope.kind!=="repo"?` scoped to ${d.scope.kind}:${d.scope.ref}`:""));let g=He(t,m.project,"assist");if("error"in g){S.sendAuditStartResult(d.requestId,{ok:!1,error:g.error});return}let E=await ls({projectId:d.projectId,repoPath:m.repoPath,role:d.role,scope:d.scope,detailLevel:d.detailLevel,model:d.model,agent:g,jira:s(m.project.repoName)});if(!E.ok){S.sendAuditStartResult(d.requestId,{ok:!1,error:E.error});return}S.sendAuditStartResult(d.requestId,{ok:!0,audit:E.audit})}catch(g){S.sendAuditStartResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onAuditList:async d=>{try{S.sendAuditListResult(d.requestId,{ok:!0,audits:Cu(d.projectId)})}catch(m){S.sendAuditListResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditGet:async d=>{try{let m=Nu(d.projectId,d.auditId);if(!m){S.sendAuditGetResult(d.requestId,{ok:!1,error:"audit not found on this runner"});return}S.sendAuditGetResult(d.requestId,{ok:!0,audit:m})}catch(m){S.sendAuditGetResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditReview:async d=>{try{let m=$a(d.projectId,d.auditId,{selected:d.selected,ticketed:d.ticketed,verdicts:d.verdicts,verdictBy:d.verdictBy});if(!m){S.sendAuditReviewResult(d.requestId,{ok:!1,error:"audit not found on this runner"});return}let g=x(d.projectId);if(g&&d.verdicts.length){let E=[];for(let P of d.verdicts){if(P.verdict==="valid"||m.lessonsWritten.includes(P.findingId))continue;let V=m.findings.find(ee=>ee.id===P.findingId);V&&(Ma(g.repoPath,m.role,Uu(V,P.verdict,P.note,d.verdictBy)),E.push(P.findingId),y.info(`Lesson written (${m.role}): ${P.verdict} - ${V.title.slice(0,60)}`))}E.length&&(m=$a(d.projectId,d.auditId,{markLessonsWritten:E})??m)}S.sendAuditReviewResult(d.requestId,{ok:!0,audit:m})}catch(m){S.sendAuditReviewResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onKnowledgeList:async d=>{let m=x(d.projectId);if(!m){S.sendKnowledgeListResult(d.requestId,{ok:!1,error:$(d.projectId)});return}try{S.sendKnowledgeListResult(d.requestId,{ok:!0,files:Fu(m.repoPath)})}catch(g){S.sendKnowledgeListResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onKnowledgeSave:async d=>{let m=x(d.projectId);if(!m){S.sendKnowledgeSaveResult(d.requestId,{ok:!1,error:$(d.projectId)});return}try{d.append?Ma(m.repoPath,d.role,qu(d.content,d.by),d.level):Bu(m.repoPath,d.role,d.level,d.source,d.name,d.content),y.info(`Knowledge ${d.append?"taught":"saved"}: ${d.role}/${d.level}/${d.name}`),S.sendKnowledgeSaveResult(d.requestId,{ok:!0})}catch(g){S.sendKnowledgeSaveResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onEpicList:async d=>{let m=x(d.projectId);if(!m){S.sendEpicListResult(d.requestId,{ok:!1,error:$(d.projectId)});return}try{let g=s(m.project.repoName);if(d.epicKey){let E=await g.epicChildren(d.epicKey);S.sendEpicListResult(d.requestId,{ok:!0,children:E})}else{let E=await g.searchEpics(m.project.jiraProjectKey);S.sendEpicListResult(d.requestId,{ok:!0,epics:E})}}catch(g){S.sendEpicListResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onEpicSuggest:async d=>{let m=x(d.projectId);if(!m){S.sendEpicSuggestResult(d.requestId,{ok:!1,error:$(d.projectId)});return}try{let g=s(m.project.repoName),E=await g.epicChildren(d.epicKey),P=vu(E);if(!P.length){S.sendEpicSuggestResult(d.requestId,{ok:!1,error:`every child of ${d.epicKey} is already done or in an agent's hands - nothing to sequence`});return}if(P.length===1){S.sendEpicSuggestResult(d.requestId,{ok:!0,issueKey:P[0].key,reason:"It's the only pending ticket left in this epic.",considered:1});return}let V=await Promise.all(P.slice(0,12).map(async re=>{try{let B=await g.getIssue(re.key);return{...re,description:B.description}}catch{return{...re,description:""}}})),ee=(await g.getIssue(d.epicKey).catch(()=>null))?.summary??"";y.info(`Epic suggest: weighing ${V.length} pending children of ${d.epicKey}`);let Y=He(t,m.project,"assist");if("error"in Y){S.sendEpicSuggestResult(d.requestId,{ok:!1,error:Y.error});return}let D=await Y.adapter.run({repoPath:m.repoPath,prompt:wu(d.epicKey,ee,V),timeoutSeconds:150,bin:Y.bin,mode:"read_only",maxTurns:20,sessionId:(0,oi.randomUUID)(),model:d.model||"claude-sonnet-5",onLog:()=>{}}),L=ku(D.resultText,V.map(re=>re.key));if("error"in L){S.sendEpicSuggestResult(d.requestId,{ok:!1,error:L.error});return}y.info(`Epic suggest: ${d.epicKey} -> do ${L.issueKey} first`),S.sendEpicSuggestResult(d.requestId,{ok:!0,issueKey:L.issueKey,reason:L.reason,considered:V.length})}catch(g){S.sendEpicSuggestResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onTeamCreds:async d=>{try{let m=ye()??t;if(m.github?.token&&!m.github.login)try{let{GitHubClient:E}=await Promise.resolve().then(()=>(ht(),fr));m.github.login=await new E(m.github.token).whoami(),fe(m)}catch{}let g=pu(m,d.emails);S.sendTeamCredsResult(d.requestId,{ok:!0,...g})}catch(m){S.sendTeamCredsResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRepoUnmap:d=>{try{let m=ye();if(!m){S.sendRepoUnmapResult(d.requestId,{ok:!1,error:"this runner has no config file"});return}let g=m.repos[d.repoName];if(!g){S.sendRepoUnmapResult(d.requestId,{ok:!0,removedPath:""});return}let E=g.path;delete m.repos[d.repoName];for(let P of Object.keys(m.environments).filter(V=>V.startsWith(`${d.repoName}:`)))delete m.environments[P];m.auditSchedules=m.auditSchedules.filter(P=>P.repoName!==d.repoName),fe(m),Qt(),y.info(`Unmapped "${d.repoName}" (was ${E}) - its project was deleted on the dashboard. The checkout on disk was NOT touched.`),S.sendRepoUnmapResult(d.requestId,{ok:!0,removedPath:E})}catch(m){S.sendRepoUnmapResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupRecheck:d=>{try{let m=x(d.projectId);if(!m){S.sendSetupRecheckResult(d.requestId,{ok:!1,error:$(d.projectId)});return}S.sendSetupRecheckResult(d.requestId,{ok:!0,checks:Pd({repoPath:m.repoPath,environments:d.environments})})}catch(m){S.sendSetupRecheckResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupStatus:async d=>{try{let m=ye()??t,{buildSetupReport:g}=await Promise.resolve().then(()=>(Xp(),Jp)),E=await g(m,d.repoNames,t);S.sendSetupStatusResult(d.requestId,{ok:!0,...E})}catch(m){S.sendSetupStatusResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdGenerate:async d=>{try{let m=x(d.projectId);if(!m){S.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=d.kind==="deploy"?"DEPLOY.md":d.kind==="design"?"DESIGN.md":"CLAUDE.md";y.info(`Setup: drafting ${g} for ${m.project.repoName}`);let E="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.",P=`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.
988
1037
 
989
1038
  Ten things decide whether this document can actually be run:
990
1039
  1. Open with TWO sections, and put every finding in the right one. "## Blockers" is only for things that make the deploy IMPOSSIBLE or produce a broken release: no restart mechanism, an install command that exits non-zero, a build that cannot run. "## Warnings" is for everything that leaves a WORKING release with something degraded - one feature returning an error, a check that is weaker than it should be, a reproducibility risk. Apply this test to each one and state the answer: if the deploy still produces a site that serves its pages, it is a WARNING, never a blocker. A secret that only one route needs is the standard example - the site deploys and works, one endpoint errors, so it is a warning. Blockers are also different from VERIFY: markers, which are questions. Every entry in BOTH sections MUST end with a sentence starting "Fix:" naming the smallest concrete action that closes it and who can do it - someone with shell on that machine, or a code change that can become a ticket. A blocker without a fix is just bad news, and it is read by someone who cannot open the document to go looking for the answer. Write "None" under either heading that has nothing - do not pad it, and do not promote a warning to a blocker to make the list look thorough.
@@ -1003,7 +1052,7 @@ Reply with ONLY the file content - no preamble, no fences around the whole thing
1003
1052
  THESE ENVIRONMENTS ARE ALREADY DECLARED for this project - write a section for EACH one, no more and no fewer, and target each one's own health checks at its own URL:
1004
1053
  `+d.environments.map(B=>`- ${B.name}`+(B.branch?` (branch ${B.branch})`:"")+(B.publicUrl?` serves ${B.publicUrl}`:" - no URL given")+(B.onThisRunner?", its deploy commands run ON THIS MACHINE, in "+(B.workdir?`${B.workdir}`:B.dedicatedCheckout?"a checkout of its own, managed by the runner":"THE MAPPED CHECKOUT - the same directory as every other environment"):", deployed by a DIFFERENT machine - this runner cannot see it")).join(`
1005
1054
  `)+`
1006
- If the repo shows no evidence of how one of them deploys, still write its section with VERIFY: markers rather than dropping it.`:"")+(d.kind==="deploy"?Ha({repoPath:m.repoPath,urls:d.environments.map(B=>B.publicUrl).filter(Boolean)})+as(m.repoPath):""),V=`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.`,ee=`A deploy contract was drafted for this repository and it reported the blockers below - things that stop an automated deploy from running at all. Your job is to tell ONE person, sitting at a terminal on this machine, exactly how to close them.
1055
+ If the repo shows no evidence of how one of them deploys, still write its section with VERIFY: markers rather than dropping it.`:"")+(d.kind==="deploy"?nl({repoPath:m.repoPath,urls:d.environments.map(B=>B.publicUrl).filter(Boolean)})+ps(m.repoPath):""),V=`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.`,ee=`A deploy contract was drafted for this repository and it reported the blockers below - things that stop an automated deploy from running at all. Your job is to tell ONE person, sitting at a terminal on this machine, exactly how to close them.
1007
1056
 
1008
1057
  BLOCKERS AS REPORTED:
1009
1058
  `+d.blockers.map((B,le)=>`${le+1}. ${B}`).join(`
@@ -1042,4 +1091,4 @@ Reply with ONLY the guide - no preamble.`+(d.environments.length?`
1042
1091
 
1043
1092
  THE ENVIRONMENTS AS ALLWRIGHT HAS THEM TODAY - your instructions have to end with these matching reality:
1044
1093
  `+d.environments.map(B=>`- ${B.name}`+(B.branch?` (branch ${B.branch})`:"")+(B.publicUrl?` serves ${B.publicUrl}`:"")+(B.onThisRunner?", deploy commands run ON THIS MACHINE, in "+(B.workdir?B.workdir:B.dedicatedCheckout?"a checkout of its own":"the MAPPED CHECKOUT, shared with every other environment"):", deployed by a DIFFERENT machine - none of the commands below can set it up, and the facts below say nothing about it")).join(`
1045
- `):"")+Ha({repoPath:m.repoPath,urls:d.environments.map(B=>B.publicUrl).filter(Boolean)})+as(m.repoPath),Y=Ke(t,m.project,"assist");if("error"in Y){S.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,content:"",error:Y.error});return}let D=0,re=(await Y.adapter.run({repoPath:m.repoPath,prompt:d.kind==="deploy"?P:d.kind==="design"?V:d.kind==="unblock"?ee:E,timeoutSeconds:600,bin:Y.bin,mode:"read_only",maxTurns:40,sessionId:(0,Xs.randomUUID)(),onLog:(B,le)=>{B==="agent"&&d.streamId&&S.send({type:"chat.stream",requestId:d.streamId,seq:D++,text:le.slice(0,8e3)})}})).resultText.trim();if(!re){S.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:"the agent returned no content - try again"});return}S.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!0,content:re})}catch(m){S.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdSave:async d=>{try{let m=x(d.projectId);if(!m){S.sendSetupClaudeMdSaveResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=d.kind==="deploy"?"DEPLOY.md":d.kind==="design"?"DESIGN.md":"CLAUDE.md",E=await Cl({repoPath:m.repoPath,relPath:g,content:d.content,overwrite:d.overwrite,commitMessage:`Add ${g} (agent-drafted, human-approved via Allwright)`});E.ok&&y.info(`Setup: wrote human-approved ${g} to ${m.repoPath} - ${E.note}`),S.sendSetupClaudeMdSaveResult(d.requestId,E)}catch(m){S.sendSetupClaudeMdSaveResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRepoDocSave:async d=>{try{let m=x(d.projectId);if(!m){S.sendRepoDocSaveResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=await Cl({repoPath:m.repoPath,relPath:d.relPath,content:d.content,overwrite:d.overwrite,commitMessage:`Add ${d.relPath.trim()} (written in Allwright Compose, human-approved)`});g.ok&&y.info(`Saved approved doc ${d.relPath} into ${m.repoPath}`),S.sendRepoDocSaveResult(d.requestId,g)}catch(m){S.sendRepoDocSaveResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditStats:d=>{try{S.sendAuditStatsResult(d.requestId,{ok:!0,byProject:wu(d.projectIds,d.since)})}catch(m){S.sendAuditStatsResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRunnerUpdate:async d=>{if(!process.env.INVOCATION_ID){S.sendRunnerUpdateResult(d.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 E=bn.default.dirname(process.execPath),P=Ge.default.existsSync(bn.default.join(E,"npm"))?bn.default.join(E,"npm"):"npm";(0,Wt.execFile)(P,["install","-g","allwright@latest"],{timeout:18e4,env:{...process.env,PATH:`${E}:${process.env.PATH??""}`}},(V,ee,Y)=>{if(V){S.sendRunnerUpdateResult(d.requestId,{ok:!1,error:`npm install failed: ${(Y||V.message).slice(0,300)} - on the machine run: allwright update && sudo systemctl restart allwright`});return}S.sendRunnerUpdateResult(d.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(f.idle){m();return}if(b){S.sendRunnerUpdateResult(d.requestId,{ok:!0,scheduled:!0,note:"an update is already scheduled and will install once the current work finishes"});return}let g=f.busyCount;S.sendRunnerUpdateResult(d.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(()=>{f.idle&&(clearInterval(b),b=null,m())},5e3)},onTestFix:async d=>{let m=g=>S.sendTestFixResult(d.requestId,{ok:!1,note:g});try{let g=ss(d.runId);if(!g){m("this runner no longer has that PR on file - it may have been decided already");return}let E=t.repos[g.repoName];if(!E){m(`no local checkout mapped for "${g.repoName}" on this machine`);return}let P=Ce(t,g.repoName);if(!P){m("no GitHub token on this runner for that repo");return}let V=await new $e(P).getPullRequest(g.owner,g.repo,g.prNumber);if(!V){m("that pull request no longer exists on GitHub");return}if(V.merged||V.state==="closed"){m("that pull request is already merged or closed - there is nothing left to fix");return}let ee=c.find(re=>re.repoName===g.repoName),Y=g.nextDecisionSeq??1e5,D=(re,B)=>{S.send({type:"run.log",runId:d.runId,seq:Y++,ts:new Date().toISOString(),level:re,message:B}),g.nextDecisionSeq=Y,dt(g)},L=await Wd({cfg:t,repoPath:E.path,branch:g.branch,baseBranch:V.baseRef||"main",issueKey:g.issueKey,agentId:ee?.defaultAgent||Ze.DEFAULT_AGENT_ID,configDir:g.agentConfigDir,failedTests:d.failedTests,timeoutSeconds:900,onLog:D});L.ok&&L.headSha&&(g.headSha=L.headSha,dt(g),S.send({type:"run.status",runId:d.runId,status:"awaiting_approval",headSha:L.headSha,failedTests:L.remaining??[],...L.testsPassed!==void 0?{testsPassed:L.testsPassed}:{},...L.testsTotal!==void 0?{testsTotal:L.testsTotal}:{},...L.costUsd!==void 0?{costUsd:L.costUsd}:{},...L.inputTokens!==void 0?{inputTokens:L.inputTokens}:{},...L.outputTokens!==void 0?{outputTokens:L.outputTokens}:{}})),ct(E.path,{issueKey:g.issueKey,runId:d.runId,title:L.ok?L.headSha?(L.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:L.note.slice(0,500)}),S.sendTestFixResult(d.requestId,L)}catch(g){m(g instanceof Error?g.message.slice(0,300):String(g))}},onRunAnswer:async d=>{try{let m=await f.answerPendingInput(d.runId,d.text,d.answeredBy);S.sendRunAnswerResult(d.requestId,m)}catch(m){S.sendRunAnswerResult(d.requestId,{ok:!1,error:m instanceof Error?m.message.slice(0,300):String(m)})}},onResolveConflict:async d=>{let m=g=>S.sendResolveConflictResult(d.requestId,{ok:!1,note:g});try{let g=ss(d.runId);if(!g){m("this runner no longer has that PR on file - it may have been decided already");return}let E=t.repos[g.repoName];if(!E){m(`no local checkout mapped for "${g.repoName}" on this machine`);return}let P=Ce(t,g.repoName);if(!P){m("no GitHub token on this runner for that repo");return}let V=await new $e(P).getPullRequest(g.owner,g.repo,g.prNumber);if(!V){m("that pull request no longer exists on GitHub");return}if(!V.baseRef){m("GitHub did not report the PR's base branch, so there is nothing to merge in");return}let ee=c.find(re=>re.repoName===g.repoName),Y=g.nextDecisionSeq??1e5,D=(re,B)=>{S.send({type:"run.log",runId:d.runId,seq:Y++,ts:new Date().toISOString(),level:re,message:B}),g.nextDecisionSeq=Y,dt(g)},L=await Zd({cfg:t,repoPath:E.path,branch:g.branch,baseBranch:V.baseRef,issueKey:g.issueKey,agentId:ee?.defaultAgent||Ze.DEFAULT_AGENT_ID,configDir:g.agentConfigDir,timeoutSeconds:900,onLog:D});L.ok&&L.headSha&&(g.headSha=L.headSha,g.conflictNotified=!1,dt(g),S.send({type:"run.pr.conflict",runId:d.runId,conflicted:!1}),S.send({type:"run.status",runId:d.runId,status:"awaiting_approval",headSha:L.headSha,...L.costUsd!==void 0?{costUsd:L.costUsd}:{},...L.inputTokens!==void 0?{inputTokens:L.inputTokens}:{},...L.outputTokens!==void 0?{outputTokens:L.outputTokens}:{}})),S.sendResolveConflictResult(d.requestId,L)}catch(g){m(g instanceof Error?g.message.slice(0,300):String(g))}},onAgentProfiles:d=>{try{let m=E=>{try{return Ge.default.existsSync(E)&&Ge.default.readdirSync(E).length>0}catch{return!1}},g=Object.entries(t.claudeProfiles).map(([E,P])=>({agent:"claude-code",name:E,loggedIn:m(P.configDir)}));S.sendAgentProfilesResult(d.requestId,{ok:!0,profiles:g,defaultLoggedIn:m(bn.default.join(wo.default.homedir(),".claude")),agentsWithoutProfiles:Ze.REGISTERED_AGENTS.filter(E=>!E.capabilities.loginProfiles).map(E=>E.id)})}catch(m){S.sendAgentProfilesResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onJiraUsers:async d=>{try{let m=await n.searchUsers(d.query);S.sendJiraUsersResult(d.requestId,{ok:!0,users:m})}catch(m){S.sendJiraUsersResult(d.requestId,{ok:!1,users:[],error:m instanceof Error?m.message:String(m)})}}});v.transport=S,f=new Qi(t,s,S);let G=Object.values(ur()).filter(d=>d.kind==="implement").map(d=>d.repoPath);ra(Object.values(t.repos).map(d=>d.path),G).catch(()=>{}),S.start(),f.start();let O=()=>{y.info("shutting down"),b&&clearInterval(b),S.stop(),gc(process.pid),Ko(),process.exit(0)},M=!1,W=()=>{if(M){y.warn("second stop signal - exiting NOW; the interrupted run will be marked failed"),O();return}if(M=!0,f.stop(),f.idle){O();return}y.info(`stop requested - no new work will start; waiting for ${f.busyCount} active run(s)/deploy(s) to finish. Send the signal again to kill them immediately.`);let d=setInterval(()=>{f.idle&&(clearInterval(d),O())},3e3)};process.on("SIGINT",W),process.on("SIGTERM",W),process.on("SIGHUP",()=>{try{let d=oe();if(!d.jira)throw new Error("no Jira credentials in the reloaded config");for(let m of Object.keys(t))delete t[m];Object.assign(t,d),n=new Pe(d.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(d){y.error(`config reload failed - keeping the running config: ${d instanceof Error?d.message:String(d)}`)}})}Te.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 t=>{let e=oe();if(t.foreground){ww(e);return}let n=Mn();if(n&&zn(n)){y.info(`already running in the background (pid ${n}). Use \`allwright status\` or \`stop\`.`);return}let r=Fr();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=fc(),i=(0,Wt.spawn)(process.execPath,[process.argv[1],"start","--foreground"],{detached:!0,stdio:["ignore",s,s]});i.unref(),mc(i.pid),y.info(`Runner started in the background (pid ${i.pid}).`),y.info(`Logs: ${fi()}`),y.info("It will keep polling Jira until you run `allwright stop` - closing this terminal is fine.")});Te.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(t=>{let e=Mn();if(!e||!zn(e)){y.info("no background runner is running"),e&&Ge.default.rmSync(qr(),{force:!0});return}if(t.force){process.kill(e,"SIGKILL"),Ge.default.rmSync(qr(),{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.`)});Te.command("status").description("Check whether the background runner is running").action(()=>{let t=Mn();t&&zn(t)?y.info(`running in the background (pid ${t})`):y.info("not running")});Te.parseAsync().catch(t=>{y.error(t instanceof Error?t.message:String(t)),process.exit(1)});
1094
+ `):"")+nl({repoPath:m.repoPath,urls:d.environments.map(B=>B.publicUrl).filter(Boolean)})+ps(m.repoPath),Y=He(t,m.project,"assist");if("error"in Y){S.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,content:"",error:Y.error});return}let D=0,re=(await Y.adapter.run({repoPath:m.repoPath,prompt:d.kind==="deploy"?P:d.kind==="design"?V:d.kind==="unblock"?ee:E,timeoutSeconds:600,bin:Y.bin,mode:"read_only",maxTurns:40,sessionId:(0,oi.randomUUID)(),onLog:(B,le)=>{B==="agent"&&d.streamId&&S.send({type:"chat.stream",requestId:d.streamId,seq:D++,text:le.slice(0,8e3)})}})).resultText.trim();if(!re){S.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:"the agent returned no content - try again"});return}S.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!0,content:re})}catch(m){S.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdSave:async d=>{try{let m=x(d.projectId);if(!m){S.sendSetupClaudeMdSaveResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=d.kind==="deploy"?"DEPLOY.md":d.kind==="design"?"DESIGN.md":"CLAUDE.md",E=await ql({repoPath:m.repoPath,relPath:g,content:d.content,overwrite:d.overwrite,commitMessage:`Add ${g} (agent-drafted, human-approved via Allwright)`});E.ok&&y.info(`Setup: wrote human-approved ${g} to ${m.repoPath} - ${E.note}`),S.sendSetupClaudeMdSaveResult(d.requestId,E)}catch(m){S.sendSetupClaudeMdSaveResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRepoDocSave:async d=>{try{let m=x(d.projectId);if(!m){S.sendRepoDocSaveResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=await ql({repoPath:m.repoPath,relPath:d.relPath,content:d.content,overwrite:d.overwrite,commitMessage:`Add ${d.relPath.trim()} (written in Allwright Compose, human-approved)`});g.ok&&y.info(`Saved approved doc ${d.relPath} into ${m.repoPath}`),S.sendRepoDocSaveResult(d.requestId,g)}catch(m){S.sendRepoDocSaveResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditStats:d=>{try{S.sendAuditStatsResult(d.requestId,{ok:!0,byProject:$u(d.projectIds,d.since)})}catch(m){S.sendAuditStatsResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRunnerUpdate:async d=>{if(!process.env.INVOCATION_ID){S.sendRunnerUpdateResult(d.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 E=Xt.default.dirname(process.execPath),P=Ve.default.existsSync(Xt.default.join(E,"npm"))?Xt.default.join(E,"npm"):"npm";(0,en.execFile)(P,["install","-g","allwright@latest"],{timeout:18e4,env:{...process.env,PATH:`${E}:${process.env.PATH??""}`}},(V,ee,Y)=>{if(V){S.sendRunnerUpdateResult(d.requestId,{ok:!1,error:`npm install failed: ${(Y||V.message).slice(0,300)} - on the machine run: allwright update && sudo systemctl restart allwright`});return}S.sendRunnerUpdateResult(d.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(f.idle){m();return}if(b){S.sendRunnerUpdateResult(d.requestId,{ok:!0,scheduled:!0,note:"an update is already scheduled and will install once the current work finishes"});return}let g=f.busyCount;S.sendRunnerUpdateResult(d.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(()=>{f.idle&&(clearInterval(b),b=null,m())},5e3)},onTestFix:async d=>{let m=g=>S.sendTestFixResult(d.requestId,{ok:!1,note:g});try{let g=us(d.runId);if(!g){m("this runner no longer has that PR on file - it may have been decided already");return}let E=t.repos[g.repoName];if(!E){m(`no local checkout mapped for "${g.repoName}" on this machine`);return}let P=$e(t,g.repoName);if(!P){m("no GitHub token on this runner for that repo");return}let V=await new Pe(P).getPullRequest(g.owner,g.repo,g.prNumber);if(!V){m("that pull request no longer exists on GitHub");return}if(V.merged||V.state==="closed"){m("that pull request is already merged or closed - there is nothing left to fix");return}let ee=c.find(re=>re.repoName===g.repoName),Y=g.nextDecisionSeq??1e5,D=(re,B)=>{S.send({type:"run.log",runId:d.runId,seq:Y++,ts:new Date().toISOString(),level:re,message:B}),g.nextDecisionSeq=Y,pt(g)},L=await ih({cfg:t,repoPath:E.path,branch:g.branch,baseBranch:V.baseRef||"main",issueKey:g.issueKey,agentId:ee?.defaultAgent||We.DEFAULT_AGENT_ID,configDir:g.agentConfigDir,failedTests:d.failedTests,timeoutSeconds:900,onLog:D});L.ok&&L.headSha&&(g.headSha=L.headSha,pt(g),S.send({type:"run.status",runId:d.runId,status:"awaiting_approval",headSha:L.headSha,failedTests:L.remaining??[],...L.testsPassed!==void 0?{testsPassed:L.testsPassed}:{},...L.testsTotal!==void 0?{testsTotal:L.testsTotal}:{},...L.costUsd!==void 0?{costUsd:L.costUsd}:{},...L.inputTokens!==void 0?{inputTokens:L.inputTokens}:{},...L.outputTokens!==void 0?{outputTokens:L.outputTokens}:{}})),dt(E.path,{issueKey:g.issueKey,runId:d.runId,title:L.ok?L.headSha?(L.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:L.note.slice(0,500)}),S.sendTestFixResult(d.requestId,L)}catch(g){m(g instanceof Error?g.message.slice(0,300):String(g))}},onRunAnswer:async d=>{try{let m=await f.answerPendingInput(d.runId,d.text,d.answeredBy);S.sendRunAnswerResult(d.requestId,m)}catch(m){S.sendRunAnswerResult(d.requestId,{ok:!1,error:m instanceof Error?m.message.slice(0,300):String(m)})}},onResolveConflict:async d=>{let m=g=>S.sendResolveConflictResult(d.requestId,{ok:!1,note:g});try{let g=us(d.runId);if(!g){m("this runner no longer has that PR on file - it may have been decided already");return}let E=t.repos[g.repoName];if(!E){m(`no local checkout mapped for "${g.repoName}" on this machine`);return}let P=$e(t,g.repoName);if(!P){m("no GitHub token on this runner for that repo");return}let V=await new Pe(P).getPullRequest(g.owner,g.repo,g.prNumber);if(!V){m("that pull request no longer exists on GitHub");return}if(!V.baseRef){m("GitHub did not report the PR's base branch, so there is nothing to merge in");return}let ee=c.find(re=>re.repoName===g.repoName),Y=g.nextDecisionSeq??1e5,D=(re,B)=>{S.send({type:"run.log",runId:d.runId,seq:Y++,ts:new Date().toISOString(),level:re,message:B}),g.nextDecisionSeq=Y,pt(g)},L=await rh({cfg:t,repoPath:E.path,branch:g.branch,baseBranch:V.baseRef,issueKey:g.issueKey,agentId:ee?.defaultAgent||We.DEFAULT_AGENT_ID,configDir:g.agentConfigDir,timeoutSeconds:900,onLog:D});L.ok&&L.headSha&&(g.headSha=L.headSha,g.conflictNotified=!1,pt(g),S.send({type:"run.pr.conflict",runId:d.runId,conflicted:!1}),S.send({type:"run.status",runId:d.runId,status:"awaiting_approval",headSha:L.headSha,...L.costUsd!==void 0?{costUsd:L.costUsd}:{},...L.inputTokens!==void 0?{inputTokens:L.inputTokens}:{},...L.outputTokens!==void 0?{outputTokens:L.outputTokens}:{}})),S.sendResolveConflictResult(d.requestId,L)}catch(g){m(g instanceof Error?g.message.slice(0,300):String(g))}},onAgentProfiles:d=>{try{let m=E=>{try{return Ve.default.existsSync(E)&&Ve.default.readdirSync(E).length>0}catch{return!1}},g=Object.entries(t.claudeProfiles).map(([E,P])=>({agent:"claude-code",name:E,loggedIn:m(P.configDir)}));S.sendAgentProfilesResult(d.requestId,{ok:!0,profiles:g,defaultLoggedIn:m(Xt.default.join(ai.default.homedir(),".claude")),agentsWithoutProfiles:We.REGISTERED_AGENTS.filter(E=>!E.capabilities.loginProfiles).map(E=>E.id)})}catch(m){S.sendAgentProfilesResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onJiraUsers:async d=>{try{let m=await n.searchUsers(d.query);S.sendJiraUsersResult(d.requestId,{ok:!0,users:m})}catch(m){S.sendJiraUsersResult(d.requestId,{ok:!1,users:[],error:m instanceof Error?m.message:String(m)})}}});v.transport=S,f=new lo(t,s,S);let G=Object.values(gr()).filter(d=>d.kind==="implement").map(d=>d.repoPath);fa(Object.values(t.repos).map(d=>d.path),G).catch(()=>{}),S.start(),f.start();let O=()=>{y.info("shutting down"),b&&clearInterval(b),S.stop(),Rc(process.pid),ta(),process.exit(0)},M=!1,W=()=>{if(M){y.warn("second stop signal - exiting NOW; the interrupted run will be marked failed"),O();return}if(M=!0,f.stop(),f.idle){O();return}y.info(`stop requested - no new work will start; waiting for ${f.busyCount} active run(s)/deploy(s) to finish. Send the signal again to kill them immediately.`);let d=setInterval(()=>{f.idle&&(clearInterval(d),O())},3e3)};process.on("SIGINT",W),process.on("SIGTERM",W),process.on("SIGHUP",()=>{try{let d=oe();if(!d.jira)throw new Error("no Jira credentials in the reloaded config");for(let m of Object.keys(t))delete t[m];Object.assign(t,d),n=new Ne(d.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(d){y.error(`config reload failed - keeping the running config: ${d instanceof Error?d.message:String(d)}`)}})}xe.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 t=>{let e=oe();if(t.foreground){Vw(e);return}let n=Fn();if(n&&Bn(n)){y.info(`already running in the background (pid ${n}). Use \`allwright status\` or \`stop\`.`);return}let r=Vr();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=xc(),i=(0,en.spawn)(process.execPath,[process.argv[1],"start","--foreground"],{detached:!0,stdio:["ignore",s,s]});i.unref(),Ec(i.pid),y.info(`Runner started in the background (pid ${i.pid}).`),y.info(`Logs: ${ki()}`),y.info("It will keep polling Jira until you run `allwright stop` - closing this terminal is fine.")});xe.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(t=>{let e=Fn();if(!e||!Bn(e)){y.info("no background runner is running"),e&&Ve.default.rmSync(Zr(),{force:!0});return}if(t.force){process.kill(e,"SIGKILL"),Ve.default.rmSync(Zr(),{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.`)});xe.command("status").description("Check whether the background runner is running").action(()=>{let t=Fn();t&&Bn(t)?y.info(`running in the background (pid ${t})`):y.info("not running")});xe.parseAsync().catch(t=>{y.error(t instanceof Error?t.message:String(t)),process.exit(1)});