allwright 1.59.0 → 1.60.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 +188 -178
  2. package/package.json +1 -1
package/bin/allwright.js CHANGED
@@ -1,32 +1,32 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Kf=Object.create;var fi=Object.defineProperty;var Hf=Object.getOwnPropertyDescriptor;var Gf=Object.getOwnPropertyNames;var Zf=Object.getPrototypeOf,Wf=Object.prototype.hasOwnProperty;var ve=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var ae=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}},on=(t,e)=>{for(var n in e)fi(t,n,{get:e[n],enumerable:!0})},Tc=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Gf(e))!Wf.call(t,s)&&s!==n&&fi(t,s,{get:()=>e[s],enumerable:!(r=Hf(e,s))||r.enumerable});return t};var I=(t,e,n)=>(n=t!=null?Kf(Zf(t)):{},Tc(e||!t||!t.__esModule?fi(n,"default",{value:t,enumerable:!0}):n,t)),Vf=t=>Tc(fi({},"__esModule",{value:!0}),t);var js=ae(Yo=>{var mi=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 mi{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Yo.CommanderError=mi;Yo.InvalidArgumentError=Jo});var gi=ae(Qo=>{var{InvalidArgumentError:Jf}=js(),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 Jf(`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 Yf(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}Qo.Argument=Xo;Qo.humanReadableArgName=Yf});var ta=ae(xc=>{var{humanReadableArgName:Xf}=gi(),ea=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=>Xf(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(k,x){if(x){let A=`${k.padEnd(r+o)}${x}`;return n.wrap(A,s-i,r+o)}return k}function c(k){return k.join(`
2
+ "use strict";var nm=Object.create;var Xo=Object.defineProperty;var rm=Object.getOwnPropertyDescriptor;var sm=Object.getOwnPropertyNames;var im=Object.getPrototypeOf,om=Object.prototype.hasOwnProperty;var ye=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var ae=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}},an=(t,e)=>{for(var n in e)Xo(t,n,{get:e[n],enumerable:!0})},am=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of sm(e))!om.call(t,s)&&s!==n&&Xo(t,s,{get:()=>e[s],enumerable:!(r=rm(e,s))||r.enumerable});return t};var I=(t,e,n)=>(n=t!=null?nm(im(t)):{},am(e||!t||!t.__esModule?Xo(n,"default",{value:t,enumerable:!0}):n,t));var Ns=ae(ea=>{var mi=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}},Qo=class extends mi{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};ea.CommanderError=mi;ea.InvalidArgumentError=Qo});var gi=ae(na=>{var{InvalidArgumentError:lm}=Ns(),ta=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 lm(`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 cm(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}na.Argument=ta;na.humanReadableArgName=cm});var sa=ae(Nc=>{var{humanReadableArgName:um}=gi(),ra=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=>um(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(k,x){if(x){let A=`${k.padEnd(r+o)}${x}`;return n.wrap(A,s-i,r+o)}return k}function c(k){return k.join(`
3
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(k=>l(n.argumentTerm(k),n.argumentDescription(k)));f.length>0&&(u=u.concat(["Arguments:",c(f),""]));let w=n.visibleOptions(e).map(k=>l(n.optionTerm(k),n.optionDescription(k)));if(w.length>0&&(u=u.concat(["Options:",c(w),""])),this.showGlobalOptions){let k=n.visibleGlobalOptions(e).map(x=>l(n.optionTerm(x),n.optionDescription(x)));k.length>0&&(u=u.concat(["Global Options:",c(k),""]))}let b=n.visibleCommands(e).map(k=>l(n.subcommandTerm(k),n.subcommandDescription(k)));return b.length>0&&(u=u.concat(["Commands:",c(b),""])),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),w="\\s\u200B",b=new RegExp(`
7
7
  |.{1,${l-1}}([${w}]|$)|[^${w}]+?([${w}]|$)`,"g"),k=u.match(b)||[];return c+k.map((x,A)=>x===`
8
8
  `?"":(A>0?p:"")+x.trimEnd()).join(`
9
- `)}};xc.Help=ea});var ia=ae(sa=>{var{InvalidArgumentError:Qf}=js(),na=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=tm(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 Qf(`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 em(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},ra=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 em(t){return t.split("-").reduce((e,n)=>e+n[0].toUpperCase()+n.slice(1))}function tm(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}}sa.Option=na;sa.DualOptions=ra});var Ic=ae(Rc=>{function nm(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 rm(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=nm(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
+ `)}};Nc.Help=ra});var la=ae(aa=>{var{InvalidArgumentError:dm}=Ns(),ia=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=pm(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 dm(`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 hm(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},oa=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 hm(t){return t.split("-").reduce((e,n)=>e+n[0].toUpperCase()+n.slice(1))}function pm(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}}aa.Option=ia;aa.DualOptions=oa});var Mc=ae(Oc=>{function fm(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 mm(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=fm(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]}?)`:""}Rc.suggestSimilar=rm});var Pc=ae($c=>{var sm=require("node:events").EventEmitter,oa=require("node:child_process"),Nt=require("node:path"),aa=require("node:fs"),ye=require("node:process"),{Argument:im,humanReadableArgName:om}=gi(),{CommanderError:la}=js(),{Help:am}=ta(),{Option:Ec,DualOptions:lm}=ia(),{suggestSimilar:Ac}=Ic(),ca=class t extends sm{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=>ye.stdout.write(n),writeErr:n=>ye.stderr.write(n),getOutHelpWidth:()=>ye.stdout.isTTY?ye.stdout.columns:void 0,getErrHelpWidth:()=>ye.stderr.isTTY?ye.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 am,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 im(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 la(e,n,r)),ye.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 Ec(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 Ec)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){ye.versions?.electron&&(n.from="electron");let s=ye.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(n.from="eval")}e===void 0&&(e=ye.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":ye.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 w=Nt.resolve(p,f);if(aa.existsSync(w))return w;if(s.includes(Nt.extname(f)))return;let b=s.find(k=>aa.existsSync(`${w}${k}`));if(b)return`${w}${b}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,l=this._executableDir||"";if(this._scriptPath){let p;try{p=aa.realpathSync(this._scriptPath)}catch{p=this._scriptPath}l=Nt.resolve(Nt.dirname(p),l)}if(l){let p=i(l,o);if(!p&&!e._executableFile&&this._scriptPath){let f=Nt.basename(this._scriptPath,Nt.extname(this._scriptPath));f!==this._name&&(p=i(l,`${f}-${e._name}`))}o=p||o}r=s.includes(Nt.extname(o));let c;ye.platform!=="win32"?r?(n.unshift(o),n=Cc(ye.execArgv).concat(n),c=oa.spawn(ye.argv[0],n,{stdio:"inherit"})):c=oa.spawn(o,n,{stdio:"inherit"}):(n.unshift(o),n=Cc(ye.execArgv).concat(n),c=oa.spawn(ye.execPath,n,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{ye.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 la(p,"commander.executeSubCommandAsync","(close)")):ye.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",w=`'${o}' does not exist
11
+ (Did you mean ${r[0]}?)`:""}Oc.suggestSimilar=mm});var qc=ae(Uc=>{var gm=require("node:events").EventEmitter,ca=require("node:child_process"),Ot=require("node:path"),ua=require("node:fs"),be=require("node:process"),{Argument:ym,humanReadableArgName:bm}=gi(),{CommanderError:da}=Ns(),{Help:wm}=sa(),{Option:zc,DualOptions:vm}=la(),{suggestSimilar:Dc}=Mc(),ha=class t extends gm{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=>be.stdout.write(n),writeErr:n=>be.stderr.write(n),getOutHelpWidth:()=>be.stdout.isTTY?be.stdout.columns:void 0,getErrHelpWidth:()=>be.stderr.isTTY?be.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 wm,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 ym(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 da(e,n,r)),be.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 zc(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 zc)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){be.versions?.electron&&(n.from="electron");let s=be.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(n.from="eval")}e===void 0&&(e=be.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":be.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 w=Ot.resolve(p,f);if(ua.existsSync(w))return w;if(s.includes(Ot.extname(f)))return;let b=s.find(k=>ua.existsSync(`${w}${k}`));if(b)return`${w}${b}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,l=this._executableDir||"";if(this._scriptPath){let p;try{p=ua.realpathSync(this._scriptPath)}catch{p=this._scriptPath}l=Ot.resolve(Ot.dirname(p),l)}if(l){let p=i(l,o);if(!p&&!e._executableFile&&this._scriptPath){let f=Ot.basename(this._scriptPath,Ot.extname(this._scriptPath));f!==this._name&&(p=i(l,`${f}-${e._name}`))}o=p||o}r=s.includes(Ot.extname(o));let c;be.platform!=="win32"?r?(n.unshift(o),n=Lc(be.execArgv).concat(n),c=ca.spawn(be.argv[0],n,{stdio:"inherit"})):c=ca.spawn(o,n,{stdio:"inherit"}):(n.unshift(o),n=Lc(be.execArgv).concat(n),c=ca.spawn(be.execPath,n,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{be.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 da(p,"commander.executeSubCommandAsync","(close)")):be.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",w=`'${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(w)}else if(p.code==="EACCES")throw new Error(`'${o}' not executable`);if(!u)ye.exit(1);else{let f=new la(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(w)}else if(p.code==="EACCES")throw new Error(`'${o}' not executable`);if(!u)be.exit(1);else{let f=new da(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 ye.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()}`,ye.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new lm(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=Ac(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=Ac(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=>om(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=Nt.basename(e,Nt.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=ye.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 be.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()}`,be.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new vm(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=Dc(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=Dc(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=>bm(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=Ot.basename(e,Ot.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=be.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 Cc(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})}$c.Command=ca});var Mc=ae(Xe=>{var{Argument:jc}=gi(),{Command:ua}=Pc(),{CommanderError:cm,InvalidArgumentError:Nc}=js(),{Help:um}=ta(),{Option:Oc}=ia();Xe.program=new ua;Xe.createCommand=t=>new ua(t);Xe.createOption=(t,e)=>new Oc(t,e);Xe.createArgument=(t,e)=>new jc(t,e);Xe.Command=ua;Xe.Option=Oc;Xe.Argument=jc;Xe.Help=um;Xe.CommanderError=cm;Xe.InvalidArgumentError=Nc;Xe.InvalidOptionArgumentError=Nc});var se,da,D,wt,Ns=ve(()=>{(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})(se||(se={}));(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(da||(da={}));D=se.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),wt=t=>{switch(typeof t){case"undefined":return D.undefined;case"string":return D.string;case"number":return Number.isNaN(t)?D.nan:D.number;case"boolean":return D.boolean;case"function":return D.function;case"bigint":return D.bigint;case"symbol":return D.symbol;case"object":return Array.isArray(t)?D.array:t===null?D.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?D.promise:typeof Map<"u"&&t instanceof Map?D.map:typeof Set<"u"&&t instanceof Set?D.set:typeof Date<"u"&&t instanceof Date?D.date:D.object;default:return D.unknown}}});var E,dm,Le,yi=ve(()=>{Ns();E=se.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"]),dm=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Le=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,se.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()}};Le.create=t=>new Le(t)});var hm,Ot,ha=ve(()=>{yi();Ns();hm=(t,e)=>{let n;switch(t.code){case E.invalid_type:t.received===D.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case E.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,se.jsonStringifyReplacer)}`;break;case E.unrecognized_keys:n=`Unrecognized key(s) in object: ${se.joinValues(t.keys,", ")}`;break;case E.invalid_union:n="Invalid input";break;case E.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${se.joinValues(t.options)}`;break;case E.invalid_enum_value:n=`Invalid enum value. Expected ${se.joinValues(t.options)}, received '${t.received}'`;break;case E.invalid_arguments:n="Invalid function arguments";break;case E.invalid_return_type:n="Invalid function return type";break;case E.invalid_date:n="Invalid date";break;case E.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}"`:se.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case E.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 E.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 E.custom:n="Invalid input";break;case E.invalid_intersection_types:n="Intersection results could not be merged";break;case E.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case E.not_finite:n="Number must be finite";break;default:n=e.defaultError,se.assertNever(t)}return{message:n}},Ot=hm});function pm(t){Lc=t}function Fr(){return Lc}var Lc,bi=ve(()=>{ha();Lc=Ot});function N(t,e){let n=Fr(),r=Os({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Ot?void 0:Ot].filter(s=>!!s)});t.common.issues.push(r)}var Os,fm,Ie,W,Pn,Ae,wi,vi,an,Br,pa=ve(()=>{bi();ha();Os=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}},fm=[];Ie=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 W;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 W;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}}},W=Object.freeze({status:"aborted"}),Pn=t=>({status:"dirty",value:t}),Ae=t=>({status:"valid",value:t}),wi=t=>t.status==="aborted",vi=t=>t.status==="dirty",an=t=>t.status==="valid",Br=t=>typeof Promise<"u"&&t instanceof Promise});var Uc=ve(()=>{});var F,qc=ve(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(F||(F={}))});function Q(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}}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 $m(t){return new RegExp(`^${Hc(t)}$`)}function Gc(t){let e=`${Kc}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 Pm(t,e){return!!((e==="v4"||!e)&&Tm.test(t)||(e==="v6"||!e)&&Rm.test(t))}function jm(t,e){if(!vm.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 Nm(t,e){return!!((e==="v4"||!e)&&xm.test(t)||(e==="v6"||!e)&&Im.test(t))}function Om(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}function Kr(t){if(t instanceof Ue){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=Qe.create(Kr(r))}return new Ue({...t._def,shape:()=>e})}else return t instanceof Dt?new Dt({...t._def,type:Kr(t.element)}):t instanceof Qe?Qe.create(Kr(t.unwrap())):t instanceof kt?kt.create(Kr(t.unwrap())):t instanceof vt?vt.create(t.items.map(e=>Kr(e))):t}function ma(t,e){let n=wt(t),r=wt(e);if(t===e)return{valid:!0,data:t};if(n===D.object&&r===D.object){let s=se.objectKeys(e),i=se.objectKeys(t).filter(l=>s.indexOf(l)!==-1),o={...t,...e};for(let l of i){let c=ma(t[l],e[l]);if(!c.valid)return{valid:!1};o[l]=c.data}return{valid:!0,data:o}}else if(n===D.array&&r===D.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=ma(o,l);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===D.date&&r===D.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function Zc(t,e){return new Bn({values:t,typeName:V.ZodEnum,...Q(e)})}function Bc(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function Wc(t,e={},n){return t?cn.create().superRefine((r,s)=>{let i=t(r);if(i instanceof Promise)return i.then(o=>{if(!o){let l=Bc(e,r),c=l.fatal??n??!0;s.addIssue({code:"custom",...l,fatal:c})}});if(!i){let o=Bc(e,r),l=o.fatal??n??!0;s.addIssue({code:"custom",...o,fatal:l})}}):cn.create()}var et,Fc,re,mm,gm,ym,bm,wm,vm,km,_m,Sm,fa,Tm,xm,Rm,Im,Em,Am,Kc,Cm,ln,jn,Nn,On,Mn,Hr,zn,Dn,cn,zt,dt,Gr,Dt,Ue,Ln,Mt,ki,Un,vt,_i,Zr,Wr,Si,qn,Fn,Bn,Kn,un,tt,Qe,kt,Hn,Gn,Vr,Mm,Ms,zs,Zn,zm,V,Dm,Vc,Jc,Lm,Um,Yc,qm,Fm,Bm,Km,Hm,Gm,Zm,Wm,Vm,Jm,Ym,Xm,Qm,eg,tg,ng,rg,sg,ig,og,ag,lg,cg,ug,dg,hg,pg,fg,mg,gg,yg,bg,wg,vg,Xc=ve(()=>{yi();bi();qc();pa();Ns();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}},Fc=(t,e)=>{if(an(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 Le(t.common.issues);return this._error=n,this._error}}};re=class{get description(){return this._def.description}_getType(e){return wt(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:wt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ie,ctx:{common:e.parent.common,data:e.data,parsedType:wt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(Br(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:wt(e)},s=this._parseSync({data:e,path:r.path,parent:r});return Fc(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:wt(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return an(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=>an(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:wt(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(Br(s)?s:Promise.resolve(s));return Fc(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:E.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 tt({schema:this,typeName:V.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 kt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Dt.create(this)}promise(){return un.create(this,this._def)}or(e){return Ln.create([this,e],this._def)}and(e){return Un.create(this,e,this._def)}transform(e){return new tt({...Q(this._def),schema:this,typeName:V.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new Hn({...Q(this._def),innerType:this,defaultValue:n,typeName:V.ZodDefault})}brand(){return new Ms({typeName:V.ZodBranded,type:this,...Q(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Gn({...Q(this._def),innerType:this,catchValue:n,typeName:V.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return zs.create(this,e)}readonly(){return Zn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},mm=/^c[^\s-]{8,}$/i,gm=/^[0-9a-z]+$/,ym=/^[0-9A-HJKMNP-TV-Z]{26}$/i,bm=/^[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,wm=/^[a-z0-9_-]{21}$/i,vm=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,km=/^[-+]?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)?)??$/,_m=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Sm="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Tm=/^(?:(?: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])$/,xm=/^(?:(?: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])$/,Rm=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Im=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Em=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Am=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Kc="((\\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])))",Cm=new RegExp(`^${Kc}$`);ln=class t extends re{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==D.string){let i=this._getOrReturnCtx(e);return N(i,{code:E.invalid_type,expected:D.string,received:i.parsedType}),W}let r=new Ie,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:E.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:E.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:E.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):l&&N(s,{code:E.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")_m.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"email",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")fa||(fa=new RegExp(Sm,"u")),fa.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"emoji",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")bm.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"uuid",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")wm.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"nanoid",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")mm.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"cuid",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")gm.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"cuid2",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")ym.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"ulid",code:E.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:E.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:E.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:E.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:E.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:E.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Gc(i).test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{code:E.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?Cm.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{code:E.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?$m(i).test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{code:E.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?km.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"duration",code:E.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?Pm(e.data,i.version)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"ip",code:E.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?jm(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"jwt",code:E.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?Nm(e.data,i.version)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"cidr",code:E.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?Em.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"base64",code:E.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?Am.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"base64url",code:E.invalid_string,message:i.message}),r.dirty()):se.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:E.invalid_string,...F.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...F.errToObj(e)})}url(e){return this._addCheck({kind:"url",...F.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...F.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...F.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...F.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...F.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...F.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...F.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...F.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...F.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...F.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...F.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...F.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,...F.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,...F.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...F.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...F.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...F.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...F.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...F.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...F.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...F.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...F.errToObj(n)})}nonempty(e){return this.min(1,F.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}};ln.create=t=>new ln({checks:[],typeName:V.ZodString,coerce:t?.coerce??!1,...Q(t)});jn=class t extends re{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)!==D.number){let i=this._getOrReturnCtx(e);return N(i,{code:E.invalid_type,expected:D.number,received:i.parsedType}),W}let r,s=new Ie;for(let i of this._def.checks)i.kind==="int"?se.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),N(r,{code:E.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:E.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:E.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Om(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),N(r,{code:E.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:E.not_finite,message:i.message}),s.dirty()):se.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,F.toString(n))}gt(e,n){return this.setLimit("min",e,!1,F.toString(n))}lte(e,n){return this.setLimit("max",e,!0,F.toString(n))}lt(e,n){return this.setLimit("max",e,!1,F.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:F.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:F.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:F.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:F.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:F.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:F.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:F.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:F.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:F.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:F.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"&&se.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)}};jn.create=t=>new jn({checks:[],typeName:V.ZodNumber,coerce:t?.coerce||!1,...Q(t)});Nn=class t extends re{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)!==D.bigint)return this._getInvalidInput(e);let r,s=new Ie;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:E.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:E.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:E.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):se.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return N(n,{code:E.invalid_type,expected:D.bigint,received:n.parsedType}),W}gte(e,n){return this.setLimit("min",e,!0,F.toString(n))}gt(e,n){return this.setLimit("min",e,!1,F.toString(n))}lte(e,n){return this.setLimit("max",e,!0,F.toString(n))}lt(e,n){return this.setLimit("max",e,!1,F.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:F.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:F.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:F.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:F.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:F.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:F.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}};Nn.create=t=>new Nn({checks:[],typeName:V.ZodBigInt,coerce:t?.coerce??!1,...Q(t)});On=class extends re{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==D.boolean){let r=this._getOrReturnCtx(e);return N(r,{code:E.invalid_type,expected:D.boolean,received:r.parsedType}),W}return Ae(e.data)}};On.create=t=>new On({typeName:V.ZodBoolean,coerce:t?.coerce||!1,...Q(t)});Mn=class t extends re{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==D.date){let i=this._getOrReturnCtx(e);return N(i,{code:E.invalid_type,expected:D.date,received:i.parsedType}),W}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return N(i,{code:E.invalid_date}),W}let r=new Ie,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),N(s,{code:E.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:E.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):se.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:F.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:F.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}};Mn.create=t=>new Mn({checks:[],coerce:t?.coerce||!1,typeName:V.ZodDate,...Q(t)});Hr=class extends re{_parse(e){if(this._getType(e)!==D.symbol){let r=this._getOrReturnCtx(e);return N(r,{code:E.invalid_type,expected:D.symbol,received:r.parsedType}),W}return Ae(e.data)}};Hr.create=t=>new Hr({typeName:V.ZodSymbol,...Q(t)});zn=class extends re{_parse(e){if(this._getType(e)!==D.undefined){let r=this._getOrReturnCtx(e);return N(r,{code:E.invalid_type,expected:D.undefined,received:r.parsedType}),W}return Ae(e.data)}};zn.create=t=>new zn({typeName:V.ZodUndefined,...Q(t)});Dn=class extends re{_parse(e){if(this._getType(e)!==D.null){let r=this._getOrReturnCtx(e);return N(r,{code:E.invalid_type,expected:D.null,received:r.parsedType}),W}return Ae(e.data)}};Dn.create=t=>new Dn({typeName:V.ZodNull,...Q(t)});cn=class extends re{constructor(){super(...arguments),this._any=!0}_parse(e){return Ae(e.data)}};cn.create=t=>new cn({typeName:V.ZodAny,...Q(t)});zt=class extends re{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ae(e.data)}};zt.create=t=>new zt({typeName:V.ZodUnknown,...Q(t)});dt=class extends re{_parse(e){let n=this._getOrReturnCtx(e);return N(n,{code:E.invalid_type,expected:D.never,received:n.parsedType}),W}};dt.create=t=>new dt({typeName:V.ZodNever,...Q(t)});Gr=class extends re{_parse(e){if(this._getType(e)!==D.undefined){let r=this._getOrReturnCtx(e);return N(r,{code:E.invalid_type,expected:D.void,received:r.parsedType}),W}return Ae(e.data)}};Gr.create=t=>new Gr({typeName:V.ZodVoid,...Q(t)});Dt=class t extends re{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==D.array)return N(n,{code:E.invalid_type,expected:D.array,received:n.parsedType}),W;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?E.too_big:E.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:E.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:E.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=>Ie.mergeArray(r,o));let i=[...n.data].map((o,l)=>s.type._parseSync(new et(n,o,n.path,l)));return Ie.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:F.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:F.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:F.toString(n)}})}nonempty(e){return this.min(1,e)}};Dt.create=(t,e)=>new Dt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:V.ZodArray,...Q(e)});Ue=class t extends re{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=se.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==D.object){let u=this._getOrReturnCtx(e);return N(u,{code:E.invalid_type,expected:D.object,received:u.parsedType}),W}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),l=[];if(!(this._def.catchall instanceof dt&&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 dt){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:E.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,w=await p.value;u.push({key:f,value:w,alwaysSet:p.alwaysSet})}return u}).then(u=>Ie.mergeObjectSync(r,u)):Ie.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return F.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:F.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:V.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 se.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 se.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return Kr(this)}partial(e){let n={};for(let r of se.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 se.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 Zc(se.objectKeys(this.shape))}};Ue.create=(t,e)=>new Ue({shape:()=>t,unknownKeys:"strip",catchall:dt.create(),typeName:V.ZodObject,...Q(e)});Ue.strictCreate=(t,e)=>new Ue({shape:()=>t,unknownKeys:"strict",catchall:dt.create(),typeName:V.ZodObject,...Q(e)});Ue.lazycreate=(t,e)=>new Ue({shape:t,unknownKeys:"strip",catchall:dt.create(),typeName:V.ZodObject,...Q(e)});Ln=class extends re{_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 Le(l.ctx.common.issues));return N(n,{code:E.invalid_union,unionErrors:o}),W}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 Le(c));return N(n,{code:E.invalid_union,unionErrors:l}),W}}get options(){return this._def.options}};Ln.create=(t,e)=>new Ln({options:t,typeName:V.ZodUnion,...Q(e)});Mt=t=>t instanceof qn?Mt(t.schema):t instanceof tt?Mt(t.innerType()):t instanceof Fn?[t.value]:t instanceof Bn?t.options:t instanceof Kn?se.objectValues(t.enum):t instanceof Hn?Mt(t._def.innerType):t instanceof zn?[void 0]:t instanceof Dn?[null]:t instanceof Qe?[void 0,...Mt(t.unwrap())]:t instanceof kt?[null,...Mt(t.unwrap())]:t instanceof Ms||t instanceof Zn?Mt(t.unwrap()):t instanceof Gn?Mt(t._def.innerType):[],ki=class t extends re{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==D.object)return N(n,{code:E.invalid_type,expected:D.object,received:n.parsedType}),W;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:E.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),W)}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=Mt(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:V.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...Q(r)})}};Un=class extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=(i,o)=>{if(wi(i)||wi(o))return W;let l=ma(i.value,o.value);return l.valid?((vi(i)||vi(o))&&n.dirty(),{status:n.value,value:l.data}):(N(r,{code:E.invalid_intersection_types}),W)};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}))}};Un.create=(t,e,n)=>new Un({left:t,right:e,typeName:V.ZodIntersection,...Q(n)});vt=class t extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==D.array)return N(r,{code:E.invalid_type,expected:D.array,received:r.parsedType}),W;if(r.data.length<this._def.items.length)return N(r,{code:E.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),W;!this._def.rest&&r.data.length>this._def.items.length&&(N(r,{code:E.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=>Ie.mergeArray(n,o)):Ie.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};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:V.ZodTuple,rest:null,...Q(e)})};_i=class t extends re{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!==D.object)return N(r,{code:E.invalid_type,expected:D.object,received:r.parsedType}),W;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?Ie.mergeObjectAsync(n,s):Ie.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof re?new t({keyType:e,valueType:n,typeName:V.ZodRecord,...Q(r)}):new t({keyType:ln.create(),valueType:e,typeName:V.ZodRecord,...Q(n)})}},Zr=class extends re{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!==D.map)return N(r,{code:E.invalid_type,expected:D.map,received:r.parsedType}),W;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 W;(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 W;(u.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(u.value,p.value)}return{status:n.value,value:l}}}};Zr.create=(t,e,n)=>new Zr({valueType:e,keyType:t,typeName:V.ZodMap,...Q(n)});Wr=class t extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==D.set)return N(r,{code:E.invalid_type,expected:D.set,received:r.parsedType}),W;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(N(r,{code:E.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:E.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 W;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:F.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:F.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};Wr.create=(t,e)=>new Wr({valueType:t,minSize:null,maxSize:null,typeName:V.ZodSet,...Q(e)});Si=class t extends re{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==D.function)return N(n,{code:E.invalid_type,expected:D.function,received:n.parsedType}),W;function r(l,c){return Os({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Fr(),Ot].filter(u=>!!u),issueData:{code:E.invalid_arguments,argumentsError:c}})}function s(l,c){return Os({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Fr(),Ot].filter(u=>!!u),issueData:{code:E.invalid_return_type,returnTypeError:c}})}let i={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof un){let l=this;return Ae(async function(...c){let u=new Le([]),p=await l._def.args.parseAsync(c,i).catch(b=>{throw u.addIssue(r(c,b)),u}),f=await Reflect.apply(o,this,p);return await l._def.returns._def.type.parseAsync(f,i).catch(b=>{throw u.addIssue(s(f,b)),u})})}else{let l=this;return Ae(function(...c){let u=l._def.args.safeParse(c,i);if(!u.success)throw new Le([r(c,u.error)]);let p=Reflect.apply(o,this,u.data),f=l._def.returns.safeParse(p,i);if(!f.success)throw new Le([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(zt.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(zt.create()),returns:n||zt.create(),typeName:V.ZodFunction,...Q(r)})}},qn=class extends re{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})}};qn.create=(t,e)=>new qn({getter:t,typeName:V.ZodLazy,...Q(e)});Fn=class extends re{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return N(n,{received:n.data,code:E.invalid_literal,expected:this._def.value}),W}return{status:"valid",value:e.data}}get value(){return this._def.value}};Fn.create=(t,e)=>new Fn({value:t,typeName:V.ZodLiteral,...Q(e)});Bn=class t extends re{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return N(n,{expected:se.joinValues(r),received:n.parsedType,code:E.invalid_type}),W}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:E.invalid_enum_value,options:r}),W}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})}};Bn.create=Zc;Kn=class extends re{_parse(e){let n=se.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==D.string&&r.parsedType!==D.number){let s=se.objectValues(n);return N(r,{expected:se.joinValues(s),received:r.parsedType,code:E.invalid_type}),W}if(this._cache||(this._cache=new Set(se.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=se.objectValues(n);return N(r,{received:r.data,code:E.invalid_enum_value,options:s}),W}return Ae(e.data)}get enum(){return this._def.values}};Kn.create=(t,e)=>new Kn({values:t,typeName:V.ZodNativeEnum,...Q(e)});un=class extends re{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==D.promise&&n.common.async===!1)return N(n,{code:E.invalid_type,expected:D.promise,received:n.parsedType}),W;let r=n.parsedType===D.promise?n.data:Promise.resolve(n.data);return Ae(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};un.create=(t,e)=>new un({type:t,typeName:V.ZodPromise,...Q(e)});tt=class extends re{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===V.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 W;let c=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return c.status==="aborted"?W:c.status==="dirty"?Pn(c.value):n.value==="dirty"?Pn(c.value):c});{if(n.value==="aborted")return W;let l=this._def.schema._parseSync({data:o,path:r.path,parent:r});return l.status==="aborted"?W:l.status==="dirty"?Pn(l.value):n.value==="dirty"?Pn(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"?W:(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"?W:(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(!an(o))return W;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=>an(o)?Promise.resolve(s.transform(o.value,i)).then(l=>({status:n.value,value:l})):W);se.assertNever(s)}};tt.create=(t,e,n)=>new tt({schema:t,typeName:V.ZodEffects,effect:e,...Q(n)});tt.createWithPreprocess=(t,e,n)=>new tt({schema:e,effect:{type:"preprocess",transform:t},typeName:V.ZodEffects,...Q(n)});Qe=class extends re{_parse(e){return this._getType(e)===D.undefined?Ae(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Qe.create=(t,e)=>new Qe({innerType:t,typeName:V.ZodOptional,...Q(e)});kt=class extends re{_parse(e){return this._getType(e)===D.null?Ae(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};kt.create=(t,e)=>new kt({innerType:t,typeName:V.ZodNullable,...Q(e)});Hn=class extends re{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===D.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Hn.create=(t,e)=>new Hn({innerType:t,typeName:V.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Q(e)});Gn=class extends re{_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 Br(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Le(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Le(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Gn.create=(t,e)=>new Gn({innerType:t,typeName:V.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Q(e)});Vr=class extends re{_parse(e){if(this._getType(e)!==D.nan){let r=this._getOrReturnCtx(e);return N(r,{code:E.invalid_type,expected:D.nan,received:r.parsedType}),W}return{status:"valid",value:e.data}}};Vr.create=t=>new Vr({typeName:V.ZodNaN,...Q(t)});Mm=Symbol("zod_brand"),Ms=class extends re{_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}},zs=class t extends re{_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"?W:i.status==="dirty"?(n.dirty(),Pn(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"?W: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:V.ZodPipeline})}},Zn=class extends re{_parse(e){let n=this._def.innerType._parse(e),r=s=>(an(s)&&(s.value=Object.freeze(s.value)),s);return Br(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};Zn.create=(t,e)=>new Zn({innerType:t,typeName:V.ZodReadonly,...Q(e)});zm={object:Ue.lazycreate};(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"})(V||(V={}));Dm=(t,e={message:`Input not instance of ${t.name}`})=>Wc(n=>n instanceof t,e),Vc=ln.create,Jc=jn.create,Lm=Vr.create,Um=Nn.create,Yc=On.create,qm=Mn.create,Fm=Hr.create,Bm=zn.create,Km=Dn.create,Hm=cn.create,Gm=zt.create,Zm=dt.create,Wm=Gr.create,Vm=Dt.create,Jm=Ue.create,Ym=Ue.strictCreate,Xm=Ln.create,Qm=ki.create,eg=Un.create,tg=vt.create,ng=_i.create,rg=Zr.create,sg=Wr.create,ig=Si.create,og=qn.create,ag=Fn.create,lg=Bn.create,cg=Kn.create,ug=un.create,dg=tt.create,hg=Qe.create,pg=kt.create,fg=tt.createWithPreprocess,mg=zs.create,gg=()=>Vc().optional(),yg=()=>Jc().optional(),bg=()=>Yc().optional(),wg={string:(t=>ln.create({...t,coerce:!0})),number:(t=>jn.create({...t,coerce:!0})),boolean:(t=>On.create({...t,coerce:!0})),bigint:(t=>Nn.create({...t,coerce:!0})),date:(t=>Mn.create({...t,coerce:!0}))},vg=W});var _={};on(_,{BRAND:()=>Mm,DIRTY:()=>Pn,EMPTY_PATH:()=>fm,INVALID:()=>W,NEVER:()=>vg,OK:()=>Ae,ParseStatus:()=>Ie,Schema:()=>re,ZodAny:()=>cn,ZodArray:()=>Dt,ZodBigInt:()=>Nn,ZodBoolean:()=>On,ZodBranded:()=>Ms,ZodCatch:()=>Gn,ZodDate:()=>Mn,ZodDefault:()=>Hn,ZodDiscriminatedUnion:()=>ki,ZodEffects:()=>tt,ZodEnum:()=>Bn,ZodError:()=>Le,ZodFirstPartyTypeKind:()=>V,ZodFunction:()=>Si,ZodIntersection:()=>Un,ZodIssueCode:()=>E,ZodLazy:()=>qn,ZodLiteral:()=>Fn,ZodMap:()=>Zr,ZodNaN:()=>Vr,ZodNativeEnum:()=>Kn,ZodNever:()=>dt,ZodNull:()=>Dn,ZodNullable:()=>kt,ZodNumber:()=>jn,ZodObject:()=>Ue,ZodOptional:()=>Qe,ZodParsedType:()=>D,ZodPipeline:()=>zs,ZodPromise:()=>un,ZodReadonly:()=>Zn,ZodRecord:()=>_i,ZodSchema:()=>re,ZodSet:()=>Wr,ZodString:()=>ln,ZodSymbol:()=>Hr,ZodTransformer:()=>tt,ZodTuple:()=>vt,ZodType:()=>re,ZodUndefined:()=>zn,ZodUnion:()=>Ln,ZodUnknown:()=>zt,ZodVoid:()=>Gr,addIssueToContext:()=>N,any:()=>Hm,array:()=>Vm,bigint:()=>Um,boolean:()=>Yc,coerce:()=>wg,custom:()=>Wc,date:()=>qm,datetimeRegex:()=>Gc,defaultErrorMap:()=>Ot,discriminatedUnion:()=>Qm,effect:()=>dg,enum:()=>lg,function:()=>ig,getErrorMap:()=>Fr,getParsedType:()=>wt,instanceof:()=>Dm,intersection:()=>eg,isAborted:()=>wi,isAsync:()=>Br,isDirty:()=>vi,isValid:()=>an,late:()=>zm,lazy:()=>og,literal:()=>ag,makeIssue:()=>Os,map:()=>rg,nan:()=>Lm,nativeEnum:()=>cg,never:()=>Zm,null:()=>Km,nullable:()=>pg,number:()=>Jc,object:()=>Jm,objectUtil:()=>da,oboolean:()=>bg,onumber:()=>yg,optional:()=>hg,ostring:()=>gg,pipeline:()=>mg,preprocess:()=>fg,promise:()=>ug,quotelessJson:()=>dm,record:()=>ng,set:()=>sg,setErrorMap:()=>pm,strictObject:()=>Ym,string:()=>Vc,symbol:()=>Fm,transformer:()=>dg,tuple:()=>tg,undefined:()=>Bm,union:()=>Xm,unknown:()=>Gm,util:()=>se,void:()=>Wm});var ga=ve(()=>{bi();pa();Uc();Ns();Xc();yi()});var Jr=ve(()=>{ga();ga()});function oe(){let t=process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR;if(t)return t;let e=xi.default.join(Ti.default.homedir(),".config","allwright"),n=xi.default.join(Ti.default.homedir(),".config","ticketpilot");return!Lt.default.existsSync(e)&&Lt.default.existsSync(n)?n:e}function Ut(){return xi.default.join(oe(),"runner.json")}function be(){let t=Ut();if(!Lt.default.existsSync(t))return null;let e=JSON.parse(Lt.default.readFileSync(t,"utf8"));return ya.parse(e)}function ge(t){let e=oe();Lt.default.mkdirSync(e,{recursive:!0,mode:448});let n=Ut(),r=n+".tmp";Lt.default.writeFileSync(r,JSON.stringify(t,null,2)+`
24
- `,{mode:384}),Lt.default.renameSync(r,n),Lt.default.chmodSync(n,384)}function Ri(t,e){return`${t}:${e}`}function qt(t,e,n){return t.environments[Ri(e,n)]?.secrets??{}}function Ii(t,e){return t.repos[e]?.jira??t.jira}function Ei(t){return!t.jira&&!Object.values(t.repos).some(e=>e.jira)}function le(){let t=be();if(!t)throw new Error(`No runner config found at ${Ut()}. Run \`allwright init\` first.`);return t}var Lt,Ti,xi,Qc,ya,Ce=ve(()=>{"use strict";Lt=I(require("node:fs"),1),Ti=I(require("node:os"),1),xi=I(require("node:path"),1);Jr();Qc=_.object({baseUrl:_.string().url(),email:_.string().email(),apiToken:_.string().min(1)}),ya=_.object({controlPlaneUrl:_.string().url(),runnerId:_.string().optional(),runnerToken:_.string().optional(),runnerName:_.string().default(Ti.default.hostname()),jira:Qc.optional(),repos:_.record(_.object({path:_.string(),jira:Qc.optional(),github:_.object({token:_.string().min(1),login:_.string().optional()}).optional()})).default({}),github:_.object({token:_.string().min(1),login:_.string().optional()}).optional(),githubUsers:_.record(_.object({token:_.string().min(1),login:_.string().optional()})).default({}),deploy:_.object({enabled:_.boolean().default(!1)}).default({enabled:!1}),environments:_.record(_.object({secrets:_.record(_.string()).default({})})).default({}),claudeProfiles:_.record(_.object({configDir:_.string()})).default({}),claudeBin:_.string().default("claude"),agents:_.record(_.object({bin:_.string()})).default({}),jiraUsers:_.record(_.object({email:_.string().email(),apiToken:_.string().min(1)})).default({}),auditSchedules:_.array(_.object({repoName:_.string(),role:_.enum(["security","testing"]),intervalHours:_.number().int().min(6).max(720)})).default([]),pollIntervalSeconds:_.number().int().min(10).max(600).default(30)})});var Ds=ae(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.getParsedType=de.ZodParsedType=de.objectUtil=de.util=void 0;var ka;(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})(ka||(de.util=ka={}));var uu;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(uu||(de.objectUtil=uu={}));de.ZodParsedType=ka.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var Eg=t=>{switch(typeof t){case"undefined":return de.ZodParsedType.undefined;case"string":return de.ZodParsedType.string;case"number":return Number.isNaN(t)?de.ZodParsedType.nan:de.ZodParsedType.number;case"boolean":return de.ZodParsedType.boolean;case"function":return de.ZodParsedType.function;case"bigint":return de.ZodParsedType.bigint;case"symbol":return de.ZodParsedType.symbol;case"object":return Array.isArray(t)?de.ZodParsedType.array:t===null?de.ZodParsedType.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?de.ZodParsedType.promise:typeof Map<"u"&&t instanceof Map?de.ZodParsedType.map:typeof Set<"u"&&t instanceof Set?de.ZodParsedType.set:typeof Date<"u"&&t instanceof Date?de.ZodParsedType.date:de.ZodParsedType.object;default:return de.ZodParsedType.unknown}};de.getParsedType=Eg});var Ni=ae(pn=>{"use strict";Object.defineProperty(pn,"__esModule",{value:!0});pn.ZodError=pn.quotelessJson=pn.ZodIssueCode=void 0;var du=Ds();pn.ZodIssueCode=du.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 Ag=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");pn.quotelessJson=Ag;var Ls=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,du.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()}};pn.ZodError=Ls;Ls.create=t=>new Ls(t)});var Sa=ae(_a=>{"use strict";Object.defineProperty(_a,"__esModule",{value:!0});var $e=Ni(),Jn=Ds(),Cg=(t,e)=>{let n;switch(t.code){case $e.ZodIssueCode.invalid_type:t.received===Jn.ZodParsedType.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case $e.ZodIssueCode.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,Jn.util.jsonStringifyReplacer)}`;break;case $e.ZodIssueCode.unrecognized_keys:n=`Unrecognized key(s) in object: ${Jn.util.joinValues(t.keys,", ")}`;break;case $e.ZodIssueCode.invalid_union:n="Invalid input";break;case $e.ZodIssueCode.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Jn.util.joinValues(t.options)}`;break;case $e.ZodIssueCode.invalid_enum_value:n=`Invalid enum value. Expected ${Jn.util.joinValues(t.options)}, received '${t.received}'`;break;case $e.ZodIssueCode.invalid_arguments:n="Invalid function arguments";break;case $e.ZodIssueCode.invalid_return_type:n="Invalid function return type";break;case $e.ZodIssueCode.invalid_date:n="Invalid date";break;case $e.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}"`:Jn.util.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case $e.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 $e.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 $e.ZodIssueCode.custom:n="Invalid input";break;case $e.ZodIssueCode.invalid_intersection_types:n="Intersection results could not be merged";break;case $e.ZodIssueCode.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case $e.ZodIssueCode.not_finite:n="Number must be finite";break;default:n=e.defaultError,Jn.util.assertNever(t)}return{message:n}};_a.default=Cg});var Oi=ae(fn=>{"use strict";var $g=fn&&fn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(fn,"__esModule",{value:!0});fn.defaultErrorMap=void 0;fn.setErrorMap=Pg;fn.getErrorMap=jg;var hu=$g(Sa());fn.defaultErrorMap=hu.default;var pu=hu.default;function Pg(t){pu=t}function jg(){return pu}});var xa=ae(ce=>{"use strict";var Ng=ce&&ce.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(ce,"__esModule",{value:!0});ce.isAsync=ce.isValid=ce.isDirty=ce.isAborted=ce.OK=ce.DIRTY=ce.INVALID=ce.ParseStatus=ce.EMPTY_PATH=ce.makeIssue=void 0;ce.addIssueToContext=zg;var Og=Oi(),fu=Ng(Sa()),Mg=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}};ce.makeIssue=Mg;ce.EMPTY_PATH=[];function zg(t,e){let n=(0,Og.getErrorMap)(),r=(0,ce.makeIssue)({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===fu.default?void 0:fu.default].filter(s=>!!s)});t.common.issues.push(r)}var Ta=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 ce.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 ce.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}}};ce.ParseStatus=Ta;ce.INVALID=Object.freeze({status:"aborted"});var Dg=t=>({status:"dirty",value:t});ce.DIRTY=Dg;var Lg=t=>({status:"valid",value:t});ce.OK=Lg;var Ug=t=>t.status==="aborted";ce.isAborted=Ug;var qg=t=>t.status==="dirty";ce.isDirty=qg;var Fg=t=>t.status==="valid";ce.isValid=Fg;var Bg=t=>typeof Promise<"u"&&t instanceof Promise;ce.isAsync=Bg});var gu=ae(mu=>{"use strict";Object.defineProperty(mu,"__esModule",{value:!0})});var bu=ae(Mi=>{"use strict";Object.defineProperty(Mi,"__esModule",{value:!0});Mi.errorUtil=void 0;var yu;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(yu||(Mi.errorUtil=yu={}))});var Cu=ae(S=>{"use strict";Object.defineProperty(S,"__esModule",{value:!0});S.discriminatedUnion=S.date=S.boolean=S.bigint=S.array=S.any=S.coerce=S.ZodFirstPartyTypeKind=S.late=S.ZodSchema=S.Schema=S.ZodReadonly=S.ZodPipeline=S.ZodBranded=S.BRAND=S.ZodNaN=S.ZodCatch=S.ZodDefault=S.ZodNullable=S.ZodOptional=S.ZodTransformer=S.ZodEffects=S.ZodPromise=S.ZodNativeEnum=S.ZodEnum=S.ZodLiteral=S.ZodLazy=S.ZodFunction=S.ZodSet=S.ZodMap=S.ZodRecord=S.ZodTuple=S.ZodIntersection=S.ZodDiscriminatedUnion=S.ZodUnion=S.ZodObject=S.ZodArray=S.ZodVoid=S.ZodNever=S.ZodUnknown=S.ZodAny=S.ZodNull=S.ZodUndefined=S.ZodSymbol=S.ZodDate=S.ZodBoolean=S.ZodBigInt=S.ZodNumber=S.ZodString=S.ZodType=void 0;S.NEVER=S.void=S.unknown=S.union=S.undefined=S.tuple=S.transformer=S.symbol=S.string=S.strictObject=S.set=S.record=S.promise=S.preprocess=S.pipeline=S.ostring=S.optional=S.onumber=S.oboolean=S.object=S.number=S.nullable=S.null=S.never=S.nativeEnum=S.nan=S.map=S.literal=S.lazy=S.intersection=S.instanceof=S.function=S.enum=S.effect=void 0;S.datetimeRegex=Su;S.custom=xu;var C=Ni(),zi=Oi(),H=bu(),T=xa(),P=Ds(),rt=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}},wu=(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 C.ZodError(t.common.issues);return this._error=n,this._error}}};function ee(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(0,P.getParsedType)(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:(0,P.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new T.ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:(0,P.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let 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,P.getParsedType)(e)},s=this._parseSync({data:e,path:r.path,parent:r});return wu(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,P.getParsedType)(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent: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,P.getParsedType)(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await((0,T.isAsync)(s)?s:Promise.resolve(s));return wu(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:C.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 He({schema:this,typeName:J.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 nt.create(this,this._def)}nullable(){return St.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Kt.create(this)}promise(){return yn.create(this,this._def)}or(e){return rr.create([this,e],this._def)}and(e){return sr.create(this,e,this._def)}transform(e){return new He({...ee(this._def),schema:this,typeName:J.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new cr({...ee(this._def),innerType:this,defaultValue:n,typeName:J.ZodDefault})}brand(){return new Us({typeName:J.ZodBranded,type:this,...ee(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new ur({...ee(this._def),innerType:this,catchValue:n,typeName:J.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return qs.create(this,e)}readonly(){return dr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};S.ZodType=te;S.Schema=te;S.ZodSchema=te;var Kg=/^c[^\s-]{8,}$/i,Hg=/^[0-9a-z]+$/,Gg=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Zg=/^[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,Wg=/^[a-z0-9_-]{21}$/i,Vg=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Jg=/^[-+]?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)?)??$/,Yg=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Xg="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ra,Qg=/^(?:(?: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])$/,ey=/^(?:(?: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])$/,ty=/^(([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]))$/,ny=/^(([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])$/,ry=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,sy=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ku="((\\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])))",iy=new RegExp(`^${ku}$`);function _u(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 oy(t){return new RegExp(`^${_u(t)}$`)}function Su(t){let e=`${ku}T${_u(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 ay(t,e){return!!((e==="v4"||!e)&&Qg.test(t)||(e==="v6"||!e)&&ty.test(t))}function ly(t,e){if(!Vg.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 cy(t,e){return!!((e==="v4"||!e)&&ey.test(t)||(e==="v6"||!e)&&ny.test(t))}var mn=class t extends te{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==P.ZodParsedType.string){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:C.ZodIssueCode.invalid_type,expected:P.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:C.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:C.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:C.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):l&&(0,T.addIssueToContext)(s,{code:C.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")Yg.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"email",code:C.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Ra||(Ra=new RegExp(Xg,"u")),Ra.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"emoji",code:C.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")Zg.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"uuid",code:C.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")Wg.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"nanoid",code:C.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")Kg.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"cuid",code:C.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")Hg.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"cuid2",code:C.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")Gg.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"ulid",code:C.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:C.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:C.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:C.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:C.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:C.ZodIssueCode.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Su(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:C.ZodIssueCode.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?iy.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:C.ZodIssueCode.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?oy(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:C.ZodIssueCode.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?Jg.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"duration",code:C.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?ay(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"ip",code:C.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?ly(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"jwt",code:C.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?cy(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"cidr",code:C.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?ry.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"base64",code:C.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?sy.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"base64url",code:C.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):P.util.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:C.ZodIssueCode.invalid_string,...H.errorUtil.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...H.errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...H.errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...H.errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...H.errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...H.errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...H.errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...H.errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...H.errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...H.errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...H.errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...H.errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...H.errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...H.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,...H.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,...H.errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...H.errorUtil.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...H.errorUtil.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...H.errorUtil.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...H.errorUtil.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...H.errorUtil.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...H.errorUtil.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...H.errorUtil.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...H.errorUtil.errToObj(n)})}nonempty(e){return this.min(1,H.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}};S.ZodString=mn;mn.create=t=>new mn({checks:[],typeName:J.ZodString,coerce:t?.coerce??!1,...ee(t)});function uy(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 Yn=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)!==P.ZodParsedType.number){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:C.ZodIssueCode.invalid_type,expected:P.ZodParsedType.number,received:i.parsedType}),T.INVALID}let r,s=new T.ParseStatus;for(let i of this._def.checks)i.kind==="int"?P.util.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:C.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:C.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:C.ZodIssueCode.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?uy(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:C.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:C.ZodIssueCode.not_finite,message:i.message}),s.dirty()):P.util.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,H.errorUtil.toString(n))}gt(e,n){return this.setLimit("min",e,!1,H.errorUtil.toString(n))}lte(e,n){return this.setLimit("max",e,!0,H.errorUtil.toString(n))}lt(e,n){return this.setLimit("max",e,!1,H.errorUtil.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:H.errorUtil.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:H.errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:H.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:H.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:H.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:H.errorUtil.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:H.errorUtil.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:H.errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:H.errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:H.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"&&P.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)}};S.ZodNumber=Yn;Yn.create=t=>new Yn({checks:[],typeName:J.ZodNumber,coerce:t?.coerce||!1,...ee(t)});var Xn=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)!==P.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:C.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:C.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:C.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):P.util.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:P.ZodParsedType.bigint,received:n.parsedType}),T.INVALID}gte(e,n){return this.setLimit("min",e,!0,H.errorUtil.toString(n))}gt(e,n){return this.setLimit("min",e,!1,H.errorUtil.toString(n))}lte(e,n){return this.setLimit("max",e,!0,H.errorUtil.toString(n))}lt(e,n){return this.setLimit("max",e,!1,H.errorUtil.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:H.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:H.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:H.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:H.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:H.errorUtil.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:H.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}};S.ZodBigInt=Xn;Xn.create=t=>new Xn({checks:[],typeName:J.ZodBigInt,coerce:t?.coerce??!1,...ee(t)});var Qn=class extends te{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==P.ZodParsedType.boolean){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:C.ZodIssueCode.invalid_type,expected:P.ZodParsedType.boolean,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};S.ZodBoolean=Qn;Qn.create=t=>new Qn({typeName:J.ZodBoolean,coerce:t?.coerce||!1,...ee(t)});var er=class t extends te{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==P.ZodParsedType.date){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:C.ZodIssueCode.invalid_type,expected:P.ZodParsedType.date,received:i.parsedType}),T.INVALID}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:C.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:C.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:C.ZodIssueCode.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):P.util.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:H.errorUtil.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:H.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}};S.ZodDate=er;er.create=t=>new er({checks:[],coerce:t?.coerce||!1,typeName:J.ZodDate,...ee(t)});var ns=class extends te{_parse(e){if(this._getType(e)!==P.ZodParsedType.symbol){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:C.ZodIssueCode.invalid_type,expected:P.ZodParsedType.symbol,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};S.ZodSymbol=ns;ns.create=t=>new ns({typeName:J.ZodSymbol,...ee(t)});var tr=class extends te{_parse(e){if(this._getType(e)!==P.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:C.ZodIssueCode.invalid_type,expected:P.ZodParsedType.undefined,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};S.ZodUndefined=tr;tr.create=t=>new tr({typeName:J.ZodUndefined,...ee(t)});var nr=class extends te{_parse(e){if(this._getType(e)!==P.ZodParsedType.null){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:C.ZodIssueCode.invalid_type,expected:P.ZodParsedType.null,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};S.ZodNull=nr;nr.create=t=>new nr({typeName:J.ZodNull,...ee(t)});var gn=class extends te{constructor(){super(...arguments),this._any=!0}_parse(e){return(0,T.OK)(e.data)}};S.ZodAny=gn;gn.create=t=>new gn({typeName:J.ZodAny,...ee(t)});var Bt=class extends te{constructor(){super(...arguments),this._unknown=!0}_parse(e){return(0,T.OK)(e.data)}};S.ZodUnknown=Bt;Bt.create=t=>new Bt({typeName:J.ZodUnknown,...ee(t)});var ht=class extends te{_parse(e){let n=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:P.ZodParsedType.never,received:n.parsedType}),T.INVALID}};S.ZodNever=ht;ht.create=t=>new ht({typeName:J.ZodNever,...ee(t)});var rs=class extends te{_parse(e){if(this._getType(e)!==P.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:C.ZodIssueCode.invalid_type,expected:P.ZodParsedType.void,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};S.ZodVoid=rs;rs.create=t=>new rs({typeName:J.ZodVoid,...ee(t)});var Kt=class t extends te{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==P.ZodParsedType.array)return(0,T.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:P.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?C.ZodIssueCode.too_big:C.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:C.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:C.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 rt(n,o,n.path,l)))).then(o=>T.ParseStatus.mergeArray(r,o));let i=[...n.data].map((o,l)=>s.type._parseSync(new rt(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:H.errorUtil.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:H.errorUtil.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:H.errorUtil.toString(n)}})}nonempty(e){return this.min(1,e)}};S.ZodArray=Kt;Kt.create=(t,e)=>new Kt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:J.ZodArray,...ee(e)});function ts(t){if(t instanceof qe){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=nt.create(ts(r))}return new qe({...t._def,shape:()=>e})}else return t instanceof Kt?new Kt({...t._def,type:ts(t.element)}):t instanceof nt?nt.create(ts(t.unwrap())):t instanceof St?St.create(ts(t.unwrap())):t instanceof _t?_t.create(t.items.map(e=>ts(e))):t}var qe=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=P.util.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==P.ZodParsedType.object){let u=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(u,{code:C.ZodIssueCode.invalid_type,expected:P.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 ht&&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 rt(s,f,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof ht){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:C.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 rt(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,w=await p.value;u.push({key:f,value:w,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 H.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:H.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:J.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 P.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 P.util.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return ts(this)}partial(e){let n={};for(let r of P.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 P.util.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof nt;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return Tu(P.util.objectKeys(this.shape))}};S.ZodObject=qe;qe.create=(t,e)=>new qe({shape:()=>t,unknownKeys:"strip",catchall:ht.create(),typeName:J.ZodObject,...ee(e)});qe.strictCreate=(t,e)=>new qe({shape:()=>t,unknownKeys:"strict",catchall:ht.create(),typeName:J.ZodObject,...ee(e)});qe.lazycreate=(t,e)=>new qe({shape:t,unknownKeys:"strip",catchall:ht.create(),typeName:J.ZodObject,...ee(e)});var rr=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 C.ZodError(l.ctx.common.issues));return(0,T.addIssueToContext)(n,{code:C.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 C.ZodError(c));return(0,T.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_union,unionErrors:l}),T.INVALID}}get options(){return this._def.options}};S.ZodUnion=rr;rr.create=(t,e)=>new rr({options:t,typeName:J.ZodUnion,...ee(e)});var Ft=t=>t instanceof ir?Ft(t.schema):t instanceof He?Ft(t.innerType()):t instanceof or?[t.value]:t instanceof ar?t.options:t instanceof lr?P.util.objectValues(t.enum):t instanceof cr?Ft(t._def.innerType):t instanceof tr?[void 0]:t instanceof nr?[null]:t instanceof nt?[void 0,...Ft(t.unwrap())]:t instanceof St?[null,...Ft(t.unwrap())]:t instanceof Us||t instanceof dr?Ft(t.unwrap()):t instanceof ur?Ft(t._def.innerType):[],Di=class t extends te{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==P.ZodParsedType.object)return(0,T.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:P.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:C.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=Ft(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:J.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...ee(r)})}};S.ZodDiscriminatedUnion=Di;function Ia(t,e){let n=(0,P.getParsedType)(t),r=(0,P.getParsedType)(e);if(t===e)return{valid:!0,data:t};if(n===P.ZodParsedType.object&&r===P.ZodParsedType.object){let s=P.util.objectKeys(e),i=P.util.objectKeys(t).filter(l=>s.indexOf(l)!==-1),o={...t,...e};for(let l of i){let c=Ia(t[l],e[l]);if(!c.valid)return{valid:!1};o[l]=c.data}return{valid:!0,data:o}}else if(n===P.ZodParsedType.array&&r===P.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=Ia(o,l);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===P.ZodParsedType.date&&r===P.ZodParsedType.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var sr=class extends te{_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=Ia(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:C.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}))}};S.ZodIntersection=sr;sr.create=(t,e,n)=>new sr({left:t,right:e,typeName:J.ZodIntersection,...ee(n)});var _t=class t extends te{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==P.ZodParsedType.array)return(0,T.addIssueToContext)(r,{code:C.ZodIssueCode.invalid_type,expected:P.ZodParsedType.array,received:r.parsedType}),T.INVALID;if(r.data.length<this._def.items.length)return(0,T.addIssueToContext)(r,{code:C.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:C.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 rt(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})}};S.ZodTuple=_t;_t.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new _t({items:t,typeName:J.ZodTuple,rest:null,...ee(e)})};var Li=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!==P.ZodParsedType.object)return(0,T.addIssueToContext)(r,{code:C.ZodIssueCode.invalid_type,expected:P.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 rt(r,l,r.path,l)),value:o._parse(new rt(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 te?new t({keyType:e,valueType:n,typeName:J.ZodRecord,...ee(r)}):new t({keyType:mn.create(),valueType:e,typeName:J.ZodRecord,...ee(n)})}};S.ZodRecord=Li;var ss=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!==P.ZodParsedType.map)return(0,T.addIssueToContext)(r,{code:C.ZodIssueCode.invalid_type,expected:P.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 rt(r,l,r.path,[u,"key"])),value:i._parse(new rt(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}}}};S.ZodMap=ss;ss.create=(t,e,n)=>new ss({valueType:e,keyType:t,typeName:J.ZodMap,...ee(n)});var is=class t extends te{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==P.ZodParsedType.set)return(0,T.addIssueToContext)(r,{code:C.ZodIssueCode.invalid_type,expected:P.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:C.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:C.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 rt(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:H.errorUtil.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:H.errorUtil.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};S.ZodSet=is;is.create=(t,e)=>new is({valueType:t,minSize:null,maxSize:null,typeName:J.ZodSet,...ee(e)});var Ui=class t extends te{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==P.ZodParsedType.function)return(0,T.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:P.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,zi.getErrorMap)(),zi.defaultErrorMap].filter(u=>!!u),issueData:{code:C.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,zi.getErrorMap)(),zi.defaultErrorMap].filter(u=>!!u),issueData:{code:C.ZodIssueCode.invalid_return_type,returnTypeError:c}})}let i={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof yn){let l=this;return(0,T.OK)(async function(...c){let u=new C.ZodError([]),p=await l._def.args.parseAsync(c,i).catch(b=>{throw u.addIssue(r(c,b)),u}),f=await Reflect.apply(o,this,p);return await l._def.returns._def.type.parseAsync(f,i).catch(b=>{throw u.addIssue(s(f,b)),u})})}else{let l=this;return(0,T.OK)(function(...c){let u=l._def.args.safeParse(c,i);if(!u.success)throw new C.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 C.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:_t.create(e).rest(Bt.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||_t.create([]).rest(Bt.create()),returns:n||Bt.create(),typeName:J.ZodFunction,...ee(r)})}};S.ZodFunction=Ui;var ir=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})}};S.ZodLazy=ir;ir.create=(t,e)=>new ir({getter:t,typeName:J.ZodLazy,...ee(e)});var or=class extends te{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(n,{received:n.data,code:C.ZodIssueCode.invalid_literal,expected:this._def.value}),T.INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}};S.ZodLiteral=or;or.create=(t,e)=>new or({value:t,typeName:J.ZodLiteral,...ee(e)});function Tu(t,e){return new ar({values:t,typeName:J.ZodEnum,...ee(e)})}var ar=class t extends te{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return(0,T.addIssueToContext)(n,{expected:P.util.joinValues(r),received:n.parsedType,code:C.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:C.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})}};S.ZodEnum=ar;ar.create=Tu;var lr=class extends te{_parse(e){let n=P.util.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==P.ZodParsedType.string&&r.parsedType!==P.ZodParsedType.number){let s=P.util.objectValues(n);return(0,T.addIssueToContext)(r,{expected:P.util.joinValues(s),received:r.parsedType,code:C.ZodIssueCode.invalid_type}),T.INVALID}if(this._cache||(this._cache=new Set(P.util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=P.util.objectValues(n);return(0,T.addIssueToContext)(r,{received:r.data,code:C.ZodIssueCode.invalid_enum_value,options:s}),T.INVALID}return(0,T.OK)(e.data)}get enum(){return this._def.values}};S.ZodNativeEnum=lr;lr.create=(t,e)=>new lr({values:t,typeName:J.ZodNativeEnum,...ee(e)});var yn=class extends te{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==P.ZodParsedType.promise&&n.common.async===!1)return(0,T.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:P.ZodParsedType.promise,received:n.parsedType}),T.INVALID;let r=n.parsedType===P.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})))}};S.ZodPromise=yn;yn.create=(t,e)=>new yn({type:t,typeName:J.ZodPromise,...ee(e)});var He=class extends te{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===J.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);P.util.assertNever(s)}};S.ZodEffects=He;S.ZodTransformer=He;He.create=(t,e,n)=>new He({schema:t,typeName:J.ZodEffects,effect:e,...ee(n)});He.createWithPreprocess=(t,e,n)=>new He({schema:e,effect:{type:"preprocess",transform:t},typeName:J.ZodEffects,...ee(n)});var nt=class extends te{_parse(e){return this._getType(e)===P.ZodParsedType.undefined?(0,T.OK)(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};S.ZodOptional=nt;nt.create=(t,e)=>new nt({innerType:t,typeName:J.ZodOptional,...ee(e)});var St=class extends te{_parse(e){return this._getType(e)===P.ZodParsedType.null?(0,T.OK)(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};S.ZodNullable=St;St.create=(t,e)=>new St({innerType:t,typeName:J.ZodNullable,...ee(e)});var cr=class extends te{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===P.ZodParsedType.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};S.ZodDefault=cr;cr.create=(t,e)=>new cr({innerType:t,typeName:J.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ee(e)});var ur=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(0,T.isAsync)(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new C.ZodError(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new C.ZodError(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};S.ZodCatch=ur;ur.create=(t,e)=>new ur({innerType:t,typeName:J.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ee(e)});var os=class extends te{_parse(e){if(this._getType(e)!==P.ZodParsedType.nan){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:C.ZodIssueCode.invalid_type,expected:P.ZodParsedType.nan,received:r.parsedType}),T.INVALID}return{status:"valid",value:e.data}}};S.ZodNaN=os;os.create=t=>new os({typeName:J.ZodNaN,...ee(t)});S.BRAND=Symbol("zod_brand");var Us=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.ZodBranded=Us;var qs=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"?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:J.ZodPipeline})}};S.ZodPipeline=qs;var dr=class extends te{_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}};S.ZodReadonly=dr;dr.create=(t,e)=>new dr({innerType:t,typeName:J.ZodReadonly,...ee(e)});function vu(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function xu(t,e={},n){return t?gn.create().superRefine((r,s)=>{let i=t(r);if(i instanceof Promise)return i.then(o=>{if(!o){let l=vu(e,r),c=l.fatal??n??!0;s.addIssue({code:"custom",...l,fatal:c})}});if(!i){let o=vu(e,r),l=o.fatal??n??!0;s.addIssue({code:"custom",...o,fatal:l})}}):gn.create()}S.late={object:qe.lazycreate};var J;(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"})(J||(S.ZodFirstPartyTypeKind=J={}));var dy=(t,e={message:`Input not instance of ${t.name}`})=>xu(n=>n instanceof t,e);S.instanceof=dy;var Ru=mn.create;S.string=Ru;var Iu=Yn.create;S.number=Iu;var hy=os.create;S.nan=hy;var py=Xn.create;S.bigint=py;var Eu=Qn.create;S.boolean=Eu;var fy=er.create;S.date=fy;var my=ns.create;S.symbol=my;var gy=tr.create;S.undefined=gy;var yy=nr.create;S.null=yy;var by=gn.create;S.any=by;var wy=Bt.create;S.unknown=wy;var vy=ht.create;S.never=vy;var ky=rs.create;S.void=ky;var _y=Kt.create;S.array=_y;var Sy=qe.create;S.object=Sy;var Ty=qe.strictCreate;S.strictObject=Ty;var xy=rr.create;S.union=xy;var Ry=Di.create;S.discriminatedUnion=Ry;var Iy=sr.create;S.intersection=Iy;var Ey=_t.create;S.tuple=Ey;var Ay=Li.create;S.record=Ay;var Cy=ss.create;S.map=Cy;var $y=is.create;S.set=$y;var Py=Ui.create;S.function=Py;var jy=ir.create;S.lazy=jy;var Ny=or.create;S.literal=Ny;var Oy=ar.create;S.enum=Oy;var My=lr.create;S.nativeEnum=My;var zy=yn.create;S.promise=zy;var Au=He.create;S.effect=Au;S.transformer=Au;var Dy=nt.create;S.optional=Dy;var Ly=St.create;S.nullable=Ly;var Uy=He.createWithPreprocess;S.preprocess=Uy;var qy=qs.create;S.pipeline=qy;var Fy=()=>Ru().optional();S.ostring=Fy;var By=()=>Iu().optional();S.onumber=By;var Ky=()=>Eu().optional();S.oboolean=Ky;S.coerce={string:(t=>mn.create({...t,coerce:!0})),number:(t=>Yn.create({...t,coerce:!0})),boolean:(t=>Qn.create({...t,coerce:!0})),bigint:(t=>Xn.create({...t,coerce:!0})),date:(t=>er.create({...t,coerce:!0}))};S.NEVER=T.INVALID});var Ea=ae(st=>{"use strict";var Hy=st&&st.__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]})),as=st&&st.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Hy(e,t,n)};Object.defineProperty(st,"__esModule",{value:!0});as(Oi(),st);as(xa(),st);as(gu(),st);as(Ds(),st);as(Cu(),st);as(Ni(),st)});var ju=ae(Fe=>{"use strict";var $u=Fe&&Fe.__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]})),Gy=Fe&&Fe.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Zy=Fe&&Fe.__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)&&$u(e,t,n);return Gy(e,t),e},Wy=Fe&&Fe.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&$u(e,t,n)};Object.defineProperty(Fe,"__esModule",{value:!0});Fe.z=void 0;var Pu=Zy(Ea());Fe.z=Pu;Wy(Ea(),Fe);Fe.default=Pu});var ke=ae(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});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.RUNNER_UNINSTALL_COMMAND=h.PROTOCOL_VERSION=h.GITHUB_TOKEN_PERMISSIONS=void 0;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.AuditExplainResultMsg=h.AuditExplainMsg=h.ChatCancelMsg=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=h.ChatLoadResultMsg=void 0;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.AutopilotPlanResultMsg=h.AutopilotPlanMsg=h.AutopilotNextMsg=h.RunnerUninstallResultMsg=h.RunnerUpdateResultMsg=h.AgentProfilesResultMsg=h.AgentProfilesMsg=h.RunPrConflictMsg=h.RunResolveConflictResultMsg=h.RunAnswerResultMsg=h.RunAnswerMsg=h.RunTestFixResultMsg=h.RunTestFixMsg=h.RunResolveConflictMsg=h.RunnerUninstallMsg=h.RunnerUpdateMsg=h.RepoDocSaveResultMsg=h.RepoDocSaveMsg=h.SetupClaudeMdSaveResultMsg=h.SetupClaudeMdSaveMsg=h.SetupClaudeMdGenerateResultMsg=h.SetupClaudeMdGenerateMsg=h.SetupRecheckResultMsg=h.SetupRecheckMsg=h.RepoUnmapResultMsg=h.RepoUnmapMsg=h.SetupStatusResultMsg=h.SetupStatusMsg=h.DeploySuggestResultMsg=h.SelfMigrationApplyResultMsg=void 0;h.DEFAULT_DEPLOY_SUGGEST_PROMPT_TEMPLATE=h.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE=h.DEPLOY_FIX_PROMPT_TEMPLATE=h.PROMPT_PRESETS=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=void 0;h.missingAgentCapabilities=Vy;h.replyPreferenceAppendix=Yy;h.pendingMigrationsAppendix=Xy;h.isSelfMigrationFilename=Qy;h.parseRunnerMsg=eb;h.parseServerMsg=tb;var a=ju();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.69";h.RUNNER_UNINSTALL_COMMAND="sudo allwright service uninstall";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 Vy(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 Jy=t=>t.includes(h.NEEDS_INPUT_COMMENT_MARKER)||h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS.some(e=>t.includes(e));h.needsInputMarkerIn=Jy;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 Yy(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 Lc(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})}Uc.Command=ha});var Hc=ae(Xe=>{var{Argument:Fc}=gi(),{Command:pa}=qc(),{CommanderError:km,InvalidArgumentError:Bc}=Ns(),{Help:_m}=sa(),{Option:Kc}=la();Xe.program=new pa;Xe.createCommand=t=>new pa(t);Xe.createOption=(t,e)=>new Kc(t,e);Xe.createArgument=(t,e)=>new Fc(t,e);Xe.Command=pa;Xe.Option=Kc;Xe.Argument=Fc;Xe.Help=_m;Xe.CommanderError=km;Xe.InvalidArgumentError=Bc;Xe.InvalidOptionArgumentError=Bc});var ie,fa,D,vt,Os=ye(()=>{(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})(ie||(ie={}));(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(fa||(fa={}));D=ie.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),vt=t=>{switch(typeof t){case"undefined":return D.undefined;case"string":return D.string;case"number":return Number.isNaN(t)?D.nan:D.number;case"boolean":return D.boolean;case"function":return D.function;case"bigint":return D.bigint;case"symbol":return D.symbol;case"object":return Array.isArray(t)?D.array:t===null?D.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?D.promise:typeof Map<"u"&&t instanceof Map?D.map:typeof Set<"u"&&t instanceof Set?D.set:typeof Date<"u"&&t instanceof Date?D.date:D.object;default:return D.unknown}}});var E,Sm,Le,yi=ye(()=>{Os();E=ie.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"]),Sm=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Le=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,ie.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()}};Le.create=t=>new Le(t)});var Tm,Mt,ma=ye(()=>{yi();Os();Tm=(t,e)=>{let n;switch(t.code){case E.invalid_type:t.received===D.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case E.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,ie.jsonStringifyReplacer)}`;break;case E.unrecognized_keys:n=`Unrecognized key(s) in object: ${ie.joinValues(t.keys,", ")}`;break;case E.invalid_union:n="Invalid input";break;case E.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ie.joinValues(t.options)}`;break;case E.invalid_enum_value:n=`Invalid enum value. Expected ${ie.joinValues(t.options)}, received '${t.received}'`;break;case E.invalid_arguments:n="Invalid function arguments";break;case E.invalid_return_type:n="Invalid function return type";break;case E.invalid_date:n="Invalid date";break;case E.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}"`:ie.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case E.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 E.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 E.custom:n="Invalid input";break;case E.invalid_intersection_types:n="Intersection results could not be merged";break;case E.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case E.not_finite:n="Number must be finite";break;default:n=e.defaultError,ie.assertNever(t)}return{message:n}},Mt=Tm});function xm(t){Wc=t}function Br(){return Wc}var Wc,bi=ye(()=>{ma();Wc=Mt});function N(t,e){let n=Br(),r=Ms({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Mt?void 0:Mt].filter(s=>!!s)});t.common.issues.push(r)}var Ms,Rm,Ie,W,jn,Ae,wi,vi,ln,Kr,ga=ye(()=>{bi();ma();Ms=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}},Rm=[];Ie=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 W;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 W;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}}},W=Object.freeze({status:"aborted"}),jn=t=>({status:"dirty",value:t}),Ae=t=>({status:"valid",value:t}),wi=t=>t.status==="aborted",vi=t=>t.status==="dirty",ln=t=>t.status==="valid",Kr=t=>typeof Promise<"u"&&t instanceof Promise});var Vc=ye(()=>{});var F,Jc=ye(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(F||(F={}))});function Q(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}}function eu(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 Bm(t){return new RegExp(`^${eu(t)}$`)}function tu(t){let e=`${Qc}T${eu(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 Km(t,e){return!!((e==="v4"||!e)&&Mm.test(t)||(e==="v6"||!e)&&Dm.test(t))}function Hm(t,e){if(!Pm.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 Gm(t,e){return!!((e==="v4"||!e)&&zm.test(t)||(e==="v6"||!e)&&Lm.test(t))}function Zm(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}function Hr(t){if(t instanceof Ue){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=Qe.create(Hr(r))}return new Ue({...t._def,shape:()=>e})}else return t instanceof Lt?new Lt({...t._def,type:Hr(t.element)}):t instanceof Qe?Qe.create(Hr(t.unwrap())):t instanceof _t?_t.create(Hr(t.unwrap())):t instanceof kt?kt.create(t.items.map(e=>Hr(e))):t}function ba(t,e){let n=vt(t),r=vt(e);if(t===e)return{valid:!0,data:t};if(n===D.object&&r===D.object){let s=ie.objectKeys(e),i=ie.objectKeys(t).filter(l=>s.indexOf(l)!==-1),o={...t,...e};for(let l of i){let c=ba(t[l],e[l]);if(!c.valid)return{valid:!1};o[l]=c.data}return{valid:!0,data:o}}else if(n===D.array&&r===D.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=ba(o,l);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===D.date&&r===D.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function nu(t,e){return new Kn({values:t,typeName:V.ZodEnum,...Q(e)})}function Xc(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function ru(t,e={},n){return t?un.create().superRefine((r,s)=>{let i=t(r);if(i instanceof Promise)return i.then(o=>{if(!o){let l=Xc(e,r),c=l.fatal??n??!0;s.addIssue({code:"custom",...l,fatal:c})}});if(!i){let o=Xc(e,r),l=o.fatal??n??!0;s.addIssue({code:"custom",...o,fatal:l})}}):un.create()}var et,Yc,re,Im,Em,Am,Cm,$m,Pm,jm,Nm,Om,ya,Mm,zm,Dm,Lm,Um,qm,Qc,Fm,cn,Nn,On,Mn,zn,Gr,Dn,Ln,un,Dt,ht,Zr,Lt,Ue,Un,zt,ki,qn,kt,_i,Wr,Vr,Si,Fn,Bn,Kn,Hn,dn,tt,Qe,_t,Gn,Zn,Jr,Wm,zs,Ds,Wn,Vm,V,Jm,su,iu,Ym,Xm,ou,Qm,eg,tg,ng,rg,sg,ig,og,ag,lg,cg,ug,dg,hg,pg,fg,mg,gg,yg,bg,wg,vg,kg,_g,Sg,Tg,xg,Rg,Ig,Eg,Ag,Cg,$g,Pg,au=ye(()=>{yi();bi();Jc();ga();Os();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}},Yc=(t,e)=>{if(ln(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 Le(t.common.issues);return this._error=n,this._error}}};re=class{get description(){return this._def.description}_getType(e){return vt(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:vt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ie,ctx:{common:e.parent.common,data:e.data,parsedType:vt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(Kr(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:vt(e)},s=this._parseSync({data:e,path:r.path,parent:r});return Yc(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:vt(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return ln(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=>ln(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:vt(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(Kr(s)?s:Promise.resolve(s));return Yc(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:E.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 tt({schema:this,typeName:V.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 _t.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Lt.create(this)}promise(){return dn.create(this,this._def)}or(e){return Un.create([this,e],this._def)}and(e){return qn.create(this,e,this._def)}transform(e){return new tt({...Q(this._def),schema:this,typeName:V.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new Gn({...Q(this._def),innerType:this,defaultValue:n,typeName:V.ZodDefault})}brand(){return new zs({typeName:V.ZodBranded,type:this,...Q(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Zn({...Q(this._def),innerType:this,catchValue:n,typeName:V.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Ds.create(this,e)}readonly(){return Wn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Im=/^c[^\s-]{8,}$/i,Em=/^[0-9a-z]+$/,Am=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Cm=/^[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,$m=/^[a-z0-9_-]{21}$/i,Pm=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,jm=/^[-+]?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)?)??$/,Nm=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Om="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Mm=/^(?:(?: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])$/,zm=/^(?:(?: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])$/,Dm=/^(([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]))$/,Lm=/^(([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])$/,Um=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,qm=/^([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])))",Fm=new RegExp(`^${Qc}$`);cn=class t extends re{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==D.string){let i=this._getOrReturnCtx(e);return N(i,{code:E.invalid_type,expected:D.string,received:i.parsedType}),W}let r=new Ie,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:E.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:E.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:E.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):l&&N(s,{code:E.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")Nm.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"email",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")ya||(ya=new RegExp(Om,"u")),ya.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"emoji",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")Cm.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"uuid",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")$m.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"nanoid",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")Im.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"cuid",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")Em.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"cuid2",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")Am.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"ulid",code:E.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:E.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:E.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:E.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:E.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:E.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?tu(i).test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{code:E.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?Fm.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{code:E.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Bm(i).test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{code:E.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?jm.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"duration",code:E.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?Km(e.data,i.version)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"ip",code:E.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?Hm(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"jwt",code:E.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?Gm(e.data,i.version)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"cidr",code:E.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?Um.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"base64",code:E.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?qm.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"base64url",code:E.invalid_string,message:i.message}),r.dirty()):ie.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:E.invalid_string,...F.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...F.errToObj(e)})}url(e){return this._addCheck({kind:"url",...F.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...F.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...F.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...F.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...F.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...F.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...F.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...F.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...F.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...F.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...F.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...F.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,...F.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,...F.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...F.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...F.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...F.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...F.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...F.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...F.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...F.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...F.errToObj(n)})}nonempty(e){return this.min(1,F.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}};cn.create=t=>new cn({checks:[],typeName:V.ZodString,coerce:t?.coerce??!1,...Q(t)});Nn=class t extends re{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)!==D.number){let i=this._getOrReturnCtx(e);return N(i,{code:E.invalid_type,expected:D.number,received:i.parsedType}),W}let r,s=new Ie;for(let i of this._def.checks)i.kind==="int"?ie.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),N(r,{code:E.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:E.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:E.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Zm(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),N(r,{code:E.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:E.not_finite,message:i.message}),s.dirty()):ie.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,F.toString(n))}gt(e,n){return this.setLimit("min",e,!1,F.toString(n))}lte(e,n){return this.setLimit("max",e,!0,F.toString(n))}lt(e,n){return this.setLimit("max",e,!1,F.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:F.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:F.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:F.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:F.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:F.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:F.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:F.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:F.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:F.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:F.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"&&ie.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)}};Nn.create=t=>new Nn({checks:[],typeName:V.ZodNumber,coerce:t?.coerce||!1,...Q(t)});On=class t extends re{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)!==D.bigint)return this._getInvalidInput(e);let r,s=new Ie;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:E.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:E.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:E.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):ie.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return N(n,{code:E.invalid_type,expected:D.bigint,received:n.parsedType}),W}gte(e,n){return this.setLimit("min",e,!0,F.toString(n))}gt(e,n){return this.setLimit("min",e,!1,F.toString(n))}lte(e,n){return this.setLimit("max",e,!0,F.toString(n))}lt(e,n){return this.setLimit("max",e,!1,F.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:F.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:F.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:F.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:F.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:F.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:F.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}};On.create=t=>new On({checks:[],typeName:V.ZodBigInt,coerce:t?.coerce??!1,...Q(t)});Mn=class extends re{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==D.boolean){let r=this._getOrReturnCtx(e);return N(r,{code:E.invalid_type,expected:D.boolean,received:r.parsedType}),W}return Ae(e.data)}};Mn.create=t=>new Mn({typeName:V.ZodBoolean,coerce:t?.coerce||!1,...Q(t)});zn=class t extends re{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==D.date){let i=this._getOrReturnCtx(e);return N(i,{code:E.invalid_type,expected:D.date,received:i.parsedType}),W}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return N(i,{code:E.invalid_date}),W}let r=new Ie,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),N(s,{code:E.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:E.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):ie.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:F.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:F.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}};zn.create=t=>new zn({checks:[],coerce:t?.coerce||!1,typeName:V.ZodDate,...Q(t)});Gr=class extends re{_parse(e){if(this._getType(e)!==D.symbol){let r=this._getOrReturnCtx(e);return N(r,{code:E.invalid_type,expected:D.symbol,received:r.parsedType}),W}return Ae(e.data)}};Gr.create=t=>new Gr({typeName:V.ZodSymbol,...Q(t)});Dn=class extends re{_parse(e){if(this._getType(e)!==D.undefined){let r=this._getOrReturnCtx(e);return N(r,{code:E.invalid_type,expected:D.undefined,received:r.parsedType}),W}return Ae(e.data)}};Dn.create=t=>new Dn({typeName:V.ZodUndefined,...Q(t)});Ln=class extends re{_parse(e){if(this._getType(e)!==D.null){let r=this._getOrReturnCtx(e);return N(r,{code:E.invalid_type,expected:D.null,received:r.parsedType}),W}return Ae(e.data)}};Ln.create=t=>new Ln({typeName:V.ZodNull,...Q(t)});un=class extends re{constructor(){super(...arguments),this._any=!0}_parse(e){return Ae(e.data)}};un.create=t=>new un({typeName:V.ZodAny,...Q(t)});Dt=class extends re{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ae(e.data)}};Dt.create=t=>new Dt({typeName:V.ZodUnknown,...Q(t)});ht=class extends re{_parse(e){let n=this._getOrReturnCtx(e);return N(n,{code:E.invalid_type,expected:D.never,received:n.parsedType}),W}};ht.create=t=>new ht({typeName:V.ZodNever,...Q(t)});Zr=class extends re{_parse(e){if(this._getType(e)!==D.undefined){let r=this._getOrReturnCtx(e);return N(r,{code:E.invalid_type,expected:D.void,received:r.parsedType}),W}return Ae(e.data)}};Zr.create=t=>new Zr({typeName:V.ZodVoid,...Q(t)});Lt=class t extends re{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==D.array)return N(n,{code:E.invalid_type,expected:D.array,received:n.parsedType}),W;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?E.too_big:E.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:E.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:E.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=>Ie.mergeArray(r,o));let i=[...n.data].map((o,l)=>s.type._parseSync(new et(n,o,n.path,l)));return Ie.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:F.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:F.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:F.toString(n)}})}nonempty(e){return this.min(1,e)}};Lt.create=(t,e)=>new Lt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:V.ZodArray,...Q(e)});Ue=class t extends re{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=ie.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==D.object){let u=this._getOrReturnCtx(e);return N(u,{code:E.invalid_type,expected:D.object,received:u.parsedType}),W}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),l=[];if(!(this._def.catchall instanceof ht&&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 ht){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:E.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,w=await p.value;u.push({key:f,value:w,alwaysSet:p.alwaysSet})}return u}).then(u=>Ie.mergeObjectSync(r,u)):Ie.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return F.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:F.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:V.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 ie.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 ie.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return Hr(this)}partial(e){let n={};for(let r of ie.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 ie.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 nu(ie.objectKeys(this.shape))}};Ue.create=(t,e)=>new Ue({shape:()=>t,unknownKeys:"strip",catchall:ht.create(),typeName:V.ZodObject,...Q(e)});Ue.strictCreate=(t,e)=>new Ue({shape:()=>t,unknownKeys:"strict",catchall:ht.create(),typeName:V.ZodObject,...Q(e)});Ue.lazycreate=(t,e)=>new Ue({shape:t,unknownKeys:"strip",catchall:ht.create(),typeName:V.ZodObject,...Q(e)});Un=class extends re{_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 Le(l.ctx.common.issues));return N(n,{code:E.invalid_union,unionErrors:o}),W}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 Le(c));return N(n,{code:E.invalid_union,unionErrors:l}),W}}get options(){return this._def.options}};Un.create=(t,e)=>new Un({options:t,typeName:V.ZodUnion,...Q(e)});zt=t=>t instanceof Fn?zt(t.schema):t instanceof tt?zt(t.innerType()):t instanceof Bn?[t.value]:t instanceof Kn?t.options:t instanceof Hn?ie.objectValues(t.enum):t instanceof Gn?zt(t._def.innerType):t instanceof Dn?[void 0]:t instanceof Ln?[null]:t instanceof Qe?[void 0,...zt(t.unwrap())]:t instanceof _t?[null,...zt(t.unwrap())]:t instanceof zs||t instanceof Wn?zt(t.unwrap()):t instanceof Zn?zt(t._def.innerType):[],ki=class t extends re{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==D.object)return N(n,{code:E.invalid_type,expected:D.object,received:n.parsedType}),W;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:E.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),W)}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=zt(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:V.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...Q(r)})}};qn=class extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=(i,o)=>{if(wi(i)||wi(o))return W;let l=ba(i.value,o.value);return l.valid?((vi(i)||vi(o))&&n.dirty(),{status:n.value,value:l.data}):(N(r,{code:E.invalid_intersection_types}),W)};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}))}};qn.create=(t,e,n)=>new qn({left:t,right:e,typeName:V.ZodIntersection,...Q(n)});kt=class t extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==D.array)return N(r,{code:E.invalid_type,expected:D.array,received:r.parsedType}),W;if(r.data.length<this._def.items.length)return N(r,{code:E.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),W;!this._def.rest&&r.data.length>this._def.items.length&&(N(r,{code:E.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=>Ie.mergeArray(n,o)):Ie.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};kt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new kt({items:t,typeName:V.ZodTuple,rest:null,...Q(e)})};_i=class t extends re{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!==D.object)return N(r,{code:E.invalid_type,expected:D.object,received:r.parsedType}),W;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?Ie.mergeObjectAsync(n,s):Ie.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof re?new t({keyType:e,valueType:n,typeName:V.ZodRecord,...Q(r)}):new t({keyType:cn.create(),valueType:e,typeName:V.ZodRecord,...Q(n)})}},Wr=class extends re{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!==D.map)return N(r,{code:E.invalid_type,expected:D.map,received:r.parsedType}),W;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 W;(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 W;(u.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(u.value,p.value)}return{status:n.value,value:l}}}};Wr.create=(t,e,n)=>new Wr({valueType:e,keyType:t,typeName:V.ZodMap,...Q(n)});Vr=class t extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==D.set)return N(r,{code:E.invalid_type,expected:D.set,received:r.parsedType}),W;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(N(r,{code:E.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:E.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 W;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:F.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:F.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};Vr.create=(t,e)=>new Vr({valueType:t,minSize:null,maxSize:null,typeName:V.ZodSet,...Q(e)});Si=class t extends re{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==D.function)return N(n,{code:E.invalid_type,expected:D.function,received:n.parsedType}),W;function r(l,c){return Ms({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Br(),Mt].filter(u=>!!u),issueData:{code:E.invalid_arguments,argumentsError:c}})}function s(l,c){return Ms({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Br(),Mt].filter(u=>!!u),issueData:{code:E.invalid_return_type,returnTypeError:c}})}let i={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof dn){let l=this;return Ae(async function(...c){let u=new Le([]),p=await l._def.args.parseAsync(c,i).catch(b=>{throw u.addIssue(r(c,b)),u}),f=await Reflect.apply(o,this,p);return await l._def.returns._def.type.parseAsync(f,i).catch(b=>{throw u.addIssue(s(f,b)),u})})}else{let l=this;return Ae(function(...c){let u=l._def.args.safeParse(c,i);if(!u.success)throw new Le([r(c,u.error)]);let p=Reflect.apply(o,this,u.data),f=l._def.returns.safeParse(p,i);if(!f.success)throw new Le([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:kt.create(e).rest(Dt.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||kt.create([]).rest(Dt.create()),returns:n||Dt.create(),typeName:V.ZodFunction,...Q(r)})}},Fn=class extends re{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})}};Fn.create=(t,e)=>new Fn({getter:t,typeName:V.ZodLazy,...Q(e)});Bn=class extends re{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return N(n,{received:n.data,code:E.invalid_literal,expected:this._def.value}),W}return{status:"valid",value:e.data}}get value(){return this._def.value}};Bn.create=(t,e)=>new Bn({value:t,typeName:V.ZodLiteral,...Q(e)});Kn=class t extends re{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return N(n,{expected:ie.joinValues(r),received:n.parsedType,code:E.invalid_type}),W}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:E.invalid_enum_value,options:r}),W}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})}};Kn.create=nu;Hn=class extends re{_parse(e){let n=ie.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==D.string&&r.parsedType!==D.number){let s=ie.objectValues(n);return N(r,{expected:ie.joinValues(s),received:r.parsedType,code:E.invalid_type}),W}if(this._cache||(this._cache=new Set(ie.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=ie.objectValues(n);return N(r,{received:r.data,code:E.invalid_enum_value,options:s}),W}return Ae(e.data)}get enum(){return this._def.values}};Hn.create=(t,e)=>new Hn({values:t,typeName:V.ZodNativeEnum,...Q(e)});dn=class extends re{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==D.promise&&n.common.async===!1)return N(n,{code:E.invalid_type,expected:D.promise,received:n.parsedType}),W;let r=n.parsedType===D.promise?n.data:Promise.resolve(n.data);return Ae(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};dn.create=(t,e)=>new dn({type:t,typeName:V.ZodPromise,...Q(e)});tt=class extends re{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===V.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 W;let c=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return c.status==="aborted"?W:c.status==="dirty"?jn(c.value):n.value==="dirty"?jn(c.value):c});{if(n.value==="aborted")return W;let l=this._def.schema._parseSync({data:o,path:r.path,parent:r});return l.status==="aborted"?W:l.status==="dirty"?jn(l.value):n.value==="dirty"?jn(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"?W:(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"?W:(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(!ln(o))return W;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=>ln(o)?Promise.resolve(s.transform(o.value,i)).then(l=>({status:n.value,value:l})):W);ie.assertNever(s)}};tt.create=(t,e,n)=>new tt({schema:t,typeName:V.ZodEffects,effect:e,...Q(n)});tt.createWithPreprocess=(t,e,n)=>new tt({schema:e,effect:{type:"preprocess",transform:t},typeName:V.ZodEffects,...Q(n)});Qe=class extends re{_parse(e){return this._getType(e)===D.undefined?Ae(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Qe.create=(t,e)=>new Qe({innerType:t,typeName:V.ZodOptional,...Q(e)});_t=class extends re{_parse(e){return this._getType(e)===D.null?Ae(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};_t.create=(t,e)=>new _t({innerType:t,typeName:V.ZodNullable,...Q(e)});Gn=class extends re{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===D.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Gn.create=(t,e)=>new Gn({innerType:t,typeName:V.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Q(e)});Zn=class extends re{_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 Kr(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Le(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Le(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Zn.create=(t,e)=>new Zn({innerType:t,typeName:V.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Q(e)});Jr=class extends re{_parse(e){if(this._getType(e)!==D.nan){let r=this._getOrReturnCtx(e);return N(r,{code:E.invalid_type,expected:D.nan,received:r.parsedType}),W}return{status:"valid",value:e.data}}};Jr.create=t=>new Jr({typeName:V.ZodNaN,...Q(t)});Wm=Symbol("zod_brand"),zs=class extends re{_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}},Ds=class t extends re{_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"?W:i.status==="dirty"?(n.dirty(),jn(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"?W: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:V.ZodPipeline})}},Wn=class extends re{_parse(e){let n=this._def.innerType._parse(e),r=s=>(ln(s)&&(s.value=Object.freeze(s.value)),s);return Kr(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};Wn.create=(t,e)=>new Wn({innerType:t,typeName:V.ZodReadonly,...Q(e)});Vm={object:Ue.lazycreate};(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"})(V||(V={}));Jm=(t,e={message:`Input not instance of ${t.name}`})=>ru(n=>n instanceof t,e),su=cn.create,iu=Nn.create,Ym=Jr.create,Xm=On.create,ou=Mn.create,Qm=zn.create,eg=Gr.create,tg=Dn.create,ng=Ln.create,rg=un.create,sg=Dt.create,ig=ht.create,og=Zr.create,ag=Lt.create,lg=Ue.create,cg=Ue.strictCreate,ug=Un.create,dg=ki.create,hg=qn.create,pg=kt.create,fg=_i.create,mg=Wr.create,gg=Vr.create,yg=Si.create,bg=Fn.create,wg=Bn.create,vg=Kn.create,kg=Hn.create,_g=dn.create,Sg=tt.create,Tg=Qe.create,xg=_t.create,Rg=tt.createWithPreprocess,Ig=Ds.create,Eg=()=>su().optional(),Ag=()=>iu().optional(),Cg=()=>ou().optional(),$g={string:(t=>cn.create({...t,coerce:!0})),number:(t=>Nn.create({...t,coerce:!0})),boolean:(t=>Mn.create({...t,coerce:!0})),bigint:(t=>On.create({...t,coerce:!0})),date:(t=>zn.create({...t,coerce:!0}))},Pg=W});var _={};an(_,{BRAND:()=>Wm,DIRTY:()=>jn,EMPTY_PATH:()=>Rm,INVALID:()=>W,NEVER:()=>Pg,OK:()=>Ae,ParseStatus:()=>Ie,Schema:()=>re,ZodAny:()=>un,ZodArray:()=>Lt,ZodBigInt:()=>On,ZodBoolean:()=>Mn,ZodBranded:()=>zs,ZodCatch:()=>Zn,ZodDate:()=>zn,ZodDefault:()=>Gn,ZodDiscriminatedUnion:()=>ki,ZodEffects:()=>tt,ZodEnum:()=>Kn,ZodError:()=>Le,ZodFirstPartyTypeKind:()=>V,ZodFunction:()=>Si,ZodIntersection:()=>qn,ZodIssueCode:()=>E,ZodLazy:()=>Fn,ZodLiteral:()=>Bn,ZodMap:()=>Wr,ZodNaN:()=>Jr,ZodNativeEnum:()=>Hn,ZodNever:()=>ht,ZodNull:()=>Ln,ZodNullable:()=>_t,ZodNumber:()=>Nn,ZodObject:()=>Ue,ZodOptional:()=>Qe,ZodParsedType:()=>D,ZodPipeline:()=>Ds,ZodPromise:()=>dn,ZodReadonly:()=>Wn,ZodRecord:()=>_i,ZodSchema:()=>re,ZodSet:()=>Vr,ZodString:()=>cn,ZodSymbol:()=>Gr,ZodTransformer:()=>tt,ZodTuple:()=>kt,ZodType:()=>re,ZodUndefined:()=>Dn,ZodUnion:()=>Un,ZodUnknown:()=>Dt,ZodVoid:()=>Zr,addIssueToContext:()=>N,any:()=>rg,array:()=>ag,bigint:()=>Xm,boolean:()=>ou,coerce:()=>$g,custom:()=>ru,date:()=>Qm,datetimeRegex:()=>tu,defaultErrorMap:()=>Mt,discriminatedUnion:()=>dg,effect:()=>Sg,enum:()=>vg,function:()=>yg,getErrorMap:()=>Br,getParsedType:()=>vt,instanceof:()=>Jm,intersection:()=>hg,isAborted:()=>wi,isAsync:()=>Kr,isDirty:()=>vi,isValid:()=>ln,late:()=>Vm,lazy:()=>bg,literal:()=>wg,makeIssue:()=>Ms,map:()=>mg,nan:()=>Ym,nativeEnum:()=>kg,never:()=>ig,null:()=>ng,nullable:()=>xg,number:()=>iu,object:()=>lg,objectUtil:()=>fa,oboolean:()=>Cg,onumber:()=>Ag,optional:()=>Tg,ostring:()=>Eg,pipeline:()=>Ig,preprocess:()=>Rg,promise:()=>_g,quotelessJson:()=>Sm,record:()=>fg,set:()=>gg,setErrorMap:()=>xm,strictObject:()=>cg,string:()=>su,symbol:()=>eg,transformer:()=>Sg,tuple:()=>pg,undefined:()=>tg,union:()=>ug,unknown:()=>sg,util:()=>ie,void:()=>og});var wa=ye(()=>{bi();ga();Vc();Os();au();yi()});var Yr=ye(()=>{wa();wa()});function oe(){let t=process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR;if(t)return t;let e=xi.default.join(Ti.default.homedir(),".config","allwright"),n=xi.default.join(Ti.default.homedir(),".config","ticketpilot");return!Ut.default.existsSync(e)&&Ut.default.existsSync(n)?n:e}function qt(){return xi.default.join(oe(),"runner.json")}function we(){let t=qt();if(!Ut.default.existsSync(t))return null;let e=JSON.parse(Ut.default.readFileSync(t,"utf8"));return va.parse(e)}function ge(t){let e=oe();Ut.default.mkdirSync(e,{recursive:!0,mode:448});let n=qt(),r=n+".tmp";Ut.default.writeFileSync(r,JSON.stringify(t,null,2)+`
24
+ `,{mode:384}),Ut.default.renameSync(r,n),Ut.default.chmodSync(n,384)}function Ri(t,e){return`${t}:${e}`}function Ft(t,e,n){return t.environments[Ri(e,n)]?.secrets??{}}function Ii(t,e){return t.repos[e]?.jira??t.jira}function Ei(t){return!t.jira&&!Object.values(t.repos).some(e=>e.jira)}function le(){let t=we();if(!t)throw new Error(`No runner config found at ${qt()}. Run \`allwright init\` first.`);return t}var Ut,Ti,xi,lu,va,Ce=ye(()=>{"use strict";Ut=I(require("node:fs"),1),Ti=I(require("node:os"),1),xi=I(require("node:path"),1);Yr();lu=_.object({baseUrl:_.string().url(),email:_.string().email(),apiToken:_.string().min(1)}),va=_.object({controlPlaneUrl:_.string().url(),runnerId:_.string().optional(),runnerToken:_.string().optional(),runnerName:_.string().default(Ti.default.hostname()),jira:lu.optional(),repos:_.record(_.object({path:_.string(),jira:lu.optional(),github:_.object({token:_.string().min(1),login:_.string().optional()}).optional()})).default({}),github:_.object({token:_.string().min(1),login:_.string().optional()}).optional(),githubUsers:_.record(_.object({token:_.string().min(1),login:_.string().optional()})).default({}),deploy:_.object({enabled:_.boolean().default(!1)}).default({enabled:!1}),environments:_.record(_.object({secrets:_.record(_.string()).default({})})).default({}),claudeProfiles:_.record(_.object({configDir:_.string()})).default({}),claudeBin:_.string().default("claude"),agents:_.record(_.object({bin:_.string()})).default({}),jiraUsers:_.record(_.object({email:_.string().email(),apiToken:_.string().min(1)})).default({}),auditSchedules:_.array(_.object({repoName:_.string(),role:_.enum(["security","testing"]),intervalHours:_.number().int().min(6).max(720)})).default([]),pollIntervalSeconds:_.number().int().min(10).max(600).default(30)})});var Ls=ae(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.getParsedType=de.ZodParsedType=de.objectUtil=de.util=void 0;var Ta;(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})(Ta||(de.util=Ta={}));var wu;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(wu||(de.objectUtil=wu={}));de.ZodParsedType=Ta.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var Ug=t=>{switch(typeof t){case"undefined":return de.ZodParsedType.undefined;case"string":return de.ZodParsedType.string;case"number":return Number.isNaN(t)?de.ZodParsedType.nan:de.ZodParsedType.number;case"boolean":return de.ZodParsedType.boolean;case"function":return de.ZodParsedType.function;case"bigint":return de.ZodParsedType.bigint;case"symbol":return de.ZodParsedType.symbol;case"object":return Array.isArray(t)?de.ZodParsedType.array:t===null?de.ZodParsedType.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?de.ZodParsedType.promise:typeof Map<"u"&&t instanceof Map?de.ZodParsedType.map:typeof Set<"u"&&t instanceof Set?de.ZodParsedType.set:typeof Date<"u"&&t instanceof Date?de.ZodParsedType.date:de.ZodParsedType.object;default:return de.ZodParsedType.unknown}};de.getParsedType=Ug});var Ni=ae(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.ZodError=fn.quotelessJson=fn.ZodIssueCode=void 0;var vu=Ls();fn.ZodIssueCode=vu.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 qg=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");fn.quotelessJson=qg;var Us=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,vu.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()}};fn.ZodError=Us;Us.create=t=>new Us(t)});var Ra=ae(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});var $e=Ni(),Yn=Ls(),Fg=(t,e)=>{let n;switch(t.code){case $e.ZodIssueCode.invalid_type:t.received===Yn.ZodParsedType.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case $e.ZodIssueCode.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,Yn.util.jsonStringifyReplacer)}`;break;case $e.ZodIssueCode.unrecognized_keys:n=`Unrecognized key(s) in object: ${Yn.util.joinValues(t.keys,", ")}`;break;case $e.ZodIssueCode.invalid_union:n="Invalid input";break;case $e.ZodIssueCode.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Yn.util.joinValues(t.options)}`;break;case $e.ZodIssueCode.invalid_enum_value:n=`Invalid enum value. Expected ${Yn.util.joinValues(t.options)}, received '${t.received}'`;break;case $e.ZodIssueCode.invalid_arguments:n="Invalid function arguments";break;case $e.ZodIssueCode.invalid_return_type:n="Invalid function return type";break;case $e.ZodIssueCode.invalid_date:n="Invalid date";break;case $e.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}"`:Yn.util.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case $e.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 $e.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 $e.ZodIssueCode.custom:n="Invalid input";break;case $e.ZodIssueCode.invalid_intersection_types:n="Intersection results could not be merged";break;case $e.ZodIssueCode.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case $e.ZodIssueCode.not_finite:n="Number must be finite";break;default:n=e.defaultError,Yn.util.assertNever(t)}return{message:n}};xa.default=Fg});var Oi=ae(mn=>{"use strict";var Bg=mn&&mn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(mn,"__esModule",{value:!0});mn.defaultErrorMap=void 0;mn.setErrorMap=Kg;mn.getErrorMap=Hg;var ku=Bg(Ra());mn.defaultErrorMap=ku.default;var _u=ku.default;function Kg(t){_u=t}function Hg(){return _u}});var Ea=ae(ce=>{"use strict";var Gg=ce&&ce.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(ce,"__esModule",{value:!0});ce.isAsync=ce.isValid=ce.isDirty=ce.isAborted=ce.OK=ce.DIRTY=ce.INVALID=ce.ParseStatus=ce.EMPTY_PATH=ce.makeIssue=void 0;ce.addIssueToContext=Vg;var Zg=Oi(),Su=Gg(Ra()),Wg=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}};ce.makeIssue=Wg;ce.EMPTY_PATH=[];function Vg(t,e){let n=(0,Zg.getErrorMap)(),r=(0,ce.makeIssue)({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Su.default?void 0:Su.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 ce.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 ce.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}}};ce.ParseStatus=Ia;ce.INVALID=Object.freeze({status:"aborted"});var Jg=t=>({status:"dirty",value:t});ce.DIRTY=Jg;var Yg=t=>({status:"valid",value:t});ce.OK=Yg;var Xg=t=>t.status==="aborted";ce.isAborted=Xg;var Qg=t=>t.status==="dirty";ce.isDirty=Qg;var ey=t=>t.status==="valid";ce.isValid=ey;var ty=t=>typeof Promise<"u"&&t instanceof Promise;ce.isAsync=ty});var xu=ae(Tu=>{"use strict";Object.defineProperty(Tu,"__esModule",{value:!0})});var Iu=ae(Mi=>{"use strict";Object.defineProperty(Mi,"__esModule",{value:!0});Mi.errorUtil=void 0;var Ru;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(Ru||(Mi.errorUtil=Ru={}))});var Lu=ae(S=>{"use strict";Object.defineProperty(S,"__esModule",{value:!0});S.discriminatedUnion=S.date=S.boolean=S.bigint=S.array=S.any=S.coerce=S.ZodFirstPartyTypeKind=S.late=S.ZodSchema=S.Schema=S.ZodReadonly=S.ZodPipeline=S.ZodBranded=S.BRAND=S.ZodNaN=S.ZodCatch=S.ZodDefault=S.ZodNullable=S.ZodOptional=S.ZodTransformer=S.ZodEffects=S.ZodPromise=S.ZodNativeEnum=S.ZodEnum=S.ZodLiteral=S.ZodLazy=S.ZodFunction=S.ZodSet=S.ZodMap=S.ZodRecord=S.ZodTuple=S.ZodIntersection=S.ZodDiscriminatedUnion=S.ZodUnion=S.ZodObject=S.ZodArray=S.ZodVoid=S.ZodNever=S.ZodUnknown=S.ZodAny=S.ZodNull=S.ZodUndefined=S.ZodSymbol=S.ZodDate=S.ZodBoolean=S.ZodBigInt=S.ZodNumber=S.ZodString=S.ZodType=void 0;S.NEVER=S.void=S.unknown=S.union=S.undefined=S.tuple=S.transformer=S.symbol=S.string=S.strictObject=S.set=S.record=S.promise=S.preprocess=S.pipeline=S.ostring=S.optional=S.onumber=S.oboolean=S.object=S.number=S.nullable=S.null=S.never=S.nativeEnum=S.nan=S.map=S.literal=S.lazy=S.intersection=S.instanceof=S.function=S.enum=S.effect=void 0;S.datetimeRegex=Pu;S.custom=Nu;var C=Ni(),zi=Oi(),H=Iu(),T=Ea(),P=Ls(),rt=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}},Eu=(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 C.ZodError(t.common.issues);return this._error=n,this._error}}};function ee(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(0,P.getParsedType)(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:(0,P.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new T.ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:(0,P.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let 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,P.getParsedType)(e)},s=this._parseSync({data:e,path:r.path,parent:r});return Eu(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,P.getParsedType)(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent: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,P.getParsedType)(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await((0,T.isAsync)(s)?s:Promise.resolve(s));return Eu(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:C.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 He({schema:this,typeName:J.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 nt.create(this,this._def)}nullable(){return Tt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ht.create(this)}promise(){return bn.create(this,this._def)}or(e){return sr.create([this,e],this._def)}and(e){return ir.create(this,e,this._def)}transform(e){return new He({...ee(this._def),schema:this,typeName:J.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new ur({...ee(this._def),innerType:this,defaultValue:n,typeName:J.ZodDefault})}brand(){return new qs({typeName:J.ZodBranded,type:this,...ee(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new dr({...ee(this._def),innerType:this,catchValue:n,typeName:J.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Fs.create(this,e)}readonly(){return hr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};S.ZodType=te;S.Schema=te;S.ZodSchema=te;var ny=/^c[^\s-]{8,}$/i,ry=/^[0-9a-z]+$/,sy=/^[0-9A-HJKMNP-TV-Z]{26}$/i,iy=/^[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,oy=/^[a-z0-9_-]{21}$/i,ay=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ly=/^[-+]?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)?)??$/,cy=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,uy="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Aa,dy=/^(?:(?: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])$/,hy=/^(?:(?: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])$/,py=/^(([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]))$/,fy=/^(([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])$/,my=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,gy=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Cu="((\\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])))",yy=new RegExp(`^${Cu}$`);function $u(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 by(t){return new RegExp(`^${$u(t)}$`)}function Pu(t){let e=`${Cu}T${$u(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 wy(t,e){return!!((e==="v4"||!e)&&dy.test(t)||(e==="v6"||!e)&&py.test(t))}function vy(t,e){if(!ay.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 ky(t,e){return!!((e==="v4"||!e)&&hy.test(t)||(e==="v6"||!e)&&fy.test(t))}var gn=class t extends te{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==P.ZodParsedType.string){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:C.ZodIssueCode.invalid_type,expected:P.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:C.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:C.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:C.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):l&&(0,T.addIssueToContext)(s,{code:C.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")cy.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"email",code:C.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Aa||(Aa=new RegExp(uy,"u")),Aa.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"emoji",code:C.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")iy.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"uuid",code:C.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")oy.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"nanoid",code:C.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")ny.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"cuid",code:C.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")ry.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"cuid2",code:C.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")sy.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"ulid",code:C.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:C.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:C.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:C.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:C.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:C.ZodIssueCode.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Pu(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:C.ZodIssueCode.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?yy.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:C.ZodIssueCode.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?by(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:C.ZodIssueCode.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?ly.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"duration",code:C.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?wy(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"ip",code:C.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?vy(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"jwt",code:C.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?ky(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"cidr",code:C.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?my.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"base64",code:C.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?gy.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"base64url",code:C.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):P.util.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:C.ZodIssueCode.invalid_string,...H.errorUtil.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...H.errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...H.errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...H.errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...H.errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...H.errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...H.errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...H.errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...H.errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...H.errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...H.errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...H.errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...H.errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...H.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,...H.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,...H.errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...H.errorUtil.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...H.errorUtil.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...H.errorUtil.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...H.errorUtil.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...H.errorUtil.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...H.errorUtil.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...H.errorUtil.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...H.errorUtil.errToObj(n)})}nonempty(e){return this.min(1,H.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}};S.ZodString=gn;gn.create=t=>new gn({checks:[],typeName:J.ZodString,coerce:t?.coerce??!1,...ee(t)});function _y(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 Xn=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)!==P.ZodParsedType.number){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:C.ZodIssueCode.invalid_type,expected:P.ZodParsedType.number,received:i.parsedType}),T.INVALID}let r,s=new T.ParseStatus;for(let i of this._def.checks)i.kind==="int"?P.util.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:C.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:C.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:C.ZodIssueCode.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?_y(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:C.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:C.ZodIssueCode.not_finite,message:i.message}),s.dirty()):P.util.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,H.errorUtil.toString(n))}gt(e,n){return this.setLimit("min",e,!1,H.errorUtil.toString(n))}lte(e,n){return this.setLimit("max",e,!0,H.errorUtil.toString(n))}lt(e,n){return this.setLimit("max",e,!1,H.errorUtil.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:H.errorUtil.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:H.errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:H.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:H.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:H.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:H.errorUtil.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:H.errorUtil.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:H.errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:H.errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:H.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"&&P.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)}};S.ZodNumber=Xn;Xn.create=t=>new Xn({checks:[],typeName:J.ZodNumber,coerce:t?.coerce||!1,...ee(t)});var Qn=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)!==P.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:C.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:C.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:C.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):P.util.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:P.ZodParsedType.bigint,received:n.parsedType}),T.INVALID}gte(e,n){return this.setLimit("min",e,!0,H.errorUtil.toString(n))}gt(e,n){return this.setLimit("min",e,!1,H.errorUtil.toString(n))}lte(e,n){return this.setLimit("max",e,!0,H.errorUtil.toString(n))}lt(e,n){return this.setLimit("max",e,!1,H.errorUtil.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:H.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:H.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:H.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:H.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:H.errorUtil.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:H.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}};S.ZodBigInt=Qn;Qn.create=t=>new Qn({checks:[],typeName:J.ZodBigInt,coerce:t?.coerce??!1,...ee(t)});var er=class extends te{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==P.ZodParsedType.boolean){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:C.ZodIssueCode.invalid_type,expected:P.ZodParsedType.boolean,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};S.ZodBoolean=er;er.create=t=>new er({typeName:J.ZodBoolean,coerce:t?.coerce||!1,...ee(t)});var tr=class t extends te{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==P.ZodParsedType.date){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:C.ZodIssueCode.invalid_type,expected:P.ZodParsedType.date,received:i.parsedType}),T.INVALID}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:C.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:C.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:C.ZodIssueCode.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):P.util.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:H.errorUtil.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:H.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}};S.ZodDate=tr;tr.create=t=>new tr({checks:[],coerce:t?.coerce||!1,typeName:J.ZodDate,...ee(t)});var rs=class extends te{_parse(e){if(this._getType(e)!==P.ZodParsedType.symbol){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:C.ZodIssueCode.invalid_type,expected:P.ZodParsedType.symbol,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};S.ZodSymbol=rs;rs.create=t=>new rs({typeName:J.ZodSymbol,...ee(t)});var nr=class extends te{_parse(e){if(this._getType(e)!==P.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:C.ZodIssueCode.invalid_type,expected:P.ZodParsedType.undefined,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};S.ZodUndefined=nr;nr.create=t=>new nr({typeName:J.ZodUndefined,...ee(t)});var rr=class extends te{_parse(e){if(this._getType(e)!==P.ZodParsedType.null){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:C.ZodIssueCode.invalid_type,expected:P.ZodParsedType.null,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};S.ZodNull=rr;rr.create=t=>new rr({typeName:J.ZodNull,...ee(t)});var yn=class extends te{constructor(){super(...arguments),this._any=!0}_parse(e){return(0,T.OK)(e.data)}};S.ZodAny=yn;yn.create=t=>new yn({typeName:J.ZodAny,...ee(t)});var Kt=class extends te{constructor(){super(...arguments),this._unknown=!0}_parse(e){return(0,T.OK)(e.data)}};S.ZodUnknown=Kt;Kt.create=t=>new Kt({typeName:J.ZodUnknown,...ee(t)});var pt=class extends te{_parse(e){let n=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:P.ZodParsedType.never,received:n.parsedType}),T.INVALID}};S.ZodNever=pt;pt.create=t=>new pt({typeName:J.ZodNever,...ee(t)});var ss=class extends te{_parse(e){if(this._getType(e)!==P.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:C.ZodIssueCode.invalid_type,expected:P.ZodParsedType.void,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};S.ZodVoid=ss;ss.create=t=>new ss({typeName:J.ZodVoid,...ee(t)});var Ht=class t extends te{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==P.ZodParsedType.array)return(0,T.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:P.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?C.ZodIssueCode.too_big:C.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:C.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:C.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 rt(n,o,n.path,l)))).then(o=>T.ParseStatus.mergeArray(r,o));let i=[...n.data].map((o,l)=>s.type._parseSync(new rt(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:H.errorUtil.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:H.errorUtil.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:H.errorUtil.toString(n)}})}nonempty(e){return this.min(1,e)}};S.ZodArray=Ht;Ht.create=(t,e)=>new Ht({type:t,minLength:null,maxLength:null,exactLength:null,typeName:J.ZodArray,...ee(e)});function ns(t){if(t instanceof qe){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=nt.create(ns(r))}return new qe({...t._def,shape:()=>e})}else return t instanceof Ht?new Ht({...t._def,type:ns(t.element)}):t instanceof nt?nt.create(ns(t.unwrap())):t instanceof Tt?Tt.create(ns(t.unwrap())):t instanceof St?St.create(t.items.map(e=>ns(e))):t}var qe=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=P.util.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==P.ZodParsedType.object){let u=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(u,{code:C.ZodIssueCode.invalid_type,expected:P.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 pt&&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 rt(s,f,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof pt){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:C.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 rt(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,w=await p.value;u.push({key:f,value:w,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 H.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:H.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:J.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 P.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 P.util.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return ns(this)}partial(e){let n={};for(let r of P.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 P.util.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof nt;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return ju(P.util.objectKeys(this.shape))}};S.ZodObject=qe;qe.create=(t,e)=>new qe({shape:()=>t,unknownKeys:"strip",catchall:pt.create(),typeName:J.ZodObject,...ee(e)});qe.strictCreate=(t,e)=>new qe({shape:()=>t,unknownKeys:"strict",catchall:pt.create(),typeName:J.ZodObject,...ee(e)});qe.lazycreate=(t,e)=>new qe({shape:t,unknownKeys:"strip",catchall:pt.create(),typeName:J.ZodObject,...ee(e)});var sr=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 C.ZodError(l.ctx.common.issues));return(0,T.addIssueToContext)(n,{code:C.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 C.ZodError(c));return(0,T.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_union,unionErrors:l}),T.INVALID}}get options(){return this._def.options}};S.ZodUnion=sr;sr.create=(t,e)=>new sr({options:t,typeName:J.ZodUnion,...ee(e)});var Bt=t=>t instanceof or?Bt(t.schema):t instanceof He?Bt(t.innerType()):t instanceof ar?[t.value]:t instanceof lr?t.options:t instanceof cr?P.util.objectValues(t.enum):t instanceof ur?Bt(t._def.innerType):t instanceof nr?[void 0]:t instanceof rr?[null]:t instanceof nt?[void 0,...Bt(t.unwrap())]:t instanceof Tt?[null,...Bt(t.unwrap())]:t instanceof qs||t instanceof hr?Bt(t.unwrap()):t instanceof dr?Bt(t._def.innerType):[],Di=class t extends te{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==P.ZodParsedType.object)return(0,T.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:P.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:C.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=Bt(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:J.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...ee(r)})}};S.ZodDiscriminatedUnion=Di;function Ca(t,e){let n=(0,P.getParsedType)(t),r=(0,P.getParsedType)(e);if(t===e)return{valid:!0,data:t};if(n===P.ZodParsedType.object&&r===P.ZodParsedType.object){let s=P.util.objectKeys(e),i=P.util.objectKeys(t).filter(l=>s.indexOf(l)!==-1),o={...t,...e};for(let l of i){let c=Ca(t[l],e[l]);if(!c.valid)return{valid:!1};o[l]=c.data}return{valid:!0,data:o}}else if(n===P.ZodParsedType.array&&r===P.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=Ca(o,l);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===P.ZodParsedType.date&&r===P.ZodParsedType.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var ir=class extends te{_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=Ca(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:C.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}))}};S.ZodIntersection=ir;ir.create=(t,e,n)=>new ir({left:t,right:e,typeName:J.ZodIntersection,...ee(n)});var St=class t extends te{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==P.ZodParsedType.array)return(0,T.addIssueToContext)(r,{code:C.ZodIssueCode.invalid_type,expected:P.ZodParsedType.array,received:r.parsedType}),T.INVALID;if(r.data.length<this._def.items.length)return(0,T.addIssueToContext)(r,{code:C.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:C.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 rt(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})}};S.ZodTuple=St;St.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new St({items:t,typeName:J.ZodTuple,rest:null,...ee(e)})};var Li=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!==P.ZodParsedType.object)return(0,T.addIssueToContext)(r,{code:C.ZodIssueCode.invalid_type,expected:P.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 rt(r,l,r.path,l)),value:o._parse(new rt(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 te?new t({keyType:e,valueType:n,typeName:J.ZodRecord,...ee(r)}):new t({keyType:gn.create(),valueType:e,typeName:J.ZodRecord,...ee(n)})}};S.ZodRecord=Li;var is=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!==P.ZodParsedType.map)return(0,T.addIssueToContext)(r,{code:C.ZodIssueCode.invalid_type,expected:P.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 rt(r,l,r.path,[u,"key"])),value:i._parse(new rt(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}}}};S.ZodMap=is;is.create=(t,e,n)=>new is({valueType:e,keyType:t,typeName:J.ZodMap,...ee(n)});var os=class t extends te{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==P.ZodParsedType.set)return(0,T.addIssueToContext)(r,{code:C.ZodIssueCode.invalid_type,expected:P.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:C.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:C.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 rt(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:H.errorUtil.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:H.errorUtil.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};S.ZodSet=os;os.create=(t,e)=>new os({valueType:t,minSize:null,maxSize:null,typeName:J.ZodSet,...ee(e)});var Ui=class t extends te{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==P.ZodParsedType.function)return(0,T.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:P.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,zi.getErrorMap)(),zi.defaultErrorMap].filter(u=>!!u),issueData:{code:C.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,zi.getErrorMap)(),zi.defaultErrorMap].filter(u=>!!u),issueData:{code:C.ZodIssueCode.invalid_return_type,returnTypeError:c}})}let i={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof bn){let l=this;return(0,T.OK)(async function(...c){let u=new C.ZodError([]),p=await l._def.args.parseAsync(c,i).catch(b=>{throw u.addIssue(r(c,b)),u}),f=await Reflect.apply(o,this,p);return await l._def.returns._def.type.parseAsync(f,i).catch(b=>{throw u.addIssue(s(f,b)),u})})}else{let l=this;return(0,T.OK)(function(...c){let u=l._def.args.safeParse(c,i);if(!u.success)throw new C.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 C.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:St.create(e).rest(Kt.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||St.create([]).rest(Kt.create()),returns:n||Kt.create(),typeName:J.ZodFunction,...ee(r)})}};S.ZodFunction=Ui;var or=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})}};S.ZodLazy=or;or.create=(t,e)=>new or({getter:t,typeName:J.ZodLazy,...ee(e)});var ar=class extends te{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(n,{received:n.data,code:C.ZodIssueCode.invalid_literal,expected:this._def.value}),T.INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}};S.ZodLiteral=ar;ar.create=(t,e)=>new ar({value:t,typeName:J.ZodLiteral,...ee(e)});function ju(t,e){return new lr({values:t,typeName:J.ZodEnum,...ee(e)})}var lr=class t extends te{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return(0,T.addIssueToContext)(n,{expected:P.util.joinValues(r),received:n.parsedType,code:C.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:C.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})}};S.ZodEnum=lr;lr.create=ju;var cr=class extends te{_parse(e){let n=P.util.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==P.ZodParsedType.string&&r.parsedType!==P.ZodParsedType.number){let s=P.util.objectValues(n);return(0,T.addIssueToContext)(r,{expected:P.util.joinValues(s),received:r.parsedType,code:C.ZodIssueCode.invalid_type}),T.INVALID}if(this._cache||(this._cache=new Set(P.util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=P.util.objectValues(n);return(0,T.addIssueToContext)(r,{received:r.data,code:C.ZodIssueCode.invalid_enum_value,options:s}),T.INVALID}return(0,T.OK)(e.data)}get enum(){return this._def.values}};S.ZodNativeEnum=cr;cr.create=(t,e)=>new cr({values:t,typeName:J.ZodNativeEnum,...ee(e)});var bn=class extends te{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==P.ZodParsedType.promise&&n.common.async===!1)return(0,T.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:P.ZodParsedType.promise,received:n.parsedType}),T.INVALID;let r=n.parsedType===P.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})))}};S.ZodPromise=bn;bn.create=(t,e)=>new bn({type:t,typeName:J.ZodPromise,...ee(e)});var He=class extends te{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===J.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);P.util.assertNever(s)}};S.ZodEffects=He;S.ZodTransformer=He;He.create=(t,e,n)=>new He({schema:t,typeName:J.ZodEffects,effect:e,...ee(n)});He.createWithPreprocess=(t,e,n)=>new He({schema:e,effect:{type:"preprocess",transform:t},typeName:J.ZodEffects,...ee(n)});var nt=class extends te{_parse(e){return this._getType(e)===P.ZodParsedType.undefined?(0,T.OK)(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};S.ZodOptional=nt;nt.create=(t,e)=>new nt({innerType:t,typeName:J.ZodOptional,...ee(e)});var Tt=class extends te{_parse(e){return this._getType(e)===P.ZodParsedType.null?(0,T.OK)(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};S.ZodNullable=Tt;Tt.create=(t,e)=>new Tt({innerType:t,typeName:J.ZodNullable,...ee(e)});var ur=class extends te{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===P.ZodParsedType.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};S.ZodDefault=ur;ur.create=(t,e)=>new ur({innerType:t,typeName:J.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ee(e)});var dr=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(0,T.isAsync)(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new C.ZodError(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new C.ZodError(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};S.ZodCatch=dr;dr.create=(t,e)=>new dr({innerType:t,typeName:J.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ee(e)});var as=class extends te{_parse(e){if(this._getType(e)!==P.ZodParsedType.nan){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:C.ZodIssueCode.invalid_type,expected:P.ZodParsedType.nan,received:r.parsedType}),T.INVALID}return{status:"valid",value:e.data}}};S.ZodNaN=as;as.create=t=>new as({typeName:J.ZodNaN,...ee(t)});S.BRAND=Symbol("zod_brand");var qs=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.ZodBranded=qs;var Fs=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"?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:J.ZodPipeline})}};S.ZodPipeline=Fs;var hr=class extends te{_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}};S.ZodReadonly=hr;hr.create=(t,e)=>new hr({innerType:t,typeName:J.ZodReadonly,...ee(e)});function Au(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function Nu(t,e={},n){return t?yn.create().superRefine((r,s)=>{let i=t(r);if(i instanceof Promise)return i.then(o=>{if(!o){let l=Au(e,r),c=l.fatal??n??!0;s.addIssue({code:"custom",...l,fatal:c})}});if(!i){let o=Au(e,r),l=o.fatal??n??!0;s.addIssue({code:"custom",...o,fatal:l})}}):yn.create()}S.late={object:qe.lazycreate};var J;(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"})(J||(S.ZodFirstPartyTypeKind=J={}));var Sy=(t,e={message:`Input not instance of ${t.name}`})=>Nu(n=>n instanceof t,e);S.instanceof=Sy;var Ou=gn.create;S.string=Ou;var Mu=Xn.create;S.number=Mu;var Ty=as.create;S.nan=Ty;var xy=Qn.create;S.bigint=xy;var zu=er.create;S.boolean=zu;var Ry=tr.create;S.date=Ry;var Iy=rs.create;S.symbol=Iy;var Ey=nr.create;S.undefined=Ey;var Ay=rr.create;S.null=Ay;var Cy=yn.create;S.any=Cy;var $y=Kt.create;S.unknown=$y;var Py=pt.create;S.never=Py;var jy=ss.create;S.void=jy;var Ny=Ht.create;S.array=Ny;var Oy=qe.create;S.object=Oy;var My=qe.strictCreate;S.strictObject=My;var zy=sr.create;S.union=zy;var Dy=Di.create;S.discriminatedUnion=Dy;var Ly=ir.create;S.intersection=Ly;var Uy=St.create;S.tuple=Uy;var qy=Li.create;S.record=qy;var Fy=is.create;S.map=Fy;var By=os.create;S.set=By;var Ky=Ui.create;S.function=Ky;var Hy=or.create;S.lazy=Hy;var Gy=ar.create;S.literal=Gy;var Zy=lr.create;S.enum=Zy;var Wy=cr.create;S.nativeEnum=Wy;var Vy=bn.create;S.promise=Vy;var Du=He.create;S.effect=Du;S.transformer=Du;var Jy=nt.create;S.optional=Jy;var Yy=Tt.create;S.nullable=Yy;var Xy=He.createWithPreprocess;S.preprocess=Xy;var Qy=Fs.create;S.pipeline=Qy;var eb=()=>Ou().optional();S.ostring=eb;var tb=()=>Mu().optional();S.onumber=tb;var nb=()=>zu().optional();S.oboolean=nb;S.coerce={string:(t=>gn.create({...t,coerce:!0})),number:(t=>Xn.create({...t,coerce:!0})),boolean:(t=>er.create({...t,coerce:!0})),bigint:(t=>Qn.create({...t,coerce:!0})),date:(t=>tr.create({...t,coerce:!0}))};S.NEVER=T.INVALID});var $a=ae(st=>{"use strict";var rb=st&&st.__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]})),ls=st&&st.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&rb(e,t,n)};Object.defineProperty(st,"__esModule",{value:!0});ls(Oi(),st);ls(Ea(),st);ls(xu(),st);ls(Ls(),st);ls(Lu(),st);ls(Ni(),st)});var Fu=ae(Fe=>{"use strict";var Uu=Fe&&Fe.__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]})),sb=Fe&&Fe.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),ib=Fe&&Fe.__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)&&Uu(e,t,n);return sb(e,t),e},ob=Fe&&Fe.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Uu(e,t,n)};Object.defineProperty(Fe,"__esModule",{value:!0});Fe.z=void 0;var qu=ib($a());Fe.z=qu;ob($a(),Fe);Fe.default=qu});var ke=ae(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});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.RUNNER_UNINSTALL_COMMAND=h.PROTOCOL_VERSION=h.GITHUB_TOKEN_PERMISSIONS=void 0;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.AuditExplainResultMsg=h.AuditExplainMsg=h.ChatCancelMsg=h.ChatDiagnosticResultMsg=h.ChatDiagnosticMsg=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=h.ChatLoadResultMsg=void 0;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.AutopilotPlanResultMsg=h.AutopilotPlanMsg=h.AutopilotNextMsg=h.RunnerUninstallResultMsg=h.RunnerUpdateResultMsg=h.AgentProfilesResultMsg=h.AgentProfilesMsg=h.RunPrConflictMsg=h.RunResolveConflictResultMsg=h.RunAnswerResultMsg=h.RunAnswerMsg=h.RunTestFixResultMsg=h.RunTestFixMsg=h.RunResolveConflictMsg=h.RunnerUninstallMsg=h.RunnerUpdateMsg=h.RepoDocSaveResultMsg=h.RepoDocSaveMsg=h.SetupClaudeMdSaveResultMsg=h.SetupClaudeMdSaveMsg=h.SetupClaudeMdGenerateResultMsg=h.SetupClaudeMdGenerateMsg=h.SetupRecheckResultMsg=h.SetupRecheckMsg=h.RepoUnmapResultMsg=h.RepoUnmapMsg=h.SetupStatusResultMsg=h.SetupStatusMsg=h.DeploySuggestResultMsg=h.SelfMigrationApplyResultMsg=h.SelfMigrationApplyMsg=h.SELF_MIGRATION_DIR=void 0;h.DEFAULT_DEPLOY_SUGGEST_PROMPT_TEMPLATE=h.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE=h.DEPLOY_FIX_PROMPT_TEMPLATE=h.PROMPT_PRESETS=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=void 0;h.missingAgentCapabilities=ab;h.replyPreferenceAppendix=cb;h.pendingMigrationsAppendix=ub;h.isSelfMigrationFilename=db;h.parseRunnerMsg=hb;h.parseServerMsg=pb;var a=Fu();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.70";h.RUNNER_UNINSTALL_COMMAND="sudo allwright service uninstall";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 ab(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 lb=t=>t.includes(h.NEEDS_INPUT_COMMENT_MARKER)||h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS.some(e=>t.includes(e));h.needsInputMarkerIn=lb;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 cb(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?`
25
25
 
26
26
  HOW TO WRITE THE REPLY - the person you are answering chose this, so it applies to every reply in this conversation:
27
27
  - ${e.join(`
28
28
  - `)}
29
- `:""}function Xy(t){if(!t.length)return"";let e="```";return`
29
+ `:""}function ub(t){if(!t.length)return"";let e="```";return`
30
30
 
31
31
  PENDING DATABASE MIGRATIONS (fact, read from this database's own ledger just now):
32
32
  `+t.map(n=>`- ${h.SELF_MIGRATION_DIR}/${n}`).join(`
@@ -35,7 +35,7 @@ These files are checked in but NOT applied to the database this control plane ru
35
35
  ${e}action
36
36
  {"type": "apply-migration", "file": "<one filename from the list above>"}
37
37
  ${e}
38
- 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","functional"]);h.KnowledgeRole=a.z.enum(["security","testing","architecture","functional","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"),baseUrl:a.z.string().default("")});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.ChatCancelMsg=a.z.object({type:a.z.literal("chat.cancel"),requestId:a.z.string(),turnId:a.z.string()});h.AuditExplainMsg=a.z.object({type:a.z.literal("audit.explain"),requestId:a.z.string(),projectId:a.z.string(),auditId:a.z.string(),findingId:a.z.string()});h.AuditExplainResultMsg=a.z.object({type:a.z.literal("audit.explain.result"),requestId:a.z.string(),ok:a.z.boolean().default(!0),error:a.z.string().default(""),explanation:a.z.string().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 Qy(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.RunnerUninstallMsg=a.z.object({type:a.z.literal("runner.uninstall"),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.RunnerUninstallResultMsg=a.z.object({type:a.z.literal("runner.uninstall.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),note:a.z.string().default(""),serviceRemoved:a.z.boolean().default(!1),configRemoved:a.z.boolean().default(!1)});h.AutopilotNextMsg=a.z.object({type:a.z.literal("autopilot.next"),requestId:a.z.string()});h.AutopilotPlanMsg=a.z.object({type:a.z.literal("autopilot.plan"),requestId:a.z.string(),projectId:a.z.string(),batchId:a.z.string(),issueKeys:a.z.array(a.z.string()).min(1).max(50)});h.AutopilotPlanResultMsg=a.z.object({type:a.z.literal("autopilot.plan.result"),requestId:a.z.string(),ok:a.z.boolean().default(!0),error:a.z.string().default(""),order:a.z.array(a.z.string()).default([]),chains:a.z.array(a.z.array(a.z.string())).default([]),dependencies:a.z.array(a.z.tuple([a.z.string(),a.z.string()])).default([]),reasoning:a.z.string().default("")});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),batchId:a.z.string().default(""),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.AuditExplainResultMsg,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.RunnerUninstallResultMsg,h.AgentProfilesResultMsg,h.RunPrConflictMsg,h.RunResolveConflictResultMsg,h.RunTestFixResultMsg,h.RunAnswerResultMsg,h.AuditStatsResultMsg,h.AutopilotNextMsg,h.AutopilotReportMsg,h.AutopilotPlanResultMsg]);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.AuditExplainMsg,h.ChatCancelMsg,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.RunnerUninstallMsg,h.AgentProfilesMsg,h.RunResolveConflictMsg,h.RunTestFixMsg,h.RunAnswerMsg,h.AuditStatsMsg,h.AutopilotNextResultMsg,h.AutopilotPlanMsg]);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 eb(t){return h.RunnerToServerMsg.parse(t)}function tb(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
+ 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","functional"]);h.KnowledgeRole=a.z.enum(["security","testing","architecture","functional","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"),baseUrl:a.z.string().default("")});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.ChatDiagnosticMsg=a.z.object({type:a.z.literal("chat.diagnostic"),requestId:a.z.string(),projectId:a.z.string(),command:a.z.string().max(40),args:a.z.record(a.z.unknown()).default({})});h.ChatDiagnosticResultMsg=a.z.object({type:a.z.literal("chat.diagnostic.result"),requestId:a.z.string(),ok:a.z.boolean().default(!0),commandLine:a.z.string().default(""),output:a.z.string().default("")});h.ChatCancelMsg=a.z.object({type:a.z.literal("chat.cancel"),requestId:a.z.string(),turnId:a.z.string()});h.AuditExplainMsg=a.z.object({type:a.z.literal("audit.explain"),requestId:a.z.string(),projectId:a.z.string(),auditId:a.z.string(),findingId:a.z.string()});h.AuditExplainResultMsg=a.z.object({type:a.z.literal("audit.explain.result"),requestId:a.z.string(),ok:a.z.boolean().default(!0),error:a.z.string().default(""),explanation:a.z.string().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 db(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.RunnerUninstallMsg=a.z.object({type:a.z.literal("runner.uninstall"),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.RunnerUninstallResultMsg=a.z.object({type:a.z.literal("runner.uninstall.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),note:a.z.string().default(""),serviceRemoved:a.z.boolean().default(!1),configRemoved:a.z.boolean().default(!1)});h.AutopilotNextMsg=a.z.object({type:a.z.literal("autopilot.next"),requestId:a.z.string()});h.AutopilotPlanMsg=a.z.object({type:a.z.literal("autopilot.plan"),requestId:a.z.string(),projectId:a.z.string(),batchId:a.z.string(),issueKeys:a.z.array(a.z.string()).min(1).max(50)});h.AutopilotPlanResultMsg=a.z.object({type:a.z.literal("autopilot.plan.result"),requestId:a.z.string(),ok:a.z.boolean().default(!0),error:a.z.string().default(""),order:a.z.array(a.z.string()).default([]),chains:a.z.array(a.z.array(a.z.string())).default([]),dependencies:a.z.array(a.z.tuple([a.z.string(),a.z.string()])).default([]),reasoning:a.z.string().default("")});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),batchId:a.z.string().default(""),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.AuditExplainResultMsg,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.RunnerUninstallResultMsg,h.AgentProfilesResultMsg,h.RunPrConflictMsg,h.RunResolveConflictResultMsg,h.RunTestFixResultMsg,h.RunAnswerResultMsg,h.AuditStatsResultMsg,h.AutopilotNextMsg,h.AutopilotReportMsg,h.AutopilotPlanResultMsg,h.ChatDiagnosticResultMsg]);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.AuditExplainMsg,h.ChatCancelMsg,h.ChatDiagnosticMsg,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.RunnerUninstallMsg,h.AgentProfilesMsg,h.RunResolveConflictMsg,h.RunTestFixMsg,h.RunAnswerMsg,h.AuditStatsMsg,h.AutopilotNextResultMsg,h.AutopilotPlanMsg]);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 hb(t){return h.RunnerToServerMsg.parse(t)}function pb(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.
39
39
 
40
40
  Ticket {{issueKey}}: {{summary}}
41
41
 
@@ -290,45 +290,45 @@ Rules for the steps:
290
290
  - "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.
291
291
  - Prefer commands that are safe to re-run; a deploy may be retried.
292
292
  - Order matters: install, build, test (if cheap), then release.
293
- - If you genuinely cannot tell how this repo is deployed, return an empty "steps" array and explain what is missing in "notes".`});var Bu={};on(Bu,{DELETE_MANIFEST_FILE:()=>Ht,MAX_CHANGED_FILES:()=>bn,MAX_CHANGED_LINES:()=>wn,abortMerge:()=>_n,applyDeleteManifest:()=>ls,branchForIssue:()=>Na,branchSha:()=>Gi,branchesDiffer:()=>Fa,checkDiffSafety:()=>kn,checkoutBranchInWorktree:()=>Oa,commitAll:()=>pr,commitMergeResolution:()=>La,deleteStaleBranch:()=>$a,diffAgainstDefault:()=>Zi,envCheckoutPath:()=>Fu,envCheckoutsRoot:()=>qu,fetchBase:()=>vn,findConflictMarkers:()=>Wi,headSha:()=>it,mergeBaseIntoWorktree:()=>Da,mergeTicketBranch:()=>za,originUrl:()=>mr,parseOwnerRepo:()=>pt,prepareEnvCheckout:()=>Ma,pruneWorktrees:()=>ja,pushBranch:()=>fr,pushEnvBranch:()=>qa,pushWipBranch:()=>Aa,removeWorktree:()=>Tt,resetHard:()=>cs,statusSnapshot:()=>Ca,unresolvedAmong:()=>Ua,worktreeAdd:()=>Pa,worktreeAddExisting:()=>Bs,worktreeFingerprint:()=>Hi,worktreesRoot:()=>Gt});async function K(t,e,n={}){try{let{stdout:r}=await Lu("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 ls(t){let e={deleted:[],refused:[]},n=pe.default.join(t,Ht);if(!Te.default.existsSync(n))return e;let r=pe.default.resolve(t),s=Te.default.readFileSync(n,"utf8").split(`
294
- `).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#"));for(let i of s.slice(0,200)){if(pe.default.isAbsolute(i)){e.refused.push(`${i} - absolute paths are not allowed`);continue}let o=pe.default.resolve(r,i);if(o!==r&&!o.startsWith(r+pe.default.sep)){e.refused.push(`${i} - escapes the worktree`);continue}let l=pe.default.relative(r,o).split(pe.default.sep).join("/");if(l===Ht)continue;if(Uu.some(u=>u.test(l))){e.refused.push(`${i} - protected path (CI/hook files are never touched)`);continue}let c;try{c=Te.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{Te.default.rmSync(o),e.deleted.push(l)}catch(u){e.refused.push(`${i} - ${u instanceof Error?u.message:"delete failed"}`)}}return Te.default.rmSync(n,{force:!0}),e}async function Aa(t,e){await K(t,["push","--force","origin",`HEAD:refs/heads/${e}`],{timeoutMs:3e5})}async function Hi(t){let e=await K(t,["status","--porcelain"]),n=await K(t,["diff","--numstat"]),r=e.split(`
293
+ - If you genuinely cannot tell how this repo is deployed, return an empty "steps" array and explain what is missing in "notes".`});var Xu={};an(Xu,{DELETE_MANIFEST_FILE:()=>Gt,MAX_CHANGED_FILES:()=>wn,MAX_CHANGED_LINES:()=>vn,abortMerge:()=>Sn,applyDeleteManifest:()=>cs,branchForIssue:()=>za,branchSha:()=>Gi,branchesDiffer:()=>Ha,checkDiffSafety:()=>_n,checkoutBranchInWorktree:()=>Da,commitAll:()=>fr,commitMergeResolution:()=>Fa,deleteStaleBranch:()=>Na,diffAgainstDefault:()=>Zi,envCheckoutPath:()=>Yu,envCheckoutsRoot:()=>Ju,fetchBase:()=>kn,findConflictMarkers:()=>Wi,headSha:()=>it,mergeBaseIntoWorktree:()=>qa,mergeTicketBranch:()=>Ua,originUrl:()=>gr,parseOwnerRepo:()=>ft,prepareEnvCheckout:()=>La,pruneWorktrees:()=>Ma,pushBranch:()=>mr,pushEnvBranch:()=>Ka,pushWipBranch:()=>Pa,removeWorktree:()=>xt,resetHard:()=>us,statusSnapshot:()=>ja,unresolvedAmong:()=>Ba,worktreeAdd:()=>Oa,worktreeAddExisting:()=>Ks,worktreeFingerprint:()=>Hi,worktreesRoot:()=>Zt});async function K(t,e,n={}){try{let{stdout:r}=await Wu("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 cs(t){let e={deleted:[],refused:[]},n=pe.default.join(t,Gt);if(!Te.default.existsSync(n))return e;let r=pe.default.resolve(t),s=Te.default.readFileSync(n,"utf8").split(`
294
+ `).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#"));for(let i of s.slice(0,200)){if(pe.default.isAbsolute(i)){e.refused.push(`${i} - absolute paths are not allowed`);continue}let o=pe.default.resolve(r,i);if(o!==r&&!o.startsWith(r+pe.default.sep)){e.refused.push(`${i} - escapes the worktree`);continue}let l=pe.default.relative(r,o).split(pe.default.sep).join("/");if(l===Gt)continue;if(Vu.some(u=>u.test(l))){e.refused.push(`${i} - protected path (CI/hook files are never touched)`);continue}let c;try{c=Te.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{Te.default.rmSync(o),e.deleted.push(l)}catch(u){e.refused.push(`${i} - ${u instanceof Error?u.message:"delete failed"}`)}}return Te.default.rmSync(n,{force:!0}),e}async function Pa(t,e){await K(t,["push","--force","origin",`HEAD:refs/heads/${e}`],{timeoutMs:3e5})}async function Hi(t){let e=await K(t,["status","--porcelain"]),n=await K(t,["diff","--numstat"]),r=e.split(`
295
295
  `).filter(s=>s.startsWith("??")).map(s=>s.slice(3).trim()).slice(0,500).map(s=>{try{let i=Te.default.statSync(pe.default.join(t,s));return`${s}:${i.size}:${i.mtimeMs}`}catch{return s}}).join(`
296
296
  `);return`${e}
297
297
  --
298
298
  ${n}
299
299
  --
300
- ${r}`}async function Ca(t){let e=(await K(t,["rev-parse","--abbrev-ref","HEAD"])).trim(),n=(await K(t,["log","--oneline","-1"])).trim(),r=(await K(t,["status","--porcelain"])).trim(),s=r?r.split(`
300
+ ${r}`}async function ja(t){let e=(await K(t,["rev-parse","--abbrev-ref","HEAD"])).trim(),n=(await K(t,["log","--oneline","-1"])).trim(),r=(await K(t,["status","--porcelain"])).trim(),s=r?r.split(`
301
301
  `):[],i=s.slice(0,15).join(`
302
302
  `),o=s.length>15?`
303
303
  (\u2026 ${s.length-15} more)`:"";return`branch ${e} @ ${n}
304
304
  working tree: ${s.length?`
305
- ${i}${o}`:"clean"}`}function Gt(){let t=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(Te.default.existsSync(pe.default.join(hr.default.homedir(),".cache","ticketpilot"))?pe.default.join(hr.default.homedir(),".cache","ticketpilot"):pe.default.join(hr.default.homedir(),".cache","allwright"));return pe.default.join(t,"worktrees")}async function vn(t,e){try{await K(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 $a(t,e){try{let n=await K(t,["worktree","list","--porcelain"]),r=Gt(),s=null;for(let i of n.split(`
306
- `))i.startsWith("worktree ")&&(s=i.slice(9).trim()),i===`branch refs/heads/${e}`&&s&&s.startsWith(r)&&await K(t,["worktree","remove","--force",s]);await K(t,["worktree","prune"])}catch{}try{await K(t,["branch","-D",e])}catch{}}async function Pa(t,e,n,r){Te.default.mkdirSync(pe.default.dirname(e),{recursive:!0,mode:448}),await K(t,["worktree","add","-b",n,e,`origin/${r}`])}async function pr(t,e){if(await K(t,["add","-A"]),!(await K(t,["status","--porcelain"])).trim())throw new Error("Claude wrote no changes - nothing to commit");await K(t,["-c",`user.name=${Bi}`,"-c",`user.email=${Ki}`,"commit","-m",e])}async function kn(t,e){let r=(await K(t,["diff","--name-only",`origin/${e}...HEAD`])).split(`
307
- `).filter(Boolean),s=r.filter(u=>Uu.some(p=>p.test(u))),i=await K(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<=bn&&o+l<=wn,files:r.length,insertions:o,deletions:l,forbidden:s}}async function fr(t,e){await K(t,["fetch","--prune","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],{timeoutMs:12e4}).catch(()=>K(t,["update-ref","-d",`refs/remotes/origin/${e}`]).catch(()=>{})),await K(t,["push","--force-with-lease","-u","origin",e],{timeoutMs:3e5})}async function it(t){return(await K(t,["rev-parse","HEAD"])).trim()}async function Gi(t,e){try{return(await K(t,["rev-parse","--verify",`refs/heads/${e}`])).trim()}catch{return null}}async function cs(t,e){await K(t,["reset","--hard",e])}async function Tt(t,e){try{await K(t,["worktree","remove","--force",e])}catch{Te.default.rmSync(e,{recursive:!0,force:!0})}}async function ja(t,e=[]){let n=new Set(e.map(s=>pe.default.basename(pe.default.resolve(s))).filter(s=>s.length>0)),r=Gt();if(Te.default.existsSync(r))for(let s of Te.default.readdirSync(r))n.has(s)||Te.default.rmSync(pe.default.join(r,s),{recursive:!0,force:!0});for(let s of t)try{await K(s,["worktree","prune"])}catch{}}async function Na(t,e){return await K(t,["fetch","origin","--prune"]).catch(()=>{}),(await K(t,["branch","-r","--list",`*${e}*`])).split(`
308
- `).map(s=>s.trim()).filter(s=>s&&!s.includes("->"))[0]??null}async function Zi(t,e,n=6e4){let s=(await K(t,["symbolic-ref","refs/remotes/origin/HEAD"]).catch(()=>"")).trim().replace("refs/remotes/","")||"origin/main",i=await K(t,["diff","--stat",`${s}...${e}`]),o=await K(t,["diff",`${s}...${e}`]);return{base:s,stat:i.slice(0,4e3),diff:o.slice(0,n)}}function qu(){let t=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(Te.default.existsSync(pe.default.join(hr.default.homedir(),".cache","ticketpilot"))?pe.default.join(hr.default.homedir(),".cache","ticketpilot"):pe.default.join(hr.default.homedir(),".cache","allwright"));return pe.default.join(t,"env-checkouts")}function Mu(t){return t.replace(/[^\w.-]+/g,"_")}async function Oa(t,e,n){await K(t,["fetch","origin"],{timeoutMs:3e5}),await K(t,["reset","--hard"]),await K(t,["checkout","-B",e,n])}function Fu(t,e){return pe.default.join(qu(),Mu(t),Mu(e))}async function Ma(t){let e=Fu(t.repoName,t.envName);return await K(t.repoPath,["fetch","origin",t.branch],{timeoutMs:3e5}),Te.default.existsSync(pe.default.join(e,".git"))?await K(e,["fetch","origin",t.branch],{timeoutMs:3e5}):(Te.default.rmSync(e,{recursive:!0,force:!0}),Te.default.mkdirSync(pe.default.dirname(e),{recursive:!0,mode:448}),await K(t.repoPath,["worktree","prune"]).catch(()=>{}),await K(t.repoPath,["worktree","add","--detach",e,`origin/${t.branch}`])),t.attached?await K(e,["checkout","-B",t.branch,`origin/${t.branch}`]):await K(e,["checkout","--force","--detach",`origin/${t.branch}`]),e}async function za(t,e,n){try{await K(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 K(t,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyMerged:!0}}catch{}try{return await K(t,["-c",`user.name=${Bi}`,"-c",`user.email=${Ki}`,"merge","--no-ff","-m",n,`origin/${e}`]),{ok:!0}}catch(r){return await K(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 Da(t,e){await K(t,["fetch","origin",e],{timeoutMs:3e5});try{return await K(t,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyUpToDate:!0}}catch{}try{return await K(t,["-c",`user.name=${Bi}`,"-c",`user.email=${Ki}`,"merge","--no-edit",`origin/${e}`]),{ok:!0,alreadyUpToDate:!1}}catch(n){let s=(await K(t,["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
309
- `).filter(Boolean);return s.length?{ok:!1,conflicts:s}:(await K(t,["merge","--abort"]).catch(()=>{}),{ok:!1,conflicts:null,reason:n instanceof Error?n.message.slice(0,300):String(n)})}}async function _n(t){await K(t,["merge","--abort"]).catch(()=>{})}async function La(t,e){await K(t,["add","-A"]),await K(t,["-c",`user.name=${Bi}`,"-c",`user.email=${Ki}`,"commit","--no-edit","-m",e])}async function Ua(t,e){let n=new Set(await Wi(t));return e.filter(r=>n.has(r))}async function Wi(t){let e=new Set;try{let r=await K(t,["grep","-l","-I","-E","^(<{7}|>{7})( |$)"]);for(let s of r.split(`
305
+ ${i}${o}`:"clean"}`}function Zt(){let t=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(Te.default.existsSync(pe.default.join(pr.default.homedir(),".cache","ticketpilot"))?pe.default.join(pr.default.homedir(),".cache","ticketpilot"):pe.default.join(pr.default.homedir(),".cache","allwright"));return pe.default.join(t,"worktrees")}async function kn(t,e){try{await K(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 Na(t,e){try{let n=await K(t,["worktree","list","--porcelain"]),r=Zt(),s=null;for(let i of n.split(`
306
+ `))i.startsWith("worktree ")&&(s=i.slice(9).trim()),i===`branch refs/heads/${e}`&&s&&s.startsWith(r)&&await K(t,["worktree","remove","--force",s]);await K(t,["worktree","prune"])}catch{}try{await K(t,["branch","-D",e])}catch{}}async function Oa(t,e,n,r){Te.default.mkdirSync(pe.default.dirname(e),{recursive:!0,mode:448}),await K(t,["worktree","add","-b",n,e,`origin/${r}`])}async function fr(t,e){if(await K(t,["add","-A"]),!(await K(t,["status","--porcelain"])).trim())throw new Error("Claude wrote no changes - nothing to commit");await K(t,["-c",`user.name=${Bi}`,"-c",`user.email=${Ki}`,"commit","-m",e])}async function _n(t,e){let r=(await K(t,["diff","--name-only",`origin/${e}...HEAD`])).split(`
307
+ `).filter(Boolean),s=r.filter(u=>Vu.some(p=>p.test(u))),i=await K(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<=wn&&o+l<=vn,files:r.length,insertions:o,deletions:l,forbidden:s}}async function mr(t,e){await K(t,["fetch","--prune","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],{timeoutMs:12e4}).catch(()=>K(t,["update-ref","-d",`refs/remotes/origin/${e}`]).catch(()=>{})),await K(t,["push","--force-with-lease","-u","origin",e],{timeoutMs:3e5})}async function it(t){return(await K(t,["rev-parse","HEAD"])).trim()}async function Gi(t,e){try{return(await K(t,["rev-parse","--verify",`refs/heads/${e}`])).trim()}catch{return null}}async function us(t,e){await K(t,["reset","--hard",e])}async function xt(t,e){try{await K(t,["worktree","remove","--force",e])}catch{Te.default.rmSync(e,{recursive:!0,force:!0})}}async function Ma(t,e=[]){let n=new Set(e.map(s=>pe.default.basename(pe.default.resolve(s))).filter(s=>s.length>0)),r=Zt();if(Te.default.existsSync(r))for(let s of Te.default.readdirSync(r))n.has(s)||Te.default.rmSync(pe.default.join(r,s),{recursive:!0,force:!0});for(let s of t)try{await K(s,["worktree","prune"])}catch{}}async function za(t,e){return await K(t,["fetch","origin","--prune"]).catch(()=>{}),(await K(t,["branch","-r","--list",`*${e}*`])).split(`
308
+ `).map(s=>s.trim()).filter(s=>s&&!s.includes("->"))[0]??null}async function Zi(t,e,n=6e4){let s=(await K(t,["symbolic-ref","refs/remotes/origin/HEAD"]).catch(()=>"")).trim().replace("refs/remotes/","")||"origin/main",i=await K(t,["diff","--stat",`${s}...${e}`]),o=await K(t,["diff",`${s}...${e}`]);return{base:s,stat:i.slice(0,4e3),diff:o.slice(0,n)}}function Ju(){let t=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(Te.default.existsSync(pe.default.join(pr.default.homedir(),".cache","ticketpilot"))?pe.default.join(pr.default.homedir(),".cache","ticketpilot"):pe.default.join(pr.default.homedir(),".cache","allwright"));return pe.default.join(t,"env-checkouts")}function Hu(t){return t.replace(/[^\w.-]+/g,"_")}async function Da(t,e,n){await K(t,["fetch","origin"],{timeoutMs:3e5}),await K(t,["reset","--hard"]),await K(t,["checkout","-B",e,n])}function Yu(t,e){return pe.default.join(Ju(),Hu(t),Hu(e))}async function La(t){let e=Yu(t.repoName,t.envName);return await K(t.repoPath,["fetch","origin",t.branch],{timeoutMs:3e5}),Te.default.existsSync(pe.default.join(e,".git"))?await K(e,["fetch","origin",t.branch],{timeoutMs:3e5}):(Te.default.rmSync(e,{recursive:!0,force:!0}),Te.default.mkdirSync(pe.default.dirname(e),{recursive:!0,mode:448}),await K(t.repoPath,["worktree","prune"]).catch(()=>{}),await K(t.repoPath,["worktree","add","--detach",e,`origin/${t.branch}`])),t.attached?await K(e,["checkout","-B",t.branch,`origin/${t.branch}`]):await K(e,["checkout","--force","--detach",`origin/${t.branch}`]),e}async function Ua(t,e,n){try{await K(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 K(t,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyMerged:!0}}catch{}try{return await K(t,["-c",`user.name=${Bi}`,"-c",`user.email=${Ki}`,"merge","--no-ff","-m",n,`origin/${e}`]),{ok:!0}}catch(r){return await K(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 qa(t,e){await K(t,["fetch","origin",e],{timeoutMs:3e5});try{return await K(t,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyUpToDate:!0}}catch{}try{return await K(t,["-c",`user.name=${Bi}`,"-c",`user.email=${Ki}`,"merge","--no-edit",`origin/${e}`]),{ok:!0,alreadyUpToDate:!1}}catch(n){let s=(await K(t,["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
309
+ `).filter(Boolean);return s.length?{ok:!1,conflicts:s}:(await K(t,["merge","--abort"]).catch(()=>{}),{ok:!1,conflicts:null,reason:n instanceof Error?n.message.slice(0,300):String(n)})}}async function Sn(t){await K(t,["merge","--abort"]).catch(()=>{})}async function Fa(t,e){await K(t,["add","-A"]),await K(t,["-c",`user.name=${Bi}`,"-c",`user.email=${Ki}`,"commit","--no-edit","-m",e])}async function Ba(t,e){let n=new Set(await Wi(t));return e.filter(r=>n.has(r))}async function Wi(t){let e=new Set;try{let r=await K(t,["grep","-l","-I","-E","^(<{7}|>{7})( |$)"]);for(let s of r.split(`
310
310
  `).filter(Boolean))e.add(s)}catch{}let n=[];try{n=(await K(t,["grep","-l","-I","-E","^={7}$"])).split(`
311
- `).filter(Boolean).filter(s=>!e.has(s))}catch{}for(let r of n)try{let s=await K(t,["show",`HEAD:${r}`]);/^={7}$/m.test(s)||e.add(r)}catch{e.add(r)}return[...e]}async function Bs(t,e,n){Te.default.mkdirSync(pe.default.dirname(e),{recursive:!0,mode:448}),await K(t,["fetch","origin",n],{timeoutMs:3e5}),await K(t,["worktree","add","--detach",e,`origin/${n}`]),await K(e,["checkout","-B",n,`origin/${n}`])}async function qa(t,e){try{await K(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 Fa(t,e,n){try{return await Lu("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 mr(t){return(await K(t,["config","--get","remote.origin.url"])).trim()}function pt(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 Te,hr,pe,zu,Du,Lu,Bi,Ki,bn,wn,Uu,Ht,xt=ve(()=>{"use strict";Te=I(require("node:fs"),1),hr=I(require("node:os"),1),pe=I(require("node:path"),1),zu=require("node:child_process"),Du=require("node:util"),Lu=(0,Du.promisify)(zu.execFile),Bi="Allwright Agent",Ki="agent@ticketpilot.local",bn=200,wn=2e4,Uu=[/^\.github\/workflows\//,/^\.git\b/,/(^|\/)\.githooks\//];Ht=".ticketpilot-delete"});function Vi(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 je(t,e){return t.repos[e]?.github?.token??t.github?.token??null}function Vu(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",w=f==="own"?t.githubUsers[c].login??"":f==="shared"?i:"";return{email:c,jira:u,jiraAs:p,github:f,githubAs:w}});return{githubShared:s,sharedGithubLogin:i,entries:o}}var gr=ve(()=>{"use strict"});var al,g,Wt=ve(()=>{"use strict";al=()=>new Date().toISOString(),g={info:t=>console.log(`${al()} [info] ${t}`),warn:t=>console.warn(`${al()} [warn] ${t}`),error:t=>console.error(`${al()} [error] ${t}`)}});var Cd={};on(Cd,{crawlSite:()=>Tb,extractLinks:()=>Ed,formatCrawlReport:()=>xb,pageIssues:()=>Ad});function Ed(t,e,n){let r=new Set;for(let s of t.matchAll(/href\s*=\s*["']([^"']+)["']/gi)){let i=s[1].trim();if(!(!i||i.startsWith("#")||i.startsWith("mailto:")||i.startsWith("tel:")||i.startsWith("javascript:")))try{let o=new URL(i,e);if(o.hash="",o.origin!==n||/\.(png|jpe?g|gif|svg|webp|ico|css|js|mjs|woff2?|ttf|pdf|zip|mp4|webm)$/i.test(o.pathname))continue;r.add(o.toString())}catch{}}return[...r]}function Ad(t){let e=[],{html:n}=t;return t.status>=400&&e.push(`returns HTTP ${t.status}`),t.status===200&&((/<title[^>]*>([\s\S]*?)<\/title>/i.exec(n)?.[1]?.trim()??"")||e.push("no <title>"),/<h1[\s>]/i.test(n)||e.push("no <h1>"),t.url.startsWith("https:")&&/(?:src|href)\s*=\s*["']http:\/\//i.test(n)&&e.push("loads http:// resources from an https page (mixed content - browsers block these)"),/<a\s[^>]*href\s*=\s*["']\s*["']/i.test(n)&&e.push("has links with an empty href")),t.ms>5e3&&e.push(`took ${(t.ms/1e3).toFixed(1)}s to respond`),e}async function Tb(t){let e=new URL(t),n=e.origin,r=Date.now(),s={baseUrl:e.toString(),pages:[],notes:[]},i=new Map,o=[e.toString()],l=new Set(o),c=new Map,u=async w=>{let b=Date.now();try{let k=await fetch(w,{redirect:"follow",signal:AbortSignal.timeout(15e3),headers:{"user-agent":"Allwright-functional-audit (reads pages, changes nothing)"}}),x=await k.arrayBuffer(),A=x.byteLength,$=new TextDecoder().decode(x.slice(0,3e6));return{status:k.status,html:$,ms:Date.now()-b,bytes:A}}catch{return{status:0,html:"",ms:Date.now()-b,bytes:0}}};for(;o.length&&s.pages.length<30&&Date.now()-r<12e4;){let w=o.shift(),{status:b,html:k,ms:x,bytes:A}=await u(w),$=/<title[^>]*>([\s\S]*?)<\/title>/i.exec(k)?.[1]?.trim()??"",z=Ad({status:b,html:k,url:w,ms:x});if(b===0&&z.push("did not respond at all (timeout or connection failure)"),s.pages.push({url:w,status:b,ms:x,bytes:A,title:$,linkedFrom:[...i.get(w)??[]].slice(0,3),issues:z}),$&&c.set($,[...c.get($)??[],w]),b===200&&k)for(let v of Ed(k,w,n))i.has(v)||i.set(v,new Set),i.get(v).add(w),l.has(v)||(l.add(v),o.push(v))}let p=[...c.entries()].filter(([,w])=>w.length>1);for(let[w,b]of p.slice(0,5))s.notes.push(`${b.length} pages share the title "${w.slice(0,60)}" (${b.slice(0,3).join(", ")})`);return(await u(new URL("/allwright-crawl-probe-404",n).toString())).status===200&&s.notes.push("an unknown path returns HTTP 200 - a catch-all is answering everything, so broken links on this site LOOK fine to a crawler and to search engines"),o.length&&s.notes.push(`stopped at ${s.pages.length} pages (cap) - ${o.length} discovered links not visited`),s.notes.push("crawled without JavaScript: what curl sees. Client-side rendering, broken interactivity and console errors are NOT covered by this evidence - do not claim they were checked."),s}function xb(t){let e=t.pages.map(n=>{let r=n.issues.length?` !! ${n.issues.join("; ")}`:"",s=n.linkedFrom.length?` (linked from ${n.linkedFrom.join(", ")})`:"";return`${n.status} ${n.ms}ms ${Math.round(n.bytes/1024)}KB ${n.url}${s}${r}`}).join(`
311
+ `).filter(Boolean).filter(s=>!e.has(s))}catch{}for(let r of n)try{let s=await K(t,["show",`HEAD:${r}`]);/^={7}$/m.test(s)||e.add(r)}catch{e.add(r)}return[...e]}async function Ks(t,e,n){Te.default.mkdirSync(pe.default.dirname(e),{recursive:!0,mode:448}),await K(t,["fetch","origin",n],{timeoutMs:3e5}),await K(t,["worktree","add","--detach",e,`origin/${n}`]),await K(e,["checkout","-B",n,`origin/${n}`])}async function Ka(t,e){try{await K(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 Ha(t,e,n){try{return await Wu("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 gr(t){return(await K(t,["config","--get","remote.origin.url"])).trim()}function ft(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 Te,pr,pe,Gu,Zu,Wu,Bi,Ki,wn,vn,Vu,Gt,Rt=ye(()=>{"use strict";Te=I(require("node:fs"),1),pr=I(require("node:os"),1),pe=I(require("node:path"),1),Gu=require("node:child_process"),Zu=require("node:util"),Wu=(0,Zu.promisify)(Gu.execFile),Bi="Allwright Agent",Ki="agent@ticketpilot.local",wn=200,vn=2e4,Vu=[/^\.github\/workflows\//,/^\.git\b/,/(^|\/)\.githooks\//];Gt=".ticketpilot-delete"});function Vi(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 je(t,e){return t.repos[e]?.github?.token??t.github?.token??null}function sd(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",w=f==="own"?t.githubUsers[c].login??"":f==="shared"?i:"";return{email:c,jira:u,jiraAs:p,github:f,githubAs:w}});return{githubShared:s,sharedGithubLogin:i,entries:o}}var yr=ye(()=>{"use strict"});var ul,y,Vt=ye(()=>{"use strict";ul=()=>new Date().toISOString(),y={info:t=>console.log(`${ul()} [info] ${t}`),warn:t=>console.warn(`${ul()} [warn] ${t}`),error:t=>console.error(`${ul()} [error] ${t}`)}});var Ld={};an(Ld,{crawlSite:()=>Mb,extractLinks:()=>zd,formatCrawlReport:()=>zb,pageIssues:()=>Dd});function zd(t,e,n){let r=new Set;for(let s of t.matchAll(/href\s*=\s*["']([^"']+)["']/gi)){let i=s[1].trim();if(!(!i||i.startsWith("#")||i.startsWith("mailto:")||i.startsWith("tel:")||i.startsWith("javascript:")))try{let o=new URL(i,e);if(o.hash="",o.origin!==n||/\.(png|jpe?g|gif|svg|webp|ico|css|js|mjs|woff2?|ttf|pdf|zip|mp4|webm)$/i.test(o.pathname))continue;r.add(o.toString())}catch{}}return[...r]}function Dd(t){let e=[],{html:n}=t;return t.status>=400&&e.push(`returns HTTP ${t.status}`),t.status===200&&((/<title[^>]*>([\s\S]*?)<\/title>/i.exec(n)?.[1]?.trim()??"")||e.push("no <title>"),/<h1[\s>]/i.test(n)||e.push("no <h1>"),t.url.startsWith("https:")&&/(?:src|href)\s*=\s*["']http:\/\//i.test(n)&&e.push("loads http:// resources from an https page (mixed content - browsers block these)"),/<a\s[^>]*href\s*=\s*["']\s*["']/i.test(n)&&e.push("has links with an empty href")),t.ms>5e3&&e.push(`took ${(t.ms/1e3).toFixed(1)}s to respond`),e}async function Mb(t){let e=new URL(t),n=e.origin,r=Date.now(),s={baseUrl:e.toString(),pages:[],notes:[]},i=new Map,o=[e.toString()],l=new Set(o),c=new Map,u=async w=>{let b=Date.now();try{let k=await fetch(w,{redirect:"follow",signal:AbortSignal.timeout(15e3),headers:{"user-agent":"Allwright-functional-audit (reads pages, changes nothing)"}}),x=await k.arrayBuffer(),A=x.byteLength,$=new TextDecoder().decode(x.slice(0,3e6));return{status:k.status,html:$,ms:Date.now()-b,bytes:A}}catch{return{status:0,html:"",ms:Date.now()-b,bytes:0}}};for(;o.length&&s.pages.length<30&&Date.now()-r<12e4;){let w=o.shift(),{status:b,html:k,ms:x,bytes:A}=await u(w),$=/<title[^>]*>([\s\S]*?)<\/title>/i.exec(k)?.[1]?.trim()??"",z=Dd({status:b,html:k,url:w,ms:x});if(b===0&&z.push("did not respond at all (timeout or connection failure)"),s.pages.push({url:w,status:b,ms:x,bytes:A,title:$,linkedFrom:[...i.get(w)??[]].slice(0,3),issues:z}),$&&c.set($,[...c.get($)??[],w]),b===200&&k)for(let v of zd(k,w,n))i.has(v)||i.set(v,new Set),i.get(v).add(w),l.has(v)||(l.add(v),o.push(v))}let p=[...c.entries()].filter(([,w])=>w.length>1);for(let[w,b]of p.slice(0,5))s.notes.push(`${b.length} pages share the title "${w.slice(0,60)}" (${b.slice(0,3).join(", ")})`);return(await u(new URL("/allwright-crawl-probe-404",n).toString())).status===200&&s.notes.push("an unknown path returns HTTP 200 - a catch-all is answering everything, so broken links on this site LOOK fine to a crawler and to search engines"),o.length&&s.notes.push(`stopped at ${s.pages.length} pages (cap) - ${o.length} discovered links not visited`),s.notes.push("crawled without JavaScript: what curl sees. Client-side rendering, broken interactivity and console errors are NOT covered by this evidence - do not claim they were checked."),s}function zb(t){let e=t.pages.map(n=>{let r=n.issues.length?` !! ${n.issues.join("; ")}`:"",s=n.linkedFrom.length?` (linked from ${n.linkedFrom.join(", ")})`:"";return`${n.status} ${n.ms}ms ${Math.round(n.bytes/1024)}KB ${n.url}${s}${r}`}).join(`
312
312
  `);return`CRAWL OF THE RUNNING SITE (${t.baseUrl}) - gathered by the runner just now, GET only, same-origin only:
313
313
  ${e}
314
314
 
315
315
  SITE-WIDE:
316
316
  ${t.notes.map(n=>`- ${n}`).join(`
317
- `)}`}var $d=ve(()=>{"use strict"});var wr={};on(wr,{GitHubClient:()=>Ne});var Pb,Ne,mt=ve(()=>{"use strict";Pb=process.env.TICKETPILOT_GITHUB_API??"https://api.github.com",Ne=class{constructor(e){this.token=e}token;async request(e,n,r){let s=await fetch(`${Pb}${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 fh(t,e=512e3){try{let n=vs.default.statSync(t);return!n.isFile()||n.size>e?null:vs.default.readFileSync(t,"utf8")}catch{return null}}function mh(t,e=60){try{return vs.default.readdirSync(t).slice(0,e).map(n=>mo.default.join(t,n)).filter(n=>{try{return vs.default.statSync(n).isFile()}catch{return!1}})}catch{return[]}}function go(t,e=sw){let n=t.replace(/\/+$/,"");if(!n)return[];let r=[];for(let s of e)for(let i of mh(s)){if(!i.endsWith(".service"))continue;let o=fh(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(`${mo.default.basename(i,".service")} (User=${c})`+(l?` runs: ${l}`:""))}return r}function gh(t,e=iw,n=ow){let r=t.map(o=>o.trim().toLowerCase()).filter(Boolean);if(!r.length)return[];let s=[...e,...n.flatMap(o=>mh(o))],i=[];for(let o of s){let l=fh(o);if(!l)continue;let c=l.toLowerCase(),u=r.find(f=>c.includes(f));if(!u)continue;let p=l.split(`
318
- `).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 ks(t){let e=l=>{try{return(0,fo.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(`
317
+ `)}`}var Ud=ye(()=>{"use strict"});var vr={};an(vr,{GitHubClient:()=>Ne});var Kb,Ne,gt=ye(()=>{"use strict";Kb=process.env.TICKETPILOT_GITHUB_API??"https://api.github.com",Ne=class{constructor(e){this.token=e}token;async request(e,n,r){let s=await fetch(`${Kb}${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 Sh(t,e=512e3){try{let n=ks.default.statSync(t);return!n.isFile()||n.size>e?null:ks.default.readFileSync(t,"utf8")}catch{return null}}function Th(t,e=60){try{return ks.default.readdirSync(t).slice(0,e).map(n=>mo.default.join(t,n)).filter(n=>{try{return ks.default.statSync(n).isFile()}catch{return!1}})}catch{return[]}}function go(t,e=gw){let n=t.replace(/\/+$/,"");if(!n)return[];let r=[];for(let s of e)for(let i of Th(s)){if(!i.endsWith(".service"))continue;let o=Sh(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(`${mo.default.basename(i,".service")} (User=${c})`+(l?` runs: ${l}`:""))}return r}function xh(t,e=yw,n=bw){let r=t.map(o=>o.trim().toLowerCase()).filter(Boolean);if(!r.length)return[];let s=[...e,...n.flatMap(o=>Th(o))],i=[];for(let o of s){let l=Sh(o);if(!l)continue;let c=l.toLowerCase(),u=r.find(f=>c.includes(f));if(!u)continue;let p=l.split(`
318
+ `).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 _s(t){let e=l=>{try{return(0,fo.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(`
319
319
  `).map(l=>l.split(/\s+/)[1]??"").map(l=>l.replace(/^refs\/heads\//,"")).filter(Boolean):null,o=[`
320
320
 
321
321
  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(`
322
322
  `).join(", ")}`),s&&o.push(`- remote-tracking refs already fetched here: ${s.split(`
323
323
  `).join(", ")}`),i&&s){let l=new Set(s.split(`
324
324
  `).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(`
325
- `)}function aw(){let t=o=>{try{return(0,fo.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,fo.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`
325
+ `)}function ww(){let t=o=>{try{return(0,fo.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,fo.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`
326
326
 
327
327
  WHAT THIS MACHINE ALREADY RUNS - build the answer on these, never on a tool that is not here:
328
328
  - installed: ${r.join(", ")||"(none of the usual ones)"}
329
329
  - NOT installed: ${s.join(", ")||"(none missing)"}
330
330
  - reverse proxy currently running: ${i.join(", ")||"(none)"}
331
- 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 lw(t){try{return new URL(t).hostname}catch{return""}}function xl(t){let e=t.urls.map(lw).filter(Boolean),n=go(t.repoPath),r=gh(e),s=[`
331
+ 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 vw(t){try{return new URL(t).hostname}catch{return""}}function El(t){let e=t.urls.map(vw).filter(Boolean),n=go(t.repoPath),r=xh(e),s=[`
332
332
 
333
333
  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}):
334
334
  `+n.map(i=>` - ${i}`).join(`
@@ -337,13 +337,24 @@ ABOUT THE MACHINE THIS RUNS ON - gathered by the runner just now, read-only. Tru
337
337
  `+r.map(i=>` - ${i}`).join(`
338
338
  `)+`
339
339
  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(`
340
- `)+aw()}function yh(t){let e=[],n=o=>o.workdir.trim()||t.repoPath,r=ks(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=go(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?gh([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.publicUrl){let u="";try{u=new URL(o.publicUrl).hostname}catch{u=""}if(u){let p="";for(let f of["DEPLOY.md",".ticketpilot/deploy.md","docs/DEPLOY.md"])try{p=vs.default.readFileSync(mo.default.join(l,f),"utf8");break}catch{}if(p){let f=p.includes(u);e.push({environment:o.name,question:`DEPLOY.md mentions ${u}`,ok:f,blocking:!1,detail:f?"":"the deploy contract never names this URL - it likely describes an older address. Re-draft DEPLOY.md from Setup (the draft reads the declared environments), then regenerate the steps."})}}}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 fo,vs,mo,sw,iw,ow,yo=ve(()=>{"use strict";fo=require("node:child_process"),vs=I(require("node:fs"),1),mo=I(require("node:path"),1),sw=["/etc/systemd/system","/lib/systemd/system","/usr/lib/systemd/system"],iw=["/etc/caddy/Caddyfile","/usr/local/etc/caddy/Caddyfile","/etc/nginx/nginx.conf"],ow=["/etc/nginx/sites-enabled","/etc/nginx/conf.d","/etc/caddy/conf.d","/etc/caddy/sites-enabled"]});var Uh={};on(Uh,{MAX_CHAIN_DEPTH:()=>Lh,breakChain:()=>zl,chainOf:()=>Ol,chainSessionFor:()=>xo,loadBatchPlan:()=>Nl,nextMemberWillChain:()=>Dl,recordChainSession:()=>Ml,saveBatchPlan:()=>Ew});function Ew(t){Qs.default.mkdirSync(jl(),{recursive:!0,mode:448}),Qs.default.writeFileSync(To.default.join(jl(),`${t.batchId}.json`),JSON.stringify(t,null,2),{mode:384})}function Nl(t){if(!t)return null;try{return JSON.parse(Qs.default.readFileSync(To.default.join(jl(),`${t}.json`),"utf8"))}catch{return null}}function Ol(t,e){return t?t.chains.find(n=>n.includes(e)&&n.length>1)??null:null}function xo(t,e,n){let r=e.indexOf(n);if(r<=0)return null;let s=_o.get(So(t,e));return!s||s.lastIssue!==e[r-1]||s.depth>=Lh||!Qs.default.existsSync(s.worktreePath)?null:s}function Ml(t,e,n,r){let s=_o.get(So(t,e));_o.set(So(t,e),{sessionId:r.sessionId,worktreePath:r.worktreePath,depth:(s?.depth??0)+1,lastIssue:n})}function zl(t,e){_o.delete(So(t,e))}function Dl(t,e){if(!t)return!1;let n=t.indexOf(e);return n!==-1&&n<t.length-1}var Qs,To,Lh,jl,_o,So,Ll=ve(()=>{"use strict";Qs=I(require("node:fs"),1),To=I(require("node:path"),1);Ce();Lh=3,jl=()=>To.default.join(oe(),"autopilot-plans");_o=new Map,So=(t,e)=>`${t}:${e[0]}`});var Xt=ae((lT,mp)=>{"use strict";var pp=["nodebuffer","arraybuffer","fragments"],fp=typeof Blob<"u";fp&&pp.push("blob");mp.exports={BINARY_TYPES:pp,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:fp,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var ti=ae((cT,Ao)=>{"use strict";var{EMPTY_BUFFER:ev}=Xt(),Zl=Buffer[Symbol.species];function tv(t,e){if(t.length===0)return ev;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 Zl(n.buffer,n.byteOffset,r):n}function gp(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function yp(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function nv(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Wl(t){if(Wl.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Zl(t):ArrayBuffer.isView(t)?e=new Zl(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Wl.readOnly=!1),e}Ao.exports={concat:tv,mask:gp,toArrayBuffer:nv,toBuffer:Wl,unmask:yp};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");Ao.exports.mask=function(e,n,r,s,i){i<48?gp(e,n,r,s,i):t.mask(e,n,r,s,i)},Ao.exports.unmask=function(e,n){e.length<32?yp(e,n):t.unmask(e,n)}}catch{}});var vp=ae((uT,wp)=>{"use strict";var bp=Symbol("kDone"),Vl=Symbol("kRun"),Jl=class{constructor(e){this[bp]=()=>{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[bp])}}};wp.exports=Jl});var Ts=ae((dT,Tp)=>{"use strict";var ni=require("zlib"),kp=ti(),rv=vp(),{kStatusCode:_p}=Xt(),sv=Buffer[Symbol.species],iv=Buffer.from([0,0,255,255]),$o=Symbol("permessage-deflate"),Qt=Symbol("total-length"),_s=Symbol("callback"),In=Symbol("buffers"),Ss=Symbol("error"),Co,Yl=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,!Co){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Co=new rv(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[_s];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){Co.add(s=>{this._decompress(e,n,(i,o)=>{s(),r(i,o)})})}compress(e,n,r){Co.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"?ni.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=ni.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[$o]=this,this._inflate[Qt]=0,this._inflate[In]=[],this._inflate.on("error",av),this._inflate.on("data",Sp)}this._inflate[_s]=r,this._inflate.write(e),n&&this._inflate.write(iv),this._inflate.flush(()=>{let i=this._inflate[Ss];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=kp.concat(this._inflate[In],this._inflate[Qt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Qt]=0,this._inflate[In]=[],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"?ni.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=ni.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[Qt]=0,this._deflate[In]=[],this._deflate.on("data",ov)}this._deflate[_s]=r,this._deflate.write(e),this._deflate.flush(ni.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=kp.concat(this._deflate[In],this._deflate[Qt]);n&&(i=new sv(i.buffer,i.byteOffset,i.length-4)),this._deflate[_s]=null,this._deflate[Qt]=0,this._deflate[In]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};Tp.exports=Yl;function ov(t){this[In].push(t),this[Qt]+=t.length}function Sp(t){if(this[Qt]+=t.length,this[$o]._maxPayload<1||this[Qt]<=this[$o]._maxPayload){this[In].push(t);return}this[Ss]=new RangeError("Max payload size exceeded"),this[Ss].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Ss][_p]=1009,this.removeListener("data",Sp),this.reset()}function av(t){if(this[$o]._inflate=null,this[Ss]){this[_s](this[Ss]);return}t[_p]=1007,this[_s](t)}});var xs=ae((hT,Po)=>{"use strict";var{isUtf8:xp}=require("buffer"),{hasBlob:lv}=Xt(),cv=[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 uv(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Xl(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 dv(t){return lv&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Po.exports={isBlob:dv,isValidStatusCode:uv,isValidUTF8:Xl,tokenChars:cv};if(xp)Po.exports.isValidUTF8=function(t){return t.length<24?Xl(t):xp(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");Po.exports.isValidUTF8=function(e){return e.length<32?Xl(e):t(e)}}catch{}});var rc=ae((pT,Pp)=>{"use strict";var{Writable:hv}=require("stream"),Rp=Ts(),{BINARY_TYPES:pv,EMPTY_BUFFER:Ip,kStatusCode:fv,kWebSocket:mv}=Xt(),{concat:Ql,toArrayBuffer:gv,unmask:yv}=ti(),{isValidStatusCode:bv,isValidUTF8:Ep}=xs(),jo=Buffer[Symbol.species],at=0,Ap=1,Cp=2,$p=3,ec=4,tc=5,No=6,nc=class extends hv{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||pv[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[mv]=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=at}_write(e,n,r){if(this._opcode===8&&this._state==at)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 jo(r.buffer,r.byteOffset+e,r.length-e),new jo(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 jo(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 at:this.getInfo(e);break;case Ap:this.getPayloadLength16(e);break;case Cp:this.getPayloadLength64(e);break;case $p:this.getMask();break;case ec:this.getData(e);break;case tc:case No: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[Rp.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=Ap:this._payloadLength===127?this._state=Cp: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=$p:this._state=ec}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=ec}getData(e){let n=Ip;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&&yv(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=tc,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Rp.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===at&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=at;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=Ql(r,n):this._binaryType==="arraybuffer"?s=gv(Ql(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=at):(this._state=No,setImmediate(()=>{this.emit("message",s,!0),this._state=at,this.startLoop(e)}))}else{let s=Ql(r,n);if(!this._skipUTF8Validation&&!Ep(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===tc||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=at):(this._state=No,setImmediate(()=>{this.emit("message",s,!1),this._state=at,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Ip),this.end();else{let r=e.readUInt16BE(0);if(!bv(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new jo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Ep(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=at;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=at):(this._state=No,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=at,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[fv]=s,o}};Pp.exports=nc});var oc=ae((mT,Op)=>{"use strict";var{Duplex:fT}=require("stream"),{randomFillSync:wv}=require("crypto"),{types:{isUint8Array:vv}}=require("util"),jp=Ts(),{EMPTY_BUFFER:kv,kWebSocket:_v,NOOP:Sv}=Xt(),{isBlob:Rs,isValidStatusCode:Tv}=xs(),{mask:Np,toBuffer:Nr}=ti(),lt=Symbol("kByteLength"),xv=Buffer.alloc(4),Oo=8*1024,Or,Is=Oo,bt=0,Rv=1,Iv=2,sc=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=bt,this.onerror=Sv,this[_v]=void 0}static frame(e,n){let r,s=!1,i=2,o=!1;n.mask&&(r=n.maskBuffer||xv,n.generateMask?n.generateMask(r):(Is===Oo&&(Or===void 0&&(Or=Buffer.alloc(Oo)),wv(Or,0,Oo),Is=0),r[0]=Or[Is++],r[1]=Or[Is++],r[2]=Or[Is++],r[3]=Or[Is++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let l;typeof e=="string"?(!n.mask||o)&&n[lt]!==void 0?l=n[lt]:(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?(Np(e,r,u,i,l),[u]):(Np(e,r,e,0,l),[u,e])):[u,e]}close(e,n,r,s){let i;if(e===void 0)i=kv;else{if(typeof e!="number"||!Tv(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(vv(n))i.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[lt]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==bt?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):Rs(e)?(s=e.size,i=!1):(e=Nr(e),s=e.length,i=Nr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[lt]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Rs(e)?this._state!==bt?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==bt?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):Rs(e)?(s=e.size,i=!1):(e=Nr(e),s=e.length,i=Nr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[lt]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Rs(e)?this._state!==bt?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==bt?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let s=this._extensions[jp.extensionName],i=n.binary?2:1,o=n.compress,l,c;typeof e=="string"?(l=Buffer.byteLength(e),c=!1):Rs(e)?(l=e.size,c=!1):(e=Nr(e),l=e.length,c=Nr.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={[lt]:l,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};Rs(e)?this._state!==bt?this.enqueue([this.getBlobData,e,this._compress,u,r]):this.getBlobData(e,this._compress,u,r):this._state!==bt?this.enqueue([this.dispatch,e,this._compress,u,r]):this.dispatch(e,this._compress,u,r)}getBlobData(e,n,r,s){this._bufferedBytes+=r[lt],this._state=Iv,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let l=new Error("The socket was closed while the blob was being read");process.nextTick(ic,this,l,s);return}this._bufferedBytes-=r[lt];let o=Nr(i);n?this.dispatch(o,n,r,s):(this._state=bt,this.sendFrame(t.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(Ev,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[jp.extensionName];this._bufferedBytes+=r[lt],this._state=Rv,i.compress(e,r.fin,(o,l)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");ic(this,c,s);return}this._bufferedBytes-=r[lt],this._state=bt,r.readOnly=!1,this.sendFrame(t.frame(l,r),s),this.dequeue()})}dequeue(){for(;this._state===bt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][lt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][lt],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)}};Op.exports=sc;function ic(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 Ev(t,e,n){ic(t,e,n),t.onerror(e)}});var Kp=ae((gT,Bp)=>{"use strict";var{kForOnEventAttribute:ri,kListener:ac}=Xt(),Mp=Symbol("kCode"),zp=Symbol("kData"),Dp=Symbol("kError"),Lp=Symbol("kMessage"),Up=Symbol("kReason"),Es=Symbol("kTarget"),qp=Symbol("kType"),Fp=Symbol("kWasClean"),en=class{constructor(e){this[Es]=null,this[qp]=e}get target(){return this[Es]}get type(){return this[qp]}};Object.defineProperty(en.prototype,"target",{enumerable:!0});Object.defineProperty(en.prototype,"type",{enumerable:!0});var Mr=class extends en{constructor(e,n={}){super(e),this[Mp]=n.code===void 0?0:n.code,this[Up]=n.reason===void 0?"":n.reason,this[Fp]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Mp]}get reason(){return this[Up]}get wasClean(){return this[Fp]}};Object.defineProperty(Mr.prototype,"code",{enumerable:!0});Object.defineProperty(Mr.prototype,"reason",{enumerable:!0});Object.defineProperty(Mr.prototype,"wasClean",{enumerable:!0});var As=class extends en{constructor(e,n={}){super(e),this[Dp]=n.error===void 0?null:n.error,this[Lp]=n.message===void 0?"":n.message}get error(){return this[Dp]}get message(){return this[Lp]}};Object.defineProperty(As.prototype,"error",{enumerable:!0});Object.defineProperty(As.prototype,"message",{enumerable:!0});var si=class extends en{constructor(e,n={}){super(e),this[zp]=n.data===void 0?null:n.data}get data(){return this[zp]}};Object.defineProperty(si.prototype,"data",{enumerable:!0});var Av={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[ri]&&s[ac]===e&&!s[ri])return;let r;if(t==="message")r=function(i,o){let l=new si("message",{data:o?i:i.toString()});l[Es]=this,Mo(e,this,l)};else if(t==="close")r=function(i,o){let l=new Mr("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});l[Es]=this,Mo(e,this,l)};else if(t==="error")r=function(i){let o=new As("error",{error:i,message:i.message});o[Es]=this,Mo(e,this,o)};else if(t==="open")r=function(){let i=new en("open");i[Es]=this,Mo(e,this,i)};else return;r[ri]=!!n[ri],r[ac]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[ac]===e&&!n[ri]){this.removeListener(t,n);break}}};Bp.exports={CloseEvent:Mr,ErrorEvent:As,Event:en,EventTarget:Av,MessageEvent:si};function Mo(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var zo=ae((yT,Hp)=>{"use strict";var{tokenChars:ii}=xs();function Ct(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function Cv(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&&ii[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 b=t.slice(c,p);u===44?(Ct(e,b,n),n=Object.create(null)):o=b,c=p=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);else if(l===void 0)if(p===-1&&ii[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),Ct(n,t.slice(c,p),!0),u===44&&(Ct(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(ii[u]!==1)throw new SyntaxError(`Unexpected character at index ${f}`);c===-1?c=f:r||(r=!0),s=!1}else if(i)if(ii[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&&ii[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 b=t.slice(c,p);r&&(b=b.replace(/\\/g,""),r=!1),Ct(n,l,b),u===44&&(Ct(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 w=t.slice(c,p);return o===void 0?Ct(e,w,n):(l===void 0?Ct(n,w,!0):r?Ct(n,l,w.replace(/\\/g,"")):Ct(n,l,w),Ct(e,o,n)),e}function $v(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(", ")}Hp.exports={format:$v,parse:Cv}});var qo=ae((vT,rf)=>{"use strict";var Pv=require("events"),jv=require("https"),Nv=require("http"),Wp=require("net"),Ov=require("tls"),{randomBytes:Mv,createHash:zv}=require("crypto"),{Duplex:bT,Readable:wT}=require("stream"),{URL:lc}=require("url"),En=Ts(),Dv=rc(),Lv=oc(),{isBlob:Uv}=xs(),{BINARY_TYPES:Gp,CLOSE_TIMEOUT:qv,EMPTY_BUFFER:Do,GUID:Fv,kForOnEventAttribute:cc,kListener:Bv,kStatusCode:Kv,kWebSocket:xe,NOOP:Vp}=Xt(),{EventTarget:{addEventListener:Hv,removeEventListener:Gv}}=Kp(),{format:Zv,parse:Wv}=zo(),{toBuffer:Vv}=ti(),Jp=Symbol("kAborted"),uc=[8,13],tn=["CONNECTING","OPEN","CLOSING","CLOSED"],Jv=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,fe=class t extends Pv{constructor(e,n,r){super(),this._binaryType=Gp[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Do,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]),Yp(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Gp.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 Dv({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 Lv(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[xe]=this,i[xe]=this,e[xe]=this,s.on("conclude",Qv),s.on("drain",ek),s.on("error",tk),s.on("message",nk),s.on("ping",rk),s.on("pong",sk),i.onerror=ik,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",ef),e.on("data",Uo),e.on("end",tf),e.on("error",nf),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[En.extensionName]&&this._extensions[En.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){Ze(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())}),Qp(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){dc(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Do,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){dc(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Do,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){dc(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[En.extensionName]||(s.compress=!1),this._sender.send(e||Do,s,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Ze(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(fe,"CONNECTING",{enumerable:!0,value:tn.indexOf("CONNECTING")});Object.defineProperty(fe.prototype,"CONNECTING",{enumerable:!0,value:tn.indexOf("CONNECTING")});Object.defineProperty(fe,"OPEN",{enumerable:!0,value:tn.indexOf("OPEN")});Object.defineProperty(fe.prototype,"OPEN",{enumerable:!0,value:tn.indexOf("OPEN")});Object.defineProperty(fe,"CLOSING",{enumerable:!0,value:tn.indexOf("CLOSING")});Object.defineProperty(fe.prototype,"CLOSING",{enumerable:!0,value:tn.indexOf("CLOSING")});Object.defineProperty(fe,"CLOSED",{enumerable:!0,value:tn.indexOf("CLOSED")});Object.defineProperty(fe.prototype,"CLOSED",{enumerable:!0,value:tn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(fe.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(fe.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[cc])return e[Bv];return null},set(e){for(let n of this.listeners(t))if(n[cc]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[cc]:!0})}})});fe.prototype.addEventListener=Hv;fe.prototype.removeEventListener=Gv;rf.exports=fe;function Yp(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:qv,protocolVersion:uc[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,!uc.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${uc.join(", ")})`);let i;if(e instanceof lc)i=e;else try{i=new lc(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;Lo(t,x);return}let u=o?443:80,p=Mv(16).toString("base64"),f=o?jv.request:Nv.request,w=new Set,b;if(s.createConnection=s.createConnection||(o?Xv:Yv),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&&(b=new En({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=Zv({[En.extensionName]:b.offer()})),n.length){for(let x of n){if(typeof x!="string"||!Jv.test(x)||w.has(x))throw new SyntaxError("An invalid or duplicated subprotocol was specified");w.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 k;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[A,$]of Object.entries(x))r.headers[A.toLowerCase()]=$}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")),k=t._req=f(s),t._redirects&&t.emit("redirect",t.url,k)}else k=t._req=f(s);s.timeout&&k.on("timeout",()=>{Ze(t,k,"Opening handshake has timed out")}),k.on("error",x=>{k===null||k[Jp]||(k=t._req=null,Lo(t,x))}),k.on("response",x=>{let A=x.headers.location,$=x.statusCode;if(A&&s.followRedirects&&$>=300&&$<400){if(++t._redirects>s.maxRedirects){Ze(t,k,"Maximum redirects exceeded");return}k.abort();let z;try{z=new lc(A,e)}catch{let L=new SyntaxError(`Invalid URL: ${A}`);Lo(t,L);return}Yp(t,z,n,r)}else t.emit("unexpected-response",k,x)||Ze(t,k,`Unexpected server response: ${x.statusCode}`)}),k.on("upgrade",(x,A,$)=>{if(t.emit("upgrade",x),t.readyState!==fe.CONNECTING)return;k=t._req=null;let z=x.headers.upgrade;if(z===void 0||z.toLowerCase()!=="websocket"){Ze(t,A,"Invalid Upgrade header");return}let v=zv("sha1").update(p+Fv).digest("base64");if(x.headers["sec-websocket-accept"]!==v){Ze(t,A,"Invalid Sec-WebSocket-Accept header");return}let L=x.headers["sec-websocket-protocol"],O;if(L!==void 0?w.size?w.has(L)||(O="Server sent an invalid subprotocol"):O="Server sent a subprotocol but none was requested":w.size&&(O="Server sent no subprotocol"),O){Ze(t,A,O);return}L&&(t._protocol=L);let Y=x.headers["sec-websocket-extensions"];if(Y!==void 0){if(!b){Ze(t,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let M;try{M=Wv(Y)}catch{Ze(t,A,"Invalid Sec-WebSocket-Extensions header");return}let d=Object.keys(M);if(d.length!==1||d[0]!==En.extensionName){Ze(t,A,"Server indicated an extension that was not requested");return}try{b.accept(M[En.extensionName])}catch{Ze(t,A,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[En.extensionName]=b}t.setSocket(A,$,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(k,t):k.end()}function Lo(t,e){t._readyState=fe.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Yv(t){return t.path=t.socketPath,Wp.connect(t)}function Xv(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Wp.isIP(t.host)?"":t.host),Ov.connect(t)}function Ze(t,e,n){t._readyState=fe.CLOSING;let r=new Error(n);Error.captureStackTrace(r,Ze),e.setHeader?(e[Jp]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Lo,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function dc(t,e,n){if(e){let r=Uv(e)?e.size:Vv(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${tn[t.readyState]})`);process.nextTick(n,r)}}function Qv(t,e){let n=this[xe];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[xe]!==void 0&&(n._socket.removeListener("data",Uo),process.nextTick(Xp,n._socket),t===1005?n.close():n.close(t,e))}function ek(){let t=this[xe];t.isPaused||t._socket.resume()}function tk(t){let e=this[xe];e._socket[xe]!==void 0&&(e._socket.removeListener("data",Uo),process.nextTick(Xp,e._socket),e.close(t[Kv])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Zp(){this[xe].emitClose()}function nk(t,e){this[xe].emit("message",t,e)}function rk(t){let e=this[xe];e._autoPong&&e.pong(t,!this._isServer,Vp),e.emit("ping",t)}function sk(t){this[xe].emit("pong",t)}function Xp(t){t.resume()}function ik(t){let e=this[xe];e.readyState!==fe.CLOSED&&(e.readyState===fe.OPEN&&(e._readyState=fe.CLOSING,Qp(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Qp(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function ef(){let t=this[xe];if(this.removeListener("close",ef),this.removeListener("data",Uo),this.removeListener("end",tf),t._readyState=fe.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[xe]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Zp),t._receiver.on("finish",Zp))}function Uo(t){this[xe]._receiver.write(t)||this.pause()}function tf(){let t=this[xe];t._readyState=fe.CLOSING,t._receiver.end(),this.end()}function nf(){let t=this[xe];this.removeListener("error",nf),this.on("error",Vp),t&&(t._readyState=fe.CLOSING,this.destroy())}});var lf=ae((_T,af)=>{"use strict";var kT=qo(),{Duplex:ok}=require("stream");function sf(t){t.emit("close")}function ak(){!this.destroyed&&this._writableState.finished&&this.destroy()}function of(t){this.removeListener("error",of),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function lk(t,e){let n=!0,r=new ok({...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(sf,r);return}let o=!1;t.once("error",function(c){o=!0,i(c)}),t.once("close",function(){o||i(s),process.nextTick(sf,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",ak),r.on("error",of),r}af.exports=lk});var hc=ae((ST,cf)=>{"use strict";var{tokenChars:ck}=xs();function uk(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&&ck[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}cf.exports={parse:uk}});var gf=ae((xT,mf)=>{"use strict";var dk=require("events"),Fo=require("http"),{Duplex:TT}=require("stream"),{createHash:hk}=require("crypto"),uf=zo(),zr=Ts(),pk=hc(),fk=qo(),{CLOSE_TIMEOUT:mk,GUID:gk,kWebSocket:yk}=Xt(),bk=/^[+/0-9A-Za-z]{22}==$/,df=0,hf=1,ff=2,pc=class extends dk{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:mk,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:fk,...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=Fo.createServer((r,s)=>{let i=Fo.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=wk(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=df}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===ff){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(oi,this);return}if(e&&this.once("close",e),this._state!==hf)if(this._state=hf,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(oi,this):process.nextTick(oi,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{oi(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",pf);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,l=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Dr(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Dr(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!bk.test(i)){Dr(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(l!==13&&l!==8){Dr(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){ai(n,400);return}let c=e.headers["sec-websocket-protocol"],u=new Set;if(c!==void 0)try{u=pk.parse(c)}catch{Dr(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 w=new zr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let b=uf.parse(p);b[zr.extensionName]&&(w.accept(b[zr.extensionName]),f[zr.extensionName]=w)}catch{Dr(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let w={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(w,(b,k,x,A)=>{if(!b)return ai(n,k||401,x,A);this.completeUpgrade(f,i,u,e,n,r,s)});return}if(!this.options.verifyClient(w))return ai(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[yk])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>df)return ai(i,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${hk("sha1").update(n+gk).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[zr.extensionName]){let f=e[zr.extensionName].params,w=uf.format({[zr.extensionName]:[f]});u.push(`Sec-WebSocket-Extensions: ${w}`),p._extensions=e}this.emit("headers",u,s),i.write(u.concat(`\r
340
+ `)+ww()}function Rh(t){let e=[],n=o=>o.workdir.trim()||t.repoPath,r=_s(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=go(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?xh([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.publicUrl){let u="";try{u=new URL(o.publicUrl).hostname}catch{u=""}if(u){let p="";for(let f of["DEPLOY.md",".ticketpilot/deploy.md","docs/DEPLOY.md"])try{p=ks.default.readFileSync(mo.default.join(l,f),"utf8");break}catch{}if(p){let f=p.includes(u);e.push({environment:o.name,question:`DEPLOY.md mentions ${u}`,ok:f,blocking:!1,detail:f?"":"the deploy contract never names this URL - it likely describes an older address. Re-draft DEPLOY.md from Setup (the draft reads the declared environments), then regenerate the steps."})}}}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 fo,ks,mo,gw,yw,bw,yo=ye(()=>{"use strict";fo=require("node:child_process"),ks=I(require("node:fs"),1),mo=I(require("node:path"),1),gw=["/etc/systemd/system","/lib/systemd/system","/usr/lib/systemd/system"],yw=["/etc/caddy/Caddyfile","/usr/local/etc/caddy/Caddyfile","/etc/nginx/nginx.conf"],bw=["/etc/nginx/sites-enabled","/etc/nginx/conf.d","/etc/caddy/conf.d","/etc/caddy/sites-enabled"]});function Cl(t){return t.replace(/([A-Za-z_][A-Za-z0-9_]*)=(\S+)/g,(e,n,r)=>kw.test(n)?`${n}=<redacted>`:e)}function Xt(t,e){try{let r=(0,Eh.execFileSync)(t,e,{encoding:"utf8",timeout:1e4,maxBuffer:2e6,stdio:["ignore","pipe","pipe"]}).trim();return r?r.slice(0,Ih):null}catch(n){let r=n,s=`${r?.stdout??""}${r?.stderr??""}`.trim();return s?s.slice(0,Ih):null}}function _w(t){let e=["/etc/systemd/system","/lib/systemd/system"],n=[];for(let r of e){let s;try{s=Al.default.readdirSync(r)}catch{continue}for(let i of s)if(i.endsWith(".service"))try{let o=Al.default.readFileSync(Ah.default.join(r,i),"utf8");t&&o.includes(t)&&n.push(i.replace(/\.service$/,""))}catch{}}return[...new Set(n)].slice(0,3)}function Ch(t){let e=t.errorText.slice(-6e3),n=[],r=(o,l)=>{l&&n.push({command:o,output:Cl(l)})},s=_w(t.repoPath);for(let o of s)r(`systemctl status ${o}`,Xt("systemctl",["status",o,"--no-pager","-l"])),r(`journalctl -u ${o} -n 40`,Xt("journalctl",["-u",o,"-n","40","--no-pager"])),r(`systemctl show ${o} -p ExecStart -p Environment -p WorkingDirectory -p User`,Xt("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",Xt("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)`,Xt("bash",["-lc",`command -v ${JSON.stringify(o)} || echo "not on this PATH"`])),r("ls of the usual system locations",Xt("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",Xt("bash",["-lc","df -h | head -10"])),/EACCES|Permission denied|Operation not permitted/i.test(e)&&(r("id",Xt("id",[])),r(`ls -ld ${t.repoPath}`,Xt("bash",["-lc",`ls -ld ${JSON.stringify(t.repoPath)} 2>&1`]))),n}function $h(t){return t.length?`
341
+
342
+ 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.
343
+
344
+ `+t.map(e=>`$ ${e.command}
345
+ ${e.output}`).join(`
346
+
347
+ `)+`
348
+
349
+ 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 Eh,Al,Ah,Ih,kw,$l=ye(()=>{"use strict";Eh=require("node:child_process"),Al=I(require("node:fs"),1),Ah=I(require("node:path"),1),Ih=4e3,kw=/(TOKEN|KEY|SECRET|PASSWORD|PASSWD|CREDENTIAL|AUTH|COOKIE|SESSION)/i});var Vh={};an(Vh,{MAX_CHAIN_DEPTH:()=>Wh,breakChain:()=>Fl,chainOf:()=>Ul,chainSessionFor:()=>xo,loadBatchPlan:()=>Ll,nextMemberWillChain:()=>Bl,parsePlanAnswer:()=>Kl,recordChainSession:()=>ql,saveBatchPlan:()=>Lw});function Lw(t){ei.default.mkdirSync(Dl(),{recursive:!0,mode:448}),ei.default.writeFileSync(To.default.join(Dl(),`${t.batchId}.json`),JSON.stringify(t,null,2),{mode:384})}function Ll(t){if(!t)return null;try{return JSON.parse(ei.default.readFileSync(To.default.join(Dl(),`${t}.json`),"utf8"))}catch{return null}}function Ul(t,e){return t?t.chains.find(n=>n.includes(e)&&n.length>1)??null:null}function xo(t,e,n){let r=e.indexOf(n);if(r<=0)return null;let s=_o.get(So(t,e));return!s||s.lastIssue!==e[r-1]||s.depth>=Wh||!ei.default.existsSync(s.worktreePath)?null:s}function ql(t,e,n,r){let s=_o.get(So(t,e));_o.set(So(t,e),{sessionId:r.sessionId,worktreePath:r.worktreePath,depth:(s?.depth??0)+1,lastIssue:n})}function Fl(t,e){_o.delete(So(t,e))}function Bl(t,e){if(!t)return!1;let n=t.indexOf(e);return n!==-1&&n<t.length-1}function Kl(t,e){let n=/```(?:json)?\s*\n([\s\S]*?)```/.exec(t)??/(\{[\s\S]*\})/.exec(t);if(!n)return null;let r;try{r=JSON.parse(n[1])}catch{return null}let s=r,i=new Set(e),o=Array.isArray(s.order)?s.order.filter(p=>typeof p=="string"):[];if(o.length!==e.length||!o.every(p=>i.has(p))||new Set(o).size!==o.length)return null;let l=(Array.isArray(s.chains)?s.chains:[]).map(p=>Array.isArray(p)?p.filter(f=>typeof f=="string"&&i.has(f)):[]).filter(p=>p.length>1),c=(Array.isArray(s.dependencies)?s.dependencies:[]).map(p=>Array.isArray(p)?p:[]).filter(p=>p.length===2&&typeof p[0]=="string"&&typeof p[1]=="string"&&i.has(p[0])&&i.has(p[1])&&p[0]!==p[1]),u=typeof s.reasoning=="string"?s.reasoning.slice(0,1e3):"";return{order:o,chains:l,dependencies:c,reasoning:u}}var ei,To,Wh,Dl,_o,So,Ro=ye(()=>{"use strict";ei=I(require("node:fs"),1),To=I(require("node:path"),1);Ce();Wh=3,Dl=()=>To.default.join(oe(),"autopilot-plans");_o=new Map,So=(t,e)=>`${t}:${e[0]}`});var Qt=ae((_T,Tp)=>{"use strict";var _p=["nodebuffer","arraybuffer","fragments"],Sp=typeof Blob<"u";Sp&&_p.push("blob");Tp.exports={BINARY_TYPES:_p,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Sp,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var ni=ae((ST,Co)=>{"use strict";var{EMPTY_BUFFER:dv}=Qt(),Xl=Buffer[Symbol.species];function hv(t,e){if(t.length===0)return dv;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 Xl(n.buffer,n.byteOffset,r):n}function xp(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function Rp(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function pv(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Ql(t){if(Ql.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Xl(t):ArrayBuffer.isView(t)?e=new Xl(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Ql.readOnly=!1),e}Co.exports={concat:hv,mask:xp,toArrayBuffer:pv,toBuffer:Ql,unmask:Rp};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");Co.exports.mask=function(e,n,r,s,i){i<48?xp(e,n,r,s,i):t.mask(e,n,r,s,i)},Co.exports.unmask=function(e,n){e.length<32?Rp(e,n):t.unmask(e,n)}}catch{}});var Ap=ae((TT,Ep)=>{"use strict";var Ip=Symbol("kDone"),ec=Symbol("kRun"),tc=class{constructor(e){this[Ip]=()=>{this.pending--,this[ec]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[ec]()}[ec](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Ip])}}};Ep.exports=tc});var xs=ae((xT,jp)=>{"use strict";var ri=require("zlib"),Cp=ni(),fv=Ap(),{kStatusCode:$p}=Qt(),mv=Buffer[Symbol.species],gv=Buffer.from([0,0,255,255]),Po=Symbol("permessage-deflate"),en=Symbol("total-length"),Ss=Symbol("callback"),En=Symbol("buffers"),Ts=Symbol("error"),$o,nc=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,!$o){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;$o=new fv(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[Ss];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){$o.add(s=>{this._decompress(e,n,(i,o)=>{s(),r(i,o)})})}compress(e,n,r){$o.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"?ri.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=ri.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Po]=this,this._inflate[en]=0,this._inflate[En]=[],this._inflate.on("error",bv),this._inflate.on("data",Pp)}this._inflate[Ss]=r,this._inflate.write(e),n&&this._inflate.write(gv),this._inflate.flush(()=>{let i=this._inflate[Ts];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=Cp.concat(this._inflate[En],this._inflate[en]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[en]=0,this._inflate[En]=[],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"?ri.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=ri.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[en]=0,this._deflate[En]=[],this._deflate.on("data",yv)}this._deflate[Ss]=r,this._deflate.write(e),this._deflate.flush(ri.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Cp.concat(this._deflate[En],this._deflate[en]);n&&(i=new mv(i.buffer,i.byteOffset,i.length-4)),this._deflate[Ss]=null,this._deflate[en]=0,this._deflate[En]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};jp.exports=nc;function yv(t){this[En].push(t),this[en]+=t.length}function Pp(t){if(this[en]+=t.length,this[Po]._maxPayload<1||this[en]<=this[Po]._maxPayload){this[En].push(t);return}this[Ts]=new RangeError("Max payload size exceeded"),this[Ts].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Ts][$p]=1009,this.removeListener("data",Pp),this.reset()}function bv(t){if(this[Po]._inflate=null,this[Ts]){this[Ss](this[Ts]);return}t[$p]=1007,this[Ss](t)}});var Rs=ae((RT,jo)=>{"use strict";var{isUtf8:Np}=require("buffer"),{hasBlob:wv}=Qt(),vv=[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 kv(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function rc(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 _v(t){return wv&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}jo.exports={isBlob:_v,isValidStatusCode:kv,isValidUTF8:rc,tokenChars:vv};if(Np)jo.exports.isValidUTF8=function(t){return t.length<24?rc(t):Np(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");jo.exports.isValidUTF8=function(e){return e.length<32?rc(e):t(e)}}catch{}});var lc=ae((IT,qp)=>{"use strict";var{Writable:Sv}=require("stream"),Op=xs(),{BINARY_TYPES:Tv,EMPTY_BUFFER:Mp,kStatusCode:xv,kWebSocket:Rv}=Qt(),{concat:sc,toArrayBuffer:Iv,unmask:Ev}=ni(),{isValidStatusCode:Av,isValidUTF8:zp}=Rs(),No=Buffer[Symbol.species],at=0,Dp=1,Lp=2,Up=3,ic=4,oc=5,Oo=6,ac=class extends Sv{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Tv[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[Rv]=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=at}_write(e,n,r){if(this._opcode===8&&this._state==at)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 No(r.buffer,r.byteOffset+e,r.length-e),new No(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 No(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 at:this.getInfo(e);break;case Dp:this.getPayloadLength16(e);break;case Lp:this.getPayloadLength64(e);break;case Up:this.getMask();break;case ic:this.getData(e);break;case oc: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[Op.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=Dp:this._payloadLength===127?this._state=Lp: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=Up:this._state=ic}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=ic}getData(e){let n=Mp;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&&Ev(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=oc,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Op.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===at&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=at;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=sc(r,n):this._binaryType==="arraybuffer"?s=Iv(sc(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=at):(this._state=Oo,setImmediate(()=>{this.emit("message",s,!0),this._state=at,this.startLoop(e)}))}else{let s=sc(r,n);if(!this._skipUTF8Validation&&!zp(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===oc||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=at):(this._state=Oo,setImmediate(()=>{this.emit("message",s,!1),this._state=at,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Mp),this.end();else{let r=e.readUInt16BE(0);if(!Av(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new No(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!zp(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=at;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=at):(this._state=Oo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=at,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[xv]=s,o}};qp.exports=ac});var dc=ae((AT,Kp)=>{"use strict";var{Duplex:ET}=require("stream"),{randomFillSync:Cv}=require("crypto"),{types:{isUint8Array:$v}}=require("util"),Fp=xs(),{EMPTY_BUFFER:Pv,kWebSocket:jv,NOOP:Nv}=Qt(),{isBlob:Is,isValidStatusCode:Ov}=Rs(),{mask:Bp,toBuffer:Or}=ni(),lt=Symbol("kByteLength"),Mv=Buffer.alloc(4),Mo=8*1024,Mr,Es=Mo,wt=0,zv=1,Dv=2,cc=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=wt,this.onerror=Nv,this[jv]=void 0}static frame(e,n){let r,s=!1,i=2,o=!1;n.mask&&(r=n.maskBuffer||Mv,n.generateMask?n.generateMask(r):(Es===Mo&&(Mr===void 0&&(Mr=Buffer.alloc(Mo)),Cv(Mr,0,Mo),Es=0),r[0]=Mr[Es++],r[1]=Mr[Es++],r[2]=Mr[Es++],r[3]=Mr[Es++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let l;typeof e=="string"?(!n.mask||o)&&n[lt]!==void 0?l=n[lt]:(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?(Bp(e,r,u,i,l),[u]):(Bp(e,r,e,0,l),[u,e])):[u,e]}close(e,n,r,s){let i;if(e===void 0)i=Pv;else{if(typeof e!="number"||!Ov(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($v(n))i.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[lt]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==wt?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):Is(e)?(s=e.size,i=!1):(e=Or(e),s=e.length,i=Or.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[lt]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Is(e)?this._state!==wt?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==wt?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):Is(e)?(s=e.size,i=!1):(e=Or(e),s=e.length,i=Or.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[lt]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Is(e)?this._state!==wt?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==wt?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let s=this._extensions[Fp.extensionName],i=n.binary?2:1,o=n.compress,l,c;typeof e=="string"?(l=Buffer.byteLength(e),c=!1):Is(e)?(l=e.size,c=!1):(e=Or(e),l=e.length,c=Or.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={[lt]:l,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};Is(e)?this._state!==wt?this.enqueue([this.getBlobData,e,this._compress,u,r]):this.getBlobData(e,this._compress,u,r):this._state!==wt?this.enqueue([this.dispatch,e,this._compress,u,r]):this.dispatch(e,this._compress,u,r)}getBlobData(e,n,r,s){this._bufferedBytes+=r[lt],this._state=Dv,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let l=new Error("The socket was closed while the blob was being read");process.nextTick(uc,this,l,s);return}this._bufferedBytes-=r[lt];let o=Or(i);n?this.dispatch(o,n,r,s):(this._state=wt,this.sendFrame(t.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(Lv,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[Fp.extensionName];this._bufferedBytes+=r[lt],this._state=zv,i.compress(e,r.fin,(o,l)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");uc(this,c,s);return}this._bufferedBytes-=r[lt],this._state=wt,r.readOnly=!1,this.sendFrame(t.frame(l,r),s),this.dequeue()})}dequeue(){for(;this._state===wt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][lt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][lt],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)}};Kp.exports=cc;function uc(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 Lv(t,e,n){uc(t,e,n),t.onerror(e)}});var Qp=ae((CT,Xp)=>{"use strict";var{kForOnEventAttribute:si,kListener:hc}=Qt(),Hp=Symbol("kCode"),Gp=Symbol("kData"),Zp=Symbol("kError"),Wp=Symbol("kMessage"),Vp=Symbol("kReason"),As=Symbol("kTarget"),Jp=Symbol("kType"),Yp=Symbol("kWasClean"),tn=class{constructor(e){this[As]=null,this[Jp]=e}get target(){return this[As]}get type(){return this[Jp]}};Object.defineProperty(tn.prototype,"target",{enumerable:!0});Object.defineProperty(tn.prototype,"type",{enumerable:!0});var zr=class extends tn{constructor(e,n={}){super(e),this[Hp]=n.code===void 0?0:n.code,this[Vp]=n.reason===void 0?"":n.reason,this[Yp]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Hp]}get reason(){return this[Vp]}get wasClean(){return this[Yp]}};Object.defineProperty(zr.prototype,"code",{enumerable:!0});Object.defineProperty(zr.prototype,"reason",{enumerable:!0});Object.defineProperty(zr.prototype,"wasClean",{enumerable:!0});var Cs=class extends tn{constructor(e,n={}){super(e),this[Zp]=n.error===void 0?null:n.error,this[Wp]=n.message===void 0?"":n.message}get error(){return this[Zp]}get message(){return this[Wp]}};Object.defineProperty(Cs.prototype,"error",{enumerable:!0});Object.defineProperty(Cs.prototype,"message",{enumerable:!0});var ii=class extends tn{constructor(e,n={}){super(e),this[Gp]=n.data===void 0?null:n.data}get data(){return this[Gp]}};Object.defineProperty(ii.prototype,"data",{enumerable:!0});var Uv={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[si]&&s[hc]===e&&!s[si])return;let r;if(t==="message")r=function(i,o){let l=new ii("message",{data:o?i:i.toString()});l[As]=this,zo(e,this,l)};else if(t==="close")r=function(i,o){let l=new zr("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});l[As]=this,zo(e,this,l)};else if(t==="error")r=function(i){let o=new Cs("error",{error:i,message:i.message});o[As]=this,zo(e,this,o)};else if(t==="open")r=function(){let i=new tn("open");i[As]=this,zo(e,this,i)};else return;r[si]=!!n[si],r[hc]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[hc]===e&&!n[si]){this.removeListener(t,n);break}}};Xp.exports={CloseEvent:zr,ErrorEvent:Cs,Event:tn,EventTarget:Uv,MessageEvent:ii};function zo(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Do=ae(($T,ef)=>{"use strict";var{tokenChars:oi}=Rs();function $t(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function qv(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&&oi[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 b=t.slice(c,p);u===44?($t(e,b,n),n=Object.create(null)):o=b,c=p=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);else if(l===void 0)if(p===-1&&oi[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),$t(n,t.slice(c,p),!0),u===44&&($t(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(oi[u]!==1)throw new SyntaxError(`Unexpected character at index ${f}`);c===-1?c=f:r||(r=!0),s=!1}else if(i)if(oi[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&&oi[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 b=t.slice(c,p);r&&(b=b.replace(/\\/g,""),r=!1),$t(n,l,b),u===44&&($t(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 w=t.slice(c,p);return o===void 0?$t(e,w,n):(l===void 0?$t(n,w,!0):r?$t(n,l,w.replace(/\\/g,"")):$t(n,l,w),$t(e,o,n)),e}function Fv(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(", ")}ef.exports={format:Fv,parse:qv}});var Fo=ae((NT,pf)=>{"use strict";var Bv=require("events"),Kv=require("https"),Hv=require("http"),rf=require("net"),Gv=require("tls"),{randomBytes:Zv,createHash:Wv}=require("crypto"),{Duplex:PT,Readable:jT}=require("stream"),{URL:pc}=require("url"),An=xs(),Vv=lc(),Jv=dc(),{isBlob:Yv}=Rs(),{BINARY_TYPES:tf,CLOSE_TIMEOUT:Xv,EMPTY_BUFFER:Lo,GUID:Qv,kForOnEventAttribute:fc,kListener:ek,kStatusCode:tk,kWebSocket:xe,NOOP:sf}=Qt(),{EventTarget:{addEventListener:nk,removeEventListener:rk}}=Qp(),{format:sk,parse:ik}=Do(),{toBuffer:ok}=ni(),of=Symbol("kAborted"),mc=[8,13],nn=["CONNECTING","OPEN","CLOSING","CLOSED"],ak=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,fe=class t extends Bv{constructor(e,n,r){super(),this._binaryType=tf[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Lo,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]),af(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){tf.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 Jv(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[xe]=this,i[xe]=this,e[xe]=this,s.on("conclude",uk),s.on("drain",dk),s.on("error",hk),s.on("message",pk),s.on("ping",fk),s.on("pong",mk),i.onerror=gk,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",uf),e.on("data",qo),e.on("end",df),e.on("error",hf),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[An.extensionName]&&this._extensions[An.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){Ze(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())}),cf(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){gc(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Lo,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){gc(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Lo,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){gc(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[An.extensionName]||(s.compress=!1),this._sender.send(e||Lo,s,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Ze(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(fe,"CONNECTING",{enumerable:!0,value:nn.indexOf("CONNECTING")});Object.defineProperty(fe.prototype,"CONNECTING",{enumerable:!0,value:nn.indexOf("CONNECTING")});Object.defineProperty(fe,"OPEN",{enumerable:!0,value:nn.indexOf("OPEN")});Object.defineProperty(fe.prototype,"OPEN",{enumerable:!0,value:nn.indexOf("OPEN")});Object.defineProperty(fe,"CLOSING",{enumerable:!0,value:nn.indexOf("CLOSING")});Object.defineProperty(fe.prototype,"CLOSING",{enumerable:!0,value:nn.indexOf("CLOSING")});Object.defineProperty(fe,"CLOSED",{enumerable:!0,value:nn.indexOf("CLOSED")});Object.defineProperty(fe.prototype,"CLOSED",{enumerable:!0,value:nn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(fe.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(fe.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[fc])return e[ek];return null},set(e){for(let n of this.listeners(t))if(n[fc]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[fc]:!0})}})});fe.prototype.addEventListener=nk;fe.prototype.removeEventListener=rk;pf.exports=fe;function af(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Xv,protocolVersion:mc[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,!mc.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${mc.join(", ")})`);let i;if(e instanceof pc)i=e;else try{i=new pc(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;Uo(t,x);return}let u=o?443:80,p=Zv(16).toString("base64"),f=o?Kv.request:Hv.request,w=new Set,b;if(s.createConnection=s.createConnection||(o?ck:lk),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&&(b=new An({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=sk({[An.extensionName]:b.offer()})),n.length){for(let x of n){if(typeof x!="string"||!ak.test(x)||w.has(x))throw new SyntaxError("An invalid or duplicated subprotocol was specified");w.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 k;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[A,$]of Object.entries(x))r.headers[A.toLowerCase()]=$}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")),k=t._req=f(s),t._redirects&&t.emit("redirect",t.url,k)}else k=t._req=f(s);s.timeout&&k.on("timeout",()=>{Ze(t,k,"Opening handshake has timed out")}),k.on("error",x=>{k===null||k[of]||(k=t._req=null,Uo(t,x))}),k.on("response",x=>{let A=x.headers.location,$=x.statusCode;if(A&&s.followRedirects&&$>=300&&$<400){if(++t._redirects>s.maxRedirects){Ze(t,k,"Maximum redirects exceeded");return}k.abort();let z;try{z=new pc(A,e)}catch{let L=new SyntaxError(`Invalid URL: ${A}`);Uo(t,L);return}af(t,z,n,r)}else t.emit("unexpected-response",k,x)||Ze(t,k,`Unexpected server response: ${x.statusCode}`)}),k.on("upgrade",(x,A,$)=>{if(t.emit("upgrade",x),t.readyState!==fe.CONNECTING)return;k=t._req=null;let z=x.headers.upgrade;if(z===void 0||z.toLowerCase()!=="websocket"){Ze(t,A,"Invalid Upgrade header");return}let v=Wv("sha1").update(p+Qv).digest("base64");if(x.headers["sec-websocket-accept"]!==v){Ze(t,A,"Invalid Sec-WebSocket-Accept header");return}let L=x.headers["sec-websocket-protocol"],O;if(L!==void 0?w.size?w.has(L)||(O="Server sent an invalid subprotocol"):O="Server sent a subprotocol but none was requested":w.size&&(O="Server sent no subprotocol"),O){Ze(t,A,O);return}L&&(t._protocol=L);let Y=x.headers["sec-websocket-extensions"];if(Y!==void 0){if(!b){Ze(t,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let M;try{M=ik(Y)}catch{Ze(t,A,"Invalid Sec-WebSocket-Extensions header");return}let d=Object.keys(M);if(d.length!==1||d[0]!==An.extensionName){Ze(t,A,"Server indicated an extension that was not requested");return}try{b.accept(M[An.extensionName])}catch{Ze(t,A,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[An.extensionName]=b}t.setSocket(A,$,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(k,t):k.end()}function Uo(t,e){t._readyState=fe.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function lk(t){return t.path=t.socketPath,rf.connect(t)}function ck(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=rf.isIP(t.host)?"":t.host),Gv.connect(t)}function Ze(t,e,n){t._readyState=fe.CLOSING;let r=new Error(n);Error.captureStackTrace(r,Ze),e.setHeader?(e[of]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Uo,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function gc(t,e,n){if(e){let r=Yv(e)?e.size:ok(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${nn[t.readyState]})`);process.nextTick(n,r)}}function uk(t,e){let n=this[xe];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[xe]!==void 0&&(n._socket.removeListener("data",qo),process.nextTick(lf,n._socket),t===1005?n.close():n.close(t,e))}function dk(){let t=this[xe];t.isPaused||t._socket.resume()}function hk(t){let e=this[xe];e._socket[xe]!==void 0&&(e._socket.removeListener("data",qo),process.nextTick(lf,e._socket),e.close(t[tk])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function nf(){this[xe].emitClose()}function pk(t,e){this[xe].emit("message",t,e)}function fk(t){let e=this[xe];e._autoPong&&e.pong(t,!this._isServer,sf),e.emit("ping",t)}function mk(t){this[xe].emit("pong",t)}function lf(t){t.resume()}function gk(t){let e=this[xe];e.readyState!==fe.CLOSED&&(e.readyState===fe.OPEN&&(e._readyState=fe.CLOSING,cf(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function cf(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function uf(){let t=this[xe];if(this.removeListener("close",uf),this.removeListener("data",qo),this.removeListener("end",df),t._readyState=fe.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[xe]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",nf),t._receiver.on("finish",nf))}function qo(t){this[xe]._receiver.write(t)||this.pause()}function df(){let t=this[xe];t._readyState=fe.CLOSING,t._receiver.end(),this.end()}function hf(){let t=this[xe];this.removeListener("error",hf),this.on("error",sf),t&&(t._readyState=fe.CLOSING,this.destroy())}});var yf=ae((MT,gf)=>{"use strict";var OT=Fo(),{Duplex:yk}=require("stream");function ff(t){t.emit("close")}function bk(){!this.destroyed&&this._writableState.finished&&this.destroy()}function mf(t){this.removeListener("error",mf),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function wk(t,e){let n=!0,r=new yk({...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(ff,r);return}let o=!1;t.once("error",function(c){o=!0,i(c)}),t.once("close",function(){o||i(s),process.nextTick(ff,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",bk),r.on("error",mf),r}gf.exports=wk});var yc=ae((zT,bf)=>{"use strict";var{tokenChars:vk}=Rs();function kk(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&&vk[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}bf.exports={parse:kk}});var xf=ae((LT,Tf)=>{"use strict";var _k=require("events"),Bo=require("http"),{Duplex:DT}=require("stream"),{createHash:Sk}=require("crypto"),wf=Do(),Dr=xs(),Tk=yc(),xk=Fo(),{CLOSE_TIMEOUT:Rk,GUID:Ik,kWebSocket:Ek}=Qt(),Ak=/^[+/0-9A-Za-z]{22}==$/,vf=0,kf=1,Sf=2,bc=class extends _k{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:Rk,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:xk,...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=Bo.createServer((r,s)=>{let i=Bo.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=Ck(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=vf}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===Sf){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(ai,this);return}if(e&&this.once("close",e),this._state!==kf)if(this._state=kf,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(ai,this):process.nextTick(ai,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{ai(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",_f);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,l=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Lr(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Lr(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!Ak.test(i)){Lr(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(l!==13&&l!==8){Lr(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){li(n,400);return}let c=e.headers["sec-websocket-protocol"],u=new Set;if(c!==void 0)try{u=Tk.parse(c)}catch{Lr(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 w=new Dr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let b=wf.parse(p);b[Dr.extensionName]&&(w.accept(b[Dr.extensionName]),f[Dr.extensionName]=w)}catch{Lr(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let w={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(w,(b,k,x,A)=>{if(!b)return li(n,k||401,x,A);this.completeUpgrade(f,i,u,e,n,r,s)});return}if(!this.options.verifyClient(w))return li(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[Ek])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>vf)return li(i,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Sk("sha1").update(n+Ik).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[Dr.extensionName]){let f=e[Dr.extensionName].params,w=wf.format({[Dr.extensionName]:[f]});u.push(`Sec-WebSocket-Extensions: ${w}`),p._extensions=e}this.emit("headers",u,s),i.write(u.concat(`\r
341
350
  `).join(`\r
342
- `)),i.removeListener("error",pf),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(oi,this)})),l(p,s)}};mf.exports=pc;function wk(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 oi(t){t._state=ff,t.emit("close")}function pf(){this.destroy()}function ai(t,e,n,r){n=n||Fo.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} ${Fo.STATUS_CODES[e]}\r
351
+ `)),i.removeListener("error",_f),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(ai,this)})),l(p,s)}};Tf.exports=bc;function Ck(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 ai(t){t._state=Sf,t.emit("close")}function _f(){this.destroy()}function li(t,e,n,r){n=n||Bo.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} ${Bo.STATUS_CODES[e]}\r
343
352
  `+Object.keys(r).map(s=>`${s}: ${r[s]}`).join(`\r
344
353
  `)+`\r
345
354
  \r
346
- `+n)}function Dr(t,e,n,r,s,i){if(t.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,Dr),t.emit("wsClientError",o,n,e)}else ai(n,r,s,i)}});var Pf={};on(Pf,{MANAGED_MARKER:()=>Wo,caddyBlock:()=>Zo,checkoutOwner:()=>Cf,detectApp:()=>Tf,envPrepare:()=>Lk,nodeBinDir:()=>Sf,pickPort:()=>Rf,portsClaimedByUnits:()=>xf,spliceCaddyBlock:()=>Af,sudoersText:()=>Ef,unitSlug:()=>_f,unitText:()=>If});function _f(t,e){let n=r=>r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return`${n(t)}-${n(e)}`.slice(0,60)}function Sf(t){let e=n=>{try{let r=(0,An.execFileSync)(n[0],n.slice(1),{encoding:"utf8",timeout:1e4}).trim();return r?Pt.default.dirname(r):null}catch{return null}};return t&&t!==ui.default.userInfo().username?e(["sudo","-u",t,"bash","-lc","command -v node"]):e(["bash","-lc","command -v node"])}function Tf(t){let e=Pt.default.join(t,"package.json");if(!Se.default.existsSync(e))return{kind:"unknown",reason:"no package.json - only Node apps are supported so far"};let n;try{n=JSON.parse(Se.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 xf(){let t=new Set;try{for(let e of Se.default.readdirSync("/etc/systemd/system"))if(e.endsWith(".service"))try{let n=Se.default.readFileSync(Pt.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 Rf(t){let e=xf(),n=r=>new Promise(s=>{let i=wc.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 If(t){return`${Wo}
355
+ `+n)}function Lr(t,e,n,r,s,i){if(t.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,Lr),t.emit("wsClientError",o,n,e)}else li(n,r,s,i)}});var Nf={};an(Nf,{CATALOGUE:()=>Rc,catalogueForPrompt:()=>Ic,describeDiagnostic:()=>Jk,runDiagnostic:()=>Yk});function Ic(){return["service_status {unit} - is a systemd service running, and why not","service_logs {unit, lines<=200} - a service's recent journal","listeners {} - what is listening on which port","disk_space {} - disk usage","dir_list {path} - list an absolute path","read_file {path, lines<=200} - the head of a file (credential stores are refused)","http_check {url} - status code and timing of one GET","git_state {path} - a checkout's branch and last commits"].join(`
356
+ `)}function Jk(t){let e=Rc[t.command];return e?e.describe(t.args??{}):null}async function Yk(t){let e=Rc[t.command];if(!e)return{ok:!1,commandLine:t.command,output:"refused: not in the catalogue"};let n=e.build(t.args??{}),r=e.describe(t.args??{});return typeof n=="string"?{ok:!1,commandLine:r,output:n}:new Promise(s=>{(0,jf.execFile)(n[0],n.slice(1),{timeout:Wk,maxBuffer:2e6},(i,o,l)=>{let c=`${o??""}${l?`
357
+ ${l}`:""}`.trim(),u=Cl(c).slice(0,Vk)||(i?String(i.message):"(no output)");s({ok:!0,commandLine:r,output:u})})})}var jf,xc,Wk,Vk,$f,Pf,Tc,ct,Wo,Rc,Ec=ye(()=>{"use strict";jf=require("node:child_process"),xc=I(require("node:fs"),1);$l();Wk=1e4,Vk=8e3,$f=/(\/\.(config|claude)\/|\/\.env($|[^a-z])|credentials|\.ssh\/|\.npmrc|runner\.json)/i,Pf=/^[a-zA-Z0-9@._-]{1,80}$/,Tc=/^\/[^\0\n]{1,300}$/,ct=t=>typeof t=="string"?t.trim():"",Wo=(t,e,n)=>{let r=typeof t=="number"?Math.floor(t):n;return r>0&&r<=e?r:n},Rc={service_status:{describe:t=>`systemctl status ${ct(t.unit)}`,build:t=>{let e=ct(t.unit);return Pf.test(e)?["systemctl","status",e,"--no-pager","-l"]:"refused: that is not a plausible unit name"}},service_logs:{describe:t=>`journalctl -u ${ct(t.unit)} -n ${Wo(t.lines,200,50)}`,build:t=>{let e=ct(t.unit);return Pf.test(e)?["journalctl","-u",e,"-n",String(Wo(t.lines,200,50)),"--no-pager"]:"refused: that is not a plausible unit name"}},listeners:{describe:()=>"ss -ltnp (what is listening on which port)",build:()=>["ss","-ltnp"]},disk_space:{describe:()=>"df -h (disk usage)",build:()=>["df","-h"]},dir_list:{describe:t=>`ls -la ${ct(t.path)}`,build:t=>{let e=ct(t.path);return Tc.test(e)?$f.test(e)?"refused: that path can hold credentials":["ls","-la",e]:"refused: absolute path required"}},read_file:{describe:t=>`head -n ${Wo(t.lines,200,100)} ${ct(t.path)}`,build:t=>{let e=ct(t.path);if(!Tc.test(e))return"refused: absolute path required";if($f.test(e))return"refused: that path can hold credentials";try{if(xc.default.statSync(e).size>2e6)return"refused: file too large for a chat"}catch{}return["head","-n",String(Wo(t.lines,200,100)),e]}},http_check:{describe:t=>`curl -sS -o /dev/null -w '%{http_code}' ${ct(t.url)}`,build:t=>{let e=ct(t.url);return/^https?:\/\/[^\s'"]{1,300}$/.test(e)?["curl","-sS","-o","/dev/null","-w","HTTP %{http_code}, %{time_total}s","--max-time","10",e]:"refused: a plain http(s) URL only"}},git_state:{describe:t=>`git -C ${ct(t.path)} status + last 3 commits`,build:t=>{let e=ct(t.path);return Tc.test(e)?xc.default.existsSync(`${e}/.git`)?["git","-C",e,"log","--oneline","-3","--decorate"]:"refused: not a git checkout":"refused: absolute path required"}}}});var Hf={};an(Hf,{MANAGED_MARKER:()=>Jo,caddyBlock:()=>Vo,checkoutOwner:()=>Bf,detectApp:()=>zf,envPrepare:()=>e_,nodeBinDir:()=>Mf,pickPort:()=>Lf,portsClaimedByUnits:()=>Df,spliceCaddyBlock:()=>Ff,sudoersText:()=>qf,unitSlug:()=>Of,unitText:()=>Uf});function Of(t,e){let n=r=>r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return`${n(t)}-${n(e)}`.slice(0,60)}function Mf(t){let e=n=>{try{let r=(0,Cn.execFileSync)(n[0],n.slice(1),{encoding:"utf8",timeout:1e4}).trim();return r?jt.default.dirname(r):null}catch{return null}};return t&&t!==di.default.userInfo().username?e(["sudo","-u",t,"bash","-lc","command -v node"]):e(["bash","-lc","command -v node"])}function zf(t){let e=jt.default.join(t,"package.json");if(!Se.default.existsSync(e))return{kind:"unknown",reason:"no package.json - only Node apps are supported so far"};let n;try{n=JSON.parse(Se.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 Df(){let t=new Set;try{for(let e of Se.default.readdirSync("/etc/systemd/system"))if(e.endsWith(".service"))try{let n=Se.default.readFileSync(jt.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 Lf(t){let e=Df(),n=r=>new Promise(s=>{let i=Ac.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 Uf(t){return`${Jo}
347
358
  [Unit]
348
359
  Description=${t.repoName} ${t.envName} (Allwright-prepared)
349
360
  After=network-online.target
@@ -373,51 +384,51 @@ RestartSec=3
373
384
 
374
385
  [Install]
375
386
  WantedBy=multi-user.target
376
- `}function Ef(t){return`${Wo}
387
+ `}function qf(t){return`${Jo}
377
388
  # Exactly two commands, exactly one unit - what a deploy needs and nothing else.
378
389
  ${t.user} ALL=(root) NOPASSWD: /usr/bin/systemctl restart ${t.slug}, /usr/bin/systemctl is-active ${t.slug}
379
- `}function Zo(t){return`# BEGIN allwright ${t.slug}
390
+ `}function Vo(t){return`# BEGIN allwright ${t.slug}
380
391
  ${t.hostname} {
381
392
  reverse_proxy 127.0.0.1:${t.port}
382
393
  }
383
- # END allwright ${t.slug}`}function Af(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*$/,"")+`
394
+ # END allwright ${t.slug}`}function Ff(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*$/,"")+`
384
395
 
385
396
  `+n+`
386
- `}function Cf(t){let e=Se.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,An.execFileSync)("id",["-nu",String(e)],{encoding:"utf8",timeout:5e3}).trim()}catch{return ui.default.userInfo().username}}function We(t,e){(0,An.execFileSync)("sudo",t,{encoding:"utf8",timeout:6e4,...e!==void 0?{input:e}:{},stdio:[e!==void 0?"pipe":"inherit","inherit","inherit"]})}function zk(t){if(t.sudoers){let e=Pt.default.join(ui.default.tmpdir(),`allwright-sudoers-${process.pid}`);Se.default.writeFileSync(e,t.content,{mode:384});try{(0,An.execFileSync)("sudo",["visudo","-cf",e],{encoding:"utf8",timeout:3e4}),We(["install","-m",t.mode,"-o","root","-g","root",e,t.path])}finally{Se.default.rmSync(e,{force:!0})}return}We(["mkdir","-p",Pt.default.dirname(t.path)]),We(["tee",t.path],t.content),We(["chmod",t.mode,t.path])}function Dk(t){try{return Se.default.readFileSync(t,"utf8").includes(Wo)}catch{return!0}}async function Lk(t){if(!Se.default.existsSync(t.dir))throw new Error(`${t.dir} does not exist - clone the repo there first`);if(!Se.default.existsSync(Pt.default.join(t.dir,".git")))throw new Error(`${t.dir} is not a git checkout`);let e=Tf(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=_f(t.repoName,t.envName),r=t.publicUrl?Uk(t.publicUrl):"";if(e.kind==="static"){if(g.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){g.info("Pass --url to wire the proxy, or configure it in your web server by hand.");return}g.info("Add a site block for it to /etc/caddy/Caddyfile yourself, for example:"),g.info(`
397
+ `}function Bf(t){let e=Se.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,Cn.execFileSync)("id",["-nu",String(e)],{encoding:"utf8",timeout:5e3}).trim()}catch{return di.default.userInfo().username}}function We(t,e){(0,Cn.execFileSync)("sudo",t,{encoding:"utf8",timeout:6e4,...e!==void 0?{input:e}:{},stdio:[e!==void 0?"pipe":"inherit","inherit","inherit"]})}function Xk(t){if(t.sudoers){let e=jt.default.join(di.default.tmpdir(),`allwright-sudoers-${process.pid}`);Se.default.writeFileSync(e,t.content,{mode:384});try{(0,Cn.execFileSync)("sudo",["visudo","-cf",e],{encoding:"utf8",timeout:3e4}),We(["install","-m",t.mode,"-o","root","-g","root",e,t.path])}finally{Se.default.rmSync(e,{force:!0})}return}We(["mkdir","-p",jt.default.dirname(t.path)]),We(["tee",t.path],t.content),We(["chmod",t.mode,t.path])}function Qk(t){try{return Se.default.readFileSync(t,"utf8").includes(Jo)}catch{return!0}}async function e_(t){if(!Se.default.existsSync(t.dir))throw new Error(`${t.dir} does not exist - clone the repo there first`);if(!Se.default.existsSync(jt.default.join(t.dir,".git")))throw new Error(`${t.dir} is not a git checkout`);let e=zf(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=Of(t.repoName,t.envName),r=t.publicUrl?t_(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(`
387
398
  ${r} {
388
399
  root * ${t.dir}/<your build output>
389
400
  file_server
390
401
  }
391
- `);return}let s=go(t.dir).filter(k=>!k.startsWith(n)),i=`/etc/systemd/system/${n}.service`;if(s.length&&!Se.default.existsSync(i)){g.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(!Dk(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=Cf(t.dir),l=Sf(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 Rf(t.port),u=[{path:i,content:If({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:Ef({slug:n,user:o}),mode:"440",sudoers:!0}];if(t.dryRun){g.info(`DRY RUN - nothing will be written. Planned (port ${c}, user ${o}):`);for(let k of u)g.info(`
402
+ `);return}let s=go(t.dir).filter(k=>!k.startsWith(n)),i=`/etc/systemd/system/${n}.service`;if(s.length&&!Se.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(!Qk(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=Bf(t.dir),l=Mf(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 Lf(t.port),u=[{path:i,content:Uf({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:qf({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 k of u)y.info(`
392
403
  --- ${k.path} (mode ${k.mode}) ---
393
- ${k.content}`);r&&g.info(`--- appended to /etc/caddy/Caddyfile ---
394
- ${Zo({slug:n,hostname:r,port:c})}`);return}for(let k of u)zk(k);let p=`/etc/allwright/env.d/${n}.env`;Se.default.existsSync(p)||(We(["install","-d","-m","755","/etc/allwright"]),We(["install","-d","-m","750","/etc/allwright/env.d"]),We(["install","-m","600","-o","root","-g","root","/dev/null",p]),g.info(`created empty ${p} - add secrets with: sudoedit ${p}`));let f=Se.default.existsSync(Pt.default.join(t.dir,".next"))||Se.default.existsSync(Pt.default.join(t.dir,"dist"));f||g.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}`),We(["systemctl","daemon-reload"]),We(["systemctl","reset-failed",n]),We(["systemctl","enable","--now",n]),r&&Fk({slug:n,hostname:r,port:c});let w=f?await qk(c,3e4):!1,b=$f(n);g.info(""),g.info(`${b?"\u2713":"\u2717"} service ${n}: ${b?"active":"NOT active - journalctl -u "+n+" -n 40"}`),f&&g.info(`${w?"\u2713":"\u2717"} listening on 127.0.0.1:${c}${w?"":" - not yet; check the journal"}`),g.info("\u2713 deploys may restart it without a password (sudoers drop-in installed)"),g.info(""),g.info(`Deploy steps should end with: sudo systemctl restart ${n}`),r&&g.info(`Health checks should target: http://127.0.0.1:${c}/ (and later https://${r}/)`),g.info(`DNS stays yours: point ${r||"your hostname"} at this machine when you are ready.`)}function Uk(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 $f(t){try{return(0,An.execFileSync)("systemctl",["is-active",t],{encoding:"utf8",timeout:1e4}).trim()==="active"}catch{return!1}}async function qk(t,e){let n=Date.now()+e;for(;Date.now()<n;){if(await new Promise(s=>{let i=wc.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 Fk(t){let e="/etc/caddy/Caddyfile";if(!Se.default.existsSync(e)||!$f("caddy")){g.warn(`caddy is not running here (or ${e} does not exist) - add this to your web server yourself:
395
- ${Zo(t)}`);return}let n;try{n=Se.default.readFileSync(e,"utf8")}catch{n=(0,An.execFileSync)("sudo",["cat",e],{encoding:"utf8",timeout:1e4})}let r=Af(n,t.slug,Zo(t));if(r===n){g.info(`caddy already routes ${t.hostname} - unchanged`);return}let s=Pt.default.join(ui.default.tmpdir(),`Caddyfile-allwright-${process.pid}`);Se.default.writeFileSync(s,r,{mode:420});try{(0,An.execFileSync)("sudo",["caddy","validate","--config",s,"--adapter","caddyfile"],{encoding:"utf8",timeout:3e4}),We(["cp",e,`${e}.bak.${Math.floor(Date.now()/1e3)}`]),We(["cp",s,e]),We(["systemctl","reload","caddy"]),g.info(`\u2713 caddy: ${t.hostname} \u2192 127.0.0.1:${t.port} (validated, reloaded, backup kept)`)}finally{Se.default.rmSync(s,{force:!0})}}var An,Se,wc,ui,Pt,Wo,jf=ve(()=>{"use strict";An=require("node:child_process"),Se=I(require("node:fs"),1),wc=I(require("node:net"),1),ui=I(require("node:os"),1),Pt=I(require("node:path"),1);Wt();yo();Wo="# managed by allwright env prepare"});var Lf={};on(Lf,{buildSetupReport:()=>Kk,claudeLoggedIn:()=>Df,repoCurrentBranch:()=>Mf,repoDefaultBranch:()=>zf});function Mf(t){try{let e=(0,hi.execFileSync)("git",["-C",t,"rev-parse","--abbrev-ref","HEAD"],{encoding:"utf8",timeout:1e4}).trim();return e==="HEAD"?"":e}catch{return""}}function zf(t){let e=(...s)=>{try{return(0,hi.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 Df(t=Nf.default.homedir()){if(Cn.default.existsSync(Ur.default.join(t,".claude",".credentials.json")))return!0;try{return!!JSON.parse(Cn.default.readFileSync(Ur.default.join(t,".claude.json"),"utf8")).oauthAccount}catch{return!1}}async function Kk(t,e,n){let r=!1,s="";if(di&&Date.now()-di.at<6e4)r=di.installed,s=di.version;else{try{let{stdout:l}=await Bk(t.claudeBin,["--version"],{timeout:1e4});r=!0,s=l.trim().slice(0,60)}catch{r=!1}di={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=Cn.default.existsSync(c.path);return{repoName:l,path:c.path,mapped:!0,liveMapped:n?!!n.repos?.[l]:!0,pathExists:u,isGit:u&&Cn.default.existsSync(Ur.default.join(c.path,".git")),currentBranch:u?Mf(c.path):"",claudeMd:u&&Cn.default.existsSync(Ur.default.join(c.path,"CLAUDE.md")),deployMd:u&&Cn.default.existsSync(Ur.default.join(c.path,"DEPLOY.md")),testMd:u&&Cn.default.existsSync(Ur.default.join(c.path,"TEST.md")),githubToken:!!je(t,l),githubTokenOwn:!!c.github?.token,defaultBranch:u?zf(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:Df()},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 hi,Cn,Nf,Ur,Of,Bk,di,Uf=ve(()=>{"use strict";hi=require("node:child_process"),Cn=I(require("node:fs"),1),Nf=I(require("node:os"),1),Ur=I(require("node:path"),1),Of=require("node:util");gr();Bk=(0,Of.promisify)(hi.execFile);di=null});var Gk={};on(Gk,{parsePlanAnswer:()=>Ff});module.exports=Vf(Gk);var Ve=I(require("node:fs"),1),pi=I(require("node:os"),1),nn=I(require("node:path"),1),sn=require("node:child_process"),qr=require("node:crypto"),$n=I(require("node:readline/promises"),1);var zc=I(Mc(),1),{program:t_,createCommand:n_,createArgument:r_,createOption:s_,CommanderError:i_,InvalidArgumentError:o_,InvalidOptionArgumentError:a_,Command:Dc,Argument:l_,Option:c_,Help:u_}=zc.default;Ce();var Ai=require("node:child_process"),Ke=I(require("node:fs"),1),Ci=I(require("node:path"),1);Ce();var kg=new Set(["runner.log","runner.pid"]);function _g(t){return Ke.default.readdirSync(t).filter(e=>!kg.has(e)&&!/\.bak-\d+$/.test(e)).sort()}function eu(t){let e=oe();if(!Ke.default.existsSync(e))throw new Error(`nothing to export - ${e} does not exist`);let n=_g(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=Ci.default.resolve(t||`ticketpilot-backup-${r}.tgz`);return Ke.default.writeFileSync(s,"",{mode:384}),(0,Ai.execFileSync)("tar",["-czf",s,"-C",e,...n]),Ke.default.chmodSync(s,384),{file:s,entries:n}}function tu(t){let e=Ci.default.resolve(t);if(!Ke.default.existsSync(e))throw new Error(`backup file not found: ${e}`);let n=(0,Ai.execFileSync)("tar",["-tzf",e],{encoding:"utf8"}).split(`
396
- `).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=oe(),s;Ke.default.existsSync(r)&&Ke.default.readdirSync(r).length&&(s=`${r}.bak-${Date.now()}`,Ke.default.renameSync(r,s)),Ke.default.mkdirSync(r,{recursive:!0,mode:448}),(0,Ai.execFileSync)("tar",["-xzf",e,"-C",r]);for(let i of Ke.default.readdirSync(r)){let o=Ci.default.join(r,i);Ke.default.statSync(o).isFile()&&Ke.default.chmodSync(o,384)}return{restored:n.map(i=>i.replace(/\/$/,"")).sort(),previousDir:s}}var Yr=I(require("node:fs"),1),dn=I(require("node:path"),1),$i=".ticketpilot-attachments",Sg=15*1024*1024,Tg=50*1024*1024,nu=20;function ru(t,e){let n=dn.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 Xr(t,e,n,r){if(!e.length)return"";let s=dn.default.join(n,$i);Yr.default.mkdirSync(s,{recursive:!0});let i=new Set,o=[],l=0;for(let c of e){if(o.length>=nu){r("warn",`attachment cap reached (${nu} files) - skipping the rest`);break}if(c.size>Sg){r("warn",`skipping attachment "${c.filename}" - ${Ig(c.size)} MB exceeds the 15 MB limit`);continue}if(l+c.size>Tg){r("warn",`attachment size budget reached - skipping "${c.filename}" and the rest`);break}try{let u=await t.downloadAttachment(c.contentUrl),p=ru(c.filename,i);Yr.default.writeFileSync(dn.default.join(s,p),u),l+=u.length,o.push(`- ${$i}/${p} (${c.mimeType||"unknown type"}, ${ba(u.length)} KB)`),r("info",`Downloaded attachment "${c.filename}" (${ba(u.length)} KB)`)}catch(u){r("warn",`could not download attachment "${c.filename}": ${u instanceof Error?u.message:u}`)}}return o.length?`
404
+ ${k.content}`);r&&y.info(`--- appended to /etc/caddy/Caddyfile ---
405
+ ${Vo({slug:n,hostname:r,port:c})}`);return}for(let k of u)Xk(k);let p=`/etc/allwright/env.d/${n}.env`;Se.default.existsSync(p)||(We(["install","-d","-m","755","/etc/allwright"]),We(["install","-d","-m","750","/etc/allwright/env.d"]),We(["install","-m","600","-o","root","-g","root","/dev/null",p]),y.info(`created empty ${p} - add secrets with: sudoedit ${p}`));let f=Se.default.existsSync(jt.default.join(t.dir,".next"))||Se.default.existsSync(jt.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}`),We(["systemctl","daemon-reload"]),We(["systemctl","reset-failed",n]),We(["systemctl","enable","--now",n]),r&&r_({slug:n,hostname:r,port:c});let w=f?await n_(c,3e4):!1,b=Kf(n);y.info(""),y.info(`${b?"\u2713":"\u2717"} service ${n}: ${b?"active":"NOT active - journalctl -u "+n+" -n 40"}`),f&&y.info(`${w?"\u2713":"\u2717"} listening on 127.0.0.1:${c}${w?"":" - 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 t_(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 Kf(t){try{return(0,Cn.execFileSync)("systemctl",["is-active",t],{encoding:"utf8",timeout:1e4}).trim()==="active"}catch{return!1}}async function n_(t,e){let n=Date.now()+e;for(;Date.now()<n;){if(await new Promise(s=>{let i=Ac.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 r_(t){let e="/etc/caddy/Caddyfile";if(!Se.default.existsSync(e)||!Kf("caddy")){y.warn(`caddy is not running here (or ${e} does not exist) - add this to your web server yourself:
406
+ ${Vo(t)}`);return}let n;try{n=Se.default.readFileSync(e,"utf8")}catch{n=(0,Cn.execFileSync)("sudo",["cat",e],{encoding:"utf8",timeout:1e4})}let r=Ff(n,t.slug,Vo(t));if(r===n){y.info(`caddy already routes ${t.hostname} - unchanged`);return}let s=jt.default.join(di.default.tmpdir(),`Caddyfile-allwright-${process.pid}`);Se.default.writeFileSync(s,r,{mode:420});try{(0,Cn.execFileSync)("sudo",["caddy","validate","--config",s,"--adapter","caddyfile"],{encoding:"utf8",timeout:3e4}),We(["cp",e,`${e}.bak.${Math.floor(Date.now()/1e3)}`]),We(["cp",s,e]),We(["systemctl","reload","caddy"]),y.info(`\u2713 caddy: ${t.hostname} \u2192 127.0.0.1:${t.port} (validated, reloaded, backup kept)`)}finally{Se.default.rmSync(s,{force:!0})}}var Cn,Se,Ac,di,jt,Jo,Gf=ye(()=>{"use strict";Cn=require("node:child_process"),Se=I(require("node:fs"),1),Ac=I(require("node:net"),1),di=I(require("node:os"),1),jt=I(require("node:path"),1);Vt();yo();Jo="# managed by allwright env prepare"});var Xf={};an(Xf,{buildSetupReport:()=>i_,claudeLoggedIn:()=>Yf,repoCurrentBranch:()=>Vf,repoDefaultBranch:()=>Jf});function Vf(t){try{let e=(0,pi.execFileSync)("git",["-C",t,"rev-parse","--abbrev-ref","HEAD"],{encoding:"utf8",timeout:1e4}).trim();return e==="HEAD"?"":e}catch{return""}}function Jf(t){let e=(...s)=>{try{return(0,pi.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 Yf(t=Zf.default.homedir()){if($n.default.existsSync(qr.default.join(t,".claude",".credentials.json")))return!0;try{return!!JSON.parse($n.default.readFileSync(qr.default.join(t,".claude.json"),"utf8")).oauthAccount}catch{return!1}}async function i_(t,e,n){let r=!1,s="";if(hi&&Date.now()-hi.at<6e4)r=hi.installed,s=hi.version;else{try{let{stdout:l}=await s_(t.claudeBin,["--version"],{timeout:1e4});r=!0,s=l.trim().slice(0,60)}catch{r=!1}hi={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=$n.default.existsSync(c.path);return{repoName:l,path:c.path,mapped:!0,liveMapped:n?!!n.repos?.[l]:!0,pathExists:u,isGit:u&&$n.default.existsSync(qr.default.join(c.path,".git")),currentBranch:u?Vf(c.path):"",claudeMd:u&&$n.default.existsSync(qr.default.join(c.path,"CLAUDE.md")),deployMd:u&&$n.default.existsSync(qr.default.join(c.path,"DEPLOY.md")),testMd:u&&$n.default.existsSync(qr.default.join(c.path,"TEST.md")),githubToken:!!je(t,l),githubTokenOwn:!!c.github?.token,defaultBranch:u?Jf(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:Yf()},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 pi,$n,Zf,qr,Wf,s_,hi,Qf=ye(()=>{"use strict";pi=require("node:child_process"),$n=I(require("node:fs"),1),Zf=I(require("node:os"),1),qr=I(require("node:path"),1),Wf=require("node:util");yr();s_=(0,Wf.promisify)(pi.execFile);hi=null});var Ve=I(require("node:fs"),1),fi=I(require("node:os"),1),rn=I(require("node:path"),1),on=require("node:child_process"),Fr=require("node:crypto"),Pn=I(require("node:readline/promises"),1);var Gc=I(Hc(),1),{program:m_,createCommand:g_,createArgument:y_,createOption:b_,CommanderError:w_,InvalidArgumentError:v_,InvalidOptionArgumentError:k_,Command:Zc,Argument:__,Option:S_,Help:T_}=Gc.default;Ce();var Ai=require("node:child_process"),Ke=I(require("node:fs"),1),Ci=I(require("node:path"),1);Ce();var jg=new Set(["runner.log","runner.pid"]);function Ng(t){return Ke.default.readdirSync(t).filter(e=>!jg.has(e)&&!/\.bak-\d+$/.test(e)).sort()}function cu(t){let e=oe();if(!Ke.default.existsSync(e))throw new Error(`nothing to export - ${e} does not exist`);let n=Ng(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=Ci.default.resolve(t||`ticketpilot-backup-${r}.tgz`);return Ke.default.writeFileSync(s,"",{mode:384}),(0,Ai.execFileSync)("tar",["-czf",s,"-C",e,...n]),Ke.default.chmodSync(s,384),{file:s,entries:n}}function uu(t){let e=Ci.default.resolve(t);if(!Ke.default.existsSync(e))throw new Error(`backup file not found: ${e}`);let n=(0,Ai.execFileSync)("tar",["-tzf",e],{encoding:"utf8"}).split(`
407
+ `).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=oe(),s;Ke.default.existsSync(r)&&Ke.default.readdirSync(r).length&&(s=`${r}.bak-${Date.now()}`,Ke.default.renameSync(r,s)),Ke.default.mkdirSync(r,{recursive:!0,mode:448}),(0,Ai.execFileSync)("tar",["-xzf",e,"-C",r]);for(let i of Ke.default.readdirSync(r)){let o=Ci.default.join(r,i);Ke.default.statSync(o).isFile()&&Ke.default.chmodSync(o,384)}return{restored:n.map(i=>i.replace(/\/$/,"")).sort(),previousDir:s}}var Xr=I(require("node:fs"),1),hn=I(require("node:path"),1),$i=".ticketpilot-attachments",Og=15*1024*1024,Mg=50*1024*1024,du=20;function hu(t,e){let n=hn.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 Qr(t,e,n,r){if(!e.length)return"";let s=hn.default.join(n,$i);Xr.default.mkdirSync(s,{recursive:!0});let i=new Set,o=[],l=0;for(let c of e){if(o.length>=du){r("warn",`attachment cap reached (${du} files) - skipping the rest`);break}if(c.size>Og){r("warn",`skipping attachment "${c.filename}" - ${Lg(c.size)} MB exceeds the 15 MB limit`);continue}if(l+c.size>Mg){r("warn",`attachment size budget reached - skipping "${c.filename}" and the rest`);break}try{let u=await t.downloadAttachment(c.contentUrl),p=hu(c.filename,i);Xr.default.writeFileSync(hn.default.join(s,p),u),l+=u.length,o.push(`- ${$i}/${p} (${c.mimeType||"unknown type"}, ${ka(u.length)} KB)`),r("info",`Downloaded attachment "${c.filename}" (${ka(u.length)} KB)`)}catch(u){r("warn",`could not download attachment "${c.filename}": ${u instanceof Error?u.message:u}`)}}return o.length?`
397
408
 
398
409
  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:
399
410
  ${o.join(`
400
411
  `)}
401
- Read them with the Read tool when relevant; images (screenshots) can be viewed directly.`:(hn(n),"")}function hn(t){Yr.default.rmSync(dn.default.join(t,$i),{recursive:!0,force:!0})}var xg=4*1024*1024,Rg=16*1024*1024;function su(t,e,n){let r=dn.default.join(t,$i,`chat-${e.replace(/[^\w-]/g,"")}`);if(!n.length)return{section:"",dir:r};Yr.default.mkdirSync(r,{recursive:!0});let s=new Set,i=[],o=0,l=dn.default.relative(t,r);for(let u of n){let p=Buffer.from(u.contentBase64,"base64");if(p.length>xg||o+p.length>Rg){i.push(`- (skipped "${u.name}" - over the upload size budget)`);continue}let f=ru(u.name,s);Yr.default.writeFileSync(dn.default.join(r,f),p),o+=p.length,i.push(`- ${l}/${f} (${ba(p.length)} KB)`)}return{section:`
412
+ Read them with the Read tool when relevant; images (screenshots) can be viewed directly.`:(pn(n),"")}function pn(t){Xr.default.rmSync(hn.default.join(t,$i),{recursive:!0,force:!0})}var zg=4*1024*1024,Dg=16*1024*1024;function pu(t,e,n){let r=hn.default.join(t,$i,`chat-${e.replace(/[^\w-]/g,"")}`);if(!n.length)return{section:"",dir:r};Xr.default.mkdirSync(r,{recursive:!0});let s=new Set,i=[],o=0,l=hn.default.relative(t,r);for(let u of n){let p=Buffer.from(u.contentBase64,"base64");if(p.length>zg||o+p.length>Dg){i.push(`- (skipped "${u.name}" - over the upload size budget)`);continue}let f=hu(u.name,s);Xr.default.writeFileSync(hn.default.join(r,f),p),o+=p.length,i.push(`- ${l}/${f} (${ka(p.length)} KB)`)}return{section:`
402
413
 
403
414
  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:
404
415
  ${i.join(`
405
416
  `)}
406
- Read them with the Read tool; images can be viewed directly.`,dir:r}}var ba=t=>Math.max(1,Math.round(t/1024)),Ig=t=>Math.round(t/(1024*1024)*10)/10;var Ee=I(require("node:fs"),1),ji=I(require("node:path"),1);Ce();function Qr(){return ji.default.join(oe(),"runner.pid")}function Pi(){return ji.default.join(oe(),"runner.log")}function iu(){Ee.default.mkdirSync(oe(),{recursive:!0,mode:448});let t=Ee.default.openSync(Pi(),"a",384);try{Ee.default.chmodSync(Pi(),384)}catch{}return t}function Wn(){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 Vn(t){try{return process.kill(t,0),!0}catch{return!1}}function ou(t){Ee.default.mkdirSync(oe(),{recursive:!0,mode:448}),Ee.default.writeFileSync(Qr(),String(t),{mode:384})}function au(t){Wn()===t&&Ee.default.rmSync(Qr(),{force:!0})}function wa(){return ji.default.join(oe(),"runner.lock")}function es(){let t=wa();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:Vn(e)?e:null}function lu(){let t=es();return t?{ok:!1,pid:t}:(Ee.default.mkdirSync(oe(),{recursive:!0,mode:448}),Ee.default.writeFileSync(wa(),String(process.pid),{mode:384}),{ok:!0})}function va(){try{let t=wa();Ee.default.existsSync(t)&&Number(Ee.default.readFileSync(t,"utf8").trim())===process.pid&&Ee.default.rmSync(t,{force:!0})}catch{}}function cu(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 qi=I(require("node:fs"),1),Fs=I(require("node:path"),1),Nu=I(ke(),1);Ce();async function Ou(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:Fi})});if(!n.ok){let i=await n.text().catch(()=>"");throw new Error(`enrollment failed (${n.status}): ${i.slice(0,300)}`)}let r=Nu.EnrollResponse.parse(await n.json()),s={...t,runnerId:r.runnerId,runnerToken:r.runnerToken};return ge(s),s}function nb(){try{let t=process.argv[1]?qi.default.realpathSync(process.argv[1]):"";for(let e of[Fs.default.dirname(t),Fs.default.dirname(Fs.default.dirname(t))]){let n=Fs.default.join(e,"package.json");if(!qi.default.existsSync(n))continue;let r=JSON.parse(qi.default.readFileSync(n,"utf8")).version;if(typeof r=="string"&&r)return r}}catch{}return"0.0.0"}var Fi=nb();xt();var Hu="Posted automatically by Allwright",rb=["Posted automatically by TicketPilot"],Rt=t=>t.includes(Hu)||rb.some(e=>t.includes(e));var sb="no Jira credentials on this runner - add them with `allwright jira set-default`";function Ka(){return new Pe({baseUrl:"",email:"",apiToken:""},!1)}var Pe=class{constructor(e,n=!0){this.auth=e;this.configured=n}auth;configured;get isConfigured(){return this.configured}assertConfigured(){if(!this.configured)throw new Error(sb)}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){this.assertConfigured();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:Ku(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:Ku(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){this.assertConfigured();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:Ba(r),...i?{parent:{key:i}}:{}}})).key}}async addAttachments(e,n){if(!n.length)return;this.assertConfigured();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:Ba(n)})}async addComment(e,n){let r=`${n}
417
+ Read them with the Read tool; images can be viewed directly.`,dir:r}}var ka=t=>Math.max(1,Math.round(t/1024)),Lg=t=>Math.round(t/(1024*1024)*10)/10;var Ee=I(require("node:fs"),1),ji=I(require("node:path"),1);Ce();function es(){return ji.default.join(oe(),"runner.pid")}function Pi(){return ji.default.join(oe(),"runner.log")}function fu(){Ee.default.mkdirSync(oe(),{recursive:!0,mode:448});let t=Ee.default.openSync(Pi(),"a",384);try{Ee.default.chmodSync(Pi(),384)}catch{}return t}function Vn(){let t=es();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 Jn(t){try{return process.kill(t,0),!0}catch{return!1}}function mu(t){Ee.default.mkdirSync(oe(),{recursive:!0,mode:448}),Ee.default.writeFileSync(es(),String(t),{mode:384})}function gu(t){Vn()===t&&Ee.default.rmSync(es(),{force:!0})}function _a(){return ji.default.join(oe(),"runner.lock")}function ts(){let t=_a();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:Jn(e)?e:null}function yu(){let t=ts();return t?{ok:!1,pid:t}:(Ee.default.mkdirSync(oe(),{recursive:!0,mode:448}),Ee.default.writeFileSync(_a(),String(process.pid),{mode:384}),{ok:!0})}function Sa(){try{let t=_a();Ee.default.existsSync(t)&&Number(Ee.default.readFileSync(t,"utf8").trim())===process.pid&&Ee.default.rmSync(t,{force:!0})}catch{}}function bu(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 qi=I(require("node:fs"),1),Bs=I(require("node:path"),1),Bu=I(ke(),1);Ce();async function Ku(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:Fi})});if(!n.ok){let i=await n.text().catch(()=>"");throw new Error(`enrollment failed (${n.status}): ${i.slice(0,300)}`)}let r=Bu.EnrollResponse.parse(await n.json()),s={...t,runnerId:r.runnerId,runnerToken:r.runnerToken};return ge(s),s}function fb(){try{let t=process.argv[1]?qi.default.realpathSync(process.argv[1]):"";for(let e of[Bs.default.dirname(t),Bs.default.dirname(Bs.default.dirname(t))]){let n=Bs.default.join(e,"package.json");if(!qi.default.existsSync(n))continue;let r=JSON.parse(qi.default.readFileSync(n,"utf8")).version;if(typeof r=="string"&&r)return r}}catch{}return"0.0.0"}var Fi=fb();Rt();var ed="Posted automatically by Allwright",mb=["Posted automatically by TicketPilot"],It=t=>t.includes(ed)||mb.some(e=>t.includes(e));var gb="no Jira credentials on this runner - add them with `allwright jira set-default`";function Za(){return new Pe({baseUrl:"",email:"",apiToken:""},!1)}var Pe=class{constructor(e,n=!0){this.auth=e;this.configured=n}auth;configured;get isConfigured(){return this.configured}assertConfigured(){if(!this.configured)throw new Error(gb)}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){this.assertConfigured();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:Qu(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:Qu(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){this.assertConfigured();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:Ga(r),...i?{parent:{key:i}}:{}}})).key}}async addAttachments(e,n){if(!n.length)return;this.assertConfigured();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:Ga(n)})}async addComment(e,n){let r=`${n}
407
418
 
408
419
  ---
409
- _${Hu} - never treated as a trigger._`;await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/comment`,{body:Ba(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 Ku(t){if(!t)return"";let e=[],n=r=>{r.text&&e.push(r.text),r.type==="hardBreak"&&e.push(`
420
+ _${ed} - never treated as a trigger._`;await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/comment`,{body:Ga(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 Qu(t){if(!t)return"";let e=[],n=r=>{r.text&&e.push(r.text),r.type==="hardBreak"&&e.push(`
410
421
  `);for(let s of r.content??[])n(s);r.type&&["paragraph","heading","listItem","codeBlock","blockquote"].includes(r.type)&&e.push(`
411
422
  `)};return n(t),e.join("").replace(/\n{3,}/g,`
412
423
 
413
- `).trim()}function Ba(t){let e=t.replace(/\r\n/g,`
424
+ `).trim()}function Ga(t){let e=t.replace(/\r\n/g,`
414
425
  `).split(`
415
426
  `),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(`
416
- `)||" "}]});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 w=e[r].match(/^\s*[-*]\s+(.*)$/);if(!w)break;f.push({type:"listItem",content:[{type:"paragraph",content:s(w[1])}]}),r++}n.push({type:"bulletList",content:f});continue}if(i.match(/^\s*\d+[.)]\s+(.*)$/)){let f=[];for(;r<e.length;){let w=e[r].match(/^\s*\d+[.)]\s+(.*)$/);if(!w)break;f.push({type:"listItem",content:[{type:"paragraph",content:s(w[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 Gu(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:
427
+ `)||" "}]});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 w=e[r].match(/^\s*[-*]\s+(.*)$/);if(!w)break;f.push({type:"listItem",content:[{type:"paragraph",content:s(w[1])}]}),r++}n.push({type:"bulletList",content:f});continue}if(i.match(/^\s*\d+[.)]\s+(.*)$/)){let f=[];for(;r<e.length;){let w=e[r].match(/^\s*\d+[.)]\s+(.*)$/);if(!w)break;f.push({type:"listItem",content:[{type:"paragraph",content:s(w[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 td(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:
417
428
 
418
429
  allwright jira user-add ${s}
419
430
 
420
- 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.`}}function Zu(t){let e=[t.jiraUrl,t.jiraEmail,t.jiraToken].filter(n=>!!n?.trim());if(t.jira===!1){if(e.length)throw new Error("--no-jira and --jira-url/--jira-email/--jira-token contradict each other - pass one or the other, never both.");return"skip"}return e.length===3?"flags":e.length?"prompt":"offer-skip"}function Wu(t){return["s","skip","n","no","later"].includes(t.trim().toLowerCase())}gr();var Sn=require("node:child_process"),Tn=I(require("node:fs"),1),Ji=I(require("node:os"),1),ds=I(require("node:path"),1),Yu=I(ke(),1);var us="allwright",Ju=`/etc/systemd/system/${us}.service`,Yi="ticketpilot-runner";function Ga(){let t=process.env.SUDO_USER&&process.env.SUDO_USER!=="root"?process.env.SUDO_USER:"",e=t||Ji.default.userInfo().username,n=t?ds.default.join("/home",t):Ji.default.homedir();return{nodePath:process.execPath,scriptPath:Tn.default.realpathSync(process.argv[1]),user:e,home:n}}function Za(t){let e=ds.default.dirname(t.nodePath);return`[Unit]
431
+ 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.`}}function nd(t){let e=[t.jiraUrl,t.jiraEmail,t.jiraToken].filter(n=>!!n?.trim());if(t.jira===!1){if(e.length)throw new Error("--no-jira and --jira-url/--jira-email/--jira-token contradict each other - pass one or the other, never both.");return"skip"}return e.length===3?"flags":e.length?"prompt":"offer-skip"}function rd(t){return["s","skip","n","no","later"].includes(t.trim().toLowerCase())}yr();var Tn=require("node:child_process"),xn=I(require("node:fs"),1),Ji=I(require("node:os"),1),hs=I(require("node:path"),1),od=I(ke(),1);var ds="allwright",id=`/etc/systemd/system/${ds}.service`,Yi="ticketpilot-runner";function Va(){let t=process.env.SUDO_USER&&process.env.SUDO_USER!=="root"?process.env.SUDO_USER:"",e=t||Ji.default.userInfo().username,n=t?hs.default.join("/home",t):Ji.default.homedir();return{nodePath:process.execPath,scriptPath:xn.default.realpathSync(process.argv[1]),user:e,home:n}}function Ja(t){let e=hs.default.dirname(t.nodePath);return`[Unit]
421
432
  Description=Allwright runner
422
433
  After=network-online.target
423
434
 
@@ -435,8 +446,8 @@ TimeoutStopSec=2h
435
446
 
436
447
  [Install]
437
448
  WantedBy=multi-user.target
438
- `}function Wa(){return process.platform==="linux"&&Tn.default.existsSync("/run/systemd/system")}function Xu(t){if(!Wa())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=Za(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 ${Ju}:`),t.info(`
439
- `+n);return}try{(0,Sn.execFileSync)("systemctl",["disable","--now",Yi]),t.info(`stopped the old ${Yi} service - this one replaces it`)}catch{}let r=es();if(r)try{process.kill(r,"SIGTERM"),t.info(`stopped the running runner (pid ${r}) - the service takes over`)}catch{}Tn.default.writeFileSync(Ju,n),(0,Sn.execFileSync)("systemctl",["daemon-reload"]),(0,Sn.execFileSync)("systemctl",["enable","--now",us]),(0,Sn.execFileSync)("systemctl",["restart",us]),t.info(`Installed and started (runs as ${e.user}, survives reboots).`),t.info(`Watch it: journalctl -u ${us} -f`),t.info("Status: allwright service status")}function ib(t){if(t.override)return[ds.default.join(t.override,"runner.json")];let e=[];for(let n of t.homes)for(let r of["allwright","ticketpilot"]){let s=ds.default.join(n,".config",r,"runner.json");e.includes(s)||e.push(s)}return e}function ob(){let t=process.env.SUDO_USER&&process.env.SUDO_USER!=="root"?process.env.SUDO_USER:"",e=[Ji.default.homedir()];return t&&e.push(ds.default.join("/home",t)),ib({override:process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR,homes:e})}function ab(){let t={removed:!1,paths:[],problems:[]};for(let e of ob())if(Tn.default.existsSync(e))try{Tn.default.rmSync(e),t.removed=!0,t.paths.push(e)}catch(n){t.problems.push(`could not delete ${e}: ${n instanceof Error?n.message:String(n)}`)}return t}function Va(){return typeof process.getuid!="function"||process.getuid()===0}function Ha(t){if(Va()){(0,Sn.execFileSync)("systemctl",t,{stdio:"ignore"});return}(0,Sn.execFileSync)("sudo",["-n","systemctl",...t],{stdio:"ignore"})}function lb(t){if(Va()){Tn.default.rmSync(t);return}(0,Sn.execFileSync)("sudo",["-n","rm","-f",t],{stdio:"ignore"})}function cb(){if(!Wa())return{removed:!1,absent:!0,error:""};let t=[us,Yi].map(e=>({name:e,file:`/etc/systemd/system/${e}.service`})).filter(e=>Tn.default.existsSync(e.file));if(t.length===0)return{removed:!1,absent:!0,error:""};try{for(let e of t){try{Ha(["disable",e.name])}catch{}lb(e.file)}return Ha(["daemon-reload"]),{removed:!0,absent:!1,error:""}}catch(e){let n=e instanceof Error?e.message:String(e);return{removed:!1,absent:!1,error:Va()?`could not remove the systemd unit: ${n}`:"removing the systemd unit needs root, and this runner does not have passwordless sudo"}}}function Ja(){if(Wa())for(let t of[us,Yi])try{Ha(["stop",t])}catch{}}function Ya(){let t=cb(),e={serviceRemoved:t.removed,serviceAbsent:t.absent,configRemoved:!1,removedPaths:[],problems:[]};if(t.error)return e.problems.push(`${t.error} - finish with: ${Yu.RUNNER_UNINSTALL_COMMAND}`),e;let n=ab();return e.configRemoved=n.removed,e.removedPaths=n.paths,e.problems=n.problems,e}function Qu(t){let e=Ya();e.serviceRemoved?(Ja(),t.info("Service stopped and removed.")):e.serviceAbsent&&t.info("No systemd service was installed here - nothing to stop.");for(let n of e.removedPaths)t.info(`Deleted ${n} - the Jira and GitHub tokens on this machine went with it.`);if(!e.configRemoved&&e.problems.length===0&&t.info("No runner config was found - there were no credentials left to delete."),t.info("Checkouts on disk were NOT touched - remove them yourself if you want them gone."),e.problems.length>0)throw new Error(e.problems.join("; "))}var ed=I(ke(),1);function td(t){return t.filter(e=>e.statusCategory!=="done"&&!e.labels.includes("agent-implemented")&&!e.labels.includes(ed.NEEDS_INPUT_LABEL))}function nd(t,e,n){let r=n.map(s=>{let i=(s.description??"").trim().slice(0,600);return`- ${s.key} [${s.status}] ${s.summary}${i?`
449
+ `}function Ya(){return process.platform==="linux"&&xn.default.existsSync("/run/systemd/system")}function ad(t){if(!Ya())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=Va(),n=Ja(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 ${id}:`),t.info(`
450
+ `+n);return}try{(0,Tn.execFileSync)("systemctl",["disable","--now",Yi]),t.info(`stopped the old ${Yi} service - this one replaces it`)}catch{}let r=ts();if(r)try{process.kill(r,"SIGTERM"),t.info(`stopped the running runner (pid ${r}) - the service takes over`)}catch{}xn.default.writeFileSync(id,n),(0,Tn.execFileSync)("systemctl",["daemon-reload"]),(0,Tn.execFileSync)("systemctl",["enable","--now",ds]),(0,Tn.execFileSync)("systemctl",["restart",ds]),t.info(`Installed and started (runs as ${e.user}, survives reboots).`),t.info(`Watch it: journalctl -u ${ds} -f`),t.info("Status: allwright service status")}function yb(t){if(t.override)return[hs.default.join(t.override,"runner.json")];let e=[];for(let n of t.homes)for(let r of["allwright","ticketpilot"]){let s=hs.default.join(n,".config",r,"runner.json");e.includes(s)||e.push(s)}return e}function bb(){let t=process.env.SUDO_USER&&process.env.SUDO_USER!=="root"?process.env.SUDO_USER:"",e=[Ji.default.homedir()];return t&&e.push(hs.default.join("/home",t)),yb({override:process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR,homes:e})}function wb(){let t={removed:!1,paths:[],problems:[]};for(let e of bb())if(xn.default.existsSync(e))try{xn.default.rmSync(e),t.removed=!0,t.paths.push(e)}catch(n){t.problems.push(`could not delete ${e}: ${n instanceof Error?n.message:String(n)}`)}return t}function Xa(){return typeof process.getuid!="function"||process.getuid()===0}function Wa(t){if(Xa()){(0,Tn.execFileSync)("systemctl",t,{stdio:"ignore"});return}(0,Tn.execFileSync)("sudo",["-n","systemctl",...t],{stdio:"ignore"})}function vb(t){if(Xa()){xn.default.rmSync(t);return}(0,Tn.execFileSync)("sudo",["-n","rm","-f",t],{stdio:"ignore"})}function kb(){if(!Ya())return{removed:!1,absent:!0,error:""};let t=[ds,Yi].map(e=>({name:e,file:`/etc/systemd/system/${e}.service`})).filter(e=>xn.default.existsSync(e.file));if(t.length===0)return{removed:!1,absent:!0,error:""};try{for(let e of t){try{Wa(["disable",e.name])}catch{}vb(e.file)}return Wa(["daemon-reload"]),{removed:!0,absent:!1,error:""}}catch(e){let n=e instanceof Error?e.message:String(e);return{removed:!1,absent:!1,error:Xa()?`could not remove the systemd unit: ${n}`:"removing the systemd unit needs root, and this runner does not have passwordless sudo"}}}function Qa(){if(Ya())for(let t of[ds,Yi])try{Wa(["stop",t])}catch{}}function el(){let t=kb(),e={serviceRemoved:t.removed,serviceAbsent:t.absent,configRemoved:!1,removedPaths:[],problems:[]};if(t.error)return e.problems.push(`${t.error} - finish with: ${od.RUNNER_UNINSTALL_COMMAND}`),e;let n=wb();return e.configRemoved=n.removed,e.removedPaths=n.paths,e.problems=n.problems,e}function ld(t){let e=el();e.serviceRemoved?(Qa(),t.info("Service stopped and removed.")):e.serviceAbsent&&t.info("No systemd service was installed here - nothing to stop.");for(let n of e.removedPaths)t.info(`Deleted ${n} - the Jira and GitHub tokens on this machine went with it.`);if(!e.configRemoved&&e.problems.length===0&&t.info("No runner config was found - there were no credentials left to delete."),t.info("Checkouts on disk were NOT touched - remove them yourself if you want them gone."),e.problems.length>0)throw new Error(e.problems.join("; "))}var cd=I(ke(),1);function ud(t){return t.filter(e=>e.statusCategory!=="done"&&!e.labels.includes("agent-implemented")&&!e.labels.includes(cd.NEEDS_INPUT_LABEL))}function dd(t,e,n){let r=n.map(s=>{let i=(s.description??"").trim().slice(0,600);return`- ${s.key} [${s.status}] ${s.summary}${i?`
440
451
  ${i.replace(/\n+/g," ")}`:""}`}).join(`
441
452
  `);return`You are looking at this repository to help sequence work on the Jira epic ${t} ("${e}"). These child tickets are still pending:
442
453
 
@@ -447,7 +458,7 @@ Pick the ONE ticket that should be implemented FIRST. Weigh, in this order: (1)
447
458
  Answer with ONLY a fenced json block, nothing after it:
448
459
  \`\`\`json
449
460
  {"issueKey": "<one of the keys above>", "reason": "<2-3 sentences: why this one first, and what it unblocks>"}
450
- \`\`\``}function rd(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 ll=require("node:crypto"),Pd=I(require("node:fs"),1);var Xa=I(require("node:fs"),1),Xi=I(require("node:path"),1),Qi=I(ke(),1),ub={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.",functional:"You are a functional tester of the RUNNING site. The runner has already crawled it - the transcript is below, and it is your primary evidence; the repository is open READ-ONLY so you can trace a broken page to its code. Report what a real visitor hits: broken links (with the page that links there), errors, missing pages, mixed content, slow responses. The crawl ran without JavaScript - never claim client-side behaviour was checked. Every finding cites a URL from the crawl AND, where you traced it, the file behind it."};function id(t,e,n,r={}){let s=e.map(p=>`### Pack: ${p.name}
461
+ \`\`\``}function hd(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 dl=require("node:crypto"),qd=I(require("node:fs"),1);var tl=I(require("node:fs"),1),Xi=I(require("node:path"),1),Qi=I(ke(),1),_b={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.",functional:"You are a functional tester of the RUNNING site. The runner has already crawled it - the transcript is below, and it is your primary evidence; the repository is open READ-ONLY so you can trace a broken page to its code. Report what a real visitor hits: broken links (with the page that links there), errors, missing pages, mixed content, slow responses. The crawl ran without JavaScript - never claim client-side behaviour was checked. Every finding cites a URL from the crawl AND, where you traced it, the file behind it."};function fd(t,e,n,r={}){let s=e.map(p=>`### Pack: ${p.name}
451
462
 
452
463
  ${p.content}`).join(`
453
464
 
@@ -476,7 +487,7 @@ This transcript is your PRIMARY evidence. A URL with issues becomes a finding; t
476
487
  ### WRITING STYLE - plain language
477
488
 
478
489
  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.
479
- 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`${ub[t]}
490
+ 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`${_b[t]}
480
491
 
481
492
  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.
482
493
 
@@ -490,20 +501,20 @@ Explore the repository first - entry points, routes, storage, tests - then audit
490
501
  "evidence": [{"file": "<repo-relative path>", "line": <number, omit if n/a>, "note": "<what is there>"}],
491
502
  "fix": "<2-4 sentences: concrete fix, specific to this code>"}]}
492
503
  \`\`\`
493
- 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.`+u}function od(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=db(l),u=c?Qi.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 db(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:"",...sd(i.line)?{line:sd(i.line)}:{},note:typeof i.note=="string"?i.note:""})).filter(i=>i.file):[],s=typeof e.ruleId=="string"?e.ruleId.trim().toUpperCase():"";return{id:hb(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:Qi.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 sd(t){let e=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):NaN;return Number.isInteger(e)&&e>0?e:void 0}function hb(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"finding"}function pb(t){try{let e=Xa.default.readFileSync(t,"utf8");return e?e.split(`
494
- `).length:0}catch{return null}}function ad(t,e){let n=Xi.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=Xi.default.resolve(n,u);if(p!==n&&!p.startsWith(n+Xi.default.sep))continue;let f;try{f=Xa.default.statSync(p)}catch{continue}if(f.isFile()){if(c.line!==void 0){let w=pb(p);if(w!==null&&c.line>w){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 Ks=I(require("node:fs"),1),Qa=I(require("node:path"),1),ld=I(ke(),1);Ce();var fb=20;function cd(){return Qa.default.join(oe(),"audits.json")}function hs(){try{return{byProject:JSON.parse(Ks.default.readFileSync(cd(),"utf8")).byProject??{}}}catch{return{byProject:{}}}}function ud(t){let e=cd();Ks.default.mkdirSync(Qa.default.dirname(e),{recursive:!0,mode:448});let n=e+".tmp";Ks.default.writeFileSync(n,JSON.stringify(t,null,2),{mode:384}),Ks.default.renameSync(n,e)}function dd(t,e){let n=hs(),r=n.byProject[t]??[];r.unshift(ld.AuditRecord.parse(e)),n.byProject[t]=r.slice(0,fb),ud(n)}function hd(t){return(hs().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 pd(t,e){let n=hs(),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 el(t,e,n){let r=hs(),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 ud(r),i}function fd(t,e){return(hs().byProject[t]??[]).find(s=>s.role===e&&(s.scope?.kind??"repo")==="repo")?.createdAt??null}function tl(t,e){return(hs().byProject[t]??[]).find(n=>n.id===e)??null}xt();var Oe=I(require("node:fs"),1),It=I(require("node:path"),1),bd=I(ke(),1);var Zt=I(require("node:fs"),1),nl=I(require("node:path"),1),mb=25e4,gb=2e5,md=`# Incident ledger
504
+ 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.`+u}function md(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=Sb(l),u=c?Qi.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 Sb(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:"",...pd(i.line)?{line:pd(i.line)}:{},note:typeof i.note=="string"?i.note:""})).filter(i=>i.file):[],s=typeof e.ruleId=="string"?e.ruleId.trim().toUpperCase():"";return{id:Tb(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:Qi.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 pd(t){let e=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):NaN;return Number.isInteger(e)&&e>0?e:void 0}function Tb(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"finding"}function xb(t){try{let e=tl.default.readFileSync(t,"utf8");return e?e.split(`
505
+ `).length:0}catch{return null}}function gd(t,e){let n=Xi.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=Xi.default.resolve(n,u);if(p!==n&&!p.startsWith(n+Xi.default.sep))continue;let f;try{f=tl.default.statSync(p)}catch{continue}if(f.isFile()){if(c.line!==void 0){let w=xb(p);if(w!==null&&c.line>w){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 Hs=I(require("node:fs"),1),nl=I(require("node:path"),1),yd=I(ke(),1);Ce();var Rb=20;function bd(){return nl.default.join(oe(),"audits.json")}function ps(){try{return{byProject:JSON.parse(Hs.default.readFileSync(bd(),"utf8")).byProject??{}}}catch{return{byProject:{}}}}function wd(t){let e=bd();Hs.default.mkdirSync(nl.default.dirname(e),{recursive:!0,mode:448});let n=e+".tmp";Hs.default.writeFileSync(n,JSON.stringify(t,null,2),{mode:384}),Hs.default.renameSync(n,e)}function vd(t,e){let n=ps(),r=n.byProject[t]??[];r.unshift(yd.AuditRecord.parse(e)),n.byProject[t]=r.slice(0,Rb),wd(n)}function kd(t){return(ps().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 _d(t,e){let n=ps(),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 rl(t,e,n){let r=ps(),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 wd(r),i}function Sd(t,e){return(ps().byProject[t]??[]).find(s=>s.role===e&&(s.scope?.kind??"repo")==="repo")?.createdAt??null}function sl(t,e){return(ps().byProject[t]??[]).find(n=>n.id===e)??null}Rt();var Oe=I(require("node:fs"),1),Et=I(require("node:path"),1),Id=I(ke(),1);var Wt=I(require("node:fs"),1),il=I(require("node:path"),1),Ib=25e4,Eb=2e5,Td=`# Incident ledger
495
506
 
496
507
  Machine-written facts about this repository's runs: what failed, what
497
508
  resolved it. Appended by the Allwright runner; humans may edit freely.
498
509
  Newest entries are at the bottom.
499
510
 
500
- `;function rl(t){return nl.default.join(t,".ticketpilot","memory","incidents.md")}function ft(t,e){try{let n=rl(t);Zt.default.mkdirSync(nl.default.dirname(n),{recursive:!0});let r=Zt.default.existsSync(n)?"":md,s=new Date().toISOString().slice(0,10),i=e.detail?.trim();Zt.default.appendFileSync(n,r+`## ${s} \xB7 ${e.issueKey} \xB7 ${e.title} (run ${e.runId})
511
+ `;function ol(t){return il.default.join(t,".ticketpilot","memory","incidents.md")}function mt(t,e){try{let n=ol(t);Wt.default.mkdirSync(il.default.dirname(n),{recursive:!0});let r=Wt.default.existsSync(n)?"":Td,s=new Date().toISOString().slice(0,10),i=e.detail?.trim();Wt.default.appendFileSync(n,r+`## ${s} \xB7 ${e.issueKey} \xB7 ${e.title} (run ${e.runId})
501
512
  `+(i?`${i.slice(0,1500)}
502
513
  `:"")+`
503
- `),yb(n)}catch{}}function Hs(t,e){try{return Zt.default.readFileSync(rl(t),"utf8").includes(`\xB7 ${e} \xB7`)}catch{return!1}}function yb(t){if(Zt.default.statSync(t).size<=mb)return;let r=Zt.default.readFileSync(t,"utf8").slice(-gb),s=r.indexOf(`
504
- ## `),i=s===-1?r:r.slice(s+1);Zt.default.writeFileSync(t,md+`*(older entries were rotated out)*
514
+ `),Ab(n)}catch{}}function Gs(t,e){try{return Wt.default.readFileSync(ol(t),"utf8").includes(`\xB7 ${e} \xB7`)}catch{return!1}}function Ab(t){if(Wt.default.statSync(t).size<=Ib)return;let r=Wt.default.readFileSync(t,"utf8").slice(-Eb),s=r.indexOf(`
515
+ ## `),i=s===-1?r:r.slice(s+1);Wt.default.writeFileSync(t,Td+`*(older entries were rotated out)*
505
516
 
506
- `+i)}function gd(t){try{return Zt.default.readFileSync(rl(t),"utf8")}catch{return null}}Ce();var bb=`# Security baseline - what to check in any repo
517
+ `+i)}function xd(t){try{return Wt.default.readFileSync(ol(t),"utf8")}catch{return null}}Ce();var Cb=`# Security baseline - what to check in any repo
507
518
 
508
519
  Every rule has a stable id. Findings must cite the id they violate.
509
520
 
@@ -546,7 +557,7 @@ Every rule has a stable id. Findings must cite the id they violate.
546
557
  - **SEC-042** TLS/redirect handling that downgrades to http.
547
558
 
548
559
  Prioritize by real exploitability in THIS codebase, not by rule order.
549
- `,wb=`# Test gaps - what to check in any repo
560
+ `,$b=`# Test gaps - what to check in any repo
550
561
 
551
562
  Every rule has a stable id. Findings must cite the id they violate.
552
563
 
@@ -576,7 +587,7 @@ Every rule has a stable id. Findings must cite the id they violate.
576
587
  flaky suspects.
577
588
 
578
589
  Report the GAP and why it is risky here, not generic coverage philosophy.
579
- `,vb=`# GDPR readiness - data-protection audit for repos with EU exposure
590
+ `,Pb=`# GDPR readiness - data-protection audit for repos with EU exposure
580
591
 
581
592
  FIRST decide exposure: if this product clearly has no EU users, no personal
582
593
  data, or is a purely static/internal tool, say so in ONE summary sentence and
@@ -620,7 +631,7 @@ rules below. Cite the rule id AND map the area to the closest GDPR article
620
631
 
621
632
  Severity: many users' data exposed or a missing legal-basis mechanism is
622
633
  high/critical; hygiene and documentation gaps are medium/low.
623
- `,kb=`# Architecture health - is this repository structurally sound?
634
+ `,jb=`# Architecture health - is this repository structurally sound?
624
635
 
625
636
  Every rule has a stable id. Findings must cite the id they violate. Judge
626
637
  against what THIS codebase is trying to be (a static site does not need
@@ -659,7 +670,7 @@ deviations.
659
670
 
660
671
  Summarize with an overall verdict: is this repository HEALTHY for its
661
672
  purpose, and what are the 2-3 structural moves with the best payoff?
662
- `,yd={security:[{name:"baseline.md",content:bb},{name:"gdpr.md",content:vb}],testing:[{name:"test-gaps.md",content:wb}],architecture:[{name:"architecture-health.md",content:kb}],functional:[],implement:[]},_b=["You are auditing code you can READ but never run or change.","You are auditing test coverage by READING code and tests","\\`area\\`"];function sl(t){return It.default.join(oe(),"knowledge",t)}function wd(t,e){return It.default.join(t,".ticketpilot","knowledge",`${e}.md`)}function il(t,e){return It.default.join(t,".ticketpilot","lessons",`${e}.md`)}function vd(t,e){let n=[],r=sl(t),s=[];if(Oe.default.existsSync(r)){for(let c of Oe.default.readdirSync(r)){if(!c.endsWith(".md"))continue;let u=It.default.join(r,c),p=Oe.default.readFileSync(u,"utf8");if(_b.some(f=>p.includes(f))&&yd[t].map(w=>w.name).includes(c)&&!p.includes("SEC-0")&&!p.includes("TEST-0")&&!p.includes("GDPR-0")){Oe.default.rmSync(u);continue}s.push(c)}s.sort()}let i=new Set(s);for(let c of yd[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:Oe.default.readFileSync(It.default.join(r,c),"utf8").slice(0,3e4),editable:!0});let o=wd(e,t);Oe.default.existsSync(o)&&n.push({level:"project",source:"pack",name:`${t}.md`,content:Oe.default.readFileSync(o,"utf8").slice(0,3e4),editable:!0});let l=il(e,t);return Oe.default.existsSync(l)&&n.push({level:"project",source:"lessons",name:`${t}.md`,content:Oe.default.readFileSync(l,"utf8").slice(0,2e4),editable:!0}),n}function eo(t,e){let n=vd(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 ol(t,e,n,r="project"){let s=r==="org"?It.default.join(sl(e),"org-lessons.md"):il(t,e);Oe.default.mkdirSync(It.default.dirname(s),{recursive:!0});let i=Oe.default.existsSync(s)?"":`# ${e} lessons (${r} level)
673
+ `,Rd={security:[{name:"baseline.md",content:Cb},{name:"gdpr.md",content:Pb}],testing:[{name:"test-gaps.md",content:$b}],architecture:[{name:"architecture-health.md",content:jb}],functional:[],implement:[]},Nb=["You are auditing code you can READ but never run or change.","You are auditing test coverage by READING code and tests","\\`area\\`"];function al(t){return Et.default.join(oe(),"knowledge",t)}function Ed(t,e){return Et.default.join(t,".ticketpilot","knowledge",`${e}.md`)}function ll(t,e){return Et.default.join(t,".ticketpilot","lessons",`${e}.md`)}function Ad(t,e){let n=[],r=al(t),s=[];if(Oe.default.existsSync(r)){for(let c of Oe.default.readdirSync(r)){if(!c.endsWith(".md"))continue;let u=Et.default.join(r,c),p=Oe.default.readFileSync(u,"utf8");if(Nb.some(f=>p.includes(f))&&Rd[t].map(w=>w.name).includes(c)&&!p.includes("SEC-0")&&!p.includes("TEST-0")&&!p.includes("GDPR-0")){Oe.default.rmSync(u);continue}s.push(c)}s.sort()}let i=new Set(s);for(let c of Rd[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:Oe.default.readFileSync(Et.default.join(r,c),"utf8").slice(0,3e4),editable:!0});let o=Ed(e,t);Oe.default.existsSync(o)&&n.push({level:"project",source:"pack",name:`${t}.md`,content:Oe.default.readFileSync(o,"utf8").slice(0,3e4),editable:!0});let l=ll(e,t);return Oe.default.existsSync(l)&&n.push({level:"project",source:"lessons",name:`${t}.md`,content:Oe.default.readFileSync(l,"utf8").slice(0,2e4),editable:!0}),n}function eo(t,e){let n=Ad(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 cl(t,e,n,r="project"){let s=r==="org"?Et.default.join(al(e),"org-lessons.md"):ll(t,e);Oe.default.mkdirSync(Et.default.dirname(s),{recursive:!0});let i=Oe.default.existsSync(s)?"":`# ${e} lessons (${r} level)
663
674
 
664
675
  Human-confirmed corrections and rules. `+(e==="implement"?`Every implement run on this repo reads this BEFORE starting work.
665
676
 
@@ -667,14 +678,14 @@ Human-confirmed corrections and rules. `+(e==="implement"?`Every implement run o
667
678
 
668
679
  `);Oe.default.appendFileSync(s,i+n.trimEnd()+`
669
680
 
670
- `)}function kd(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}
681
+ `)}function Cd(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}
671
682
  Finding \`${t.id}\` [${t.severity}] was marked **${e}**`+(r?` by ${r}`:"")+`.${n?` Reason: ${n}`:""}
672
- `+(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 _d(t,e){return`## ${new Date().toISOString().slice(0,10)} \xB7 taught${e?` by ${e}`:""}
673
- ${t.trim()}`}function Sd(t){let e=[];for(let r of bd.KnowledgeRole.options)for(let s of vd(r,t))e.push({role:r,...s});let n=gd(t);return n&&e.push({role:"implement",level:"project",source:"memory",name:"incidents.md",content:n.slice(-3e4),editable:!1}),e}function Td(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"?It.default.join(sl(e),s):r==="lessons"?il(t,e):wd(t,e);Oe.default.mkdirSync(It.default.dirname(o),{recursive:!0}),Oe.default.writeFileSync(o,i,{mode:n==="org"?384:420})}Wt();var xd=require("node:child_process"),Rd=I(require("node:fs"),1),Id=I(require("node:path"),1);function ps(t){for(let e of["TEST.md","TESTING.md","docs/TEST.md"]){let n=Id.default.join(t,e);if(Rd.default.existsSync(n))return n}return null}var Sb=/(^|\n)\s*(if|for|while|case|until)\s|\{\s*$|\)\s*\{|<<[-~]?\s*['"]?\w+|\\\s*$/;function fs(t){let e=[];for(let n of t.matchAll(/```(?:bash|sh|shell)?\s*\n([\s\S]*?)```/g)){let r=n[1],s=r.split(`
674
- `).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#"));if(s.length){if(Sb.test(r)){e.push(r.trim());continue}e.push(...s)}}return e.slice(0,10)}async function yr(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,xd.spawn)("bash",["-lc",i],{cwd:t,env:{...process.env,CI:"1",FORCE_COLOR:"0"}}),p="",f=b=>{p+=b.toString(),p.length>2e5&&(p=p.slice(-1e5))};u.stdout.on("data",f),u.stderr.on("data",f);let w=setTimeout(()=>{u.kill("SIGKILL"),p+=`
675
- [killed: timed out]`},s);u.on("close",b=>{clearTimeout(w),c({command:i,exitCode:b??-1,durationMs:Date.now()-o,tail:p.slice(-4e3)})}),u.on("error",b=>{clearTimeout(w),c({command:i,exitCode:-1,durationMs:Date.now()-o,tail:String(b)})})});n.onProgress?.(`exit ${l.exitCode} in ${Math.round(l.durationMs/1e3)}s: ${i}`),r.push(l)}return r}async function ms(t){let{packs:e,lessons:n}=eo(t.role,t.repoPath);if(!e.length&&t.role!=="functional")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.role==="functional"){if(!t.baseUrl?.trim())return{ok:!1,error:"a functional audit needs a URL to visit - pick the environment (or type the URL) when starting it"};let{crawlSite:b,formatCrawlReport:k}=await Promise.resolve().then(()=>($d(),Cd));try{r=k(await b(t.baseUrl.trim()))}catch(x){return{ok:!1,error:`could not crawl ${t.baseUrl}: ${x instanceof Error?x.message:"unreachable"}`}}}let s="";if(t.scope.kind==="ticket"&&t.scope.ref){let b=t.scope.ref,k="";try{let A=await t.jira.getIssue(b);k=`Ticket ${b}: ${A.summary}
683
+ `+(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 $d(t,e){return`## ${new Date().toISOString().slice(0,10)} \xB7 taught${e?` by ${e}`:""}
684
+ ${t.trim()}`}function Pd(t){let e=[];for(let r of Id.KnowledgeRole.options)for(let s of Ad(r,t))e.push({role:r,...s});let n=xd(t);return n&&e.push({role:"implement",level:"project",source:"memory",name:"incidents.md",content:n.slice(-3e4),editable:!1}),e}function jd(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"?Et.default.join(al(e),s):r==="lessons"?ll(t,e):Ed(t,e);Oe.default.mkdirSync(Et.default.dirname(o),{recursive:!0}),Oe.default.writeFileSync(o,i,{mode:n==="org"?384:420})}Vt();var Nd=require("node:child_process"),Od=I(require("node:fs"),1),Md=I(require("node:path"),1);function fs(t){for(let e of["TEST.md","TESTING.md","docs/TEST.md"]){let n=Md.default.join(t,e);if(Od.default.existsSync(n))return n}return null}var Ob=/(^|\n)\s*(if|for|while|case|until)\s|\{\s*$|\)\s*\{|<<[-~]?\s*['"]?\w+|\\\s*$/;function ms(t){let e=[];for(let n of t.matchAll(/```(?:bash|sh|shell)?\s*\n([\s\S]*?)```/g)){let r=n[1],s=r.split(`
685
+ `).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#"));if(s.length){if(Ob.test(r)){e.push(r.trim());continue}e.push(...s)}}return e.slice(0,10)}async function br(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,Nd.spawn)("bash",["-lc",i],{cwd:t,env:{...process.env,CI:"1",FORCE_COLOR:"0"}}),p="",f=b=>{p+=b.toString(),p.length>2e5&&(p=p.slice(-1e5))};u.stdout.on("data",f),u.stderr.on("data",f);let w=setTimeout(()=>{u.kill("SIGKILL"),p+=`
686
+ [killed: timed out]`},s);u.on("close",b=>{clearTimeout(w),c({command:i,exitCode:b??-1,durationMs:Date.now()-o,tail:p.slice(-4e3)})}),u.on("error",b=>{clearTimeout(w),c({command:i,exitCode:-1,durationMs:Date.now()-o,tail:String(b)})})});n.onProgress?.(`exit ${l.exitCode} in ${Math.round(l.durationMs/1e3)}s: ${i}`),r.push(l)}return r}async function gs(t){let{packs:e,lessons:n}=eo(t.role,t.repoPath);if(!e.length&&t.role!=="functional")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.role==="functional"){if(!t.baseUrl?.trim())return{ok:!1,error:"a functional audit needs a URL to visit - pick the environment (or type the URL) when starting it"};let{crawlSite:b,formatCrawlReport:k}=await Promise.resolve().then(()=>(Ud(),Ld));try{r=k(await b(t.baseUrl.trim()))}catch(x){return{ok:!1,error:`could not crawl ${t.baseUrl}: ${x instanceof Error?x.message:"unreachable"}`}}}let s="";if(t.scope.kind==="ticket"&&t.scope.ref){let b=t.scope.ref,k="";try{let A=await t.jira.getIssue(b);k=`Ticket ${b}: ${A.summary}
676
687
 
677
- ${A.description}`.slice(0,4e3)}catch{k=`Ticket ${b} (could not fetch its text from Jira).`}let x=await Na(t.repoPath,b).catch(()=>null);if(x){let{base:A,stat:$,diff:z}=await Zi(t.repoPath,x).catch(()=>({base:"",stat:"",diff:""}));s=`${k}
688
+ ${A.description}`.slice(0,4e3)}catch{k=`Ticket ${b} (could not fetch its text from Jira).`}let x=await za(t.repoPath,b).catch(()=>null);if(x){let{base:A,stat:$,diff:z}=await Zi(t.repoPath,x).catch(()=>({base:"",stat:"",diff:""}));s=`${k}
678
689
 
679
690
  Its implementation branch \`${x}\` vs \`${A}\`:
680
691
  \`\`\`
@@ -688,26 +699,26 @@ No implementation branch found for ${b} - audit the parts of the codebase this t
688
699
  ${k}\`\`\`
689
700
  \`\`\`diff
690
701
  ${x}
691
- \`\`\``}let i,o;if(t.role==="testing"){let b=ps(t.repoPath),k=b?fs(Pd.default.readFileSync(b,"utf8")):[];k.length&&(g.info(`Audit (testing): executing ${k.length} TEST.md command(s)`),o=await yr(t.repoPath,k,{onProgress:x=>g.info(`[test-run] ${x}`)}),i=o.map(x=>`$ ${x.command}
702
+ \`\`\``}let i,o;if(t.role==="testing"){let b=fs(t.repoPath),k=b?ms(qd.default.readFileSync(b,"utf8")):[];k.length&&(y.info(`Audit (testing): executing ${k.length} TEST.md command(s)`),o=await br(t.repoPath,k,{onProgress:x=>y.info(`[test-run] ${x}`)}),i=o.map(x=>`$ ${x.command}
692
703
  (exit ${x.exitCode}, ${Math.round(x.durationMs/1e3)}s)
693
704
  ${x.tail.slice(-2e3)}`).join(`
694
705
 
695
706
  ---
696
707
 
697
- `))}let l=t.model||t.agent.adapter.deepModel,c=t.detailLevel??"technical",u=await t.agent.adapter.run({repoPath:t.repoPath,prompt:id(t.role,e,n,{scopeNote:s,testResults:i,crawlResults:r,detailLevel:c}),timeoutSeconds:480,bin:t.agent.bin,mode:"read_only",maxTurns:120,sessionId:(0,ll.randomUUID)(),model:l,onLog:(b,k)=>{b==="agent"&&g.info(`[audit:${t.role}] ${k.slice(0,160)}`)}}),p=od(u.resultText);if("error"in p)return{ok:!1,error:p.error};let f=ad(t.repoPath,p.findings);for(let b of f.droppedFindings)g.warn(`[audit:${t.role}] dropped "${b.title}" - cited files do not exist: `+b.files.join(", "));let w={id:(0,ll.randomUUID)(),role:t.role,createdAt:new Date().toISOString(),model:u.model||l,summary:p.summary,packNames:e.map(b=>b.name),findings:f.findings,costUsd:u.costUsd??0,ticketed:{},verdicts:{},lessonsWritten:[],scope:t.scope,detailLevel:c,...o?{testRun:o}:{}};return dd(t.projectId,w),g.info(`Audit (${t.role}${t.scope.kind!=="repo"?` \xB7 ${t.scope.kind}:${t.scope.ref}`:""}) done: ${f.findings.length} finding(s)`+(p.dropped?`, ${p.dropped} malformed`:"")+(f.droppedFindings.length?`, ${f.droppedFindings.length} dropped for citing files that do not exist`:"")+(f.correctedLines?`, ${f.correctedLines} bad line number(s) stripped`:"")),{ok:!0,audit:w}}var Rn=I(ke(),1);Ce();var wl=I(require("node:fs"),1),co=I(require("node:path"),1),uo=require("node:crypto"),_e=I(ke(),1);Ce();var br=I(ke(),1);var cl=I(require("node:fs"),1),jd=I(require("node:os"),1),no=I(require("node:path"),1),Nd=require("node:child_process"),Od=I(require("node:readline"),1),Md=I(ke(),1);function to(t){return`
708
+ `))}let l=t.model||t.agent.adapter.deepModel,c=t.detailLevel??"technical",u=await t.agent.adapter.run({repoPath:t.repoPath,prompt:fd(t.role,e,n,{scopeNote:s,testResults:i,crawlResults:r,detailLevel:c}),timeoutSeconds:480,bin:t.agent.bin,mode:"read_only",maxTurns:120,sessionId:(0,dl.randomUUID)(),model:l,onLog:(b,k)=>{b==="agent"&&y.info(`[audit:${t.role}] ${k.slice(0,160)}`)}}),p=md(u.resultText);if("error"in p)return{ok:!1,error:p.error};let f=gd(t.repoPath,p.findings);for(let b of f.droppedFindings)y.warn(`[audit:${t.role}] dropped "${b.title}" - cited files do not exist: `+b.files.join(", "));let w={id:(0,dl.randomUUID)(),role:t.role,createdAt:new Date().toISOString(),model:u.model||l,summary:p.summary,packNames:e.map(b=>b.name),findings:f.findings,costUsd:u.costUsd??0,ticketed:{},verdicts:{},lessonsWritten:[],scope:t.scope,detailLevel:c,...o?{testRun:o}:{}};return vd(t.projectId,w),y.info(`Audit (${t.role}${t.scope.kind!=="repo"?` \xB7 ${t.scope.kind}:${t.scope.ref}`:""}) done: ${f.findings.length} finding(s)`+(p.dropped?`, ${p.dropped} malformed`:"")+(f.droppedFindings.length?`, ${f.droppedFindings.length} dropped for citing files that do not exist`:"")+(f.correctedLines?`, ${f.correctedLines} bad line number(s) stripped`:"")),{ok:!0,audit:w}}var In=I(ke(),1);Ce();var _l=I(require("node:fs"),1),co=I(require("node:path"),1),uo=require("node:crypto"),_e=I(ke(),1);Ce();var wr=I(ke(),1);var hl=I(require("node:fs"),1),Fd=I(require("node:os"),1),no=I(require("node:path"),1),Bd=require("node:child_process"),Kd=I(require("node:readline"),1),Hd=I(ke(),1);function to(t){return`
698
709
 
699
710
  YOUR CAPABILITIES IN THIS RUN - state them accurately, never guess:
700
711
  - 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.
701
712
  `+(t==="edit_no_shell"?`- You CAN read files and CREATE or EDIT files inside this working directory.
702
713
  `:`- You can ONLY read: Read, Glob and Grep inside this working directory. You cannot create or change a single file.
703
- `)+'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 Rb=4e3,Ib={read_only:["Read(./**)","Glob(./**)","Grep(./**)"],edit_no_shell:["Read(./**)","Glob(./**)","Grep(./**)","Edit(./**)","Write(./**)"]};function Eb(t){if(process.env.ANTHROPIC_API_KEY)return"API key";let e=t??no.default.join(jd.default.homedir(),".claude");try{if(cl.default.existsSync(no.default.join(e,".credentials.json"))||cl.default.existsSync(no.default.join(e,"credentials.json")))return"subscription"}catch{}return"unknown"}async function Ab(t){let e=["-p","--output-format","stream-json","--verbose","--allowedTools",Ib[t.mode].join(","),"--max-turns",String(t.maxTurns??60),...t.model?["--model",t.model]:[],...t.resume?["--resume",t.sessionId]:["--session-id",t.sessionId]],n=Eb(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,Nd.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 z=Date.now();z-p<Rb||(p=z,t.onUsage({inputTokens:l,outputTokens:c,cacheReadTokens:u,turns:o}))},w=!1,b=()=>{w||(w=!0,clearTimeout(x),t.signal?.removeEventListener("abort",k),r(i))},k=()=>{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",k,{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+to(t.mode)),s.stdin.end(),Od.default.createInterface({input:s.stdout}).on("line",z=>{if(!z.trim())return;let v;try{v=JSON.parse(z)}catch{t.onLog("agent",z.slice(0,1e3));return}if(v.type==="system"&&v.subtype==="init")i.model=typeof v.model=="string"?v.model:void 0,t.onLog("info",`Claude Code session started (model: ${v.model??"default"})`);else if(v.type==="assistant"){o+=1;let L=v.message?.usage;L&&(l+=Number(L.input_tokens??0)+Number(L.cache_creation_input_tokens??0),c+=Number(L.output_tokens??0),u+=Number(L.cache_read_input_tokens??0),f());for(let O of v.message?.content??[])if(O.type==="text"&&O.text?.trim())t.onLog("agent",O.text.trim().slice(0,4e3));else if(O.type==="tool_use"){let Y=O.input??{},M=["file_path","path","pattern","command","description","url"].map(m=>typeof Y[m]=="string"?`${m}=${Y[m]}`:null).filter(Boolean).join(" "),d=JSON.stringify(Y).slice(0,400);t.onLog("info",`tool ${O.name} ${M?`${M} `:""}${d}`)}}else v.type==="result"&&(i.costUsd=Number(v.total_cost_usd??0),i.inputTokens=Number(v.usage?.input_tokens??0)+Number(v.usage?.cache_creation_input_tokens??0),i.outputTokens=Number(v.usage?.output_tokens??0),l=Math.max(i.inputTokens,l),c=Math.max(i.outputTokens,c),i.inputTokens=l,i.outputTokens=c,u=Number(v.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()),v.subtype==="success"&&!v.is_error?(i.ok=!0,i.resultText=String(v.result??"")):v.subtype==="error_max_turns"?(i.turnLimitHit=!0,i.error=`hit the ${t.maxTurns??60}-turn limit before finishing`):(i.error=String(v.result??v.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 $="";s.stderr.on("data",z=>{$=($+z.toString()).slice(-2e3)}),s.on("error",z=>{i.error=`failed to start ${t.bin}: ${z.message}`,t.onLog("error",i.error),b()}),s.on("close",z=>{!i.ok&&!i.error&&(i.error=i.timedOut?i.error:`claude exited with code ${z}${$?`: ${$.slice(-500)}`:""}`),b()})})}var ro={id:"claude-code",displayName:"Claude Code",fastModel:"claude-sonnet-5",deepModel:"claude-fable-5",capabilities:Md.REGISTERED_AGENTS.find(t=>t.id==="claude-code").capabilities,run:Ab};var zd=require("node:child_process"),Dd=I(require("node:readline"),1),Ld=I(ke(),1);async function Cb(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,zd.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+to(t.mode)),r.stdin.end(),Dd.default.createInterface({input:r.stdout}).on("line",f=>{if(!f.trim())return;let w;try{w=JSON.parse(f)}catch{t.onLog("agent",f.slice(0,1e3));return}let b=w.item??w.msg??w,k=b?.type??w.type,x=b?.text??b?.message??"";k==="agent_message"&&typeof x=="string"&&x.trim()?(i=x,t.onLog("agent",x.trim().slice(0,4e3))):k==="command_execution"||k==="exec_command_begin"?t.onLog("info",`tool ${String(b?.command??"").slice(0,300)}`):k==="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 ul={id:"codex",fastModel:"",deepModel:"",displayName:"OpenAI Codex CLI (experimental)",capabilities:Ld.REGISTERED_AGENTS.find(t=>t.id==="codex").capabilities,run:Cb};var $b={[ro.id]:ro,[ul.id]:ul};function Ge(t){return $b[t||br.DEFAULT_AGENT_ID]??null}function Be(t,e){return!e||e===ro.id?t.claudeBin:t.agents[e]?.bin??e}function xn(t,e){let n=Ge(t);if(!n)return`no agent adapter named "${t}" on this runner - update the runner, or set the rule's agent to "${br.DEFAULT_AGENT_ID}"`;let r=(0,br.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 Me(t,e,n){let r=e.defaultAgent||br.DEFAULT_AGENT_ID,s=Ge(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,br.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:Be(t,s.id)}}function Vt(t,e){return t.replace(/\{\{(\w+)\}\}/g,(n,r)=>r in e?e[r]:n)}var Jd=I(ke(),1);mt();gr();xt();var ze=I(require("node:fs"),1),gs=I(require("node:path"),1);Jr();Ce();var jb=_.object({runId:_.string(),issueKey:_.string(),repoName:_.string(),owner:_.string(),repo:_.string(),prNumber:_.number().int(),prUrl:_.string(),branch:_.string(),headSha:_.string(),doneLabel:_.string(),failedLabel:_.string(),jiraTransition:_.string().optional(),mergeOnApprove:_.boolean().default(!1),mergeMethod:_.enum(["squash","merge","rebase"]).default("squash"),autoMerge:_.boolean().default(!1),nextDecisionSeq:_.number().int().default(1e5),changesRequestedNotified:_.boolean().optional(),conflictNotified:_.boolean().optional(),agentConfigDir:_.string().optional()}),Nb=_.record(jb),Ob=_.object({runId:_.string(),issueKey:_.string(),issueSummary:_.string().default(""),projectId:_.string(),repoName:_.string(),environmentName:_.string(),requestedBy:_.string().default(""),createdAt:_.string()}),Mb=_.record(Ob),zb=_.object({runId:_.string(),issueKey:_.string(),kind:_.enum(["plan","implement"]),repoPath:_.string(),sessionId:_.string(),doneLabel:_.string(),failedLabel:_.string(),timeoutSeconds:_.number(),createdAt:_.string(),questionsPostedAt:_.string(),rounds:_.number().int().default(1),nextLogSeq:_.number().int().nonnegative().default(0),baseRepoPath:_.string().optional(),repoName:_.string().optional(),branch:_.string().optional(),baseBranch:_.string().optional(),jiraTransition:_.string().optional(),jiraTransitionOnMerge:_.string().optional(),requireApproval:_.boolean().optional(),maxTurns:_.number().int().optional(),runTests:_.boolean().default(!0),mergeOnApprove:_.boolean().default(!1),mergeMethod:_.enum(["squash","merge","rebase"]).default("squash"),autoMerge:_.boolean().default(!1),issueSummary:_.string().default(""),claudeConfigDir:_.string().optional(),agent:_.string().optional(),model:_.string().optional(),actorEmail:_.string().optional()}),Db=_.object({runId:_.string(),issueKey:_.string(),issueSummary:_.string().default(""),repoName:_.string(),baseRepoPath:_.string(),branch:_.string(),baseBranch:_.string(),headSha:_.string(),requireApproval:_.boolean(),mergeOnApprove:_.boolean().default(!1),mergeMethod:_.enum(["squash","merge","rebase"]).default("squash"),autoMerge:_.boolean().default(!1),doneLabel:_.string(),failedLabel:_.string(),jiraTransition:_.string().optional(),jiraTransitionOnMerge:_.string().optional(),actorEmail:_.string().optional(),resultSummary:_.string().default(""),prSummary:_.string().default(""),costUsd:_.number().default(0),nextLogSeq:_.number().int().default(1e5),createdAt:_.string()}),Lb=_.record(Db),Ub=_.object({runId:_.string(),issueKey:_.string(),repoName:_.string(),owner:_.string(),repo:_.string(),prNumber:_.number().int(),prUrl:_.string(),jiraTransitionOnMerge:_.string().default(""),createdAt:_.string()}),qb=_.record(Ub),Fb=_.record(zb);function Ud(){return gs.default.join(oe(),"pending-runs.json")}function dl(){return gs.default.join(oe(),"pending-deploys.json")}function hl(){return gs.default.join(oe(),"pending-inputs.json")}function pl(){return gs.default.join(oe(),"merge-watch.json")}function fl(){return gs.default.join(oe(),"pending-pushes.json")}function ml(){let t=fl();if(!ze.default.existsSync(t))return{};try{return Lb.parse(JSON.parse(ze.default.readFileSync(t,"utf8")))}catch{return{}}}function so(t){let e=ml();e[t.runId]=t,Jt(fl(),e)}function io(t){return ml()[t]??null}function gl(t){let e=ml();t in e&&(delete e[t],Jt(fl(),e))}function oo(){let t=pl();if(!ze.default.existsSync(t))return{};try{return qb.parse(JSON.parse(ze.default.readFileSync(t,"utf8")))}catch{return{}}}function qd(t){let e=oo();e[t.runId]=t,Jt(pl(),e)}function Gs(t){let e=oo();t in e&&(delete e[t],Jt(pl(),e))}function Zs(){let t=Ud();if(!ze.default.existsSync(t))return{};try{return Nb.parse(JSON.parse(ze.default.readFileSync(t,"utf8")))}catch{return{}}}function Jt(t,e){ze.default.mkdirSync(oe(),{recursive:!0,mode:448});let n=t+".tmp";ze.default.writeFileSync(n,JSON.stringify(e,null,2)+`
704
- `,{mode:384}),ze.default.renameSync(n,t),ze.default.chmodSync(t,384)}function Fd(t){Jt(Ud(),t)}function gt(t){let e=Zs();e[t.runId]=t,Fd(e)}function ys(t){return Zs()[t]??null}function vr(t){let e=Zs();t in e&&(delete e[t],Fd(e))}function yl(){let t=dl();if(!ze.default.existsSync(t))return{};try{return Mb.parse(JSON.parse(ze.default.readFileSync(t,"utf8")))}catch{return{}}}function Bd(t){let e=yl();e[t.runId]=t,Jt(dl(),e)}function ao(t){return yl()[t]??null}function lo(t){let e=yl();t in e&&(delete e[t],Jt(dl(),e))}function kr(){let t=hl();if(!ze.default.existsSync(t))return{};try{return Fb.parse(JSON.parse(ze.default.readFileSync(t,"utf8")))}catch{return{}}}function Kd(t){let e=kr();e[t.runId]=t,Jt(hl(),e)}function Hd(t){return kr()[t]??null}function Et(t){let e=kr();t in e&&(delete e[t],Jt(hl(),e))}Wt();var Bb=`
714
+ `)+'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 Db=4e3,Lb={read_only:["Read(./**)","Glob(./**)","Grep(./**)"],edit_no_shell:["Read(./**)","Glob(./**)","Grep(./**)","Edit(./**)","Write(./**)"]};function Ub(t){if(process.env.ANTHROPIC_API_KEY)return"API key";let e=t??no.default.join(Fd.default.homedir(),".claude");try{if(hl.default.existsSync(no.default.join(e,".credentials.json"))||hl.default.existsSync(no.default.join(e,"credentials.json")))return"subscription"}catch{}return"unknown"}async function qb(t){let e=["-p","--output-format","stream-json","--verbose","--allowedTools",Lb[t.mode].join(","),"--max-turns",String(t.maxTurns??60),...t.model?["--model",t.model]:[],...t.resume?["--resume",t.sessionId]:["--session-id",t.sessionId]],n=Ub(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,Bd.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 z=Date.now();z-p<Db||(p=z,t.onUsage({inputTokens:l,outputTokens:c,cacheReadTokens:u,turns:o}))},w=!1,b=()=>{w||(w=!0,clearTimeout(x),t.signal?.removeEventListener("abort",k),r(i))},k=()=>{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",k,{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+to(t.mode)),s.stdin.end(),Kd.default.createInterface({input:s.stdout}).on("line",z=>{if(!z.trim())return;let v;try{v=JSON.parse(z)}catch{t.onLog("agent",z.slice(0,1e3));return}if(v.type==="system"&&v.subtype==="init")i.model=typeof v.model=="string"?v.model:void 0,t.onLog("info",`Claude Code session started (model: ${v.model??"default"})`);else if(v.type==="assistant"){o+=1;let L=v.message?.usage;L&&(l+=Number(L.input_tokens??0)+Number(L.cache_creation_input_tokens??0),c+=Number(L.output_tokens??0),u+=Number(L.cache_read_input_tokens??0),f());for(let O of v.message?.content??[])if(O.type==="text"&&O.text?.trim())t.onLog("agent",O.text.trim().slice(0,4e3));else if(O.type==="tool_use"){let Y=O.input??{},M=["file_path","path","pattern","command","description","url"].map(m=>typeof Y[m]=="string"?`${m}=${Y[m]}`:null).filter(Boolean).join(" "),d=JSON.stringify(Y).slice(0,400);t.onLog("info",`tool ${O.name} ${M?`${M} `:""}${d}`)}}else v.type==="result"&&(i.costUsd=Number(v.total_cost_usd??0),i.inputTokens=Number(v.usage?.input_tokens??0)+Number(v.usage?.cache_creation_input_tokens??0),i.outputTokens=Number(v.usage?.output_tokens??0),l=Math.max(i.inputTokens,l),c=Math.max(i.outputTokens,c),i.inputTokens=l,i.outputTokens=c,u=Number(v.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()),v.subtype==="success"&&!v.is_error?(i.ok=!0,i.resultText=String(v.result??"")):v.subtype==="error_max_turns"?(i.turnLimitHit=!0,i.error=`hit the ${t.maxTurns??60}-turn limit before finishing`):(i.error=v.subtype==="error_during_execution"?"the agent hit its turn or time limit before finishing - this question needs more room than a chat turn has. Ask something narrower, or make it a ticket so a full run (with the ability to execute) can take it.":String(v.result??v.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 $="";s.stderr.on("data",z=>{$=($+z.toString()).slice(-2e3)}),s.on("error",z=>{i.error=`failed to start ${t.bin}: ${z.message}`,t.onLog("error",i.error),b()}),s.on("close",z=>{!i.ok&&!i.error&&(i.error=i.timedOut?i.error:`claude exited with code ${z}${$?`: ${$.slice(-500)}`:""}`),b()})})}var ro={id:"claude-code",displayName:"Claude Code",fastModel:"claude-sonnet-5",deepModel:"claude-fable-5",capabilities:Hd.REGISTERED_AGENTS.find(t=>t.id==="claude-code").capabilities,run:qb};var Gd=require("node:child_process"),Zd=I(require("node:readline"),1),Wd=I(ke(),1);async function Fb(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,Gd.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+to(t.mode)),r.stdin.end(),Zd.default.createInterface({input:r.stdout}).on("line",f=>{if(!f.trim())return;let w;try{w=JSON.parse(f)}catch{t.onLog("agent",f.slice(0,1e3));return}let b=w.item??w.msg??w,k=b?.type??w.type,x=b?.text??b?.message??"";k==="agent_message"&&typeof x=="string"&&x.trim()?(i=x,t.onLog("agent",x.trim().slice(0,4e3))):k==="command_execution"||k==="exec_command_begin"?t.onLog("info",`tool ${String(b?.command??"").slice(0,300)}`):k==="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 pl={id:"codex",fastModel:"",deepModel:"",displayName:"OpenAI Codex CLI (experimental)",capabilities:Wd.REGISTERED_AGENTS.find(t=>t.id==="codex").capabilities,run:Fb};var Bb={[ro.id]:ro,[pl.id]:pl};function Ge(t){return Bb[t||wr.DEFAULT_AGENT_ID]??null}function Be(t,e){return!e||e===ro.id?t.claudeBin:t.agents[e]?.bin??e}function Rn(t,e){let n=Ge(t);if(!n)return`no agent adapter named "${t}" on this runner - update the runner, or set the rule's agent to "${wr.DEFAULT_AGENT_ID}"`;let r=(0,wr.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 Me(t,e,n){let r=e.defaultAgent||wr.DEFAULT_AGENT_ID,s=Ge(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,wr.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:Be(t,s.id)}}function Jt(t,e){return t.replace(/\{\{(\w+)\}\}/g,(n,r)=>r in e?e[r]:n)}var ih=I(ke(),1);gt();yr();Rt();var ze=I(require("node:fs"),1),ys=I(require("node:path"),1);Yr();Ce();var Hb=_.object({runId:_.string(),issueKey:_.string(),repoName:_.string(),owner:_.string(),repo:_.string(),prNumber:_.number().int(),prUrl:_.string(),branch:_.string(),headSha:_.string(),doneLabel:_.string(),failedLabel:_.string(),jiraTransition:_.string().optional(),mergeOnApprove:_.boolean().default(!1),mergeMethod:_.enum(["squash","merge","rebase"]).default("squash"),autoMerge:_.boolean().default(!1),nextDecisionSeq:_.number().int().default(1e5),changesRequestedNotified:_.boolean().optional(),conflictNotified:_.boolean().optional(),agentConfigDir:_.string().optional()}),Gb=_.record(Hb),Zb=_.object({runId:_.string(),issueKey:_.string(),issueSummary:_.string().default(""),projectId:_.string(),repoName:_.string(),environmentName:_.string(),requestedBy:_.string().default(""),createdAt:_.string()}),Wb=_.record(Zb),Vb=_.object({runId:_.string(),issueKey:_.string(),kind:_.enum(["plan","implement"]),repoPath:_.string(),sessionId:_.string(),doneLabel:_.string(),failedLabel:_.string(),timeoutSeconds:_.number(),createdAt:_.string(),questionsPostedAt:_.string(),rounds:_.number().int().default(1),nextLogSeq:_.number().int().nonnegative().default(0),baseRepoPath:_.string().optional(),repoName:_.string().optional(),branch:_.string().optional(),baseBranch:_.string().optional(),jiraTransition:_.string().optional(),jiraTransitionOnMerge:_.string().optional(),requireApproval:_.boolean().optional(),maxTurns:_.number().int().optional(),runTests:_.boolean().default(!0),mergeOnApprove:_.boolean().default(!1),mergeMethod:_.enum(["squash","merge","rebase"]).default("squash"),autoMerge:_.boolean().default(!1),issueSummary:_.string().default(""),claudeConfigDir:_.string().optional(),agent:_.string().optional(),model:_.string().optional(),actorEmail:_.string().optional()}),Jb=_.object({runId:_.string(),issueKey:_.string(),issueSummary:_.string().default(""),repoName:_.string(),baseRepoPath:_.string(),branch:_.string(),baseBranch:_.string(),headSha:_.string(),requireApproval:_.boolean(),mergeOnApprove:_.boolean().default(!1),mergeMethod:_.enum(["squash","merge","rebase"]).default("squash"),autoMerge:_.boolean().default(!1),doneLabel:_.string(),failedLabel:_.string(),jiraTransition:_.string().optional(),jiraTransitionOnMerge:_.string().optional(),actorEmail:_.string().optional(),resultSummary:_.string().default(""),prSummary:_.string().default(""),costUsd:_.number().default(0),nextLogSeq:_.number().int().default(1e5),createdAt:_.string()}),Yb=_.record(Jb),Xb=_.object({runId:_.string(),issueKey:_.string(),repoName:_.string(),owner:_.string(),repo:_.string(),prNumber:_.number().int(),prUrl:_.string(),jiraTransitionOnMerge:_.string().default(""),createdAt:_.string()}),Qb=_.record(Xb),ew=_.record(Vb);function Vd(){return ys.default.join(oe(),"pending-runs.json")}function fl(){return ys.default.join(oe(),"pending-deploys.json")}function ml(){return ys.default.join(oe(),"pending-inputs.json")}function gl(){return ys.default.join(oe(),"merge-watch.json")}function yl(){return ys.default.join(oe(),"pending-pushes.json")}function bl(){let t=yl();if(!ze.default.existsSync(t))return{};try{return Yb.parse(JSON.parse(ze.default.readFileSync(t,"utf8")))}catch{return{}}}function so(t){let e=bl();e[t.runId]=t,Yt(yl(),e)}function io(t){return bl()[t]??null}function wl(t){let e=bl();t in e&&(delete e[t],Yt(yl(),e))}function oo(){let t=gl();if(!ze.default.existsSync(t))return{};try{return Qb.parse(JSON.parse(ze.default.readFileSync(t,"utf8")))}catch{return{}}}function Jd(t){let e=oo();e[t.runId]=t,Yt(gl(),e)}function Zs(t){let e=oo();t in e&&(delete e[t],Yt(gl(),e))}function Ws(){let t=Vd();if(!ze.default.existsSync(t))return{};try{return Gb.parse(JSON.parse(ze.default.readFileSync(t,"utf8")))}catch{return{}}}function Yt(t,e){ze.default.mkdirSync(oe(),{recursive:!0,mode:448});let n=t+".tmp";ze.default.writeFileSync(n,JSON.stringify(e,null,2)+`
715
+ `,{mode:384}),ze.default.renameSync(n,t),ze.default.chmodSync(t,384)}function Yd(t){Yt(Vd(),t)}function yt(t){let e=Ws();e[t.runId]=t,Yd(e)}function bs(t){return Ws()[t]??null}function kr(t){let e=Ws();t in e&&(delete e[t],Yd(e))}function vl(){let t=fl();if(!ze.default.existsSync(t))return{};try{return Wb.parse(JSON.parse(ze.default.readFileSync(t,"utf8")))}catch{return{}}}function Xd(t){let e=vl();e[t.runId]=t,Yt(fl(),e)}function ao(t){return vl()[t]??null}function lo(t){let e=vl();t in e&&(delete e[t],Yt(fl(),e))}function _r(){let t=ml();if(!ze.default.existsSync(t))return{};try{return ew.parse(JSON.parse(ze.default.readFileSync(t,"utf8")))}catch{return{}}}function Qd(t){let e=_r();e[t.runId]=t,Yt(ml(),e)}function eh(t){return _r()[t]??null}function At(t){let e=_r();t in e&&(delete e[t],Yt(ml(),e))}Vt();var tw=`
705
716
 
706
- 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.`,Kb=`
717
+ 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.`,nw=`
707
718
 
708
- 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.`,Hb=`
719
+ 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.`,rw=`
709
720
 
710
- 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 Gd(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 Gb(t){let e=t.map(n=>`$ ${n.command} (exit ${n.exitCode})
721
+ 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 th(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 sw(t){let e=t.map(n=>`$ ${n.command} (exit ${n.exitCode})
711
722
  ${n.tail.slice(-2e3)}`).join(`
712
723
 
713
724
  `);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:
@@ -719,7 +730,7 @@ Fix what these failures point at, with the smallest change that makes them pass.
719
730
  - 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.
720
731
  - Do not ask questions; if you cannot fix something safely, say what you found and stop.
721
732
  - The runner re-runs every documented command after you finish, so a fix that breaks a previously passing command will be caught.
722
- 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 Zb(t){try{let{packs:e,lessons:n}=eo("implement",t),r="",s=e.map(o=>`### ${o.name}
733
+ 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 iw(t){try{let{packs:e,lessons:n}=eo("implement",t),r="",s=e.map(o=>`### ${o.name}
723
734
  ${o.content}`).join(`
724
735
 
725
736
  `).trim();s&&(r+=`
@@ -729,40 +740,40 @@ This repository has working rules taught to Allwright - follow them:
729
740
  \u2026${i.slice(-6e3)}`:i;r+=`
730
741
 
731
742
  Lessons from earlier runs on this repository (human-confirmed - follow them BEFORE writing code, they exist because a run got this wrong once):
732
- `+o}return r}catch{return""}}function vl(t){return wl.default.existsSync(co.default.join(t,"DESIGN.md"))?`
743
+ `+o}return r}catch{return""}}function Sl(t){return _l.default.existsSync(co.default.join(t,"DESIGN.md"))?`
733
744
 
734
- 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 Yd=5,Zd=2,Wb=8,Wd=2,Vb="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 Vs(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?Wb:Zd;for(;!o.ok&&o.turnLimitHit&&!o.cancelled&&t.capabilities.sessionResume;){if(l>=u){c=`resume cap (${u}) reached`;break}if(r&&l>=Zd){let f=await r().catch(()=>""),w=f!==""&&f!==i;if(i=f,!w){c="the last resume produced no new work";break}if(Date.now()-s>e.timeoutSeconds*Wd*1e3){c=`wall-clock budget (${Wd}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:Vb,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 Ws=new Map;function Xd(t){let e=Ws.get(t);return e?(e.abort(),!0):!1}function Qd(t){let e=new AbortController;return Ws.set(t,e),e}function eh(t){Ws.delete(t)}async function ws(t,e,n,r,s){let i=new AbortController;Ws.set(t,i);try{return await Vs(e,{...n,signal:i.signal},r,s)}finally{Ws.delete(t)}}function _r(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"&&g.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 ho(t){return t.rule.action.type==="implement"?Xb(t):t.rule.action.type==="respond"?Yb(t):Jb(t)}async function Jb(t){let{emit:e,setStatus:n,sendUsage:r,nextSeq:s}=_r(t.runId,t.transport),{trigger:i}=t.rule,o=t.rule.action;if(o.type!=="plan_only")return;let l=xn(o.agent,o.type);if(l){e("error",l),await bs(t,l),n("failed",{error:l});return}let c=(0,uo.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=Vt(o.promptTemplate,{issueKey:u.key,summary:u.summary,description:u.description||"(no description)",comments:Ys(u.comments)})+await Xr(t.jira,u.attachments,t.repoPath,e)+vl(t.repoPath)+_e.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 ws(t.runId,Ge(o.agent),{repoPath:t.repoPath,prompt:p,timeoutSeconds:o.timeoutSeconds,bin:Be(t.cfg,o.agent),configDir:t.claudeConfigDir,mode:"read_only",model:o.model||void 0,sessionId:c,onLog:(k,x)=>e(k,x),onUsage:r},e),w={costUsd:f.costUsd,inputTokens:f.inputTokens,outputTokens:f.outputTokens,billingMode:f.billingMode,model:f.model};if(!f.ok||!f.resultText.trim()){let k=f.error??"Claude Code produced no output";e("error",`Run failed: ${k}`),await bs(t,k),n(f.timedOut?"timed_out":"failed",{error:k,...f.cancelled?{errorKind:"guard"}:{},...w});return}let b=Xs(f.resultText);if(b){await po({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},b,e,n,w);return}await th({runId:t.runId,issueKey:t.issueKey,doneLabel:i.doneLabel,jira:t.jira,resultText:f.resultText,costFields:w,emit:e,setStatus:n})}catch(u){let p=u instanceof Error?u.message:String(u);e("error",`Run failed: ${p}`),await bs(t,p),n("failed",{error:p})}finally{hn(t.repoPath)}}async function kl(t,e,n,r){let{emit:s,setStatus:i,sendUsage:o,nextSeq:l}=_r(t.runId,r.transport,t.nextLogSeq);try{i("running"),s("info",`Reply received on ${t.issueKey} - continuing run \`${t.runId}\``);let c=dh(e)+await Xr(r.jiraFor(t.repoName??""),n,t.repoPath,s),u=await ws(t.runId,Ge(t.agent),{repoPath:t.repoPath,prompt:c,timeoutSeconds:t.timeoutSeconds,bin:Be(r.cfg,t.agent??""),configDir:t.claudeConfigDir,mode:"read_only",model:t.model||void 0,sessionId:t.sessionId,resume:!0,onLog:(w,b)=>s(w,b),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 w=u.error??"Claude Code produced no output";s("error",`Run failed: ${w}`),await At(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,w),Et(t.runId),i(u.timedOut?"timed_out":"failed",{error:w,...u.cancelled?{errorKind:"guard"}:{},...p});return}let f=Xs(u.resultText);if(f){if(t.rounds>=Yd){await hh(r.jiraFor(t.repoName??""),t,s,i,p);return}await po({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 th({runId:t.runId,issueKey:t.issueKey,doneLabel:t.doneLabel,jira:r.jiraFor(t.repoName??""),resultText:u.resultText,costFields:p,emit:s,setStatus:i}),Et(t.runId)}catch(c){let u=c instanceof Error?c.message:String(c);s("error",`Run failed: ${u}`),await At(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,u),Et(t.runId),i("failed",{error:u})}finally{hn(t.repoPath)}}async function th(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=`
745
+ 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 oh=5,nh=2,ow=8,rh=2,aw="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 Js(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?ow:nh;for(;!o.ok&&o.turnLimitHit&&!o.cancelled&&t.capabilities.sessionResume;){if(l>=u){c=`resume cap (${u}) reached`;break}if(r&&l>=nh){let f=await r().catch(()=>""),w=f!==""&&f!==i;if(i=f,!w){c="the last resume produced no new work";break}if(Date.now()-s>e.timeoutSeconds*rh*1e3){c=`wall-clock budget (${rh}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:aw,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 Vs=new Map;function ah(t){let e=Vs.get(t);return e?(e.abort(),!0):!1}function lh(t){let e=new AbortController;return Vs.set(t,e),e}function ch(t){Vs.delete(t)}async function vs(t,e,n,r,s){let i=new AbortController;Vs.set(t,i);try{return await Js(e,{...n,signal:i.signal},r,s)}finally{Vs.delete(t)}}function Sr(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 ho(t){return t.rule.action.type==="implement"?uw(t):t.rule.action.type==="respond"?cw(t):lw(t)}async function lw(t){let{emit:e,setStatus:n,sendUsage:r,nextSeq:s}=Sr(t.runId,t.transport),{trigger:i}=t.rule,o=t.rule.action;if(o.type!=="plan_only")return;let l=Rn(o.agent,o.type);if(l){e("error",l),await ws(t,l),n("failed",{error:l});return}let c=(0,uo.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=Jt(o.promptTemplate,{issueKey:u.key,summary:u.summary,description:u.description||"(no description)",comments:Xs(u.comments)})+await Qr(t.jira,u.attachments,t.repoPath,e)+Sl(t.repoPath)+_e.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 vs(t.runId,Ge(o.agent),{repoPath:t.repoPath,prompt:p,timeoutSeconds:o.timeoutSeconds,bin:Be(t.cfg,o.agent),configDir:t.claudeConfigDir,mode:"read_only",model:o.model||void 0,sessionId:c,onLog:(k,x)=>e(k,x),onUsage:r},e),w={costUsd:f.costUsd,inputTokens:f.inputTokens,outputTokens:f.outputTokens,billingMode:f.billingMode,model:f.model};if(!f.ok||!f.resultText.trim()){let k=f.error??"Claude Code produced no output";e("error",`Run failed: ${k}`),await ws(t,k),n(f.timedOut?"timed_out":"failed",{error:k,...f.cancelled?{errorKind:"guard"}:{},...w});return}let b=Qs(f.resultText);if(b){await po({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},b,e,n,w);return}await uh({runId:t.runId,issueKey:t.issueKey,doneLabel:i.doneLabel,jira:t.jira,resultText:f.resultText,costFields:w,emit:e,setStatus:n})}catch(u){let p=u instanceof Error?u.message:String(u);e("error",`Run failed: ${p}`),await ws(t,p),n("failed",{error:p})}finally{pn(t.repoPath)}}async function Tl(t,e,n,r){let{emit:s,setStatus:i,sendUsage:o,nextSeq:l}=Sr(t.runId,r.transport,t.nextLogSeq);try{i("running"),s("info",`Reply received on ${t.issueKey} - continuing run \`${t.runId}\``);let c=vh(e)+await Qr(r.jiraFor(t.repoName??""),n,t.repoPath,s),u=await vs(t.runId,Ge(t.agent),{repoPath:t.repoPath,prompt:c,timeoutSeconds:t.timeoutSeconds,bin:Be(r.cfg,t.agent??""),configDir:t.claudeConfigDir,mode:"read_only",model:t.model||void 0,sessionId:t.sessionId,resume:!0,onLog:(w,b)=>s(w,b),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 w=u.error??"Claude Code produced no output";s("error",`Run failed: ${w}`),await Ct(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,w),At(t.runId),i(u.timedOut?"timed_out":"failed",{error:w,...u.cancelled?{errorKind:"guard"}:{},...p});return}let f=Qs(u.resultText);if(f){if(t.rounds>=oh){await kh(r.jiraFor(t.repoName??""),t,s,i,p);return}await po({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 uh({runId:t.runId,issueKey:t.issueKey,doneLabel:t.doneLabel,jira:r.jiraFor(t.repoName??""),resultText:u.resultText,costFields:p,emit:s,setStatus:i}),At(t.runId)}catch(c){let u=c instanceof Error?c.message:String(c);s("error",`Run failed: ${u}`),await Ct(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,u),At(t.runId),i("failed",{error:u})}finally{pn(t.repoPath)}}async function uh(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=`
735
746
 
736
747
  ---
737
- _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:[_e.NEEDS_INPUT_LABEL]}),l("info",`Labeled ${n} with "${r}"`),c("succeeded",{...o,resultSummary:Sr(i)}),l("info",`Run succeeded \xB7 $${o.costUsd.toFixed(4)}`)}async function Yb(t){let{emit:e,setStatus:n,sendUsage:r}=_r(t.runId,t.transport),s=t.rule.action;if(s.type!=="respond")return;let i=xn(s.agent,s.type);if(i){e("error",i),await t.jira.addComment(t.issueKey,`**Allwright could not answer this question.**
748
+ _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:[_e.NEEDS_INPUT_LABEL]}),l("info",`Labeled ${n} with "${r}"`),c("succeeded",{...o,resultSummary:Tr(i)}),l("info",`Run succeeded \xB7 $${o.costUsd.toFixed(4)}`)}async function cw(t){let{emit:e,setStatus:n,sendUsage:r}=Sr(t.runId,t.transport),s=t.rule.action;if(s.type!=="respond")return;let i=Rn(s.agent,s.type);if(i){e("error",i),await t.jira.addComment(t.issueKey,`**Allwright could not answer this question.**
738
749
 
739
- ${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=Vt(s.promptTemplate,{issueKey:o.key,summary:o.summary,description:o.description||"(no description)",comments:Ys(o.comments),question:t.question?.body??"(see the latest comment on the ticket)",questionAuthor:t.question?.author??"the commenter"})+await Xr(t.jira,o.attachments,t.repoPath,e)+vl(t.repoPath);e("info",`Starting Claude Code in ${t.repoPath} - read-only tools, path-jailed, timeout ${s.timeoutSeconds}s`);let c=await ws(t.runId,Ge(s.agent),{repoPath:t.repoPath,prompt:l,timeoutSeconds:s.timeoutSeconds,bin:Be(t.cfg,s.agent),configDir:t.claudeConfigDir,mode:"read_only",model:s.model||void 0,sessionId:(0,uo.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.**
750
+ ${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=Jt(s.promptTemplate,{issueKey:o.key,summary:o.summary,description:o.description||"(no description)",comments:Xs(o.comments),question:t.question?.body??"(see the latest comment on the ticket)",questionAuthor:t.question?.author??"the commenter"})+await Qr(t.jira,o.attachments,t.repoPath,e)+Sl(t.repoPath);e("info",`Starting Claude Code in ${t.repoPath} - read-only tools, path-jailed, timeout ${s.timeoutSeconds}s`);let c=await vs(t.runId,Ge(s.agent),{repoPath:t.repoPath,prompt:l,timeoutSeconds:s.timeoutSeconds,bin:Be(t.cfg,s.agent),configDir:t.claudeConfigDir,mode:"read_only",model:s.model||void 0,sessionId:(0,uo.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.**
740
751
 
741
752
  Error: ${p.slice(0,800)}
742
753
 
743
- Ask again in a new comment to retry. (run \`${t.runId}\`)`).catch(f=>g.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:Sr(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{hn(t.repoPath)}}async function nh(t,e,n,r){let s=`${e}-wip`;try{return hn(t),await pr(t,`WIP: turn limit exhausted (Allwright run ${n})`),await Aa(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 rh(t){return`
754
+ 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:Tr(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{pn(t.repoPath)}}async function dh(t,e,n,r){let s=`${e}-wip`;try{return pn(t),await fr(t,`WIP: turn limit exhausted (Allwright run ${n})`),await Pa(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 hh(t){return`
744
755
 
745
- 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 Xb(t){let{emit:e,setStatus:n,sendUsage:r,nextSeq:s}=_r(t.runId,t.transport),{trigger:i}=t.rule,o=t.rule.action;if(o.type!=="implement")return;let l=xn(o.agent,o.type);if(l){e("error",l),await bs(t,l),n("failed",{error:l});return}let c=t.chain?.worktreePath??co.default.join(Gt(),t.runId),u=Vt(o.branchTemplate,{issueKey:t.issueKey}),p=t.chain?.sessionId??(0,uo.randomUUID)(),f=!1,w=!1;try{if(!Vi(be()??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(L){e("warn",`Jira start transition failed: ${L instanceof Error?L.message:L} - continuing anyway`)}let b=await mr(t.repoPath);if(e("info",`Repo origin: ${b}`),!pt(b))throw new Error(`origin "${b}" is not a GitHub remote - implement mode supports GitHub only`);e("info",`Fetching ${t.issueKey} from Jira`);let k=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 vn(t.repoPath,x),await $a(t.repoPath,u),t.chain?(e("info","Chaining onto the previous ticket's workspace - resuming its agent session (repo context cached, not re-explored)"),await Oa(c,u,`origin/${o.baseBranch}`)):await Pa(t.repoPath,c,u,x),f=!0;let A=Vt(o.promptTemplate,{issueKey:k.key,summary:k.summary,description:k.description||"(no description)",comments:Ys(k.comments)})+await Xr(t.jira,k.attachments,c,e)+vl(c)+Zb(t.repoPath)+Bb+_e.NEEDS_INPUT_OPTIONS_PROMPT+Kb+(t.project.goLiveIssueKey?Hb:"")+(o.writeTests?Jd.WRITE_TESTS_PROMPT:"")+(o.updateMemory?_e.MEMORY_UPDATE_PROMPT:"");e("info",`Starting Claude Code in the worktree - edit tools enabled, path-jailed, no shell, timeout ${o.timeoutSeconds}s`);let $=await ws(t.runId,Ge(o.agent),{repoPath:c,prompt:A,timeoutSeconds:o.timeoutSeconds,bin:Be(t.cfg,o.agent),configDir:t.claudeConfigDir,mode:"edit_no_shell",model:o.model||void 0,maxTurns:o.maxTurns,sessionId:p,resume:!!t.chain,onLog:(L,O)=>e(L,O),onUsage:r},e,()=>Hi(c)),z={costUsd:$.costUsd,inputTokens:$.inputTokens,outputTokens:$.outputTokens,billingMode:$.billingMode,model:$.model};if(!$.ok){let L=$.error??"Claude Code failed";e("error",`Run failed: ${L}`);let O=L;if($.turnLimitHit){let Y=await nh(c,u,t.runId,e);Y&&(O+=rh(Y))}ft(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:"implement failed",detail:L.slice(0,500)}),await bs(t,O),n($.timedOut?"timed_out":"failed",{error:L,...$.cancelled?{errorKind:"guard"}:{},...z});return}let v=Xs($.resultText);if(v){w=!0,await po({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:k.summary},v,e,n,z);return}hn(c),await sh({runId:t.runId,issueKey:t.issueKey,issueSummary:k.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:$.resultText,costFields:z,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}),t.onChainSession?.({sessionId:p,worktreePath:c})}catch(b){let k=b instanceof Error?b.message:String(b);e("error",`Run failed: ${k}`),ft(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:"implement failed",detail:k.slice(0,500)}),await bs(t,k),n("failed",{error:k})}finally{f&&!w&&!t.keepWorktree&&await Tt(t.repoPath,c).catch(()=>{})}}async function _l(t,e,n,r){let{emit:s,setStatus:i,sendUsage:o,nextSeq:l}=_r(t.runId,r.transport,t.nextLogSeq),c=t.repoPath,u=!1;try{if(!Vi(be()??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=dh(e)+await Xr(r.jiraFor(t.repoName??""),n,c,s),f=await ws(t.runId,Ge(t.agent),{repoPath:c,prompt:p,timeoutSeconds:t.timeoutSeconds,bin:Be(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:(k,x)=>s(k,x),onUsage:o},s,()=>Hi(c)),w={costUsd:f.costUsd,inputTokens:f.inputTokens,outputTokens:f.outputTokens,billingMode:f.billingMode,model:f.model};if(!f.ok){let k=f.error??"Claude Code failed";s("error",`Run failed: ${k}`);let x=k;if(f.turnLimitHit&&t.branch){let A=await nh(c,t.branch,t.runId,s);A&&(x+=rh(A))}await At(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,x),Et(t.runId),i(f.timedOut?"timed_out":"failed",{error:k,...f.cancelled?{errorKind:"guard"}:{},...w});return}let b=Xs(f.resultText);if(b){if(t.rounds>=Yd){await hh(r.jiraFor(t.repoName??""),t,s,i,w);return}u=!0,await po({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},b,s,i,w);return}hn(c),await sh({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:w,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}),Et(t.runId)}catch(p){let f=p instanceof Error?p.message:String(p);s("error",`Run failed: ${f}`),await At(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,f),Et(t.runId),i("failed",{error:f})}finally{u||await Tt(t.baseRepoPath??c,c).catch(()=>{})}}async function sh(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:w,repoName:b,jira:k,cfg:x,actorEmail:A,runTests:$,mergeOnApprove:z,mergeMethod:v,autoMerge:L,resultText:O,costFields:Y,emit:M,setStatus:d}=t,m=await ls(s);m.deleted.length&&M("info",`Deleted ${m.deleted.length} file(s) listed in ${Ht}: `+m.deleted.slice(0,10).join(", ")+(m.deleted.length>10?", \u2026":""));for(let ne of m.refused)M("warn",`${Ht} entry refused: ${ne}`);M("info","Committing changes"),await pr(s,`${n}: ${r}
756
+ 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 uw(t){let{emit:e,setStatus:n,sendUsage:r,nextSeq:s}=Sr(t.runId,t.transport),{trigger:i}=t.rule,o=t.rule.action;if(o.type!=="implement")return;let l=Rn(o.agent,o.type);if(l){e("error",l),await ws(t,l),n("failed",{error:l});return}let c=t.chain?.worktreePath??co.default.join(Zt(),t.runId),u=Jt(o.branchTemplate,{issueKey:t.issueKey}),p=t.chain?.sessionId??(0,uo.randomUUID)(),f=!1,w=!1;try{if(!Vi(we()??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(L){e("warn",`Jira start transition failed: ${L instanceof Error?L.message:L} - continuing anyway`)}let b=await gr(t.repoPath);if(e("info",`Repo origin: ${b}`),!ft(b))throw new Error(`origin "${b}" is not a GitHub remote - implement mode supports GitHub only`);e("info",`Fetching ${t.issueKey} from Jira`);let k=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 kn(t.repoPath,x),await Na(t.repoPath,u),t.chain?(e("info","Chaining onto the previous ticket's workspace - resuming its agent session (repo context cached, not re-explored)"),await Da(c,u,`origin/${o.baseBranch}`)):await Oa(t.repoPath,c,u,x),f=!0;let A=Jt(o.promptTemplate,{issueKey:k.key,summary:k.summary,description:k.description||"(no description)",comments:Xs(k.comments)})+await Qr(t.jira,k.attachments,c,e)+Sl(c)+iw(t.repoPath)+tw+_e.NEEDS_INPUT_OPTIONS_PROMPT+nw+(t.project.goLiveIssueKey?rw:"")+(o.writeTests?ih.WRITE_TESTS_PROMPT:"")+(o.updateMemory?_e.MEMORY_UPDATE_PROMPT:"");e("info",`Starting Claude Code in the worktree - edit tools enabled, path-jailed, no shell, timeout ${o.timeoutSeconds}s`);let $=await vs(t.runId,Ge(o.agent),{repoPath:c,prompt:A,timeoutSeconds:o.timeoutSeconds,bin:Be(t.cfg,o.agent),configDir:t.claudeConfigDir,mode:"edit_no_shell",model:o.model||void 0,maxTurns:o.maxTurns,sessionId:p,resume:!!t.chain,onLog:(L,O)=>e(L,O),onUsage:r},e,()=>Hi(c)),z={costUsd:$.costUsd,inputTokens:$.inputTokens,outputTokens:$.outputTokens,billingMode:$.billingMode,model:$.model};if(!$.ok){let L=$.error??"Claude Code failed";e("error",`Run failed: ${L}`);let O=L;if($.turnLimitHit){let Y=await dh(c,u,t.runId,e);Y&&(O+=hh(Y))}mt(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:"implement failed",detail:L.slice(0,500)}),await ws(t,O),n($.timedOut?"timed_out":"failed",{error:L,...$.cancelled?{errorKind:"guard"}:{},...z});return}let v=Qs($.resultText);if(v){w=!0,await po({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:k.summary},v,e,n,z);return}pn(c),await ph({runId:t.runId,issueKey:t.issueKey,issueSummary:k.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:$.resultText,costFields:z,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}),t.onChainSession?.({sessionId:p,worktreePath:c})}catch(b){let k=b instanceof Error?b.message:String(b);e("error",`Run failed: ${k}`),mt(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:"implement failed",detail:k.slice(0,500)}),await ws(t,k),n("failed",{error:k})}finally{f&&!w&&!t.keepWorktree&&await xt(t.repoPath,c).catch(()=>{})}}async function xl(t,e,n,r){let{emit:s,setStatus:i,sendUsage:o,nextSeq:l}=Sr(t.runId,r.transport,t.nextLogSeq),c=t.repoPath,u=!1;try{if(!Vi(we()??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=vh(e)+await Qr(r.jiraFor(t.repoName??""),n,c,s),f=await vs(t.runId,Ge(t.agent),{repoPath:c,prompt:p,timeoutSeconds:t.timeoutSeconds,bin:Be(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:(k,x)=>s(k,x),onUsage:o},s,()=>Hi(c)),w={costUsd:f.costUsd,inputTokens:f.inputTokens,outputTokens:f.outputTokens,billingMode:f.billingMode,model:f.model};if(!f.ok){let k=f.error??"Claude Code failed";s("error",`Run failed: ${k}`);let x=k;if(f.turnLimitHit&&t.branch){let A=await dh(c,t.branch,t.runId,s);A&&(x+=hh(A))}await Ct(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,x),At(t.runId),i(f.timedOut?"timed_out":"failed",{error:k,...f.cancelled?{errorKind:"guard"}:{},...w});return}let b=Qs(f.resultText);if(b){if(t.rounds>=oh){await kh(r.jiraFor(t.repoName??""),t,s,i,w);return}u=!0,await po({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},b,s,i,w);return}pn(c),await ph({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:w,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}),At(t.runId)}catch(p){let f=p instanceof Error?p.message:String(p);s("error",`Run failed: ${f}`),await Ct(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,f),At(t.runId),i("failed",{error:f})}finally{u||await xt(t.baseRepoPath??c,c).catch(()=>{})}}async function ph(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:w,repoName:b,jira:k,cfg:x,actorEmail:A,runTests:$,mergeOnApprove:z,mergeMethod:v,autoMerge:L,resultText:O,costFields:Y,emit:M,setStatus:d}=t,m=await cs(s);m.deleted.length&&M("info",`Deleted ${m.deleted.length} file(s) listed in ${Gt}: `+m.deleted.slice(0,10).join(", ")+(m.deleted.length>10?", \u2026":""));for(let ne of m.refused)M("warn",`${Gt} entry refused: ${ne}`);M("info","Committing changes"),await fr(s,`${n}: ${r}
746
757
 
747
- Allwright run ${e}`);let y=await kn(s,l);if(!y.ok){let ne=y.forbidden.length?`refusing to push: changes touch protected paths (${y.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 (${y.files} files, ${y.insertions+y.deletions} lines; limits ${bn}/${wn})`;M("error",ne),await At(k,n,e,w,ne),d("failed",{error:ne,errorKind:"guard",...Y});return}M("info",`Diff: ${y.files} file(s), +${y.insertions}/-${y.deletions}`);let R={...Y},j="",G="",X,U,B;if($){let ne=ps(s);if(!ne)M("info","No TEST.md in this repo - skipping the test run (nothing documented to run)");else{let ct=fs(wl.default.readFileSync(ne,"utf8"));if(!ct.length)M("info",`${co.default.basename(ne)} lists no commands - nothing to run`);else{M("info",`Running ${ct.length} documented test command(s) - no tokens, plain shell`);let me=await yr(s,ct,{perCommandTimeoutMs:15*6e4}),we=me.filter(ue=>ue.exitCode!==0),ut=we.length;for(let ue of me)M(ue.exitCode===0?"info":"warn",`${ue.exitCode===0?"PASS":"FAIL"} ${ue.command} (exit ${ue.exitCode})`+(ue.exitCode===0?"":`
748
- ${ue.tail.slice(-1500)}`));let jt="";if(we.length&&t.fixSession){let ue=await ew({runId:e,issueKey:n,worktreePath:s,baseBranch:l,fixSession:t.fixSession,agentConfigDir:t.agentConfigDir,cfg:x,failed:we,emit:M,sendUsage:t.sendUsage,baseCost:R});if(R.costUsd+=ue.cost.costUsd,R.inputTokens+=ue.cost.inputTokens,R.outputTokens+=ue.cost.outputTokens,ue.outcome==="cancelled"){let Ye="stopped by a person during the automatic test-fix attempt - nothing was pushed";M("warn",Ye),so({runId:e,issueKey:n,issueSummary:r,mergeOnApprove:z,mergeMethod:v,autoMerge:L,repoName:b,baseRepoPath:i,branch:o,baseBranch:l,headSha:await it(s),requireApproval:p,doneLabel:f,failedLabel:w,jiraTransition:c,jiraTransitionOnMerge:u,actorEmail:A,resultSummary:Vd(O),prSummary:bl(O)??"",costUsd:R.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),await At(k,n,e,w,`${Ye}. The commit survived on the runner - "Retry push" on the run's dashboard page ships it without a new agent run.`),d("failed",{error:Ye,errorKind:"guard",retryAvailable:!0,...R});return}if(ue.outcome==="committed"){G=ue.resultText,M("info",`Re-running ${ct.length} documented test command(s) after the fix`),me=await yr(s,ct,{perCommandTimeoutMs:15*6e4}),we=me.filter(Ye=>Ye.exitCode!==0);for(let Ye of me)M(Ye.exitCode===0?"info":"warn",`${Ye.exitCode===0?"PASS":"FAIL"} ${Ye.command} (exit ${Ye.exitCode})`+(Ye.exitCode===0?"":`
749
- ${Ye.tail.slice(-1500)}`));jt=we.length?`One automatic same-session fix attempt ran; the results above are AFTER it. First pass: ${ut} failure(s). ${ue.note}`:`The first pass had ${ut} failure(s); one automatic same-session fix attempt resolved them. ${ue.note}`}else jt=ue.note}X=we.slice(0,20).map(ue=>({command:ue.command.slice(0,500),exitCode:ue.exitCode,tail:ue.tail.slice(-4e3)})),U=me.length-we.length,B=me.length,j=`
758
+ Allwright run ${e}`);let g=await _n(s,l);if(!g.ok){let ne=g.forbidden.length?`refusing to push: changes touch protected paths (${g.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 (${g.files} files, ${g.insertions+g.deletions} lines; limits ${wn}/${vn})`;M("error",ne),await Ct(k,n,e,w,ne),d("failed",{error:ne,errorKind:"guard",...Y});return}M("info",`Diff: ${g.files} file(s), +${g.insertions}/-${g.deletions}`);let R={...Y},j="",G="",X,U,B;if($){let ne=fs(s);if(!ne)M("info","No TEST.md in this repo - skipping the test run (nothing documented to run)");else{let ut=ms(_l.default.readFileSync(ne,"utf8"));if(!ut.length)M("info",`${co.default.basename(ne)} lists no commands - nothing to run`);else{M("info",`Running ${ut.length} documented test command(s) - no tokens, plain shell`);let me=await br(s,ut,{perCommandTimeoutMs:15*6e4}),ve=me.filter(ue=>ue.exitCode!==0),dt=ve.length;for(let ue of me)M(ue.exitCode===0?"info":"warn",`${ue.exitCode===0?"PASS":"FAIL"} ${ue.command} (exit ${ue.exitCode})`+(ue.exitCode===0?"":`
759
+ ${ue.tail.slice(-1500)}`));let Nt="";if(ve.length&&t.fixSession){let ue=await hw({runId:e,issueKey:n,worktreePath:s,baseBranch:l,fixSession:t.fixSession,agentConfigDir:t.agentConfigDir,cfg:x,failed:ve,emit:M,sendUsage:t.sendUsage,baseCost:R});if(R.costUsd+=ue.cost.costUsd,R.inputTokens+=ue.cost.inputTokens,R.outputTokens+=ue.cost.outputTokens,ue.outcome==="cancelled"){let Ye="stopped by a person during the automatic test-fix attempt - nothing was pushed";M("warn",Ye),so({runId:e,issueKey:n,issueSummary:r,mergeOnApprove:z,mergeMethod:v,autoMerge:L,repoName:b,baseRepoPath:i,branch:o,baseBranch:l,headSha:await it(s),requireApproval:p,doneLabel:f,failedLabel:w,jiraTransition:c,jiraTransitionOnMerge:u,actorEmail:A,resultSummary:sh(O),prSummary:kl(O)??"",costUsd:R.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),await Ct(k,n,e,w,`${Ye}. The commit survived on the runner - "Retry push" on the run's dashboard page ships it without a new agent run.`),d("failed",{error:Ye,errorKind:"guard",retryAvailable:!0,...R});return}if(ue.outcome==="committed"){G=ue.resultText,M("info",`Re-running ${ut.length} documented test command(s) after the fix`),me=await br(s,ut,{perCommandTimeoutMs:15*6e4}),ve=me.filter(Ye=>Ye.exitCode!==0);for(let Ye of me)M(Ye.exitCode===0?"info":"warn",`${Ye.exitCode===0?"PASS":"FAIL"} ${Ye.command} (exit ${Ye.exitCode})`+(Ye.exitCode===0?"":`
760
+ ${Ye.tail.slice(-1500)}`));Nt=ve.length?`One automatic same-session fix attempt ran; the results above are AFTER it. First pass: ${dt} failure(s). ${ue.note}`:`The first pass had ${dt} failure(s); one automatic same-session fix attempt resolved them. ${ue.note}`}else Nt=ue.note}X=ve.slice(0,20).map(ue=>({command:ue.command.slice(0,500),exitCode:ue.exitCode,tail:ue.tail.slice(-4e3)})),U=me.length-ve.length,B=me.length,j=`
750
761
 
751
762
  ### Tests
752
763
  `+me.map(ue=>`- ${ue.exitCode===0?"PASS":"FAIL"} \`${ue.command}\``).join(`
753
- `)+(we.length?`
764
+ `)+(ve.length?`
754
765
 
755
- **${we.length} of ${me.length} failed.** Output is in the run log.`:`
766
+ **${ve.length} of ${me.length} failed.** Output is in the run log.`:`
756
767
 
757
- All ${me.length} passed.`)+(jt?`
768
+ All ${me.length} passed.`)+(Nt?`
758
769
 
759
- ${jt}`:""),we.length&&M("warn",`${we.length} test command(s) failed - the PR will say so; review before merging`),ut>0&&ft(i,{issueKey:n,runId:e,title:we.length?`TEST.md commands failing at PR (${we.length} of ${me.length})`:"TEST.md failures fixed by same-session retry",detail:me.map(ue=>`${ue.exitCode===0?"PASS":"FAIL"} ${ue.command}`).join(`
760
- `)+(jt?`
761
- ${jt}`:"")})}}}let q=await mr(s),ie=pt(q);if(!ie){let ne=`origin "${q}" is not a GitHub remote - implement mode supports GitHub only`;M("error",ne),await At(k,n,e,w,ne),d("failed",{error:ne,...Y});return}let Z=await it(s),he=Vd(O),De=(G?bl(G):null)??bl(O);try{await ih({gitDir:s,ownerRepo:ie,runId:e,issueKey:n,issueSummary:r,agentConfigDir:t.agentConfigDir,branch:o,baseBranch:l,jiraTransition:c,jiraTransitionOnMerge:u,requireApproval:p,doneLabel:f,failedLabel:w,repoName:b,jira:k,cfg:x,actorEmail:A,mergeOnApprove:z,mergeMethod:v,autoMerge:L,summary:he,prSummary:De??void 0,cost:R,testReport:j,failedTests:X,testsPassed:U,testsTotal:B,goLiveDraft:(G?Gd(G):null)??Gd(O)??void 0,emit:M,setStatus:d})}catch(ne){let ct=ne instanceof Error?ne.message:String(ne);so({runId:e,issueKey:n,issueSummary:r,mergeOnApprove:z,mergeMethod:v,autoMerge:L,repoName:b,baseRepoPath:i,branch:o,baseBranch:l,headSha:Z,requireApproval:p,doneLabel:f,failedLabel:w,jiraTransition:c,jiraTransitionOnMerge:u,actorEmail:A,resultSummary:he,prSummary:De??"",costUsd:R.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),M("error",`Run failed: ${ct}`),M("info",`The commit itself survived on the runner (branch ${o}) - fix the cause, then use "Retry push" on this run's dashboard page.`),await At(k,n,e,w,`${ct}
770
+ ${Nt}`:""),ve.length&&M("warn",`${ve.length} test command(s) failed - the PR will say so; review before merging`),dt>0&&mt(i,{issueKey:n,runId:e,title:ve.length?`TEST.md commands failing at PR (${ve.length} of ${me.length})`:"TEST.md failures fixed by same-session retry",detail:me.map(ue=>`${ue.exitCode===0?"PASS":"FAIL"} ${ue.command}`).join(`
771
+ `)+(Nt?`
772
+ ${Nt}`:"")})}}}let q=await gr(s),se=ft(q);if(!se){let ne=`origin "${q}" is not a GitHub remote - implement mode supports GitHub only`;M("error",ne),await Ct(k,n,e,w,ne),d("failed",{error:ne,...Y});return}let Z=await it(s),he=sh(O),De=(G?kl(G):null)??kl(O);try{await fh({gitDir:s,ownerRepo:se,runId:e,issueKey:n,issueSummary:r,agentConfigDir:t.agentConfigDir,branch:o,baseBranch:l,jiraTransition:c,jiraTransitionOnMerge:u,requireApproval:p,doneLabel:f,failedLabel:w,repoName:b,jira:k,cfg:x,actorEmail:A,mergeOnApprove:z,mergeMethod:v,autoMerge:L,summary:he,prSummary:De??void 0,cost:R,testReport:j,failedTests:X,testsPassed:U,testsTotal:B,goLiveDraft:(G?th(G):null)??th(O)??void 0,emit:M,setStatus:d})}catch(ne){let ut=ne instanceof Error?ne.message:String(ne);so({runId:e,issueKey:n,issueSummary:r,mergeOnApprove:z,mergeMethod:v,autoMerge:L,repoName:b,baseRepoPath:i,branch:o,baseBranch:l,headSha:Z,requireApproval:p,doneLabel:f,failedLabel:w,jiraTransition:c,jiraTransitionOnMerge:u,actorEmail:A,resultSummary:he,prSummary:De??"",costUsd:R.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),M("error",`Run failed: ${ut}`),M("info",`The commit itself survived on the runner (branch ${o}) - fix the cause, then use "Retry push" on this run's dashboard page.`),await Ct(k,n,e,w,`${ut}
762
773
 
763
- The agent's commit survived on the runner - "Retry push" on the dashboard's run page re-pushes it without a new agent run.`),d("failed",{error:ct,retryAvailable:!0,...R})}}var Qb={costUsd:0,inputTokens:0,outputTokens:0};async function ew(t){let{runId:e,issueKey:n,worktreePath:r,baseBranch:s,fixSession:i,cfg:o,failed:l,emit:c,sendUsage:u,baseCost:p}=t,f=Ge(i.agent);if(!f?.capabilities.sessionResume){let $=`No automatic fix attempt: the ${i.agent||"configured"} adapter cannot resume sessions.`;return c("info",$),{outcome:"skipped",note:$,cost:Qb}}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 w=await it(r),b=await ws(e,f,{repoPath:r,prompt:Gb(l),timeoutSeconds:i.timeoutSeconds,bin:Be(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:($,z)=>c($,z),onUsage:u?$=>u({...$,inputTokens:p.inputTokens+$.inputTokens,outputTokens:p.outputTokens+$.outputTokens,costUsd:$.costUsd===void 0?void 0:p.costUsd+$.costUsd}):void 0},c),k={costUsd:b.costUsd,inputTokens:b.inputTokens,outputTokens:b.outputTokens};if(b.cancelled)return{outcome:"cancelled",cost:k};if(!b.ok){let $=`One automatic fix attempt did not complete (${b.error??"agent error"}) - the results above are from the original work.`;return c("warn",$),{outcome:"agent_failed",note:$,cost:k}}if(Xs(b.resultText)){let $="One automatic fix attempt asked for human input instead of fixing - the original commit ships unchanged; answer on the PR instead.";return c("warn",$),{outcome:"agent_failed",note:$,cost:k}}let x=await ls(r);for(let $ of x.refused)c("warn",`${Ht} entry refused: ${$}`);try{await pr(r,`${n}: fix failing TEST.md commands
774
+ The agent's commit survived on the runner - "Retry push" on the dashboard's run page re-pushes it without a new agent run.`),d("failed",{error:ut,retryAvailable:!0,...R})}}var dw={costUsd:0,inputTokens:0,outputTokens:0};async function hw(t){let{runId:e,issueKey:n,worktreePath:r,baseBranch:s,fixSession:i,cfg:o,failed:l,emit:c,sendUsage:u,baseCost:p}=t,f=Ge(i.agent);if(!f?.capabilities.sessionResume){let $=`No automatic fix attempt: the ${i.agent||"configured"} adapter cannot resume sessions.`;return c("info",$),{outcome:"skipped",note:$,cost:dw}}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 w=await it(r),b=await vs(e,f,{repoPath:r,prompt:sw(l),timeoutSeconds:i.timeoutSeconds,bin:Be(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:($,z)=>c($,z),onUsage:u?$=>u({...$,inputTokens:p.inputTokens+$.inputTokens,outputTokens:p.outputTokens+$.outputTokens,costUsd:$.costUsd===void 0?void 0:p.costUsd+$.costUsd}):void 0},c),k={costUsd:b.costUsd,inputTokens:b.inputTokens,outputTokens:b.outputTokens};if(b.cancelled)return{outcome:"cancelled",cost:k};if(!b.ok){let $=`One automatic fix attempt did not complete (${b.error??"agent error"}) - the results above are from the original work.`;return c("warn",$),{outcome:"agent_failed",note:$,cost:k}}if(Qs(b.resultText)){let $="One automatic fix attempt asked for human input instead of fixing - the original commit ships unchanged; answer on the PR instead.";return c("warn",$),{outcome:"agent_failed",note:$,cost:k}}let x=await cs(r);for(let $ of x.refused)c("warn",`${Gt} entry refused: ${$}`);try{await fr(r,`${n}: fix failing TEST.md commands
764
775
 
765
- Allwright run ${e} (automatic test-fix attempt)`)}catch{let $=`An automatic fix attempt concluded no code change was warranted: ${Sr(b.resultText)}`;return c("info",$),{outcome:"no_changes",note:$,cost:k}}let A=await kn(r,s);if(!A.ok){await cs(r,w);let $=A.forbidden.length?`An automatic fix attempt touched protected paths (${A.forbidden.slice(0,3).join(", ")}) and was discarded - the results above are from the original work.`:"An automatic fix attempt pushed the diff past the safety limits and was discarded - the results above are from the original work.";return c("warn",$),{outcome:"reverted",note:$,cost:k}}return{outcome:"committed",note:`Fix attempt: ${Sr(b.resultText)}`,resultText:b.resultText,cost:k}}async function ih(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:w,requireApproval:b,doneLabel:k,failedLabel:x,repoName:A,jira:$,cfg:z,actorEmail:v,summary:L,prSummary:O,cost:Y,testReport:M,emit:d,setStatus:m}=t;d("info",`Pushing ${u} to origin`),await fr(e,u);let y=await Gi(e,u),j=`${O?.trim()?`${O.trim()}
776
+ Allwright run ${e} (automatic test-fix attempt)`)}catch{let $=`An automatic fix attempt concluded no code change was warranted: ${Tr(b.resultText)}`;return c("info",$),{outcome:"no_changes",note:$,cost:k}}let A=await _n(r,s);if(!A.ok){await us(r,w);let $=A.forbidden.length?`An automatic fix attempt touched protected paths (${A.forbidden.slice(0,3).join(", ")}) and was discarded - the results above are from the original work.`:"An automatic fix attempt pushed the diff past the safety limits and was discarded - the results above are from the original work.";return c("warn",$),{outcome:"reverted",note:$,cost:k}}return{outcome:"committed",note:`Fix attempt: ${Tr(b.resultText)}`,resultText:b.resultText,cost:k}}async function fh(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:w,requireApproval:b,doneLabel:k,failedLabel:x,repoName:A,jira:$,cfg:z,actorEmail:v,summary:L,prSummary:O,cost:Y,testReport:M,emit:d,setStatus:m}=t;d("info",`Pushing ${u} to origin`),await mr(e,u);let g=await Gi(e,u),j=`${O?.trim()?`${O.trim()}
766
777
 
767
778
  <details>
768
779
  <summary>Technical details</summary>
@@ -773,13 +784,13 @@ ${L}
773
784
 
774
785
  ---
775
786
  Jira: ${new URL(`/browse/${s}`,z.jira?.baseUrl??"").toString()}
776
- _Allwright implement run \`${r}\` \xB7 cost $${Y.costUsd.toFixed(4)}. `+(M?"Tests were run by the runner, not the agent._":"The agent has no shell and no tests were run here - review accordingly._");d("info","Opening pull request");let G=Vi(be()??z,A,v);G.source==="user"&&d("info",`PR will be authored with ${v}'s own GitHub token`);let U=await new Ne(G.token).createPullRequest(n.owner,n.repo,{title:`${s}: ${i}`.slice(0,250),head:u,base:p,body:j});d("info",`PR ready: ${U.url}`),qd({runId:r,issueKey:s,repoName:A,owner:n.owner,repo:n.repo,prNumber:U.number,prUrl:U.url,jiraTransitionOnMerge:w??"",createdAt:new Date().toISOString()}),m("posting",Y);let B={nextDecisionSeq:1e5,runId:r,issueKey:s,repoName:A,owner:n.owner,repo:n.repo,prNumber:U.number,prUrl:U.url,branch:u,headSha:y,doneLabel:k,failedLabel:x,jiraTransition:f,mergeOnApprove:o,mergeMethod:l,autoMerge:c,agentConfigDir:t.agentConfigDir};if(b)gt(B),await $.addComment(s,`**Allwright opened a pull request for review.**
787
+ _Allwright implement run \`${r}\` \xB7 cost $${Y.costUsd.toFixed(4)}. `+(M?"Tests were run by the runner, not the agent._":"The agent has no shell and no tests were run here - review accordingly._");d("info","Opening pull request");let G=Vi(we()??z,A,v);G.source==="user"&&d("info",`PR will be authored with ${v}'s own GitHub token`);let U=await new Ne(G.token).createPullRequest(n.owner,n.repo,{title:`${s}: ${i}`.slice(0,250),head:u,base:p,body:j});d("info",`PR ready: ${U.url}`),Jd({runId:r,issueKey:s,repoName:A,owner:n.owner,repo:n.repo,prNumber:U.number,prUrl:U.url,jiraTransitionOnMerge:w??"",createdAt:new Date().toISOString()}),m("posting",Y);let B={nextDecisionSeq:1e5,runId:r,issueKey:s,repoName:A,owner:n.owner,repo:n.repo,prNumber:U.number,prUrl:U.url,branch:u,headSha:g,doneLabel:k,failedLabel:x,jiraTransition:f,mergeOnApprove:o,mergeMethod:l,autoMerge:c,agentConfigDir:t.agentConfigDir};if(b)yt(B),await $.addComment(s,`**Allwright opened a pull request for review.**
777
788
 
778
789
  PR: ${U.url}
779
790
 
780
- 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}\`)`),m("awaiting_approval",{...Y,prUrl:U.url,headSha:y,resultSummary:Sr(O?.trim()||L),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}:{}}),d("info",`Awaiting approval on the dashboard \xB7 $${Y.costUsd.toFixed(4)}`);else{if(c){d("info",`Auto-merging PR #${U.number} (${l})`);let ie=je(z,A),Z=ie?await new Ne(ie).mergePullRequest(n.owner,n.repo,U.number,l,{sha:y,title:`${s} (#${U.number})`}):{merged:!1,reason:"no GitHub token applies to this repo"};Z.merged?d("info",`PR #${U.number} merged`):(d("warn",`Auto-merge did not go through - ${Z.reason}. The PR stays open.`),await $.addComment(s,`**Allwright:** the work is done and the PR is open, but auto-merge did not go through - ${Z.reason}
791
+ 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}\`)`),m("awaiting_approval",{...Y,prUrl:U.url,headSha:g,resultSummary:Tr(O?.trim()||L),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}:{}}),d("info",`Awaiting approval on the dashboard \xB7 $${Y.costUsd.toFixed(4)}`);else{if(c){d("info",`Auto-merging PR #${U.number} (${l})`);let se=je(z,A),Z=se?await new Ne(se).mergePullRequest(n.owner,n.repo,U.number,l,{sha:g,title:`${s} (#${U.number})`}):{merged:!1,reason:"no GitHub token applies to this repo"};Z.merged?d("info",`PR #${U.number} merged`):(d("warn",`Auto-merge did not go through - ${Z.reason}. The PR stays open.`),await $.addComment(s,`**Allwright:** the work is done and the PR is open, but auto-merge did not go through - ${Z.reason}
781
792
 
782
- PR: ${U.url}`))}let q=(be()??z).repos[A]?.path;q&&Hs(q,s)&&ft(q,{issueKey:s,runId:r,title:"shipped after earlier failure",detail:`PR ${U.url} merged/opened straight-through.`}),await oh({jira:$,issueKey:s},B,d),m("succeeded",{...Y,prUrl:U.url,headSha:y,resultSummary:Sr(O?.trim()||L),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}:{}}),d("info",`Run succeeded \xB7 ${U.url} \xB7 $${Y.costUsd.toFixed(4)}`)}}async function oh(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.**
793
+ PR: ${U.url}`))}let q=(we()??z).repos[A]?.path;q&&Gs(q,s)&&mt(q,{issueKey:s,runId:r,title:"shipped after earlier failure",detail:`PR ${U.url} merged/opened straight-through.`}),await mh({jira:$,issueKey:s},B,d),m("succeeded",{...Y,prUrl:U.url,headSha:g,resultSummary:Tr(O?.trim()||L),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}:{}}),d("info",`Run succeeded \xB7 ${U.url} \xB7 $${Y.costUsd.toFixed(4)}`)}}async function mh(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.**
783
794
 
784
795
  PR: ${e.prUrl}`:`**Allwright: the change is approved, but NOT merged yet.**
785
796
 
@@ -789,77 +800,68 @@ This rule is set to "my team merges on GitHub", so Allwright deliberately did no
789
800
 
790
801
  Note: ${r}`:"")+`
791
802
 
792
- (run \`${e.runId}\`)`),await t.jira.editLabels(e.issueKey,{add:[e.doneLabel],remove:[_e.NEEDS_INPUT_LABEL]}),r}async function Js(t,e,n){let r=ys(e);if(!r){g.warn(`run.approved for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:s,setStatus:i}=ch(t,e);try{let o=je(be()??t.cfg,r.repoName);if(!o)throw new Error("GitHub token missing on this runner");let l=new Ne(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}
803
+ (run \`${e.runId}\`)`),await t.jira.editLabels(e.issueKey,{add:[e.doneLabel],remove:[_e.NEEDS_INPUT_LABEL]}),r}async function Ys(t,e,n){let r=bs(e);if(!r){y.warn(`run.approved for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:s,setStatus:i}=bh(t,e);try{let o=je(we()??t.cfg,r.repoName);if(!o)throw new Error("GitHub token missing on this runner");let l=new Ne(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}
793
804
 
794
- PR: ${r.prUrl}`),i("awaiting_approval",{prUrl:r.prUrl,headSha:c.headSha,resultSummary:f});return}s("info",`PR #${r.prNumber} merged`)}{let p=(be()??t.cfg).repos[r.repoName??""]?.path;p&&Hs(p,r.issueKey)&&ft(p,{issueKey:r.issueKey,runId:e,title:"shipped after earlier failure",detail:`PR ${r.prUrl} approved and completed.`})}await oh({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.'),vr(e)}catch(o){let l=o instanceof Error?o.message:String(o);s("error",`Approval handling failed: ${l}`),await uh(t,r,l),i("failed",{error:l}),vr(e)}}async function ah(t,e){let n=ys(e);if(!n){g.warn(`run.rejected for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:r,setStatus:s}=ch(t,e);try{let i=je(be()??t.cfg,n.repoName);if(!i)throw new Error("GitHub token missing on this runner");let o=new Ne(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.**
805
+ PR: ${r.prUrl}`),i("awaiting_approval",{prUrl:r.prUrl,headSha:c.headSha,resultSummary:f});return}s("info",`PR #${r.prNumber} merged`)}{let p=(we()??t.cfg).repos[r.repoName??""]?.path;p&&Gs(p,r.issueKey)&&mt(p,{issueKey:r.issueKey,runId:e,title:"shipped after earlier failure",detail:`PR ${r.prUrl} approved and completed.`})}await mh({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.'),kr(e)}catch(o){let l=o instanceof Error?o.message:String(o);s("error",`Approval handling failed: ${l}`),await wh(t,r,l),i("failed",{error:l}),kr(e)}}async function gh(t,e){let n=bs(e);if(!n){y.warn(`run.rejected for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:r,setStatus:s}=bh(t,e);try{let i=je(we()??t.cfg,n.repoName);if(!i)throw new Error("GitHub token missing on this runner");let o=new Ne(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.**
795
806
 
796
- 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"),vr(e)}catch(i){let o=i instanceof Error?i.message:String(i);r("error",`Rejection handling failed: ${o}`),await uh(t,n,o),s("failed",{error:o}),vr(e)}}async function lh(t,e){let n=io(e);if(!n){g.warn(`run.retryPush for ${e}: no retry record (already pushed, or invalidated?)`);let{emit:l,setStatus:c,sendUsage:u}=_r(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}=_r(e,t.transport,n.nextLogSeq);try{let l=await Gi(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.`),gl(e),s("failed",{retryAvailable:!1});return}let c=await mr(n.baseRepoPath),u=pt(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 ih({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:be()??t.cfg,actorEmail:n.actorEmail,summary:n.resultSummary,prSummary:n.prSummary||void 0,cost:{costUsd:n.costUsd},emit:r,setStatus:s}),gl(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}`),so({...n,nextLogSeq:o()}),s("failed",{error:c,retryAvailable:!0})}}function ch(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"&&g.info(`[run ${e}] ${o}`)},setStatus:(i,o={})=>{t.transport.send({type:"run.status",runId:e,status:i,...o})}}}async function uh(t,e,n){try{await t.jiraFor(e.repoName??"").addComment(e.issueKey,`**Allwright could not complete the approval decision.**
807
+ 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"),kr(e)}catch(i){let o=i instanceof Error?i.message:String(i);r("error",`Rejection handling failed: ${o}`),await wh(t,n,o),s("failed",{error:o}),kr(e)}}async function yh(t,e){let n=io(e);if(!n){y.warn(`run.retryPush for ${e}: no retry record (already pushed, or invalidated?)`);let{emit:l,setStatus:c,sendUsage:u}=Sr(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}=Sr(e,t.transport,n.nextLogSeq);try{let l=await Gi(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.`),wl(e),s("failed",{retryAvailable:!1});return}let c=await gr(n.baseRepoPath),u=ft(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 fh({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:we()??t.cfg,actorEmail:n.actorEmail,summary:n.resultSummary,prSummary:n.prSummary||void 0,cost:{costUsd:n.costUsd},emit:r,setStatus:s}),wl(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}`),so({...n,nextLogSeq:o()}),s("failed",{error:c,retryAvailable:!0})}}function bh(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 wh(t,e,n){try{await t.jiraFor(e.repoName??"").addComment(e.issueKey,`**Allwright could not complete the approval decision.**
797
808
 
798
809
  Error: ${n.slice(0,800)}
799
810
 
800
811
  PR: ${e.prUrl}
801
- (run \`${e.runId}\`)`),await t.jiraFor(e.repoName??"").editLabels(e.issueKey,{add:[e.failedLabel]})}catch(r){g.error(`could not post decision failure to ${e.issueKey}: ${r}`)}}function Ys(t){if(!t.length)return"(no comments)";let e=6e4,n=t.map(i=>`${i.author} (${i.created}):
812
+ (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 Xs(t){if(!t.length)return"(no comments)";let e=6e4,n=t.map(i=>`${i.author} (${i.created}):
802
813
  ${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(`
803
814
  ---
804
- `)}function dh(t){return`The ticket author replied:
815
+ `)}function vh(t){return`The ticket author replied:
805
816
 
806
817
  ${t}
807
818
 
808
- 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 ${_e.NEEDS_INPUT_MARKER} marker).`}function Xs(t){let e=t.trim(),n=e.split(`
819
+ 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 ${_e.NEEDS_INPUT_MARKER} marker).`}function Qs(t){let e=t.trim(),n=e.split(`
809
820
  `,1)[0].trim(),r=o=>o.replace(/[^a-z]/gi,"").toUpperCase();if(r(n)!==r(_e.NEEDS_INPUT_MARKER))return null;let s=e.indexOf(`
810
- `);return s<0?null:e.slice(s+1).trim()||null}function tw(t){let n=[...t.matchAll(new RegExp(`\`\`\`${_e.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(`\`\`\`${_e.NEEDS_INPUT_ASK_FENCE}\\s*\\n[\\s\\S]*?\`\`\``,"g"),"").trim()||t.trim(),options:r}}async function po(t,e,n,r,s){let{questions:i,options:o}=tw(e);n("info",`Claude needs more information - posting questions to ${t.issueKey}`),await t.jira.addComment(t.issueKey,`**${_e.NEEDS_INPUT_COMMENT_MARKER} before it can continue.**
821
+ `);return s<0?null:e.slice(s+1).trim()||null}function pw(t){let n=[...t.matchAll(new RegExp(`\`\`\`${_e.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(`\`\`\`${_e.NEEDS_INPUT_ASK_FENCE}\\s*\\n[\\s\\S]*?\`\`\``,"g"),"").trim()||t.trim(),options:r}}async function po(t,e,n,r,s){let{questions:i,options:o}=pw(e);n("info",`Claude needs more information - posting questions to ${t.issueKey}`),await t.jira.addComment(t.issueKey,`**${_e.NEEDS_INPUT_COMMENT_MARKER} before it can continue.**
811
822
 
812
823
  ${i}
813
824
 
814
- 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:[_e.NEEDS_INPUT_LABEL]}),Kd({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:Sr(i),inputQuestions:i.slice(0,4e3),inputOptions:o}),n("info",`Waiting for an answer on ${t.issueKey} (label "${_e.NEEDS_INPUT_LABEL}") or on this run page`+(o.length?` - ${o.length} suggested answer(s) offered`:""))}async function hh(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 At(t,e.issueKey,e.runId,e.failedLabel,i),Et(e.runId),r("failed",{error:i,...s})}async function bs(t,e){await At(t.jira,t.issueKey,t.runId,t.rule.trigger.failedLabel,e)}async function At(t,e,n,r,s){try{await t.addComment(e,`**Allwright run failed.**
825
+ 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:[_e.NEEDS_INPUT_LABEL]}),Qd({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:Tr(i),inputQuestions:i.slice(0,4e3),inputOptions:o}),n("info",`Waiting for an answer on ${t.issueKey} (label "${_e.NEEDS_INPUT_LABEL}") or on this run page`+(o.length?` - ${o.length} suggested answer(s) offered`:""))}async function kh(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 Ct(t,e.issueKey,e.runId,e.failedLabel,i),At(e.runId),r("failed",{error:i,...s})}async function ws(t,e){await Ct(t.jira,t.issueKey,t.runId,t.rule.trigger.failedLabel,e)}async function Ct(t,e,n,r,s){try{await t.addComment(e,`**Allwright run failed.**
815
826
 
816
827
  Error: ${s.slice(0,800)}
817
828
 
818
- 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:[_e.NEEDS_INPUT_LABEL]})}catch(i){g.error(`could not post failure comment to ${e}: ${i}`)}}function Vd(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 bl(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 Sr(t){for(let e of t.split(`
819
- `)){let n=e.replace(/^#+\s*/,"").trim();if(n.length>10)return n.slice(0,200)}return t.slice(0,200)}var Ir=I(require("node:fs"),1);var Tr=I(require("node:fs"),1),Sl=I(require("node:os"),1),xr=I(require("node:path"),1);function nw(){try{return Sl.default.userInfo().username}catch{return"the user the runner service runs as"}}function rw(t,e){let n=xr.default.join(t,"apps","api","prisma","manual"),r=xr.default.join(t,"prisma","manual");for(let s of[n,r]){let i;try{i=Tr.default.readdirSync(s).filter(o=>o.endsWith(".sql")).sort()}catch{continue}for(let o of i.reverse())try{let l=Tr.default.readFileSync(xr.default.join(s,o),"utf8");if(new RegExp(`"${e}"`,"i").test(l))return o}catch{}}return null}function Tl(t,e){let n=t.slice(-4e3),r=nw(),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?rw(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=xr.default.join(Sl.default.homedir(),".nvm","versions","node"),f=Tr.default.readdirSync(p).sort();f.length&&(u=xr.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'
829
+ 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:[_e.NEEDS_INPUT_LABEL]})}catch(i){y.error(`could not post failure comment to ${e}: ${i}`)}}function sh(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 kl(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 Tr(t){for(let e of t.split(`
830
+ `)){let n=e.replace(/^#+\s*/,"").trim();if(n.length>10)return n.slice(0,200)}return t.slice(0,200)}var Er=I(require("node:fs"),1);var xr=I(require("node:fs"),1),Rl=I(require("node:os"),1),Rr=I(require("node:path"),1);function fw(){try{return Rl.default.userInfo().username}catch{return"the user the runner service runs as"}}function mw(t,e){let n=Rr.default.join(t,"apps","api","prisma","manual"),r=Rr.default.join(t,"prisma","manual");for(let s of[n,r]){let i;try{i=xr.default.readdirSync(s).filter(o=>o.endsWith(".sql")).sort()}catch{continue}for(let o of i.reverse())try{let l=xr.default.readFileSync(Rr.default.join(s,o),"utf8");if(new RegExp(`"${e}"`,"i").test(l))return o}catch{}}return null}function Il(t,e){let n=t.slice(-4e3),r=fw(),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?mw(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=Rr.default.join(Rl.default.homedir(),".nvm","versions","node"),f=xr.default.readdirSync(p).sort();f.length&&(u=Rr.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'
820
831
  [Service]
821
832
  Environment=PATH=${u||"<the bin directory holding node>"}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
822
- 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=(Tr.default.existsSync("/etc/systemd/system")?Tr.default.readdirSync("/etc/systemd/system").filter(w=>w.endsWith(".service")).filter(w=>{try{let b=Tr.default.readFileSync(xr.default.join("/etc/systemd/system",w),"utf8");return e?.cwd?b.includes(e.cwd):!1}catch{return!1}}).map(w=>w.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 ph(t){return t?`
833
+ 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=(xr.default.existsSync("/etc/systemd/system")?xr.default.readdirSync("/etc/systemd/system").filter(w=>w.endsWith(".service")).filter(w=>{try{let b=xr.default.readFileSync(Rr.default.join("/etc/systemd/system",w),"utf8");return e?.cwd?b.includes(e.cwd):!1}catch{return!1}}).map(w=>w.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 _h(t){return t?`
823
834
 
824
835
  What this means: ${t.cause}
825
836
  Run these ON THE DEPLOY MACHINE:
826
837
  `+t.commands.map(e=>` ${e}`).join(`
827
838
  `)+`
828
- ${t.note}`:""}var Rr=I(require("node:path"),1),Er=require("node:child_process"),El=I(require("node:readline"),1),Al=require("node:crypto"),Ar=I(ke(),1);Jr();Ce();var Eh=I(ke(),1);xt();mt();gr();yo();var wh=require("node:child_process"),Rl=I(require("node:fs"),1),vh=I(require("node:path"),1),bh=4e3,cw=/(TOKEN|KEY|SECRET|PASSWORD|PASSWD|CREDENTIAL|AUTH|COOKIE|SESSION)/i;function uw(t){return t.replace(/([A-Za-z_][A-Za-z0-9_]*)=(\S+)/g,(e,n,r)=>cw.test(n)?`${n}=<redacted>`:e)}function Yt(t,e){try{let r=(0,wh.execFileSync)(t,e,{encoding:"utf8",timeout:1e4,maxBuffer:2e6,stdio:["ignore","pipe","pipe"]}).trim();return r?r.slice(0,bh):null}catch(n){let r=n,s=`${r?.stdout??""}${r?.stderr??""}`.trim();return s?s.slice(0,bh):null}}function dw(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(vh.default.join(r,i),"utf8");t&&o.includes(t)&&n.push(i.replace(/\.service$/,""))}catch{}}return[...new Set(n)].slice(0,3)}function kh(t){let e=t.errorText.slice(-6e3),n=[],r=(o,l)=>{l&&n.push({command:o,output:uw(l)})},s=dw(t.repoPath);for(let o of s)r(`systemctl status ${o}`,Yt("systemctl",["status",o,"--no-pager","-l"])),r(`journalctl -u ${o} -n 40`,Yt("journalctl",["-u",o,"-n","40","--no-pager"])),r(`systemctl show ${o} -p ExecStart -p Environment -p WorkingDirectory -p User`,Yt("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",Yt("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)`,Yt("bash",["-lc",`command -v ${JSON.stringify(o)} || echo "not on this PATH"`])),r("ls of the usual system locations",Yt("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",Yt("bash",["-lc","df -h | head -10"])),/EACCES|Permission denied|Operation not permitted/i.test(e)&&(r("id",Yt("id",[])),r(`ls -ld ${t.repoPath}`,Yt("bash",["-lc",`ls -ld ${JSON.stringify(t.repoPath)} 2>&1`]))),n}function _h(t){return t.length?`
829
-
830
- 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.
831
-
832
- `+t.map(e=>`$ ${e.command}
833
- ${e.output}`).join(`
834
-
835
- `)+`
836
-
837
- 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.`:""}Wt();var Sh=4e3,hw=4e3;function Th(t,e){t("warn",`${e.length} step(s) still need YOU - Allwright deliberately did not run these:
839
+ ${t.note}`:""}var Ir=I(require("node:path"),1),Ar=require("node:child_process"),jl=I(require("node:readline"),1),Nl=require("node:crypto"),Cr=I(ke(),1);Yr();Ce();var zh=I(ke(),1);Rt();gt();yr();yo();$l();Vt();var Ph=4e3,Sw=4e3;function jh(t,e){t("warn",`${e.length} step(s) still need YOU - Allwright deliberately did not run these:
838
840
  `+e.map(n=>` ${n.command}${n.why?` # ${n.why}`:""}`).join(`
839
- `))}function Cl(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,hw)}),s!=="agent"&&g.info(`[deploy ${t.runId}] ${i}`)},setStatus:(s,i={})=>{t.transport.send({type:"run.status",runId:t.runId,status:s,...i})}}}var pw=/^\s*(?:ALLWRIGHT|TICKETPILOT)[-\s]MANUAL:\s*(.+)$/i;function fw(t){let e=pw.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 wo(t){let{emit:e,setStatus:n}=Cl(t),r=t.environment;try{let s=mw(t);if(s){e("error",s),await yt(t,`**Allwright could not deploy to \`${r.name}\`.**
841
+ `))}function Ol(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,Sw)}),s!=="agent"&&y.info(`[deploy ${t.runId}] ${i}`)},setStatus:(s,i={})=>{t.transport.send({type:"run.status",runId:t.runId,status:s,...i})}}}var Tw=/^\s*(?:ALLWRIGHT|TICKETPILOT)[-\s]MANUAL:\s*(.+)$/i;function xw(t){let e=Tw.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 wo(t){let{emit:e,setStatus:n}=Ol(t),r=t.environment;try{let s=Rw(t);if(s){e("error",s),await bt(t,`**Allwright could not deploy to \`${r.name}\`.**
840
842
 
841
- ${s}`),n("failed",{error:s});return}if(r.requireApproval){Bd({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 yt(t,`**Allwright: deploy to \`${r.name}\` needs approval.**
843
+ ${s}`),n("failed",{error:s});return}if(r.requireApproval){Xd({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 bt(t,`**Allwright: deploy to \`${r.name}\` needs approval.**
842
844
 
843
- ${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 Ah(t,e,n)}catch(s){let i=s instanceof Error?s.message:String(s);e("error",`Deploy failed: ${i}`),await yt(t,`**Allwright deploy to \`${r.name}\` failed.**
845
+ ${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 Dh(t,e,n)}catch(s){let i=s instanceof Error?s.message:String(s);e("error",`Deploy failed: ${i}`),await bt(t,`**Allwright deploy to \`${r.name}\` failed.**
844
846
 
845
847
  ${i.slice(0,800)}
846
848
 
847
- (run \`${t.runId}\`)`),n("failed",{error:i})}}function mw(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=qt(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&&g.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 Ah(t,e,n){let r=t.environment,s=qt(t.cfg,t.project.repoName,r.name),i=$l(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 L=Me(t.cfg,t.project,"assist"),O="error"in L?{ok:!1,error:L.error}:await ms({projectId:t.project.id,repoPath:t.repoPath,role:r.auditBeforeDeploy,scope:{kind:"repo",ref:""},model:"",agent:L,jira:t.jira});if(!O.ok)e("warn",`Pre-deploy audit could not run: ${O.error} - deploying anyway (advisory)`);else if(!O.audit.findings.length)e("info","Pre-deploy audit: no findings \u2713");else{let Y={};for(let M of O.audit.findings)Y[M.severity]=(Y[M.severity]??0)+1;e("warn",`Pre-deploy audit: ${O.audit.findings.length} finding(s) (`+Object.entries(Y).map(([M,d])=>`${d} ${M}`).join(", ")+") - full report on the Audits page. Deploying anyway (advisory).");for(let M of O.audit.findings.slice(0,5))e("warn",` [${M.severity}] ${M.title} - ${M.evidence[0]?.file??""}`)}}catch(L){e("warn",`Pre-deploy audit crashed: ${L instanceof Error?L.message:String(L)} - deploying anyway`)}}if(r.requireSyncCheck){if(!r.previousEnvBranch||!r.branch){let O=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",O),await yt(t,`**Allwright refused to deploy to \`${r.name}\`.**
849
+ (run \`${t.runId}\`)`),n("failed",{error:i})}}function Rw(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=Ft(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 Dh(t,e,n){let r=t.environment,s=Ft(t.cfg,t.project.repoName,r.name),i=Ml(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 L=Me(t.cfg,t.project,"assist"),O="error"in L?{ok:!1,error:L.error}:await gs({projectId:t.project.id,repoPath:t.repoPath,role:r.auditBeforeDeploy,scope:{kind:"repo",ref:""},model:"",agent:L,jira:t.jira});if(!O.ok)e("warn",`Pre-deploy audit could not run: ${O.error} - deploying anyway (advisory)`);else if(!O.audit.findings.length)e("info","Pre-deploy audit: no findings \u2713");else{let Y={};for(let M of O.audit.findings)Y[M.severity]=(Y[M.severity]??0)+1;e("warn",`Pre-deploy audit: ${O.audit.findings.length} finding(s) (`+Object.entries(Y).map(([M,d])=>`${d} ${M}`).join(", ")+") - full report on the Audits page. Deploying anyway (advisory).");for(let M of O.audit.findings.slice(0,5))e("warn",` [${M.severity}] ${M.title} - ${M.evidence[0]?.file??""}`)}}catch(L){e("warn",`Pre-deploy audit crashed: ${L instanceof Error?L.message:String(L)} - deploying anyway`)}}if(r.requireSyncCheck){if(!r.previousEnvBranch||!r.branch){let O=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",O),await bt(t,`**Allwright refused to deploy to \`${r.name}\`.**
848
850
 
849
851
  ${O}
850
852
 
851
- (run \`${t.runId}\`)`),n("failed",{error:O,errorKind:"guard"});return}let L=await yw(t,e);if(L){await yt(t,L.comment),n("failed",{error:L.error,...L.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 Ma({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 L=Vt(r.ticketBranchTemplate,{issueKey:t.issueKey});e("info",`Merging "${L}" into "${r.branch}"`);let O=await za(c,L,`Deploy ${t.issueKey} to ${r.name}
853
+ (run \`${t.runId}\`)`),n("failed",{error:O,errorKind:"guard"});return}let L=await Ew(t,e);if(L){await bt(t,L.comment),n("failed",{error:L.error,...L.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 La({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 L=Jt(r.ticketBranchTemplate,{issueKey:t.issueKey});e("info",`Merging "${L}" into "${r.branch}"`);let O=await Ua(c,L,`Deploy ${t.issueKey} to ${r.name}
852
854
 
853
- Allwright run ${t.runId}`);if(!O.ok){e("error",O.reason??"merge failed"),await yt(t,`**Allwright deploy to \`${r.name}\` failed before running anything.**
855
+ Allwright run ${t.runId}`);if(!O.ok){e("error",O.reason??"merge failed"),await bt(t,`**Allwright deploy to \`${r.name}\` failed before running anything.**
854
856
 
855
- ${O.reason}`),n("failed",{error:O.reason});return}O.alreadyMerged?e("info",`"${L}" is already in "${r.branch}" - nothing to merge`):(e("info",`Pushing "${r.branch}" to origin`),await qa(c,r.branch))}let p=await it(c).catch(()=>"");p&&e("info",`Deploying commit ${p.slice(0,10)}`);let f=bw(c,r.workdir),w={...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},b=0,k=r.timeoutSeconds*1e3,x=Qd(t.runId),A=()=>x.signal.aborted;try{for(let[L,O]of r.steps.entries()){if(A()){let d=`stopped from the dashboard during step ${L+1} - nothing further ran`;e("error",d),n("failed",{error:d,errorKind:"guard",deployedRef:p});return}let Y=k-(Date.now()-o);if(Y<=0){let d=`deploy exceeded its ${r.timeoutSeconds}s budget before step ${L+1}`;e("error",d),await yt(t,`**Allwright deploy to \`${r.name}\` timed out.**
857
+ ${O.reason}`),n("failed",{error:O.reason});return}O.alreadyMerged?e("info",`"${L}" is already in "${r.branch}" - nothing to merge`):(e("info",`Pushing "${r.branch}" to origin`),await Ka(c,r.branch))}let p=await it(c).catch(()=>"");p&&e("info",`Deploying commit ${p.slice(0,10)}`);let f=Aw(c,r.workdir),w={...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},b=0,k=r.timeoutSeconds*1e3,x=lh(t.runId),A=()=>x.signal.aborted;try{for(let[L,O]of r.steps.entries()){if(A()){let d=`stopped from the dashboard during step ${L+1} - nothing further ran`;e("error",d),n("failed",{error:d,errorKind:"guard",deployedRef:p});return}let Y=k-(Date.now()-o);if(Y<=0){let d=`deploy exceeded its ${r.timeoutSeconds}s budget before step ${L+1}`;e("error",d),await bt(t,`**Allwright deploy to \`${r.name}\` timed out.**
856
858
 
857
- ${d}`),n("timed_out",{error:d,deployedRef:p});return}e("info",`\u25B6 step ${L+1}/${r.steps.length}: ${O.name}`);let M=await ww({command:O.run,cwd:f,env:w,timeoutMs:Y,signal:x.signal,onLine:(d,m)=>{b++;let y=fw(m);y&&l.length<20&&l.push(y),b===Sh&&e("warn","(output truncated - deploy log limit reached)"),!(b>=Sh)&&e(d,i(m))}});if(M.timedOut){let d=`step "${O.name}" hit the ${r.timeoutSeconds}s deploy budget and was killed`;e("error",d),await yt(t,`**Allwright deploy to \`${r.name}\` timed out.**
859
+ ${d}`),n("timed_out",{error:d,deployedRef:p});return}e("info",`\u25B6 step ${L+1}/${r.steps.length}: ${O.name}`);let M=await Cw({command:O.run,cwd:f,env:w,timeoutMs:Y,signal:x.signal,onLine:(d,m)=>{b++;let g=xw(m);g&&l.length<20&&l.push(g),b===Ph&&e("warn","(output truncated - deploy log limit reached)"),!(b>=Ph)&&e(d,i(m))}});if(M.timedOut){let d=`step "${O.name}" hit the ${r.timeoutSeconds}s deploy budget and was killed`;e("error",d),await bt(t,`**Allwright deploy to \`${r.name}\` timed out.**
858
860
 
859
- ${d}`),n("timed_out",{error:d,deployedRef:p});return}if(M.code!==0){if(O.continueOnError){e("warn",`step "${O.name}" exited ${M.code} - continuing (marked continue-on-error)`);continue}let d="";try{d=i(await Ca(c))}catch{}let m=ph(Tl(M.tail??"",{cwd:c})),y=`step ${L+1} "${O.name}" failed with exit code ${M.code}`+(M.tail?`: ${i(M.tail)}`:"")+m+(d?`
861
+ ${d}`),n("timed_out",{error:d,deployedRef:p});return}if(M.code!==0){if(O.continueOnError){e("warn",`step "${O.name}" exited ${M.code} - continuing (marked continue-on-error)`);continue}let d="";try{d=i(await ja(c))}catch{}let m=_h(Il(M.tail??"",{cwd:c})),g=`step ${L+1} "${O.name}" failed with exit code ${M.code}`+(M.tail?`: ${i(M.tail)}`:"")+m+(d?`
860
862
 
861
863
  Checkout at failure:
862
- ${d}`:"");e("error",y),await yt(t,`**Allwright deploy to \`${r.name}\` failed.**
864
+ ${d}`:"");e("error",g),await bt(t,`**Allwright deploy to \`${r.name}\` failed.**
863
865
 
864
866
  Step ${L+1} \`${O.name}\` exited ${M.code}.
865
867
 
@@ -878,8 +880,8 @@ ${d.slice(0,800)}
878
880
  `+l.map(R=>`- \`${R.command}\`${R.why?` - ${R.why}`:""}`).join(`
879
881
  `)+`
880
882
 
881
- `:"")+`Nothing after it ran. Full log is on the Allwright dashboard. (run \`${t.runId}\`)`),ft(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.name} failed`,detail:`step ${L+1} "${O.name}" exit ${M.code}`+(M.tail?`
882
- ${i(M.tail).slice(0,500)}`:"")}),l.length&&Th(e,l),n("failed",{error:y.slice(0,1600),deployedRef:p,...l.length?{manualSteps:l}:{}});return}e("info",`\u2713 step ${L+1}/${r.steps.length}: ${O.name}`)}}finally{eh(t.runId)}n("posting");let $=Math.round((Date.now()-o)/1e3),z=null;r.publicUrl?.trim()&&(z=await _w(r.publicUrl.trim()),e(z?"warn":"info",z??`${r.publicUrl.trim()} points at this machine - the deploy is live there`)),t.issueKey!==Ar.BRANCH_DEPLOY_ISSUE_KEY&&await yt(t,`**Allwright deployed \`${t.issueKey}\` to \`${r.name}\`.**
883
+ `:"")+`Nothing after it ran. Full log is on the Allwright dashboard. (run \`${t.runId}\`)`),mt(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.name} failed`,detail:`step ${L+1} "${O.name}" exit ${M.code}`+(M.tail?`
884
+ ${i(M.tail).slice(0,500)}`:"")}),l.length&&jh(e,l),n("failed",{error:g.slice(0,1600),deployedRef:p,...l.length?{manualSteps:l}:{}});return}e("info",`\u2713 step ${L+1}/${r.steps.length}: ${O.name}`)}}finally{ch(t.runId)}n("posting");let $=Math.round((Date.now()-o)/1e3),z=null;r.publicUrl?.trim()&&(z=await jw(r.publicUrl.trim()),e(z?"warn":"info",z??`${r.publicUrl.trim()} points at this machine - the deploy is live there`)),t.issueKey!==Cr.BRANCH_DEPLOY_ISSUE_KEY&&await bt(t,`**Allwright deployed \`${t.issueKey}\` to \`${r.name}\`.**
883
885
 
884
886
  `+(z?`> **Live where?** ${z}
885
887
 
@@ -890,54 +892,54 @@ ${i(M.tail).slice(0,500)}`:"")}),l.length&&Th(e,l),n("failed",{error:y.slice(0,1
890
892
  `:"")+(p?`Commit: \`${p.slice(0,10)}\`${r.branch?` on \`${r.branch}\``:""}
891
893
  `:"")+`${r.steps.length} step(s) in ${$}s.`+(t.requestedBy?` Requested by ${t.requestedBy}.`:"")+`
892
894
 
893
- (run \`${t.runId}\`)`);let v=await gw(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`),Hs(t.repoPath,t.issueKey)&&ft(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&&Th(e,l),n("succeeded",{resultSummary:`Deployed to ${r.name}${p?` at ${p.slice(0,10)}`:""} in ${$}s`+(v!==null?` \xB7 ${v} ticket(s) moved to "${r.deployToColumn}"`:"")+(l.length?` \xB7 ${l.length} manual step(s) left for you`:"")+(z?` \xB7 NOT reachable at ${r.publicUrl} yet`:""),deployedRef:p,...l.length?{manualSteps:l}:{}}),e("info",`Deploy to "${r.name}" succeeded in ${$}s`)}async function gw(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}.**
895
+ (run \`${t.runId}\`)`);let v=await Iw(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`),Gs(t.repoPath,t.issueKey)&&mt(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&&jh(e,l),n("succeeded",{resultSummary:`Deployed to ${r.name}${p?` at ${p.slice(0,10)}`:""} in ${$}s`+(v!==null?` \xB7 ${v} ticket(s) moved to "${r.deployToColumn}"`:"")+(l.length?` \xB7 ${l.length} manual step(s) left for you`:"")+(z?` \xB7 NOT reachable at ${r.publicUrl} yet`:""),deployedRef:p,...l.length?{manualSteps:l}:{}}),e("info",`Deploy to "${r.name}" succeeded in ${$}s`)}async function Iw(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}.**
894
896
 
895
897
  `+(n?`Commit: \`${n.slice(0,10)}\`${r.branch?` on \`${r.branch}\``:""}
896
- `:"")+(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 yw(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}\`.**
898
+ `:"")+(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 Ew(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}\`.**
897
899
 
898
900
  ${l}
899
901
 
900
- (run \`${t.runId}\`)`});e("info",`Checking "${n.branch}" is in sync with "${r}" before deploying`);try{await vn(t.repoPath,r),await vn(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 Fa(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=je(be()??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 mr(t.repoPath),c=pt(l);if(!c)throw new Error(`could not parse a GitHub owner/repo from origin "${l}"`);let p=await new Ne(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.
902
+ (run \`${t.runId}\`)`});e("info",`Checking "${n.branch}" is in sync with "${r}" before deploying`);try{await kn(t.repoPath,r),await kn(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 Ha(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=je(we()??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 gr(t.repoPath),c=ft(l);if(!c)throw new Error(`could not parse a GitHub owner/repo from origin "${l}"`);let p=await new Ne(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.
901
903
 
902
- (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 bw(t,e){if(!e.trim())return t;let n=Rr.default.resolve(t,e),r=Rr.default.relative(t,n);if(r.startsWith("..")||Rr.default.isAbsolute(r))throw new Error(`working directory "${e}" is outside the repository checkout`);return n}function ww(t){return new Promise(e=>{let n=(0,Er.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(`
903
- `)}))},c=setTimeout(()=>{o=!0,bo(n.pid,"SIGTERM"),setTimeout(()=>bo(n.pid,"SIGKILL"),1e4).unref()},t.timeoutMs),u=()=>{t.onLine("warn","stop requested - killing this step"),bo(n.pid,"SIGTERM"),setTimeout(()=>bo(n.pid,"SIGKILL"),5e3).unref()};t.signal&&(t.signal.aborted?u():t.signal.addEventListener("abort",u,{once:!0})),El.default.createInterface({input:n.stdout}).on("line",p=>{s(p),t.onLine("info",p)}),El.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 bo(t,e){if(t)try{process.kill(-t,e)}catch{try{process.kill(t,e)}catch{}}}function $l(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 yt(t,e){if(t.issueKey!==Ar.BRANCH_DEPLOY_ISSUE_KEY)try{await t.jira.addComment(t.issueKey,e)}catch(n){g.error(`could not post deploy comment to ${t.issueKey}: ${n}`)}}function Pl(t){return ao(t)!==null}async function Ch(t,e){let n=ao(e);if(!n)return;let{emit:r,setStatus:s}=Cl({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}),lo(e);return}lo(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 Ah(o,r,s)}catch(l){let c=l instanceof Error?l.message:String(l);r("error",`Deploy failed: ${c}`),await yt(o,`**Allwright deploy failed.**
904
+ (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 Aw(t,e){if(!e.trim())return t;let n=Ir.default.resolve(t,e),r=Ir.default.relative(t,n);if(r.startsWith("..")||Ir.default.isAbsolute(r))throw new Error(`working directory "${e}" is outside the repository checkout`);return n}function Cw(t){return new Promise(e=>{let n=(0,Ar.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(`
905
+ `)}))},c=setTimeout(()=>{o=!0,bo(n.pid,"SIGTERM"),setTimeout(()=>bo(n.pid,"SIGKILL"),1e4).unref()},t.timeoutMs),u=()=>{t.onLine("warn","stop requested - killing this step"),bo(n.pid,"SIGTERM"),setTimeout(()=>bo(n.pid,"SIGKILL"),5e3).unref()};t.signal&&(t.signal.aborted?u():t.signal.addEventListener("abort",u,{once:!0})),jl.default.createInterface({input:n.stdout}).on("line",p=>{s(p),t.onLine("info",p)}),jl.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 bo(t,e){if(t)try{process.kill(-t,e)}catch{try{process.kill(t,e)}catch{}}}function Ml(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 bt(t,e){if(t.issueKey!==Cr.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 zl(t){return ao(t)!==null}async function Lh(t,e){let n=ao(e);if(!n)return;let{emit:r,setStatus:s}=Ol({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}),lo(e);return}lo(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 Dh(o,r,s)}catch(l){let c=l instanceof Error?l.message:String(l);r("error",`Deploy failed: ${c}`),await bt(o,`**Allwright deploy failed.**
904
906
 
905
- ${c.slice(0,800)}`),s("failed",{error:c})}}async function $h(t,e){let n=ao(e);if(!n)return;let{emit:r,setStatus:s}=Cl({runId:e,transport:t.transport});lo(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.**
907
+ ${c.slice(0,800)}`),s("failed",{error:c})}}async function Uh(t,e){let n=ao(e);if(!n)return;let{emit:r,setStatus:s}=Ol({runId:e,transport:t.transport});lo(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.**
906
908
 
907
- No deploy step was executed. (run \`${e}\`)`)}catch(o){g.error(`could not post rejection comment to ${n.issueKey}: ${o}`)}s("failed",{error:"deploy rejected by a reviewer"})}var vw=_.object({steps:_.array(Ar.DeployStep).max(50).default([]),requiredSecrets:_.array(_.string()).max(50).default([]),notes:_.string().default("")}),kw=[".ticketpilot/deploy.md","DEPLOY.md","DEPLOYMENT.md","docs/DEPLOY.md","docs/deploy.md","docs/deployment.md"],xh=24e3;function vo(t){for(let e of kw){let n=Rr.default.join(t,e);try{if(!Ir.default.existsSync(n))continue;let r=Ir.default.readFileSync(n,"utf8");if(!r.trim())continue;return{path:e,content:r.length>xh?r.slice(0,xh)+`
909
+ 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 $w=_.object({steps:_.array(Cr.DeployStep).max(50).default([]),requiredSecrets:_.array(_.string()).max(50).default([]),notes:_.string().default("")}),Pw=[".ticketpilot/deploy.md","DEPLOY.md","DEPLOYMENT.md","docs/DEPLOY.md","docs/deploy.md","docs/deployment.md"],Nh=24e3;function vo(t){for(let e of Pw){let n=Ir.default.join(t,e);try{if(!Er.default.existsSync(n))continue;let r=Er.default.readFileSync(n,"utf8");if(!r.trim())continue;return{path:e,content:r.length>Nh?r.slice(0,Nh)+`
908
910
 
909
- [\u2026document truncated\u2026]`:r}}catch{continue}}return null}var Rh=["docker","docker-compose","pm2","systemctl","node","pnpm","npm","yarn","make","python3","pip","rsync","ssh","caddy","nginx"];function Ph(t){return jh("bash",["-lc",`command -v ${JSON.stringify(t)}`]).trim().length>0}function jh(t,e){try{let n=(0,Er.spawnSync)(t,e,{encoding:"utf8",timeout:5e3});return n.status===0?n.stdout??"":""}catch{return""}}async function _w(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 Sw(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 Tw(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?`
911
+ [\u2026document truncated\u2026]`:r}}catch{continue}}return null}var Oh=["docker","docker-compose","pm2","systemctl","node","pnpm","npm","yarn","make","python3","pip","rsync","ssh","caddy","nginx"];function qh(t){return Fh("bash",["-lc",`command -v ${JSON.stringify(t)}`]).trim().length>0}function Fh(t,e){try{let n=(0,Ar.spawnSync)(t,e,{encoding:"utf8",timeout:5e3});return n.status===0?n.stdout??"":""}catch{return""}}async function jw(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 Nw(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 Ow(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?`
910
912
  - absolute paths the document mentions, checked on THIS machine:
911
- ${n.map(s=>` - ${s}: ${Ir.default.existsSync(s)?"EXISTS on this machine":"not found on this machine"}`).join(`
912
- `)}`:""}function xw(){let t=[],e=(n,r)=>{try{let s=(0,Er.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,Er.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&&Ir.default.existsSync(s)&&e(`${n} at ${s}`,s)}return t.length?`
913
+ ${n.map(s=>` - ${s}: ${Er.default.existsSync(s)?"EXISTS on this machine":"not found on this machine"}`).join(`
914
+ `)}`:""}function Mw(){let t=[],e=(n,r)=>{try{let s=(0,Ar.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,Ar.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&&Er.default.existsSync(s)&&e(`${n} at ${s}`,s)}return t.length?`
913
915
  - runtime versions (a MISMATCH between the runner's PATH and the system install is a common root cause):
914
916
  ${t.map(n=>` ${n}`).join(`
915
- `)}`:""}function Nh(t,e,n,r="",s="."){let i=Rh.filter(c=>Ph(c)),o=Rh.filter(c=>!i.includes(c)),l=Object.keys(qt(t,e,n));return`About the machine these steps will run on (gathered by the runner, trust it):
917
+ `)}`:""}function Bh(t,e,n,r="",s="."){let i=Oh.filter(c=>qh(c)),o=Oh.filter(c=>!i.includes(c)),l=Object.keys(Ft(t,e,n));return`About the machine these steps will run on (gathered by the runner, trust it):
916
918
  - available tools: ${i.join(", ")||"(none of the common ones)"}
917
919
  - NOT installed: ${o.join(", ")||"(none missing)"}
918
- - secrets already stored for this environment (names only): ${l.join(", ")||"(none yet)"}`+xw()+Tw(r)+ks(s)}async function Oh(t){let e=[];if(t.publicUrl?.trim()&&await Sw(t.publicUrl.trim(),e),e.push(Ir.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=Rr.default.isAbsolute(t.workdir)?t.workdir:Rr.default.join(t.repoPath,t.workdir);e.push(Ir.default.existsSync(l)?{name:"workdir",ok:!0,detail:l}:{name:"workdir",ok:!1,detail:`does not exist: ${l}`})}if(t.branch){let l=jh("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=qt(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=>!Ph(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 Mh(t){let e=Nh(t.cfg,t.repoName,t.environmentName,"",t.repoPath),n=Vt(Eh.DEPLOY_FIX_PROMPT_TEMPLATE,{envName:t.environmentName,steps:t.steps.map((p,f)=>`${f+1}. [${p.name}]${p.continueOnError?" (continues on error)":""}
920
+ - secrets already stored for this environment (names only): ${l.join(", ")||"(none yet)"}`+Mw()+Ow(r)+_s(s)}async function Kh(t){let e=[];if(t.publicUrl?.trim()&&await Nw(t.publicUrl.trim(),e),e.push(Er.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=Ir.default.isAbsolute(t.workdir)?t.workdir:Ir.default.join(t.repoPath,t.workdir);e.push(Er.default.existsSync(l)?{name:"workdir",ok:!0,detail:l}:{name:"workdir",ok:!1,detail:`does not exist: ${l}`})}if(t.branch){let l=Fh("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=Ft(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=>!qh(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 Hh(t){let e=Bh(t.cfg,t.repoName,t.environmentName,"",t.repoPath),n=Jt(zh.DEPLOY_FIX_PROMPT_TEMPLATE,{envName:t.environmentName,steps:t.steps.map((p,f)=>`${f+1}. [${p.name}]${p.continueOnError?" (continues on error)":""}
919
921
  ${p.run}`).join(`
920
- `),failedStep:t.failedStep||"(unknown)",errorText:t.errorText||"(no error text recorded)",knownCause:(()=>{let p=Tl(t.errorText,{cwd:t.repoPath});return p?`
922
+ `),failedStep:t.failedStep||"(unknown)",errorText:t.errorText||"(no error text recorded)",knownCause:(()=>{let p=Il(t.errorText,{cwd:t.repoPath});return p?`
921
923
 
922
924
  THE RUNNER ALREADY RECOGNISES THIS FAILURE, and told the operator so:
923
925
  - what it means: ${p.cause}
924
926
  - what closes it: ${p.commands.join(" ; ")}
925
927
  - ${p.note}
926
- 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:_h(kh({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,Al.randomUUID)(),onLog:()=>{}});if(!r.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:r.error??"the agent produced no output"};let s=Dh(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?vo(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 zh(t){let e=vo(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=Nh(t.cfg,t.repoName,t.environmentName,e.content,t.repoPath),r=Vt(Ar.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,Al.randomUUID)(),onLog:()=>{}});if(!s.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:s.error??"Claude Code produced no output"};let i=Dh(s.resultText);return i?{ok:!0,...i}:(g.warn(`deploy step suggestion could not be parsed. Claude's raw answer follows:
927
- `+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 Dh(t){for(let e of Rw(t)){let n;try{n=JSON.parse(e)}catch{continue}let r=vw.safeParse(Iw(n));if(r.success&&r.data.steps.length||r.success&&r.data.notes.trim())return r.data}return null}function Rw(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 Iw(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:Ih(o,l),run:o.trim()}:null;if(!o||typeof o!="object")return null;let c=o,u=Il(c.run,c.command,c.cmd,c.script,c.shell);return u?{name:(Il(c.name,c.title,c.description)??Ih(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:Il(e.notes,e.note,e.explanation)??""}}function Il(...t){for(let e of t)if(typeof e=="string"&&e.trim())return e.trim()}function Ih(t,e){return(t.split(`
928
- `)[0].trim()||`Step ${e+1}`).slice(0,120)}xt();mt();gr();function ko(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}}}Wt();Ll();var qh=24*3600*1e3,Ro=14,Aw=Ro*24*3600*1e3,Cw=new Set(["to","on","this","the","a","an","env","environment","please","now","it"]),Io=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)}hasJira(e){return!!Ii(this.cfg,e)}get jiraless(){return Ei(this.cfg)}jiralessLogged=!1;noteJiraless(){this.jiralessLogged||(this.jiralessLogged=!0,g.info("no Jira credentials on this runner - Jira polling is off. That is the deploy-only setup; add them with `allwright jira set-default` and polling starts without a restart."))}jiraWarned=new Set;warnNoJiraForRepo(e){this.jiraWarned.has(e)||(this.jiraWarned.add(e),g.warn(`no Jira credential for repo "${e}" - its rules are not being polled. Add a runner-wide one with \`allwright jira set-default\`, or one for this repo with \`allwright jira set "${e}"\`.`))}routingWarned=new Set;warnRoutingOnce(e,n){this.routingWarned.has(e)||(this.routingWarned.add(e),g.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.`}),g.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;g.info(`config synced: ${e.length} project(s), ${n.length} rule(s) (${i} enabled), ${s.length} environment(s)`),r!==this.paused&&(g.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(),this.jiraless?this.noteJiraless():g.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=fd(n.id,e.role);if(!(r&&Date.now()-new Date(r).getTime()<e.intervalHours*36e5)){this.auditInFlight=!0;try{g.info(`Scheduled ${e.role} audit of ${e.repoName} starting (every ${e.intervalHours}h)`);let s=Me(this.cfg,n,"assist");if("error"in s){g.warn(`Scheduled audit skipped: ${s.error}`);continue}let i=await ms({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;g.info(`Scheduled audit done: ${o} finding(s) - drift visible on the Audits page`)}else g.warn(`Scheduled audit failed: ${i.error}`)}catch(s){g.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)){if(this.jiraless){this.noteJiraless();return}this.jiralessLogged=!1,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){g.warn(`rule "${n.name}": no local path for repo "${r.repoName}" - run: allwright repo add "${r.repoName}" /path/to/checkout`);continue}if(!this.hasJira(r.repoName)){this.warnNoJiraForRepo(r.repoName);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){g.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 z=Date.parse(e.pausedUntil);Number.isFinite(z)&&(this.autopilotPausedUntil=z);return}let n=e.item;if(!n)return;let r=this.rules.find(z=>z.id===n.ruleId&&z.enabled),s=this.projects.find(z=>z.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=ko(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}if(!this.hasJira(o.repoName)){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:`no Jira credential for "${o.repoName}" on this machine - run \`allwright jira set-default\` there (or \`allwright jira set "${o.repoName}"\`)`});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;g.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(z){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:`could not read ${n.issueKey} from Jira: ${z instanceof Error?z.message:String(z)}`});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 w=`${r.id}:${n.issueKey}`;this.inFlight.add(w);let b=this.resolveClaudeProfile(f.runId,f.claudeProfile),k=n.batchId?Nl(n.batchId):null,x=n.continueBranch?null:Ol(k,n.issueKey),A=x?xo(n.batchId,x,n.issueKey):null,$=Dl(x,n.issueKey);this.enqueueForRepo(l.path,async()=>{try{await ho({runId:f.runId,rule:c,project:o,issueKey:n.issueKey,repoPath:l.path,cfg:this.cfg,jira:u,transport:this.transport,claudeConfigDir:b,actorEmail:f.actorEmail,continueBranch:n.continueBranch,...A?{chain:{sessionId:A.sessionId,worktreePath:A.worktreePath}}:{},keepWorktree:$,onChainSession:x?z=>Ml(n.batchId,x,n.issueKey,z):void 0}),x&&!xo(n.batchId,x,x[x.indexOf(n.issueKey)+1]??"")&&x.indexOf(n.issueKey)<x.length-1&&zl(n.batchId,x)}finally{this.inFlight.delete(w)}})}async sweepGitHubApprovals(){let e=Object.values(Zs());if(!e.length)return;let n=be()??this.cfg,r=new Map,s=i=>{let o=je(n,i);if(!o)return null;let l=r.get(o);return l||r.set(o,l=new Ne(o)),l};for(let i of e.slice(0,10)){let o=s(i.repoName);if(!o)continue;if(!this.hasJira(i.repoName)){this.warnNoJiraForRepo(i.repoName);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(b){g.warn(`review check failed for ${i.owner}/${i.repo}#${i.prNumber}: ${b instanceof Error?b.message:b}`);continue}if(!u)continue;let p={cfg:this.cfg,jiraFor:this.jiraFor,transport:this.transport};if(u.merged){g.info(`PR #${i.prNumber} for ${i.issueKey} was merged on GitHub - completing the run`),this.inFlight.add(l);try{await Js(p,i.runId,u.headSha)}finally{this.inFlight.delete(l)}continue}if(u.state==="closed"){g.info(`PR #${i.prNumber} for ${i.issueKey} was closed unmerged on GitHub - failing the run`);let b=this.jiraFor(i.repoName),k=`PR #${i.prNumber} was closed on GitHub without merging`;await b.addComment(i.issueKey,`**Allwright: the pull request for this ticket was closed on GitHub without merging.**
928
+ 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:$h(Ch({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,Nl.randomUUID)(),onLog:()=>{}});if(!r.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:r.error??"the agent produced no output"};let s=Zh(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?vo(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 Gh(t){let e=vo(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=Bh(t.cfg,t.repoName,t.environmentName,e.content,t.repoPath),r=Jt(Cr.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,Nl.randomUUID)(),onLog:()=>{}});if(!s.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:s.error??"Claude Code produced no output"};let i=Zh(s.resultText);return i?{ok:!0,...i}:(y.warn(`deploy step suggestion could not be parsed. Claude's raw answer follows:
929
+ `+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 Zh(t){for(let e of zw(t)){let n;try{n=JSON.parse(e)}catch{continue}let r=$w.safeParse(Dw(n));if(r.success&&r.data.steps.length||r.success&&r.data.notes.trim())return r.data}return null}function zw(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 Dw(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:Mh(o,l),run:o.trim()}:null;if(!o||typeof o!="object")return null;let c=o,u=Pl(c.run,c.command,c.cmd,c.script,c.shell);return u?{name:(Pl(c.name,c.title,c.description)??Mh(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:Pl(e.notes,e.note,e.explanation)??""}}function Pl(...t){for(let e of t)if(typeof e=="string"&&e.trim())return e.trim()}function Mh(t,e){return(t.split(`
930
+ `)[0].trim()||`Step ${e+1}`).slice(0,120)}Rt();gt();yr();function ko(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}}}Vt();Ro();var Jh=24*3600*1e3,Io=14,Uw=Io*24*3600*1e3,qw=new Set(["to","on","this","the","a","an","env","environment","please","now","it"]),Eo=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)}hasJira(e){return!!Ii(this.cfg,e)}get jiraless(){return Ei(this.cfg)}jiralessLogged=!1;noteJiraless(){this.jiralessLogged||(this.jiralessLogged=!0,y.info("no Jira credentials on this runner - Jira polling is off. That is the deploy-only setup; add them with `allwright jira set-default` and polling starts without a restart."))}jiraWarned=new Set;warnNoJiraForRepo(e){this.jiraWarned.has(e)||(this.jiraWarned.add(e),y.warn(`no Jira credential for repo "${e}" - its rules are not being polled. Add a runner-wide one with \`allwright jira set-default\`, or one for this repo with \`allwright jira set "${e}"\`.`))}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(),this.jiraless?this.noteJiraless():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=Sd(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=Me(this.cfg,n,"assist");if("error"in s){y.warn(`Scheduled audit skipped: ${s.error}`);continue}let i=await gs({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)){if(this.jiraless){this.noteJiraless();return}this.jiralessLogged=!1,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}if(!this.hasJira(r.repoName)){this.warnNoJiraForRepo(r.repoName);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 z=Date.parse(e.pausedUntil);Number.isFinite(z)&&(this.autopilotPausedUntil=z);return}let n=e.item;if(!n)return;let r=this.rules.find(z=>z.id===n.ruleId&&z.enabled),s=this.projects.find(z=>z.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=ko(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}if(!this.hasJira(o.repoName)){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:`no Jira credential for "${o.repoName}" on this machine - run \`allwright jira set-default\` there (or \`allwright jira set "${o.repoName}"\`)`});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(z){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:`could not read ${n.issueKey} from Jira: ${z instanceof Error?z.message:String(z)}`});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 w=`${r.id}:${n.issueKey}`;this.inFlight.add(w);let b=this.resolveClaudeProfile(f.runId,f.claudeProfile),k=n.batchId?Ll(n.batchId):null,x=n.continueBranch?null:Ul(k,n.issueKey),A=x?xo(n.batchId,x,n.issueKey):null,$=Bl(x,n.issueKey);this.enqueueForRepo(l.path,async()=>{try{await ho({runId:f.runId,rule:c,project:o,issueKey:n.issueKey,repoPath:l.path,cfg:this.cfg,jira:u,transport:this.transport,claudeConfigDir:b,actorEmail:f.actorEmail,continueBranch:n.continueBranch,...A?{chain:{sessionId:A.sessionId,worktreePath:A.worktreePath}}:{},keepWorktree:$,onChainSession:x?z=>ql(n.batchId,x,n.issueKey,z):void 0}),x&&!xo(n.batchId,x,x[x.indexOf(n.issueKey)+1]??"")&&x.indexOf(n.issueKey)<x.length-1&&Fl(n.batchId,x)}finally{this.inFlight.delete(w)}})}async sweepGitHubApprovals(){let e=Object.values(Ws());if(!e.length)return;let n=we()??this.cfg,r=new Map,s=i=>{let o=je(n,i);if(!o)return null;let l=r.get(o);return l||r.set(o,l=new Ne(o)),l};for(let i of e.slice(0,10)){let o=s(i.repoName);if(!o)continue;if(!this.hasJira(i.repoName)){this.warnNoJiraForRepo(i.repoName);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(b){y.warn(`review check failed for ${i.owner}/${i.repo}#${i.prNumber}: ${b instanceof Error?b.message:b}`);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 Ys(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 b=this.jiraFor(i.repoName),k=`PR #${i.prNumber} was closed on GitHub without merging`;await b.addComment(i.issueKey,`**Allwright: the pull request for this ticket was closed on GitHub without merging.**
929
931
 
930
932
  PR: ${i.prUrl}
931
933
 
932
- 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 b.editLabels(i.issueKey,{add:[i.failedLabel]}).catch(()=>{}),this.transport.send({type:"run.status",runId:i.runId,status:"failed",error:k}),vr(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.
934
+ 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 b.editLabels(i.issueKey,{add:[i.failedLabel]}).catch(()=>{}),this.transport.send({type:"run.status",runId:i.runId,status:"failed",error:k}),kr(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.
933
935
 
934
936
  PR: ${i.prUrl}
935
937
 
936
- 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,gt(i),g.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,gt(i)));let f=c.filter(b=>b.state==="APPROVED"||b.state==="CHANGES_REQUESTED").sort((b,k)=>b.submittedAt.localeCompare(k.submittedAt)),w=f[f.length-1];if(w){if(w.state==="CHANGES_REQUESTED"){i.changesRequestedNotified||(await this.jiraFor(i.repoName).addComment(i.issueKey,`**Allwright: changes were requested on the pull request** (by ${w.user}).
938
+ 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,yt(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,yt(i)));let f=c.filter(b=>b.state==="APPROVED"||b.state==="CHANGES_REQUESTED").sort((b,k)=>b.submittedAt.localeCompare(k.submittedAt)),w=f[f.length-1];if(w){if(w.state==="CHANGES_REQUESTED"){i.changesRequestedNotified||(await this.jiraFor(i.repoName).addComment(i.issueKey,`**Allwright: changes were requested on the pull request** (by ${w.user}).
937
939
 
938
940
  PR: ${i.prUrl}
939
941
 
940
- Reply to the review on GitHub, or reject the run on the Allwright dashboard and re-trigger with new instructions. (run \`${i.runId}\`)`).catch(()=>{}),gt({...i,changesRequestedNotified:!0}),g.info(`changes requested on PR #${i.prNumber} for ${i.issueKey} - ticket notified`));continue}if(w.commitId===u.headSha){g.info(`PR #${i.prNumber} for ${i.issueKey} approved on GitHub by ${w.user} - completing the run`),this.inFlight.add(l);try{await Js(p,i.runId,w.commitId)}catch(b){g.warn(`github-approval completion failed for ${i.runId}: ${b instanceof Error?b.message:b}`)}finally{this.inFlight.delete(l)}}}}}async sweepMergedPRs(){let e=Object.values(oo());if(!e.length)return;let n=be()??this.cfg,r=new Map,s=l=>{let c=je(n,l);if(!c)return null;let u=r.get(c);return u||r.set(c,u=new Ne(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(!this.hasJira(l.repoName)){this.warnNoJiraForRepo(l.repoName);continue}if(Date.now()-new Date(l.createdAt).getTime()>o){g.warn(`merge watch for ${l.issueKey} PR #${l.prNumber} is over 30 days old - dropping`),Gs(l.runId);continue}let u;try{u=await c.getPullRequest(l.owner,l.repo,l.prNumber)}catch(w){g.warn(`merge check failed for ${l.owner}/${l.repo}#${l.prNumber}: ${w instanceof Error?w.message:w}`);continue}if(!u){Gs(l.runId);continue}if(u.state==="open")continue;if(!u.merged){Gs(l.runId);continue}let p=this.jiraFor(l.repoName),f="";if(l.jiraTransitionOnMerge)try{f=await p.transitionByName(l.issueKey,l.jiraTransitionOnMerge)?`
942
+ Reply to the review on GitHub, or reject the run on the Allwright dashboard and re-trigger with new instructions. (run \`${i.runId}\`)`).catch(()=>{}),yt({...i,changesRequestedNotified:!0}),y.info(`changes requested on PR #${i.prNumber} for ${i.issueKey} - ticket notified`));continue}if(w.commitId===u.headSha){y.info(`PR #${i.prNumber} for ${i.issueKey} approved on GitHub by ${w.user} - completing the run`),this.inFlight.add(l);try{await Ys(p,i.runId,w.commitId)}catch(b){y.warn(`github-approval completion failed for ${i.runId}: ${b instanceof Error?b.message:b}`)}finally{this.inFlight.delete(l)}}}}}async sweepMergedPRs(){let e=Object.values(oo());if(!e.length)return;let n=we()??this.cfg,r=new Map,s=l=>{let c=je(n,l);if(!c)return null;let u=r.get(c);return u||r.set(c,u=new Ne(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(!this.hasJira(l.repoName)){this.warnNoJiraForRepo(l.repoName);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`),Zs(l.runId);continue}let u;try{u=await c.getPullRequest(l.owner,l.repo,l.prNumber)}catch(w){y.warn(`merge check failed for ${l.owner}/${l.repo}#${l.prNumber}: ${w instanceof Error?w.message:w}`);continue}if(!u){Zs(l.runId);continue}if(u.state==="open")continue;if(!u.merged){Zs(l.runId);continue}let p=this.jiraFor(l.repoName),f="";if(l.jiraTransitionOnMerge)try{f=await p.transitionByName(l.issueKey,l.jiraTransitionOnMerge)?`
941
943
 
942
944
  Ticket moved to **${l.jiraTransitionOnMerge}**.`:`
943
945
 
@@ -947,19 +949,19 @@ Note: the "${l.jiraTransitionOnMerge}" transition failed: ${w instanceof Error?w
947
949
 
948
950
  PR: ${l.prUrl} (merged at \`${u.headSha.slice(0,10)}\`)${f}
949
951
 
950
- (run \`${l.runId}\`)`)}catch(w){g.warn(`could not post merge comment to ${l.issueKey}: ${w instanceof Error?w.message:w}`);continue}g.info(`PR #${l.prNumber} for ${l.issueKey} merged - ticket updated`),Gs(l.runId)}}async sweepNeedsInput(e){let n;try{n=await this.jiraOf(e).search(`project = "${e.jiraProjectKey}" AND labels = "${Rn.NEEDS_INPUT_LABEL}"`,10)}catch(s){g.warn(`needs-input sweep failed for ${e.jiraProjectKey}: ${s instanceof Error?s.message:s}`);return}if(!n.length)return;let r=kr();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:[Rn.NEEDS_INPUT_LABEL]}).catch(()=>{}),g.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()>Aw){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(k){g.warn(`needs-input check failed for ${s.key}: ${k instanceof Error?k.message:k}`);continue}let u=new Date(l.questionsPostedAt).getTime(),p=o.comments.filter(k=>!Rt(k.body)&&new Date(k.created).getTime()>u);if(!p.length)continue;let f=Ys(p),w=o.attachments;this.inFlight.add(c),g.info(`reply received on ${s.key} - resuming run ${l.runId}`),await this.jiraOf(e).editLabels(s.key,{remove:[Rn.NEEDS_INPUT_LABEL]}).catch(k=>{g.warn(`could not remove needs-input label on ${s.key}: ${k}`)});let b={jiraFor:this.jiraFor,transport:this.transport,cfg:this.cfg};l.kind==="implement"?this.enqueueForRepo(l.baseRepoPath??l.repoPath,async()=>{try{await _l(l,f,w,b)}finally{this.inFlight.delete(c)}}):this.enqueueForRepo(l.repoPath,async()=>{try{await kl(l,f,w,b)}finally{this.inFlight.delete(c)}})}}}async answerPendingInput(e,n,r){let s=Hd(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}`:""}.**
952
+ (run \`${l.runId}\`)`)}catch(w){y.warn(`could not post merge comment to ${l.issueKey}: ${w instanceof Error?w.message:w}`);continue}y.info(`PR #${l.prNumber} for ${l.issueKey} merged - ticket updated`),Zs(l.runId)}}async sweepNeedsInput(e){let n;try{n=await this.jiraOf(e).search(`project = "${e.jiraProjectKey}" AND labels = "${In.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=_r();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:[In.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()>Uw){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(k){y.warn(`needs-input check failed for ${s.key}: ${k instanceof Error?k.message:k}`);continue}let u=new Date(l.questionsPostedAt).getTime(),p=o.comments.filter(k=>!It(k.body)&&new Date(k.created).getTime()>u);if(!p.length)continue;let f=Xs(p),w=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:[In.NEEDS_INPUT_LABEL]}).catch(k=>{y.warn(`could not remove needs-input label on ${s.key}: ${k}`)});let b={jiraFor:this.jiraFor,transport:this.transport,cfg:this.cfg};l.kind==="implement"?this.enqueueForRepo(l.baseRepoPath??l.repoPath,async()=>{try{await xl(l,f,w,b)}finally{this.inFlight.delete(c)}}):this.enqueueForRepo(l.repoPath,async()=>{try{await Tl(l,f,w,b)}finally{this.inFlight.delete(c)}})}}}async answerPendingInput(e,n,r){let s=eh(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}`:""}.**
951
953
 
952
954
  ${n}
953
955
 
954
- This run is continuing from where it left off. (run \`${e}\`)`),await o.editLabels(s.issueKey,{remove:[Rn.NEEDS_INPUT_LABEL]})}catch(f){this.inFlight.delete(i);let w=f instanceof Error?f.message:String(f);return{ok:!1,note:"",error:`could not write the answer to ${s.issueKey}: ${w}`}}g.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 _l(s,c,l,u):await kl(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){g.warn(`${e.issueKey}: needs-input unanswered for over ${Ro}d - abandoning run ${e.runId}`);try{await this.jiraOf(n).addComment(e.issueKey,`**Allwright gave up waiting for an answer.**
956
+ This run is continuing from where it left off. (run \`${e}\`)`),await o.editLabels(s.issueKey,{remove:[In.NEEDS_INPUT_LABEL]})}catch(f){this.inFlight.delete(i);let w=f instanceof Error?f.message:String(f);return{ok:!1,note:"",error:`could not write the answer to ${s.issueKey}: ${w}`}}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 xl(s,c,l,u):await Tl(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 ${Io}d - abandoning run ${e.runId}`);try{await this.jiraOf(n).addComment(e.issueKey,`**Allwright gave up waiting for an answer.**
955
957
 
956
- No reply arrived within ${Ro} 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:[Rn.NEEDS_INPUT_LABEL]})}catch(r){g.warn(`could not post staleness notice for ${e.issueKey}: ${r}`)}e.kind==="implement"&&await Tt(e.baseRepoPath??e.repoPath,e.repoPath).catch(()=>{}),Et(e.runId),this.transport.send({type:"run.status",runId:e.runId,status:"failed",error:`no reply within ${Ro} 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=ko(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"&&g.warn(`claim rejected for ${i.issueKey}: ${p.reason??"unknown"}`);continue}this.inFlight.add(o),g.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 ho({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()-qh;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)||Rt(p.body)||new Date(p.created).getTime()<l||!p.id)continue;let f=`respond:${p.id}`;if(this.inFlight.has(f))continue;let w=ko(n,c.components??[]);if("error"in w){this.warnRoutingOnce(`${e.id}:${c.key}`,`${c.key}: ${w.error}`);continue}let b=w.project,k=b.repoName===n.repoName?r:this.cfg.repos[b.repoName]?.path;if(!k){this.warnRoutingOnce(`${e.id}:${c.key}:path`,`${c.key}: routed to repo "${b.repoName}" but it has no local checkout - run: allwright repo add "${b.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"&&g.warn(`respond claim rejected for ${c.key}: ${x.reason??"unknown"}`);continue}this.inFlight.add(f),g.info(`claimed respond run ${x.runId}: ${c.key} (comment ${p.id})`+(b.repoName!==n.repoName?` (routed \u2192 ${b.repoName})`:"")+(x.claudeProfile?` (claude profile "${x.claudeProfile}")`:""));let A={author:p.author,body:p.body},$=this.resolveClaudeProfile(x.runId,x.claudeProfile);this.enqueueForRepo(k,async()=>{try{await ho({runId:x.runId,rule:e,project:b,issueKey:c.key,repoPath:k,cfg:this.cfg,jira:this.jiraOf(b),transport:this.transport,question:A,claudeConfigDir:$,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){g.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)Rt(p.body)&&(c=Math.max(c??0,new Date(p.created).getTime()));if(c===null||!l.comments.some(p=>!Rt(p.body)&&p.body.toLowerCase().includes(i)&&new Date(p.created).getTime()>c))continue;await this.jiraOf(n).editLabels(o.key,{remove:[r.doneLabel]}),g.info(`revision requested on ${o.key} (new "${r.keyword}" after completion) - done label removed, rule will re-fire`)}catch(l){g.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.**
958
+ No reply arrived within ${Io} 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:[In.NEEDS_INPUT_LABEL]})}catch(r){y.warn(`could not post staleness notice for ${e.issueKey}: ${r}`)}e.kind==="implement"&&await xt(e.baseRepoPath??e.repoPath,e.repoPath).catch(()=>{}),At(e.runId),this.transport.send({type:"run.status",runId:e.runId,status:"failed",error:`no reply within ${Io} 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=ko(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 ho({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()-Jh;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)||It(p.body)||new Date(p.created).getTime()<l||!p.id)continue;let f=`respond:${p.id}`;if(this.inFlight.has(f))continue;let w=ko(n,c.components??[]);if("error"in w){this.warnRoutingOnce(`${e.id}:${c.key}`,`${c.key}: ${w.error}`);continue}let b=w.project,k=b.repoName===n.repoName?r:this.cfg.repos[b.repoName]?.path;if(!k){this.warnRoutingOnce(`${e.id}:${c.key}:path`,`${c.key}: routed to repo "${b.repoName}" but it has no local checkout - run: allwright repo add "${b.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})`+(b.repoName!==n.repoName?` (routed \u2192 ${b.repoName})`:"")+(x.claudeProfile?` (claude profile "${x.claudeProfile}")`:""));let A={author:p.author,body:p.body},$=this.resolveClaudeProfile(x.runId,x.claudeProfile);this.enqueueForRepo(k,async()=>{try{await ho({runId:x.runId,rule:e,project:b,issueKey:c.key,repoPath:k,cfg:this.cfg,jira:this.jiraOf(b),transport:this.transport,question:A,claudeConfigDir:$,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)It(p.body)&&(c=Math.max(c??0,new Date(p.created).getTime()));if(c===null||!l.comments.some(p=>!It(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.**
957
959
 
958
960
  ${l.reason}`+(i.requestedByAccountId?`
959
961
 
960
962
  Jira account id: \`${i.requestedByAccountId}\``:"")+`
961
963
 
962
- (run \`${l.runId}\`)`).catch(u=>g.warn(`could not post refusal to ${i.issueKey}: ${u}`)),g.warn(`deploy refused for ${i.issueKey}: ${l.reason}`)):l.reason&&g.warn(`deploy claim rejected for ${i.issueKey}: ${l.reason}`);continue}let c=l.environment;this.inFlight.add(o),g.info(`claimed deploy ${l.runId}: ${i.issueKey} \u2192 ${c.name}`),this.enqueue(this.envQueues,c.id,async()=>{try{await wo({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()-qh,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 w=await this.jiraOf(n).getIssue(f.key);if(!(s.requireStatus&&w.status.toLowerCase()!==s.requireStatus.toLowerCase()))for(let b of w.comments){if(!b.body.toLowerCase().includes(o)||Rt(b.body)||new Date(b.created).getTime()<l||!b.id)continue;let k=s.envSelection==="fixed"?u:$w(b.body,r.keyword,c);p.push({issueKey:f.key,summary:f.summary,environmentName:k,requestedByAccountId:b.authorAccountId??void 0,requestedByDisplayName:b.author,dedupKey:`deploy:comment:${b.id}`,fingerprint:`comment "${r.keyword}" by ${b.author} at ${b.created}`+(k?` \u2192 ${k}`:"")})}}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}", "${Rn.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}", "${Rn.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)&&!Rt(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=>{g.error(`run crashed: ${o instanceof Error?o.stack:o}`)});e.set(n,i)}};function $w(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(!Cw.has(o.toLowerCase()))return o;return""}var Fh=I(require("node:fs"),1),Bh=I(require("node:path"),1),Ul=require("node:crypto");xt();var Pw=`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.
964
+ (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 wo({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()-Jh,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 w=await this.jiraOf(n).getIssue(f.key);if(!(s.requireStatus&&w.status.toLowerCase()!==s.requireStatus.toLowerCase()))for(let b of w.comments){if(!b.body.toLowerCase().includes(o)||It(b.body)||new Date(b.created).getTime()<l||!b.id)continue;let k=s.envSelection==="fixed"?u:Fw(b.body,r.keyword,c);p.push({issueKey:f.key,summary:f.summary,environmentName:k,requestedByAccountId:b.authorAccountId??void 0,requestedByDisplayName:b.author,dedupKey:`deploy:comment:${b.id}`,fingerprint:`comment "${r.keyword}" by ${b.author} at ${b.created}`+(k?` \u2192 ${k}`:"")})}}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}", "${In.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}", "${In.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)&&!It(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 Fw(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(!qw.has(o.toLowerCase()))return o;return""}var Yh=I(require("node:fs"),1),Xh=I(require("node:path"),1),Hl=require("node:crypto");Rt();var Bw=`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.
963
965
 
964
966
  Rules:
965
967
  - Edit ONLY the conflicted files listed below. Do not touch anything else, do not refactor, do not "improve" surrounding code.
@@ -968,10 +970,10 @@ Rules:
968
970
  - When you are done, every listed file must contain no conflict markers and must be syntactically valid.
969
971
 
970
972
  Conflicted files:
971
- `;async function Kh(t){let{cfg:e,repoPath:n,branch:r,baseBranch:s,issueKey:i,onLog:o}=t,l=Bh.default.join(Gt(),`conflict-${(0,Ul.randomUUID)().slice(0,8)}`),c=!1;try{o("info",`Preparing a worktree for ${r} to merge ${s} into it`),await Bs(n,l,r),c=!0;let u=await Da(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 k=u.conflicts;o("info",`git merged everything except ${k.length} file(s): ${k.slice(0,20).join(", ")}`+(k.length>20?", \u2026":""));let x=Ge(t.agentId);if(!x)return await _n(l),{ok:!1,note:`no adapter for agent "${t.agentId}" on this runner`};let A=xn(t.agentId,"edit_no_shell");if(A)return await _n(l),{ok:!1,note:`${A} Resolve the conflicts yourself on branch ${r}, or use Rebuild on current base.`};o("info",`Asking ${x.displayName} to resolve only those files`);let $=-1,z=setInterval(()=>{Ua(l,k).then(O=>{let Y=k.filter(M=>!O.includes(M));Y.length!==$&&($=Y.length,o("info",`Conflict progress: ${Y.length}/${k.length} resolved`+(Y.length?` \xB7 clean: ${Y.join(", ")}`:"")+(O.length?` \xB7 still conflicted: ${O.join(", ")}`:"")))}).catch(()=>{})},12e3),v=await Vs(x,{repoPath:l,prompt:Pw+k.map(O=>`- ${O}`).join(`
972
- `),timeoutSeconds:t.timeoutSeconds,bin:Be(e,t.agentId),configDir:t.configDir,mode:"edit_no_shell",sessionId:(0,Ul.randomUUID)(),onLog:(O,Y)=>o(O,Y)},(O,Y)=>o(O==="warn"?"warn":O,Y));if(clearInterval(z),p={costUsd:v.costUsd,inputTokens:v.inputTokens,outputTokens:v.outputTokens},!v.ok)return await _n(l),{ok:!1,...p,note:`The agent could not do the resolution: ${v.error??"it produced no output"}. Nothing was changed - the merge was rolled back. Fix that first, then Resolve again.`};f=!0;let L=await Wi(l);if(L.length)return await _n(l),{ok:!1,...p,note:`The agent left conflict markers in ${L.slice(0,5).join(", ")}, so nothing was pushed and the merge was rolled back. Resolve it by hand on ${r}, or use Rebuild on current base to redo the ticket against today's base.`};await La(l,`${i}: merge ${s}, conflicts resolved by the agent
973
+ `;async function Qh(t){let{cfg:e,repoPath:n,branch:r,baseBranch:s,issueKey:i,onLog:o}=t,l=Xh.default.join(Zt(),`conflict-${(0,Hl.randomUUID)().slice(0,8)}`),c=!1;try{o("info",`Preparing a worktree for ${r} to merge ${s} into it`),await Ks(n,l,r),c=!0;let u=await qa(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 k=u.conflicts;o("info",`git merged everything except ${k.length} file(s): ${k.slice(0,20).join(", ")}`+(k.length>20?", \u2026":""));let x=Ge(t.agentId);if(!x)return await Sn(l),{ok:!1,note:`no adapter for agent "${t.agentId}" on this runner`};let A=Rn(t.agentId,"edit_no_shell");if(A)return await Sn(l),{ok:!1,note:`${A} Resolve the conflicts yourself on branch ${r}, or use Rebuild on current base.`};o("info",`Asking ${x.displayName} to resolve only those files`);let $=-1,z=setInterval(()=>{Ba(l,k).then(O=>{let Y=k.filter(M=>!O.includes(M));Y.length!==$&&($=Y.length,o("info",`Conflict progress: ${Y.length}/${k.length} resolved`+(Y.length?` \xB7 clean: ${Y.join(", ")}`:"")+(O.length?` \xB7 still conflicted: ${O.join(", ")}`:"")))}).catch(()=>{})},12e3),v=await Js(x,{repoPath:l,prompt:Bw+k.map(O=>`- ${O}`).join(`
974
+ `),timeoutSeconds:t.timeoutSeconds,bin:Be(e,t.agentId),configDir:t.configDir,mode:"edit_no_shell",sessionId:(0,Hl.randomUUID)(),onLog:(O,Y)=>o(O,Y)},(O,Y)=>o(O==="warn"?"warn":O,Y));if(clearInterval(z),p={costUsd:v.costUsd,inputTokens:v.inputTokens,outputTokens:v.outputTokens},!v.ok)return await Sn(l),{ok:!1,...p,note:`The agent could not do the resolution: ${v.error??"it produced no output"}. Nothing was changed - the merge was rolled back. Fix that first, then Resolve again.`};f=!0;let L=await Wi(l);if(L.length)return await Sn(l),{ok:!1,...p,note:`The agent left conflict markers in ${L.slice(0,5).join(", ")}, so nothing was pushed and the merge was rolled back. Resolve it by hand on ${r}, or use Rebuild on current base to redo the ticket against today's base.`};await Fa(l,`${i}: merge ${s}, conflicts resolved by the agent
973
975
 
974
- Resolved via Allwright`)}let w=await kn(l,s);if(!w.ok){let k=w.forbidden.length?`the merged result touches protected paths (${w.forbidden.slice(0,5).join(", ")})`:`the merged result is too large (${w.files} files, ${w.insertions+w.deletions} lines; limits ${bn}/${wn})`;return await _n(l),{ok:!1,...p,note:`Nothing was pushed: ${k}. The merge was rolled back.`}}await fr(l,r);let b=await it(l);return o("info",`Pushed the merge to ${r} (${b.slice(0,7)})`),{ok:!0,...p,freeOfCharge:!f,headSha:b,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 _n(l).catch(()=>{}),{ok:!1,note:`Could not resolve the conflict: ${u instanceof Error?u.message.slice(0,300):String(u)}`}}finally{c&&(await Tt(n,l).catch(()=>{}),Fh.default.rmSync(l,{recursive:!0,force:!0}))}}var ql=I(require("node:fs"),1),Hh=I(require("node:path"),1),Fl=require("node:crypto");xt();function jw(t,e){let n=e.map(r=>`$ ${r.command} (exit ${r.exitCode})
976
+ Resolved via Allwright`)}let w=await _n(l,s);if(!w.ok){let k=w.forbidden.length?`the merged result touches protected paths (${w.forbidden.slice(0,5).join(", ")})`:`the merged result is too large (${w.files} files, ${w.insertions+w.deletions} lines; limits ${wn}/${vn})`;return await Sn(l),{ok:!1,...p,note:`Nothing was pushed: ${k}. The merge was rolled back.`}}await mr(l,r);let b=await it(l);return o("info",`Pushed the merge to ${r} (${b.slice(0,7)})`),{ok:!0,...p,freeOfCharge:!f,headSha:b,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 Sn(l).catch(()=>{}),{ok:!1,note:`Could not resolve the conflict: ${u instanceof Error?u.message.slice(0,300):String(u)}`}}finally{c&&(await xt(n,l).catch(()=>{}),Yh.default.rmSync(l,{recursive:!0,force:!0}))}}var Gl=I(require("node:fs"),1),ep=I(require("node:path"),1),Zl=require("node:crypto");Rt();function Kw(t,e){let n=e.map(r=>`$ ${r.command} (exit ${r.exitCode})
975
977
  ${r.tail.slice(-2e3)}`).join(`
976
978
 
977
979
  `);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:
@@ -984,17 +986,17 @@ Your ONLY job is to make these commands pass, with the smallest change possible.
984
986
  - 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.
985
987
  - Do not ask questions; if you cannot fix something safely, say what you found and stop.
986
988
  - You have no shell; the runner re-runs every documented command after you finish.
987
- End with one short paragraph stating exactly what you changed, or why you changed nothing.`}async function Gh(t){let{cfg:e,repoPath:n,branch:r,baseBranch:s,issueKey:i,failedTests:o,onLog:l}=t,c=Hh.default.join(Gt(),`testfix-${(0,Fl.randomUUID)().slice(0,8)}`),u=!1;try{let p=Ge(t.agentId);if(!p)return{ok:!1,note:`no adapter for agent "${t.agentId}" on this runner`};let f=xn(t.agentId,"edit_no_shell");if(f)return{ok:!1,note:f};l("info",`Preparing a worktree on ${r} for the test fix`),await vn(n,r),await Bs(n,c,r),u=!0,await cs(c,`origin/${r}`);let w=await it(c);l("info",`Asking ${p.displayName} to fix ${o.length} failing test command(s) - narrow prompt, failure output included, no re-exploration`);let b=await Vs(p,{repoPath:c,prompt:jw(i,o),timeoutSeconds:t.timeoutSeconds,bin:Be(e,t.agentId),configDir:t.configDir,mode:"edit_no_shell",maxTurns:60,sessionId:(0,Fl.randomUUID)(),onLog:(M,d)=>l(M,d)},(M,d)=>l(M==="warn"?"warn":M,d)),k={costUsd:b.costUsd,inputTokens:b.inputTokens,outputTokens:b.outputTokens};if(!b.ok)return{ok:!1,...k,note:`The fix agent could not run: ${b.error??"it produced no output"}. Nothing was changed or pushed.`};let x=await ls(c);for(let M of x.refused)l("warn",`${Ht} entry refused: ${M}`);let A=!0;try{await pr(c,`${i}: fix failing TEST.md commands
989
+ End with one short paragraph stating exactly what you changed, or why you changed nothing.`}async function tp(t){let{cfg:e,repoPath:n,branch:r,baseBranch:s,issueKey:i,failedTests:o,onLog:l}=t,c=ep.default.join(Zt(),`testfix-${(0,Zl.randomUUID)().slice(0,8)}`),u=!1;try{let p=Ge(t.agentId);if(!p)return{ok:!1,note:`no adapter for agent "${t.agentId}" on this runner`};let f=Rn(t.agentId,"edit_no_shell");if(f)return{ok:!1,note:f};l("info",`Preparing a worktree on ${r} for the test fix`),await kn(n,r),await Ks(n,c,r),u=!0,await us(c,`origin/${r}`);let w=await it(c);l("info",`Asking ${p.displayName} to fix ${o.length} failing test command(s) - narrow prompt, failure output included, no re-exploration`);let b=await Js(p,{repoPath:c,prompt:Kw(i,o),timeoutSeconds:t.timeoutSeconds,bin:Be(e,t.agentId),configDir:t.configDir,mode:"edit_no_shell",maxTurns:60,sessionId:(0,Zl.randomUUID)(),onLog:(M,d)=>l(M,d)},(M,d)=>l(M==="warn"?"warn":M,d)),k={costUsd:b.costUsd,inputTokens:b.inputTokens,outputTokens:b.outputTokens};if(!b.ok)return{ok:!1,...k,note:`The fix agent could not run: ${b.error??"it produced no output"}. Nothing was changed or pushed.`};let x=await cs(c);for(let M of x.refused)l("warn",`${Gt} entry refused: ${M}`);let A=!0;try{await fr(c,`${i}: fix failing TEST.md commands
988
990
 
989
- Allwright test-fix run`)}catch{A=!1}if(!A){let M=`The agent changed nothing - its own conclusion: ${b.resultText.trim().slice(0,400)||"(no explanation given)"}`;return l("info",M),{ok:!0,...k,remaining:o,note:M}}let $=await kn(c,s);if(!$.ok){await cs(c,w);let M=$.forbidden.length?`the fixed result touches protected paths (${$.forbidden.slice(0,5).join(", ")})`:`the fixed result is too large (${$.files} files, ${$.insertions+$.deletions} lines; limits ${bn}/${wn})`;return{ok:!1,...k,note:`Nothing was pushed: ${M}. The fix commit was discarded; the PR is unchanged.`}}let z=o,v,L,O=ps(c);if(O){let M=fs(ql.default.readFileSync(O,"utf8"));if(M.length){l("info",`Re-running ${M.length} documented test command(s)`);let d=await yr(c,M,{perCommandTimeoutMs:15*6e4});for(let m of d)l(m.exitCode===0?"info":"warn",`${m.exitCode===0?"PASS":"FAIL"} ${m.command} (exit ${m.exitCode})`+(m.exitCode===0?"":`
990
- ${m.tail.slice(-1500)}`));z=d.filter(m=>m.exitCode!==0).slice(0,20).map(m=>({command:m.command.slice(0,500),exitCode:m.exitCode,tail:m.tail.slice(-4e3)})),L=d.length,v=d.length-z.length}}await fr(c,r);let Y=await it(c);return l("info",`Pushed the fix to ${r} (${Y.slice(0,7)})`),{ok:!0,...k,headSha:Y,remaining:z,testsPassed:v,testsTotal:L,note:z.length?`The fix was pushed, but ${z.length} command(s) still fail - output is in the run log. The PR is the same one; review the new commit.`:"All documented test commands pass now. The PR is the same one - review the fix commit, then approve."}}catch(p){return{ok:!1,note:`Could not fix the tests: ${p instanceof Error?p.message.slice(0,300):String(p)}`}}finally{u&&(await Tt(n,c).catch(()=>{}),ql.default.rmSync(c,{recursive:!0,force:!0}))}}mt();var Cr=I(require("node:fs"),1),Wh=I(require("node:path"),1);Jr();Ce();var Nw=_.object({role:_.enum(["user","agent"]),text:_.string(),steps:_.array(_.string()).default([]),files:_.array(_.string()).default([])}),Ow=_.object({sessionId:_.string(),projectId:_.string(),title:_.string().default(""),updatedAt:_.string(),messages:_.array(Nw).default([])}),Mw=_.record(Ow),zw=10,Dw=200,Zh=2e4,Lw=30,Uw=2e3,qw=8,Fw=255;function Vh(){return Wh.default.join(oe(),"chat-sessions.json")}function Bl(){let t=Vh();if(!Cr.default.existsSync(t))return{};try{return Mw.parse(JSON.parse(Cr.default.readFileSync(t,"utf8")))}catch{return{}}}function Bw(t){Cr.default.mkdirSync(oe(),{recursive:!0,mode:448});let e=Vh(),n=e+".tmp";Cr.default.writeFileSync(n,JSON.stringify(t,null,2)+`
991
- `,{mode:384}),Cr.default.renameSync(n,e),Cr.default.chmodSync(e,384)}function Jh(t,e,n,r,s=[],i=[]){let o=Bl(),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,Zh),steps:[],files:i.slice(0,qw).map(p=>p.slice(0,Fw))},{role:"agent",text:r.slice(0,Zh),steps:s.slice(0,Lw).map(p=>p.slice(0,Uw)),files:[]}),c.messages=c.messages.slice(-Dw),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(zw))delete o[p.sessionId];Bw(o)}function Yh(t){return Object.values(Bl()).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 ei(t){return Bl()[t]??null}Wt();var Xh=36,Qh=60;function ep(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 Kw=`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:
991
+ Allwright test-fix run`)}catch{A=!1}if(!A){let M=`The agent changed nothing - its own conclusion: ${b.resultText.trim().slice(0,400)||"(no explanation given)"}`;return l("info",M),{ok:!0,...k,remaining:o,note:M}}let $=await _n(c,s);if(!$.ok){await us(c,w);let M=$.forbidden.length?`the fixed result touches protected paths (${$.forbidden.slice(0,5).join(", ")})`:`the fixed result is too large (${$.files} files, ${$.insertions+$.deletions} lines; limits ${wn}/${vn})`;return{ok:!1,...k,note:`Nothing was pushed: ${M}. The fix commit was discarded; the PR is unchanged.`}}let z=o,v,L,O=fs(c);if(O){let M=ms(Gl.default.readFileSync(O,"utf8"));if(M.length){l("info",`Re-running ${M.length} documented test command(s)`);let d=await br(c,M,{perCommandTimeoutMs:15*6e4});for(let m of d)l(m.exitCode===0?"info":"warn",`${m.exitCode===0?"PASS":"FAIL"} ${m.command} (exit ${m.exitCode})`+(m.exitCode===0?"":`
992
+ ${m.tail.slice(-1500)}`));z=d.filter(m=>m.exitCode!==0).slice(0,20).map(m=>({command:m.command.slice(0,500),exitCode:m.exitCode,tail:m.tail.slice(-4e3)})),L=d.length,v=d.length-z.length}}await mr(c,r);let Y=await it(c);return l("info",`Pushed the fix to ${r} (${Y.slice(0,7)})`),{ok:!0,...k,headSha:Y,remaining:z,testsPassed:v,testsTotal:L,note:z.length?`The fix was pushed, but ${z.length} command(s) still fail - output is in the run log. The PR is the same one; review the new commit.`:"All documented test commands pass now. The PR is the same one - review the fix commit, then approve."}}catch(p){return{ok:!1,note:`Could not fix the tests: ${p instanceof Error?p.message.slice(0,300):String(p)}`}}finally{u&&(await xt(n,c).catch(()=>{}),Gl.default.rmSync(c,{recursive:!0,force:!0}))}}gt();var $r=I(require("node:fs"),1),rp=I(require("node:path"),1);Yr();Ce();var Hw=_.object({role:_.enum(["user","agent"]),text:_.string(),steps:_.array(_.string()).default([]),files:_.array(_.string()).default([])}),Gw=_.object({sessionId:_.string(),projectId:_.string(),title:_.string().default(""),updatedAt:_.string(),messages:_.array(Hw).default([])}),Zw=_.record(Gw),Ww=10,Vw=200,np=2e4,Jw=30,Yw=2e3,Xw=8,Qw=255;function sp(){return rp.default.join(oe(),"chat-sessions.json")}function Wl(){let t=sp();if(!$r.default.existsSync(t))return{};try{return Zw.parse(JSON.parse($r.default.readFileSync(t,"utf8")))}catch{return{}}}function ev(t){$r.default.mkdirSync(oe(),{recursive:!0,mode:448});let e=sp(),n=e+".tmp";$r.default.writeFileSync(n,JSON.stringify(t,null,2)+`
993
+ `,{mode:384}),$r.default.renameSync(n,e),$r.default.chmodSync(e,384)}function ip(t,e,n,r,s=[],i=[]){let o=Wl(),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,np),steps:[],files:i.slice(0,Xw).map(p=>p.slice(0,Qw))},{role:"agent",text:r.slice(0,np),steps:s.slice(0,Jw).map(p=>p.slice(0,Yw)),files:[]}),c.messages=c.messages.slice(-Vw),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(Ww))delete o[p.sessionId];ev(o)}function op(t){return Object.values(Wl()).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 ti(t){return Wl()[t]??null}Vt();var ap=36,lp=60;function cp(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 tv=`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:
992
994
  Goal: what the user is trying to achieve.
993
995
  Decided: choices already made, including ones you talked them out of - each as one line.
994
996
  Constraints: rules, preferences and corrections the user gave you.
995
997
  Repo facts: what you learned about this codebase that is worth not re-reading.
996
998
  Open: what is still unresolved right now.
997
- Write plain statements, no preamble, no closing offer of help. Do NOT emit a ticket block.`;async function tp(t,e,n){if(!ei(e))return null;let s=Me(n,t.project,"chat");if("error"in s)return null;try{let i=await s.adapter.run({repoPath:t.repoPath,prompt:Kw,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 g.warn(`chat compaction failed: ${i instanceof Error?i.message:i}`),null}}var np=`
999
+ Write plain statements, no preamble, no closing offer of help. Do NOT emit a ticket block.`;async function up(t,e,n){if(!ti(e))return null;let s=Me(n,t.project,"chat");if("error"in s)return null;try{let i=await s.adapter.run({repoPath:t.repoPath,prompt:tv,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 dp=`
998
1000
 
999
1001
  TWO OPTIONAL BLOCKS, for the dashboard's benefit. Never mention them in your prose.
1000
1002
  1. When you ASK the user something and the sensible answers are countable, end with:
@@ -1007,12 +1009,12 @@ TWO OPTIONAL BLOCKS, for the dashboard's benefit. Never mention them in your pro
1007
1009
  ["\u2026", "\u2026"]
1008
1010
  \`\`\`
1009
1011
  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.
1010
- Never emit both blocks in one reply, and never let either replace the actual answer.`;var $r=I(require("node:fs"),1),ot=I(require("node:path"),1),Kl=300,Hw=4,rp=512*1024,Gw=new Set([".git","node_modules","dist","build","out",".next","vendor","coverage",".venv","venv","__pycache__",".turbo",".cache"]),sp=/\.mdx?$/i;function ip(t){let e=ot.default.resolve(t),n=[],r=(s,i)=>{if(i>Hw||n.length>=Kl)return;let o;try{o=$r.default.readdirSync(s,{withFileTypes:!0})}catch{return}for(let l of o){if(n.length>=Kl)return;if(!l.isFile()||!sp.test(l.name))continue;let c=ot.default.join(s,l.name);try{let u=$r.default.statSync(c);n.push({path:ot.default.relative(e,c).split(ot.default.sep).join("/"),sizeBytes:u.size,updatedAt:u.mtime.toISOString()})}catch{}}for(let l of o){if(n.length>=Kl)return;!l.isDirectory()||l.isSymbolicLink()||Gw.has(l.name)||l.name.startsWith(".")||r(ot.default.join(s,l.name),i+1)}};return r(e,0),n}function op(t,e){let n=ot.default.resolve(t);if(!sp.test(e))return{ok:!1,error:"only markdown files can be opened here"};let r=ot.default.resolve(n,e);if(r!==n&&!r.startsWith(n+ot.default.sep))return{ok:!1,error:"that path is outside the project checkout"};let s;try{s=$r.default.realpathSync(r)}catch{return{ok:!1,error:"file not found in this checkout"}}let i=(()=>{try{return $r.default.realpathSync(n)}catch{return n}})();if(s!==i&&!s.startsWith(i+ot.default.sep))return{ok:!1,error:"that path links outside the project checkout"};let o;try{o=$r.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=$r.default.readFileSync(s,"utf8"),c=Buffer.byteLength(l,"utf8")>rp;return{ok:!0,path:ot.default.relative(i,s).split(ot.default.sep).join("/"),content:c?l.slice(0,rp):l,truncated:c}}catch(l){return{ok:!1,error:l instanceof Error?l.message:"could not read the file"}}}var Je=I(ke(),1);var Eo=I(require("node:fs"),1),ap=I(require("node:path"),1);Jr();Ce();var Zw=_.object({id:_.string(),name:_.string().default(""),jiraProjectKey:_.string().default(""),repoName:_.string().default(""),jiraSiteUrl:_.string().default("")}),Ww=_.array(Zw);function lp(){return ap.default.join(oe(),"synced-projects.json")}function cp(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(oe(),{recursive:!0}),Eo.default.writeFileSync(lp(),JSON.stringify(e,null,2),{mode:384})}catch{}}function Vw(){try{let t=Ww.safeParse(JSON.parse(Eo.default.readFileSync(lp(),"utf8")));return t.success?t.data:[]}catch{return[]}}function up(t){return Vw().find(e=>e.repoName===t)??null}var Gl=I(require("node:fs"),1),Pr=I(require("node:path"),1),dp=require("node:child_process"),jr=I(ke(),1);Ce();var Jw=15e4,Hl=(t,e,n,r="")=>({ok:!1,file:t,checks:[e],output:r,error:n});function Yw(t){let e=Pr.default.join(t,"node_modules",".bin","prisma");return Gl.default.existsSync(e)?{bin:e,prefix:[]}:{bin:"npx",prefix:["--yes","prisma"]}}function Xw(t,e){if(!(0,jr.isSelfMigrationFilename)(e))return null;let n=Pr.default.join(t,jr.SELF_MIGRATION_DIR),r=Pr.default.resolve(n,e),s=Pr.default.relative(n,r);return s!==e||s.startsWith("..")||Pr.default.isAbsolute(s)?null:r}async function hp(t){let{file:e}=t,n=Xw(t.repoPath,e);if(!n)return Hl(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 Hl(e,{name:"file",ok:!1,detail:`${jr.SELF_MIGRATION_DIR}/${e} does not exist in this checkout`,fix:[`cd ${t.repoPath} && git pull`]},`${jr.SELF_MIGRATION_DIR}/${e} is not in this checkout - it may be newer than the code here`);let s=qt(t.cfg,t.repoName,t.environmentName)[t.urlSecret]?.trim();if(!s)return Hl(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=Pr.default.join(t.repoPath,"apps","api"),{bin:o,prefix:l}=Yw(i),c=$l([s]),u=await Qw(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:`${jr.SELF_MIGRATION_DIR}/${e} applied`,fix:[]}],output:p,error:""}}function Qw(t,e,n){return new Promise(r=>{(0,dp.execFile)(t,e,{cwd:n,timeout:Jw,maxBuffer:4*1024*1024,encoding:"utf8"},(s,i,o)=>{let l=[i,o].filter(Boolean).join(`
1011
- `).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 vk=I(lf(),1),kk=I(zo(),1),_k=I(Ts(),1),Sk=I(rc(),1),Tk=I(oc(),1),xk=I(hc(),1),yf=I(qo(),1),Rk=I(gf(),1);var fc=yf.default;var li=I(require("node:crypto"),1),$t=I(ke(),1);Wt();function Ik(t){let e=t&&typeof t=="object"&&"name"in t?String(t.name):null;return e?`"${e}"`:"(unnamed)"}function mc(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 Ek(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=$t.ProjectConfig.safeParse(l);c.success?r.push(c.data):mc(n,"project","",c.error.issues[0]?.message??"invalid shape")}let s=[];for(let l of Array.isArray(e.rules)?e.rules:[]){let c=$t.RuleConfig.safeParse(l);c.success?s.push(c.data):mc(n,"rule",Ik(l),c.error.issues[0]?.message??"invalid shape")}let i=[];for(let l of Array.isArray(e.environments)?e.environments:[]){let c=$t.EnvironmentConfig.safeParse(l);c.success?i.push(c.data):mc(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 Ak=2e4,Ck=6e4,$k=5e3,Bo=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===fc.OPEN}connect(){if(this.closed)return;g.info(`connecting to control plane at ${this.wsUrl}`);let e=new fc(this.wsUrl,{headers:{authorization:`Bearer ${this.runnerToken}`}});this.ws=e,e.on("open",()=>{this.backoffMs=1e3,this.sendNow({type:"hello",protocolVersion:$t.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()})},Ak)}),e.on("message",n=>{let r;try{r=JSON.parse(n.toString())}catch(i){g.warn(`ignoring malformed server message (bad JSON): ${i}`);return}let s;try{s=(0,$t.parseServerMsg)(r)}catch(i){let o=Ek(r);if(!o){g.warn(`ignoring malformed server message: ${i}`);return}for(let l of o.warnings)g.warn(l);g.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)g.error("control plane rejected this runner version (protocol mismatch). Update with: npm install -g @ticketpilot/runner");else if(n===4003){g.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);g.warn(`disconnected (code ${n}); reconnecting in ${Math.round(s/1e3)}s`),setTimeout(()=>this.connect(),s),this.backoffMs=Math.min(this.backoffMs*2,Ck)}),e.on("error",n=>{g.warn(`websocket error: ${n.message}`)})}handle(e){if(e.type==="hello.ack"){this.bootAnnounced=!0,g.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.explain")return this.events.onAuditExplain(e);if(e.type==="chat.cancel")return this.events.onChatCancel(e);if(e.type==="autopilot.plan")return this.events.onAutopilotPlan(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==="runner.uninstall")return this.events.onRunnerUninstall(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>=$k){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=li.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=li.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:li.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=li.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"}))})}sendAutopilotPlanResult(e,n){this.send({type:"autopilot.plan.result",requestId:e,ok:n.ok,error:n.error??"",order:n.order??[],chains:n.chains??[],dependencies:n.dependencies??[],reasoning:n.reasoning??""})}sendAuditExplainResult(e,n){this.send({type:"audit.explain.result",requestId:e,ok:n.ok,error:n.error??"",explanation:n.explanation??""})}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})}sendRunnerUninstallResult(e,n){this.send({type:"runner.uninstall.result",requestId:e,ok:n.ok,error:n.error,note:n.note??"",serviceRemoved:n.serviceRemoved??!1,configRemoved:n.configRemoved??!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 Ko=I(require("node:fs"),1),Cs=I(require("node:path"),1),gc=require("node:child_process"),Pk=/\.mdx?$/i,bf=6,jk=/^[\w.\- ()]+$/;function Nk(t,e){let n=e.trim().replace(/\\/g,"/").replace(/^\.\//,"");if(!n)return{ok:!1,error:"empty path"};if(Cs.default.isAbsolute(n))return{ok:!1,error:"path must be repo-relative"};if(!Pk.test(n))return{ok:!1,error:"only markdown files (.md) can be saved"};let r=n.split("/");if(r.length>bf)return{ok:!1,error:`path deeper than ${bf} levels`};for(let o of r)if(o==="."||o===".."||!jk.test(o))return{ok:!1,error:`invalid path segment "${o}"`};if(r[0]===".git")return{ok:!1,error:"cannot write under .git"};let s=Cs.default.resolve(t),i=Cs.default.resolve(s,n);return i!==s&&!i.startsWith(s+Cs.default.sep)?{ok:!1,error:"path escapes the checkout"}:{ok:!0,abs:i,rel:n}}async function yc(t){let e=Nk(t.repoPath,t.relPath);if(!e.ok)return{ok:!1,error:e.error};if(Ko.default.existsSync(e.abs)&&!t.overwrite)return{ok:!1,error:`${e.rel} already exists in this checkout`};Ko.default.mkdirSync(Cs.default.dirname(e.abs),{recursive:!0}),Ko.default.writeFileSync(e.abs,t.content.endsWith(`
1012
+ Never emit both blocks in one reply, and never let either replace the actual answer.`;var Pr=I(require("node:fs"),1),ot=I(require("node:path"),1),Vl=300,nv=4,hp=512*1024,rv=new Set([".git","node_modules","dist","build","out",".next","vendor","coverage",".venv","venv","__pycache__",".turbo",".cache"]),pp=/\.mdx?$/i;function fp(t){let e=ot.default.resolve(t),n=[],r=(s,i)=>{if(i>nv||n.length>=Vl)return;let o;try{o=Pr.default.readdirSync(s,{withFileTypes:!0})}catch{return}for(let l of o){if(n.length>=Vl)return;if(!l.isFile()||!pp.test(l.name))continue;let c=ot.default.join(s,l.name);try{let u=Pr.default.statSync(c);n.push({path:ot.default.relative(e,c).split(ot.default.sep).join("/"),sizeBytes:u.size,updatedAt:u.mtime.toISOString()})}catch{}}for(let l of o){if(n.length>=Vl)return;!l.isDirectory()||l.isSymbolicLink()||rv.has(l.name)||l.name.startsWith(".")||r(ot.default.join(s,l.name),i+1)}};return r(e,0),n}function mp(t,e){let n=ot.default.resolve(t);if(!pp.test(e))return{ok:!1,error:"only markdown files can be opened here"};let r=ot.default.resolve(n,e);if(r!==n&&!r.startsWith(n+ot.default.sep))return{ok:!1,error:"that path is outside the project checkout"};let s;try{s=Pr.default.realpathSync(r)}catch{return{ok:!1,error:"file not found in this checkout"}}let i=(()=>{try{return Pr.default.realpathSync(n)}catch{return n}})();if(s!==i&&!s.startsWith(i+ot.default.sep))return{ok:!1,error:"that path links outside the project checkout"};let o;try{o=Pr.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=Pr.default.readFileSync(s,"utf8"),c=Buffer.byteLength(l,"utf8")>hp;return{ok:!0,path:ot.default.relative(i,s).split(ot.default.sep).join("/"),content:c?l.slice(0,hp):l,truncated:c}}catch(l){return{ok:!1,error:l instanceof Error?l.message:"could not read the file"}}}var Je=I(ke(),1);var Ao=I(require("node:fs"),1),gp=I(require("node:path"),1);Yr();Ce();var sv=_.object({id:_.string(),name:_.string().default(""),jiraProjectKey:_.string().default(""),repoName:_.string().default(""),jiraSiteUrl:_.string().default("")}),iv=_.array(sv);function yp(){return gp.default.join(oe(),"synced-projects.json")}function bp(t){try{let e=t.map(n=>({id:n.id,name:n.name,jiraProjectKey:n.jiraProjectKey,repoName:n.repoName,jiraSiteUrl:n.jiraSiteUrl??""}));Ao.default.mkdirSync(oe(),{recursive:!0}),Ao.default.writeFileSync(yp(),JSON.stringify(e,null,2),{mode:384})}catch{}}function ov(){try{let t=iv.safeParse(JSON.parse(Ao.default.readFileSync(yp(),"utf8")));return t.success?t.data:[]}catch{return[]}}function wp(t){return ov().find(e=>e.repoName===t)??null}var Yl=I(require("node:fs"),1),jr=I(require("node:path"),1),vp=require("node:child_process"),Nr=I(ke(),1);Ce();var av=15e4,Jl=(t,e,n,r="")=>({ok:!1,file:t,checks:[e],output:r,error:n});function lv(t){let e=jr.default.join(t,"node_modules",".bin","prisma");return Yl.default.existsSync(e)?{bin:e,prefix:[]}:{bin:"npx",prefix:["--yes","prisma"]}}function cv(t,e){if(!(0,Nr.isSelfMigrationFilename)(e))return null;let n=jr.default.join(t,Nr.SELF_MIGRATION_DIR),r=jr.default.resolve(n,e),s=jr.default.relative(n,r);return s!==e||s.startsWith("..")||jr.default.isAbsolute(s)?null:r}async function kp(t){let{file:e}=t,n=cv(t.repoPath,e);if(!n)return Jl(e,{name:"file",ok:!1,detail:`"${e}" is not a migration filename`,fix:[]},`"${e}" is not a migration filename`);if(!Yl.default.existsSync(n))return Jl(e,{name:"file",ok:!1,detail:`${Nr.SELF_MIGRATION_DIR}/${e} does not exist in this checkout`,fix:[`cd ${t.repoPath} && git pull`]},`${Nr.SELF_MIGRATION_DIR}/${e} is not in this checkout - it may be newer than the code here`);let s=Ft(t.cfg,t.repoName,t.environmentName)[t.urlSecret]?.trim();if(!s)return Jl(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=jr.default.join(t.repoPath,"apps","api"),{bin:o,prefix:l}=lv(i),c=Ml([s]),u=await uv(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:`${Nr.SELF_MIGRATION_DIR}/${e} applied`,fix:[]}],output:p,error:""}}function uv(t,e,n){return new Promise(r=>{(0,vp.execFile)(t,e,{cwd:n,timeout:av,maxBuffer:4*1024*1024,encoding:"utf8"},(s,i,o)=>{let l=[i,o].filter(Boolean).join(`
1013
+ `).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 $k=I(yf(),1),Pk=I(Do(),1),jk=I(xs(),1),Nk=I(lc(),1),Ok=I(dc(),1),Mk=I(yc(),1),Rf=I(Fo(),1),zk=I(xf(),1);var wc=Rf.default;var ci=I(require("node:crypto"),1),Pt=I(ke(),1);Vt();function Dk(t){let e=t&&typeof t=="object"&&"name"in t?String(t.name):null;return e?`"${e}"`:"(unnamed)"}function vc(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 Lk(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=Pt.ProjectConfig.safeParse(l);c.success?r.push(c.data):vc(n,"project","",c.error.issues[0]?.message??"invalid shape")}let s=[];for(let l of Array.isArray(e.rules)?e.rules:[]){let c=Pt.RuleConfig.safeParse(l);c.success?s.push(c.data):vc(n,"rule",Dk(l),c.error.issues[0]?.message??"invalid shape")}let i=[];for(let l of Array.isArray(e.environments)?e.environments:[]){let c=Pt.EnvironmentConfig.safeParse(l);c.success?i.push(c.data):vc(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 Uk=2e4,qk=6e4,Fk=5e3,Ko=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===wc.OPEN}connect(){if(this.closed)return;y.info(`connecting to control plane at ${this.wsUrl}`);let e=new wc(this.wsUrl,{headers:{authorization:`Bearer ${this.runnerToken}`}});this.ws=e,e.on("open",()=>{this.backoffMs=1e3,this.sendNow({type:"hello",protocolVersion:Pt.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()})},Uk)}),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,Pt.parseServerMsg)(r)}catch(i){let o=Lk(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,qk)}),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.explain")return this.events.onAuditExplain(e);if(e.type==="chat.cancel")return this.events.onChatCancel(e);if(e.type==="chat.diagnostic")return this.events.onChatDiagnostic(e);if(e.type==="autopilot.plan")return this.events.onAutopilotPlan(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==="runner.uninstall")return this.events.onRunnerUninstall(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>=Fk){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=ci.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=ci.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:ci.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=ci.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"}))})}sendChatDiagnosticResult(e,n){this.send({type:"chat.diagnostic.result",requestId:e,ok:n.ok,commandLine:n.commandLine??"",output:n.output??""})}sendAutopilotPlanResult(e,n){this.send({type:"autopilot.plan.result",requestId:e,ok:n.ok,error:n.error??"",order:n.order??[],chains:n.chains??[],dependencies:n.dependencies??[],reasoning:n.reasoning??""})}sendAuditExplainResult(e,n){this.send({type:"audit.explain.result",requestId:e,ok:n.ok,error:n.error??"",explanation:n.explanation??""})}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})}sendRunnerUninstallResult(e,n){this.send({type:"runner.uninstall.result",requestId:e,ok:n.ok,error:n.error,note:n.note??"",serviceRemoved:n.serviceRemoved??!1,configRemoved:n.configRemoved??!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 Ho=I(require("node:fs"),1),$s=I(require("node:path"),1),kc=require("node:child_process"),Bk=/\.mdx?$/i,If=6,Kk=/^[\w.\- ()]+$/;function Hk(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(!Bk.test(n))return{ok:!1,error:"only markdown files (.md) can be saved"};let r=n.split("/");if(r.length>If)return{ok:!1,error:`path deeper than ${If} levels`};for(let o of r)if(o==="."||o===".."||!Kk.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 _c(t){let e=Hk(t.repoPath,t.relPath);if(!e.ok)return{ok:!1,error:e.error};if(Ho.default.existsSync(e.abs)&&!t.overwrite)return{ok:!1,error:`${e.rel} already exists in this checkout`};Ho.default.mkdirSync($s.default.dirname(e.abs),{recursive:!0}),Ho.default.writeFileSync(e.abs,t.content.endsWith(`
1012
1014
  `)?t.content:t.content+`
1013
- `);let n=i=>new Promise((o,l)=>{(0,gc.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,gc.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 Lr=I(require("node:fs"),1),bc=I(require("node:path"),1),Ho=require("node:child_process"),vf=require("node:util");Ce();gr();xt();var kf=I(ke(),1),wf=(0,vf.promisify)(Ho.execFile);function Ok(t){try{return new URL(t).host}catch{return t}}function Mk(t){try{return(0,Ho.execFileSync)("git",["-C",t,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim()}catch{return null}}async function Go(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",fix:["allwright jira set-default"],fixNote:"A server set up with `allwright init --no-jira` has none on purpose - that is fine for a machine that only deploys, but this project polls a board, so it needs one. The command asks for the Jira base URL, an account email and an API token (id.atlassian.com -> Security -> API tokens), and applies live."});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=Ok(o.baseUrl),w=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 ${w} 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 b=new Pe(o);try{let k=await b.myself();s.push({name:"jira-auth",ok:!0,detail:`authenticated as ${k.displayName} on ${f} (${w})`});try{await b.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}: ${ci(x)}`})}}catch(k){s.push({name:"jira-auth",ok:!1,detail:`Jira auth failed on ${f}: ${ci(k)}`})}}}let c=t.repos[e.repoName];if(c&&Lr.default.existsSync(c.path)){let f=bc.default.join(c.path,"CLAUDE.md"),w=Lr.default.existsSync(f)&&Lr.default.readFileSync(f,"utf8").trim().length>0;s.push({name:"memory-file",kind:"content",ok:w,detail:w?"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.",...w?{}:{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 b=vo(c.path);s.push({name:"deploy-doc",kind:"content",ok:b!==null,detail:b?`${b.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.",...b?{}:{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(!Lr.default.existsSync(c.path))s.push({name:"repo-path",ok:!1,detail:`path does not exist: ${c.path}`});else{let f=Lr.default.existsSync(bc.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 w=Be(t,f),b=f==="claude-code"?"claude-code":`agent:${f}`;try{let{stdout:k}=await wf(w,["--version"],{timeout:15e3});s.push({name:b,ok:!0,detail:k.trim().slice(0,100)})}catch(k){s.push({name:b,ok:!1,detail:`cannot run "${w}" for agent "${f}": ${ci(k)}`,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 wf("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: ${ci(f)}`})}let p=je(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 ${kf.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(()=>(mt(),wr)),w=new f(p),b=await w.whoami(),k=c&&Lr.default.existsSync(c.path)?Mk(c.path):null,x=k?pt(k):null;if(!x)s.push({name:"github-token",ok:!0,detail:`authenticated as ${b} - repo access not checked (no local checkout yet)`});else{let A=await w.repoAccess(x.owner,x.repo);s.push({name:"github-token",ok:A.ok&&A.canPush,detail:A.ok?A.canPush?`${b} has push access to ${x.owner}/${x.repo}`:`${b} can read ${x.owner}/${x.repo} but NOT push to it - implement rules will fail at the push`:`${b} cannot see ${x.owner}/${x.repo}: ${A.error}`,...A.ok&&A.canPush?{}:{fix:[`allwright github set "${e.repoName}"`],fixNote:`Two ways: edit the existing PAT on GitHub and add ${x.owner}/${x.repo} to it with contents:write and pull_requests:write - or give this repo its own token with the command above. A fine-grained PAT only ever covers ONE organisation, so a repo in a different org than your other projects always needs its own.`}})}}catch(f){s.push({name:"github-token",ok:!1,detail:ci(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 w=qt(t,e.repoName,f.name),b=f.requiredSecrets.filter(k=>!w[k]&&!process.env[k]);s.push({name:`env:${f.name}`,ok:b.length===0,detail:b.length?`missing secret(s): ${b.join(", ")} - allwright env set "${e.repoName}" "${f.name}" ${b[0]}=...`:`${f.steps.length} step(s), ${f.requiredSecrets.length} secret(s) present`+(f.branch?`, deploys origin/${f.branch}`:"")})}}return s}function ci(t){return(t instanceof Error?t.message:String(t)).slice(0,300)}Wt();yo();var Re=new Dc;Re.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(Fi);function qf(t){g.info(`Create the token at ${Je.GITHUB_TOKEN_PERMISSIONS.where}`);for(let e of Je.GITHUB_TOKEN_PERMISSIONS.steps)g.info(` - ${e}`);g.info(Je.GITHUB_TOKEN_PERMISSIONS.note),g.info(`Then paste it below for ${t}.`)}Re.command("init").description("Interactive setup: enroll this runner and store credentials locally. Jira is optional - skip it here (or pass --no-jira) on a server that only deploys.").option("--cp-url <url>","control plane URL").option("--enroll-token <token>","enrolment token from the Allwright UI").option("--name <name>","runner name",pi.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)").option("--no-jira","set this machine up WITHOUT Jira - a deploy-only server that never reads a board (add them later with `allwright jira set-default`)").action(async t=>{let e=$n.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=Zu(t),o=i==="skip";i==="offer-skip"&&(g.info("Jira: the credential below is what this machine polls your board with, and comments back under. A server that only DEPLOYS never reads a board and does not need one."),o=Wu(await e.question('Connect Jira now? [Enter = yes, or type "skip" for a deploy-only server]: ')));let l=o?void 0:{baseUrl:await n("Jira base URL (https://yourorg.atlassian.net)",t.jiraUrl),email:await n("Jira account email",t.jiraEmail),apiToken:await n("Jira API token (create at id.atlassian.com/manage-profile/security/api-tokens)",t.jiraToken,!0)},c=ya.parse({controlPlaneUrl:r,runnerName:t.name,jira:l});if(c.jira){let u=await new Pe(c.jira).myself();g.info(`Jira credential OK - authenticated as ${u.displayName}`)}c=await Ou(c,s),g.info(`Enrolled as runner "${c.runnerName}" (${c.runnerId})`),g.info(`Credentials saved to ${Ut()} (mode 600, this machine only)`),c.jira||g.info("No Jira credentials stored - this machine polls no board. That is the deploy-only setup; add them whenever you need with `allwright jira set-default` (applies live, no reinstall)."),g.info("Next: map your repo with `allwright repo add <repoName> <localPath>`, then `allwright start`")}finally{e.close()}});function Ff(t,e){let n=/```(?:json)?\s*\n([\s\S]*?)```/.exec(t)??/(\{[\s\S]*\})/.exec(t);if(!n)return null;let r;try{r=JSON.parse(n[1])}catch{return null}let s=r,i=new Set(e),o=Array.isArray(s.order)?s.order.filter(p=>typeof p=="string"):[];if(o.length!==e.length||!o.every(p=>i.has(p))||new Set(o).size!==o.length)return null;let l=(Array.isArray(s.chains)?s.chains:[]).map(p=>Array.isArray(p)?p.filter(f=>typeof f=="string"&&i.has(f)):[]).filter(p=>p.length>1),c=(Array.isArray(s.dependencies)?s.dependencies:[]).map(p=>Array.isArray(p)?p:[]).filter(p=>p.length===2&&typeof p[0]=="string"&&typeof p[1]=="string"&&i.has(p[0])&&i.has(p[1])&&p[0]!==p[1]),u=typeof s.reasoning=="string"?s.reasoning.slice(0,1e3):"";return{order:o,chains:l,dependencies:c,reasoning:u}}var vc=Re.command("repo").description("Map control-plane repo names to local checkouts");vc.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=le(),s=nn.default.resolve(e.replace(/^~(?=\/|$)/,pi.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(nn.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},ge(r),g.info(`mapped repo "${t}" -> ${s}`);try{let{originUrl:i}=await Promise.resolve().then(()=>(xt(),Bu));g.info(` origin remote: ${await i(s)} - make sure this is the repo you meant`)}catch{g.warn(` could not read an origin remote at ${s} - is it a git checkout?`)}rn()||g.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.`)});vc.command("list").description("Show configured repo mappings").action(()=>{let t=le(),e=Object.entries(t.repos);if(!e.length)return g.info("no repos mapped yet");for(let[n,r]of e)g.info(`${n} -> ${r.path}`)});var Bf=Re.command("claude").description("Per-user Claude login profiles - each teammate's runs bill their OWN Claude account");Bf.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=le(),n=e.claudeProfiles[t]?.configDir??`${Ut().replace(/runner\.json$/,"")}claude-profiles/${t}`;Ve.default.mkdirSync(n,{recursive:!0,mode:448}),e.claudeProfiles[t]={configDir:n},ge(e),g.info(`profile "${t}" -> ${n}`),g.info("Opening Claude Code with this profile. In it: run /login, complete the browser flow"),g.info("with the account this profile belongs to, then exit Claude (ctrl+c twice or /exit).");let r=(0,sn.spawn)(e.claudeBin,[],{env:{...process.env,CLAUDE_CONFIG_DIR:n},stdio:"inherit"});await new Promise(s=>r.on("exit",()=>s())),g.info(`Done. Assign it on the dashboard: Team -> the user -> Claude profile = "${t}".`),rn()});Bf.command("list").description("Show configured Claude profiles and whether each looks logged in").action(()=>{let t=le(),e=Object.entries(t.claudeProfiles);if(g.info("default: this OS user's own Claude login (no profile)"),!e.length)return g.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;g.info(`${n} -> ${r.configDir} ${s?"(logged in)":"(NOT logged in yet)"}`)}});vc.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=le();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),ge(e),g.info(`Removed "${t}" (was ${n})`),r.length&&g.info(`Also removed ${r.length} environment secret set(s): ${r.join(", ")}`),e.auditSchedules.length!==s&&g.info("Also removed its audit schedule(s)"),g.info("The checkout on disk was NOT touched - remove it yourself if you want it gone."),g.info("Restart the runner to apply. Dashboard project (if any) is deleted separately there.")});var kc=Re.command("service").description("Run the runner as a system service (starts on boot, restarts on crash)");kc.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){g.info(`
1014
- `+Za(Ga()));return}Xu(g)});kc.command("uninstall").description("Remove Allwright from this machine: stop and delete the systemd service, then delete the runner config - the file holding the Jira and GitHub tokens. Your checkouts are never touched. Run with sudo.").action(()=>Qu(g));kc.command("status").description("systemctl status for the runner service").action(()=>{(0,sn.spawn)("systemctl",["status","allwright","--no-pager"],{stdio:"inherit"}).on("exit",e=>process.exit(e??0))});Re.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()=>{g.info("Updating: npm install -g allwright@latest");let t=(0,sn.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)}),g.info("Updated. Restart the runner service to load the new version (check active runs first).")});var $s=Re.command("jira").description("Per-repo Jira site overrides - for projects living on a different Atlassian site");$s.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=le();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=up(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,ge(e),g.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),g.info(`Project ${n.jiraProjectKey} is readable with it.`)}catch{g.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.`)}rn();return}catch{g.info(`The token already on this server does not work on ${r} - asking for one that does.`)}}let o=$n.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 w={baseUrl:c,email:p,apiToken:f},b=await new Pe(w).myself();g.info(`Jira credential OK - authenticated as ${b.displayName} on ${c}`),e.repos[t].jira=w,ge(e),g.info(`Saved: repo "${t}" now polls ${c} (other repos keep the runner-wide credential)`),rn()}finally{o.close()}});$s.command("set-token").alias("set-default").description("Set or replace the RUNNER-WIDE Jira credential (the one every repo without an override uses) - including on a machine that was set up with `init --no-jira`. Atlassian API tokens also expire, which surfaces as boards quietly going empty. Prompts on stdin; validated before saving; applies live, no restart.").action(async()=>{let t=le(),e=$n.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,ge(t),g.info(`Jira credential OK - authenticated as ${c.displayName} on ${s}`),g.info(`Saved to ${Ut()} (mode 600, this machine only). Repo overrides are untouched.`),rn()}finally{e.close()}});$s.command("show").description("Show which Jira site each repo uses (never prints tokens)").action(()=>{let t=le();g.info(`runner-wide: ${t.jira?`${t.jira.baseUrl} (${t.jira.email})`:"(not configured)"}`);for(let[e,n]of Object.entries(t.repos))g.info(`${e} -> ${n.jira?`${n.jira.baseUrl} (${n.jira.email})`:"(runner-wide credential)"}`)});$s.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=le(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=$n.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();g.info(`${u.baseUrl}: OK - authenticated as ${p.displayName}`),c=!0}catch{g.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},ge(e),g.info(`Saved. Dashboard actions by ${n} now post to Jira as ${s}. No restart needed.`)}finally{r.close()}});$s.command("user-list").description("Show which Allwright users have their own Jira credential here (never prints tokens)").action(()=>{let t=le(),e=Object.entries(t.jiraUsers);if(!e.length)return g.info("none yet - everyone's dashboard clicks require one: allwright jira user-add <their-ticketpilot-email>");for(let[n,r]of e)g.info(`${n} -> posts to Jira as ${r.email}`)});$s.command("user-remove <ticketpilotEmail>").description("Delete a person's stored Jira credential").action(t=>{let e=le(),n=t.trim().toLowerCase();if(!e.jiraUsers[n])throw new Error(`no credential stored for ${n}`);delete e.jiraUsers[n],ge(e),g.info(`Removed. Dashboard actions by ${n} will now be refused until a new credential is added.`)});var Ps=Re.command("github").description("GitHub credential for implement-mode rules");Ps.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=$n.default.createInterface({input:process.stdin,output:process.stdout});try{let n=t.token??void qf("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(()=>(mt(),wr)),s=await new r(n).whoami(),i=le();i.github={token:n,login:s},ge(i),g.info(`GitHub token OK - authenticated as ${s}`),g.info(`Saved to ${Ut()} (mode 600, this machine only)`)}finally{e.close()}});Ps.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=le();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,sn.execFileSync)("git",["-C",r,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim(),o=pt(i);if(o){let{GitHubClient:l}=await Promise.resolve().then(()=>(mt(),wr)),c=new l(n),u=await c.repoAccess(o.owner,o.repo);if(u.ok&&u.canPush){let p=await c.whoami();g.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.`),g.info("Want a separately revocable one anyway? Paste it at the prompt below; press Enter to leave things as they are.")}}}catch{}let s=$n.default.createInterface({input:process.stdin,output:process.stdout});try{qf(`"${t}"`);let i=(await s.question(`GitHub token for "${t}": `)).trim();if(!i&&n){g.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(()=>(mt(),wr)),l=await new o(i).whoami();e.repos[t].github={token:i,login:l},ge(e),g.info(`GitHub token OK - authenticated as ${l}`),g.info(`Saved: repo "${t}" now uses its own token (other repos keep the runner-wide one)`)}finally{s.close()}});Ps.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=le(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=$n.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(()=>(mt(),wr)),o=await new i(s).whoami();e.githubUsers[n]={token:s,login:o},ge(e),g.info(`GitHub token OK - authenticated as ${o}`),g.info(`Saved. Implement runs triggered by ${n} now open PRs as ${o}. No restart needed.`)}finally{r.close()}});Ps.command("user-list").description("Show which Allwright users have their own GitHub token here (never prints tokens)").action(()=>{let t=le(),e=Object.entries(t.githubUsers);if(!e.length)return g.info("no per-user GitHub tokens - everyone's PRs use the repo/runner-wide token");for(let[n]of e)g.info(`${n} -> own GitHub token stored`)});Ps.command("user-remove <ticketpilotEmail>").description("Delete a person's stored GitHub token (their runs fall back to the shared token)").action(t=>{let e=le(),n=t.trim().toLowerCase();if(!e.githubUsers[n])throw new Error(`no GitHub token stored for ${n}`);delete e.githubUsers[n],ge(e),g.info(`Removed. ${n}'s runs use the repo/runner-wide token again.`)});Ps.command("show").description("Show which GitHub token each repo and person would use (never prints tokens)").action(()=>{let t=le();g.info(`runner-wide: ${t.github?.token?"token set":"(not configured)"}`);for(let[n,r]of Object.entries(t.repos))g.info(`${n} -> ${r.github?.token?"own repo token":"runner-wide token"}`);let e=Object.keys(t.githubUsers);g.info(e.length?`per-user tokens: ${e.join(", ")}`:"per-user tokens: (none)")});var _c=Re.command("audit").description("Recurring specialist audits on this runner");_c.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=le();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}],ge(r),g.info(`Scheduled: ${e} audit of "${t}" every ${s}h. Restart the runner to apply.`)});_c.command("schedules").description("List scheduled audits").action(()=>{let t=le();if(!t.auditSchedules.length)return g.info("no scheduled audits - allwright audit schedule <repo> <role> <hours>");for(let e of t.auditSchedules)g.info(`${e.repoName} \xB7 ${e.role} \xB7 every ${e.intervalHours}h`)});_c.command("unschedule <repoName> <role>").description("Remove a scheduled audit").action((t,e)=>{let n=le(),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");ge(n),g.info("Removed. Restart the runner to apply.")});var Sc=Re.command("deploy").description("Deployment settings for this machine");Sc.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=le();t.deploy={enabled:!0},ge(t),g.info("deployments ENABLED on this runner"),g.info("This runner will now execute the deploy steps configured for your environments. Review them in the dashboard before shipping to production."),rn()});Sc.command("disable").description("Stop this runner from executing any deploy steps").action(()=>{let t=le();t.deploy={enabled:!1},ge(t),g.info("deployments DISABLED on this runner"),rn()});Sc.command("status").description("Show whether deployments are enabled here, and which env secrets are stored").action(()=>{let t=le();g.info(`deployments: ${t.deploy.enabled?"enabled":"disabled"}`);let e=Object.entries(t.environments);if(!e.length)return g.info("no environment secrets stored");for(let[n,r]of e){let s=Object.keys(r.secrets);g.info(`${n}: ${s.length?s.join(", "):"(no secrets)"}`)}});var Vo=Re.command("env").description("Per-environment deploy secrets. Values stay on this machine, like your Jira token.");Vo.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=le(),s=Ri(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,ge(r),g.info(`stored ${o.length} secret(s) for ${s}: ${o.join(", ")}`),g.info(`Saved to ${Ut()} (mode 600, this machine only)`),rn()});Vo.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=le().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(()=>(jf(),Pf));await o({repoName:t,envName:e,dir:nn.default.resolve(i.replace(/^~(?=\/|$)/,pi.default.homedir())),port:n.port?Number(n.port):void 0,publicUrl:n.url,dryRun:!!n.dryRun})});Vo.command("unset <repoName> <envName> <names...>").description("Remove stored secrets for an environment").action((t,e,n)=>{let r=le(),s=Ri(t,e),i=r.environments[s];if(!i)return g.info(`nothing stored for ${s}`);for(let o of n)delete i.secrets[o];r.environments[s]=i,ge(r),g.info(`removed ${n.join(", ")} from ${s}`)});Vo.command("list").description("Show which environments have secrets stored here (names only, never values)").action(()=>{let t=le(),e=Object.entries(t.environments);if(!e.length)return g.info("no environment secrets stored");for(let[n,r]of e)g.info(`${n}: ${Object.keys(r.secrets).join(", ")||"(none)"}`)});Re.command("export [file]").description("Back up ALL runner state (config+secrets, knowledge, audits, chats) to one tarball").action(t=>{try{let e=eu(t);g.info(`Backup written: ${e.file} (${e.entries.length} entries, mode 600)`),g.warn("This file CONTAINS YOUR SECRETS (Jira/GitHub tokens). Keep it private - anyone holding it can act as this runner."),g.info(`Restore on any machine with: allwright import ${nn.default.basename(e.file)}`)}catch(e){g.error(e instanceof Error?e.message:String(e)),process.exitCode=1}});Re.command("import <file>").description("Restore runner state from an `export` tarball (existing config is kept as a .bak dir)").action(t=>{let e=Wn();if(e&&Vn(e)){g.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=tu(t);g.info(`Restored ${n.restored.length} entries into ${oe()}`),n.previousDir&&g.info(`Previous config kept at ${n.previousDir}`),g.info("Start the runner and it will reconnect with the restored identity.")}catch(n){g.error(n instanceof Error?n.message:String(n)),process.exitCode=1}});Re.command("test").alias("doctor").description("Check local setup: Jira auth, repo mappings, Claude Code binary").action(async()=>{let t=le(),e=Object.keys(t.repos),n=Ei(t);n&&g.warn("no Jira credentials on this runner - it polls no board. Expected on a deploy-only server; add them any time with `allwright jira set-default`.");let r=e.length?e.map(i=>({jiraProjectKey:"*",repoName:i})):[{jiraProjectKey:"*",repoName:"(none mapped)"}],s=!0;for(let i of r){let o=await Go(t,i),l=!Ii(t,i.repoName);for(let c of o){if(i.jiraProjectKey==="*"&&c.name==="jira-project")continue;if(l&&c.name==="jira-credentials"){n||g.warn(`[WARN] jira-credentials: nothing covers "${i.repoName}" - add a runner-wide credential with \`allwright jira set-default\`, or one for this repo with \`allwright jira set "${i.repoName}"\`.`);continue}let u=c.ok?"PASS":"FAIL";(c.ok?g.info:g.error)(`[${u}] ${c.name}: ${c.detail}`),s&&=c.ok}}s||(process.exitCode=1)});function rn(){let t=Wn()??es();if(t&&Vn(t)&&process.platform!=="win32")try{return process.kill(t,"SIGHUP"),g.info("running runner reloaded its config live - no restart needed"),!0}catch{}let e=t?cu(t):null;return g.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 Hk(t){if(!t.runnerToken)throw new Error("runner not enrolled - run `allwright init`");let e=lu();e.ok||(g.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",va);let n=t.jira?new Pe(t.jira):Ka(),r=new Map,s=d=>{let m=t.repos[d]?.jira;if(!m)return n;let y=r.get(d);return y||(y=new Pe(m),r.set(d,y)),y},i=new Map,o=(d,m)=>{let y=Gu(be()??t,d,m);switch(y.kind){case"legacy":return{jira:s(d),authored:!1};case"self":return{jira:s(d),authored:!0};case"missing":return{error:y.error};case"user":{let R=`${y.creds.baseUrl}:${y.creds.email}:${y.creds.apiToken.slice(-6)}`,j=i.get(R);return j||(j=new Pe(y.creds),i.set(R,j)),{jira:j,authored:!0}}}},l=new URL("/api/runner/ws",t.controlPlaneUrl);l.protocol=l.protocol==="https:"?"wss:":"ws:";let c=[],u=[],p=[],f,w=null,b={cfg:t,jiraFor:s,transport:null},k=new Set,x=d=>{let m=c.find(R=>R.id===d),y=m&&t.repos[m.repoName];return m&&y?{project:m,repoPath:y.path}:null},A=d=>{let m=c.find(j=>j.id===d),y=t.runnerName?`This runner ("${t.runnerName}")`:"This runner";if(!m)return`${y} does not know that project at all - it may have been deleted, or this runner has not synced yet.`;let R=Object.keys(t.repos).join(", ")||"(none)";return`${y} has no local checkout for "${m.name}" (repo "${m.repoName}"). Repos mapped here: ${R}. 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`},$={cfg:t,jiraFor:s,get transport(){return b.transport},lookup:(d,m)=>{let y=x(d),R=p.find(j=>j.projectId===d&&j.name===m);return y&&R?{...y,environment:R}:null}},z=new Map,v=new Bo(l.toString(),t.runnerToken,{runnerVersion:Fi},{onConfig:d=>{c=d.projects,cp(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){v.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:A(d.projectId)});return}let y=Me(t,m.project,"assist");if("error"in y){v.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:y.error});return}g.info(`investigating failed deploy of "${d.environmentName}" (step: ${d.failedStep||"?"})`);let R=await Mh({agent:y,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,steps:d.steps,failedStep:d.failedStep,errorText:d.errorText,cfg:t});v.sendDeploySuggestResult(d.requestId,R)},onProjectTest:async d=>{let m=c.find(R=>R.id===d.projectId);if(!m){v.sendProjectTestResult(d.requestId,!1,[{name:"config",ok:!1,detail:"project not in this runner's synced config yet"}]);return}g.info(`running connection test for project "${m.name}"`);let y=await Go(be()??t,m,p.filter(R=>R.projectId===m.id),u.filter(R=>R.projectId===m.id).map(R=>"agent"in R.action?R.action.agent:"").filter(Boolean));v.sendProjectTestResult(d.requestId,y.every(R=>R.ok),y)},onRuleDiagnose:async d=>{let m=u.find(B=>B.id===d.ruleId),y=m&&c.find(B=>B.id===m.projectId);if(!m||!y){v.sendRuleDiagnoseResult(d.requestId,{checks:[{name:"config",ok:!1,detail:"rule not in this runner's synced config yet"}],matchedCount:0,excludedCount:0,excludedSample:[]});return}g.info(`diagnosing rule "${m.name}"`);let R=await Go(be()??t,y,m.action.type==="deploy"?p.filter(B=>B.projectId===y.id):[]),j=m.action.type==="implement"?R:R.filter(B=>B.name!=="github-token"),{matchedCount:G,excludedCount:X,excludedSample:U}=await f.diagnoseRule(m,y);v.sendRuleDiagnoseResult(d.requestId,{checks:j,matchedCount:G,excludedCount:X,excludedSample:U})},onCancel:d=>{Xd(d)?g.info(`run ${d} stopped from the dashboard`):g.warn(`cancel requested for run ${d}, but nothing is running under that id here - it likely finished already`)},onApproved:(d,m)=>{if(Pl(d)){Ch($,d).catch(y=>g.error(`deploy approval crashed for ${d}: ${y instanceof Error?y.stack:y}`));return}Js(b,d,m).catch(y=>g.error(`approval handling crashed for ${d}: ${y instanceof Error?y.stack:y}`))},onRetryPush:d=>{let m=io(d),y=()=>lh(b,d).catch(R=>g.error(`retry push crashed for ${d}: ${R instanceof Error?R.stack:R}`));m?f.runOnRepoQueue(m.baseRepoPath,y):y()},onRejected:d=>{if(Pl(d)){$h($,d).catch(m=>g.error(`deploy rejection crashed for ${d}: ${m instanceof Error?m.stack:m}`));return}ah(b,d).catch(m=>g.error(`rejection handling crashed for ${d}: ${m instanceof Error?m.stack:m}`))},onDeployStart:d=>{let m=`${d.runId}#${d.attempt}`;if(k.has(m))return;k.add(m);let y=x(d.projectId);if(!y){let R=A(d.projectId);g.error(`deploy ${d.runId}: ${R}`),v.send({type:"run.status",runId:d.runId,status:"failed",error:R});return}g.info(`deploy ${d.runId} requested from the dashboard: ${d.issueKey} \u2192 ${d.environment.name}`),f.runOnEnvironmentQueue(d.environment.id,()=>wo({runId:d.runId,project:y.project,environment:d.environment,issueKey:d.issueKey,issueSummary:d.issueSummary,repoPath:y.repoPath,cfg:t,jira:s(y.project.repoName),transport:v,requestedBy:d.requestedBy}).catch(R=>g.error(`deploy crashed for ${d.runId}: ${R instanceof Error?R.stack:R}`)))},onDeploySuggest:async d=>{let m=x(d.projectId);if(!m){v.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:A(d.projectId)});return}let y=Me(t,m.project,"assist");if("error"in y){v.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:y.error});return}g.info(`asking ${y.adapter.displayName} for "${d.environmentName}" deploy steps in ${m.repoPath}`);let R=await zh({agent:y,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,notes:d.notes,timeoutSeconds:d.timeoutSeconds,cfg:t});v.sendDeploySuggestResult(d.requestId,R)},onEnvPreflight:async d=>{let m=x(d.projectId);if(!m){v.sendEnvPreflightResult(d.requestId,{ok:!1,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project"}]});return}let y=await Oh({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});v.sendEnvPreflightResult(d.requestId,y)},onSelfMigrationApply:async d=>{let m=x(d.projectId);if(!m){v.sendSelfMigrationApplyResult(d.requestId,{ok:!1,file:d.file,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project",fix:[]}],output:"",error:A(d.projectId)});return}g.info(`applying migration ${d.file} for "${d.environmentName}"`);let y=await hp({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,file:d.file,urlSecret:d.urlSecret,cfg:t});g.info(y.ok?`migration ${d.file} applied`:`migration ${d.file} failed: ${y.error}`),v.sendSelfMigrationApplyResult(d.requestId,y)},onAutopilotPlan:async d=>{try{let m=x(d.projectId);if(!m){v.sendAutopilotPlanResult(d.requestId,{ok:!1,error:A(d.projectId)});return}let y=s(m.project.repoName),R=[];for(let q of d.issueKeys)try{let ie=await y.getIssue(q);R.push(`${q}: ${ie.summary}
1015
- ${(ie.description||"").slice(0,500)}`)}catch{R.push(`${q}: (could not read from Jira)`)}let j=Me(t,m.project,"assist");if("error"in j){v.sendAutopilotPlanResult(d.requestId,{ok:!1,error:j.error});return}let G=`You are planning a work queue. Below are tickets about ONE repository. Do not open any files - the summaries are your whole input, and speed matters.
1015
+ `);let n=i=>new Promise((o,l)=>{(0,kc.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,kc.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 Ur=I(require("node:fs"),1),Sc=I(require("node:path"),1),Go=require("node:child_process"),Af=require("node:util");Ce();yr();Rt();var Cf=I(ke(),1),Ef=(0,Af.promisify)(Go.execFile);function Gk(t){try{return new URL(t).host}catch{return t}}function Zk(t){try{return(0,Go.execFileSync)("git",["-C",t,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim()}catch{return null}}async function Zo(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",fix:["allwright jira set-default"],fixNote:"A server set up with `allwright init --no-jira` has none on purpose - that is fine for a machine that only deploys, but this project polls a board, so it needs one. The command asks for the Jira base URL, an account email and an API token (id.atlassian.com -> Security -> API tokens), and applies live."});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=Gk(o.baseUrl),w=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 ${w} 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 b=new Pe(o);try{let k=await b.myself();s.push({name:"jira-auth",ok:!0,detail:`authenticated as ${k.displayName} on ${f} (${w})`});try{await b.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}: ${ui(x)}`})}}catch(k){s.push({name:"jira-auth",ok:!1,detail:`Jira auth failed on ${f}: ${ui(k)}`})}}}let c=t.repos[e.repoName];if(c&&Ur.default.existsSync(c.path)){let f=Sc.default.join(c.path,"CLAUDE.md"),w=Ur.default.existsSync(f)&&Ur.default.readFileSync(f,"utf8").trim().length>0;s.push({name:"memory-file",kind:"content",ok:w,detail:w?"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.",...w?{}:{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 b=vo(c.path);s.push({name:"deploy-doc",kind:"content",ok:b!==null,detail:b?`${b.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.",...b?{}:{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(!Ur.default.existsSync(c.path))s.push({name:"repo-path",ok:!1,detail:`path does not exist: ${c.path}`});else{let f=Ur.default.existsSync(Sc.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 w=Be(t,f),b=f==="claude-code"?"claude-code":`agent:${f}`;try{let{stdout:k}=await Ef(w,["--version"],{timeout:15e3});s.push({name:b,ok:!0,detail:k.trim().slice(0,100)})}catch(k){s.push({name:b,ok:!1,detail:`cannot run "${w}" for agent "${f}": ${ui(k)}`,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 Ef("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: ${ui(f)}`})}let p=je(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 ${Cf.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(()=>(gt(),vr)),w=new f(p),b=await w.whoami(),k=c&&Ur.default.existsSync(c.path)?Zk(c.path):null,x=k?ft(k):null;if(!x)s.push({name:"github-token",ok:!0,detail:`authenticated as ${b} - repo access not checked (no local checkout yet)`});else{let A=await w.repoAccess(x.owner,x.repo);s.push({name:"github-token",ok:A.ok&&A.canPush,detail:A.ok?A.canPush?`${b} has push access to ${x.owner}/${x.repo}`:`${b} can read ${x.owner}/${x.repo} but NOT push to it - implement rules will fail at the push`:`${b} cannot see ${x.owner}/${x.repo}: ${A.error}`,...A.ok&&A.canPush?{}:{fix:[`allwright github set "${e.repoName}"`],fixNote:`Two ways: edit the existing PAT on GitHub and add ${x.owner}/${x.repo} to it with contents:write and pull_requests:write - or give this repo its own token with the command above. A fine-grained PAT only ever covers ONE organisation, so a repo in a different org than your other projects always needs its own.`}})}}catch(f){s.push({name:"github-token",ok:!1,detail:ui(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 w=Ft(t,e.repoName,f.name),b=f.requiredSecrets.filter(k=>!w[k]&&!process.env[k]);s.push({name:`env:${f.name}`,ok:b.length===0,detail:b.length?`missing secret(s): ${b.join(", ")} - allwright env set "${e.repoName}" "${f.name}" ${b[0]}=...`:`${f.steps.length} step(s), ${f.requiredSecrets.length} secret(s) present`+(f.branch?`, deploys origin/${f.branch}`:"")})}}return s}function ui(t){return(t instanceof Error?t.message:String(t)).slice(0,300)}Vt();yo();Ro();Ec();var Re=new Zc;Re.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(Fi);function em(t){y.info(`Create the token at ${Je.GITHUB_TOKEN_PERMISSIONS.where}`);for(let e of Je.GITHUB_TOKEN_PERMISSIONS.steps)y.info(` - ${e}`);y.info(Je.GITHUB_TOKEN_PERMISSIONS.note),y.info(`Then paste it below for ${t}.`)}Re.command("init").description("Interactive setup: enroll this runner and store credentials locally. Jira is optional - skip it here (or pass --no-jira) on a server that only deploys.").option("--cp-url <url>","control plane URL").option("--enroll-token <token>","enrolment token from the Allwright UI").option("--name <name>","runner name",fi.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)").option("--no-jira","set this machine up WITHOUT Jira - a deploy-only server that never reads a board (add them later with `allwright jira set-default`)").action(async t=>{let e=Pn.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=nd(t),o=i==="skip";i==="offer-skip"&&(y.info("Jira: the credential below is what this machine polls your board with, and comments back under. A server that only DEPLOYS never reads a board and does not need one."),o=rd(await e.question('Connect Jira now? [Enter = yes, or type "skip" for a deploy-only server]: ')));let l=o?void 0:{baseUrl:await n("Jira base URL (https://yourorg.atlassian.net)",t.jiraUrl),email:await n("Jira account email",t.jiraEmail),apiToken:await n("Jira API token (create at id.atlassian.com/manage-profile/security/api-tokens)",t.jiraToken,!0)},c=va.parse({controlPlaneUrl:r,runnerName:t.name,jira:l});if(c.jira){let u=await new Pe(c.jira).myself();y.info(`Jira credential OK - authenticated as ${u.displayName}`)}c=await Ku(c,s),y.info(`Enrolled as runner "${c.runnerName}" (${c.runnerId})`),y.info(`Credentials saved to ${qt()} (mode 600, this machine only)`),c.jira||y.info("No Jira credentials stored - this machine polls no board. That is the deploy-only setup; add them whenever you need with `allwright jira set-default` (applies live, no reinstall)."),y.info("Next: map your repo with `allwright repo add <repoName> <localPath>`, then `allwright start`")}finally{e.close()}});var Cc=Re.command("repo").description("Map control-plane repo names to local checkouts");Cc.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=le(),s=rn.default.resolve(e.replace(/^~(?=\/|$)/,fi.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(rn.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},ge(r),y.info(`mapped repo "${t}" -> ${s}`);try{let{originUrl:i}=await Promise.resolve().then(()=>(Rt(),Xu));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?`)}sn()||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.`)});Cc.command("list").description("Show configured repo mappings").action(()=>{let t=le(),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 tm=Re.command("claude").description("Per-user Claude login profiles - each teammate's runs bill their OWN Claude account");tm.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=le(),n=e.claudeProfiles[t]?.configDir??`${qt().replace(/runner\.json$/,"")}claude-profiles/${t}`;Ve.default.mkdirSync(n,{recursive:!0,mode:448}),e.claudeProfiles[t]={configDir:n},ge(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,on.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}".`),sn()});tm.command("list").description("Show configured Claude profiles and whether each looks logged in").action(()=>{let t=le(),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)"}`)}});Cc.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=le();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),ge(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 $c=Re.command("service").description("Run the runner as a system service (starts on boot, restarts on crash)");$c.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(`
1016
+ `+Ja(Va()));return}ad(y)});$c.command("uninstall").description("Remove Allwright from this machine: stop and delete the systemd service, then delete the runner config - the file holding the Jira and GitHub tokens. Your checkouts are never touched. Run with sudo.").action(()=>ld(y));$c.command("status").description("systemctl status for the runner service").action(()=>{(0,on.spawn)("systemctl",["status","allwright","--no-pager"],{stdio:"inherit"}).on("exit",e=>process.exit(e??0))});Re.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,on.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 Ps=Re.command("jira").description("Per-repo Jira site overrides - for projects living on a different Atlassian site");Ps.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=le();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=wp(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,ge(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.`)}sn();return}catch{y.info(`The token already on this server does not work on ${r} - asking for one that does.`)}}let o=Pn.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 w={baseUrl:c,email:p,apiToken:f},b=await new Pe(w).myself();y.info(`Jira credential OK - authenticated as ${b.displayName} on ${c}`),e.repos[t].jira=w,ge(e),y.info(`Saved: repo "${t}" now polls ${c} (other repos keep the runner-wide credential)`),sn()}finally{o.close()}});Ps.command("set-token").alias("set-default").description("Set or replace the RUNNER-WIDE Jira credential (the one every repo without an override uses) - including on a machine that was set up with `init --no-jira`. Atlassian API tokens also expire, which surfaces as boards quietly going empty. Prompts on stdin; validated before saving; applies live, no restart.").action(async()=>{let t=le(),e=Pn.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,ge(t),y.info(`Jira credential OK - authenticated as ${c.displayName} on ${s}`),y.info(`Saved to ${qt()} (mode 600, this machine only). Repo overrides are untouched.`),sn()}finally{e.close()}});Ps.command("show").description("Show which Jira site each repo uses (never prints tokens)").action(()=>{let t=le();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)"}`)});Ps.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=le(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=Pn.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},ge(e),y.info(`Saved. Dashboard actions by ${n} now post to Jira as ${s}. No restart needed.`)}finally{r.close()}});Ps.command("user-list").description("Show which Allwright users have their own Jira credential here (never prints tokens)").action(()=>{let t=le(),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}`)});Ps.command("user-remove <ticketpilotEmail>").description("Delete a person's stored Jira credential").action(t=>{let e=le(),n=t.trim().toLowerCase();if(!e.jiraUsers[n])throw new Error(`no credential stored for ${n}`);delete e.jiraUsers[n],ge(e),y.info(`Removed. Dashboard actions by ${n} will now be refused until a new credential is added.`)});var js=Re.command("github").description("GitHub credential for implement-mode rules");js.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=Pn.default.createInterface({input:process.stdin,output:process.stdout});try{let n=t.token??void em("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(()=>(gt(),vr)),s=await new r(n).whoami(),i=le();i.github={token:n,login:s},ge(i),y.info(`GitHub token OK - authenticated as ${s}`),y.info(`Saved to ${qt()} (mode 600, this machine only)`)}finally{e.close()}});js.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=le();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,on.execFileSync)("git",["-C",r,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim(),o=ft(i);if(o){let{GitHubClient:l}=await Promise.resolve().then(()=>(gt(),vr)),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=Pn.default.createInterface({input:process.stdin,output:process.stdout});try{em(`"${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(()=>(gt(),vr)),l=await new o(i).whoami();e.repos[t].github={token:i,login:l},ge(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()}});js.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=le(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=Pn.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(()=>(gt(),vr)),o=await new i(s).whoami();e.githubUsers[n]={token:s,login:o},ge(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()}});js.command("user-list").description("Show which Allwright users have their own GitHub token here (never prints tokens)").action(()=>{let t=le(),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`)});js.command("user-remove <ticketpilotEmail>").description("Delete a person's stored GitHub token (their runs fall back to the shared token)").action(t=>{let e=le(),n=t.trim().toLowerCase();if(!e.githubUsers[n])throw new Error(`no GitHub token stored for ${n}`);delete e.githubUsers[n],ge(e),y.info(`Removed. ${n}'s runs use the repo/runner-wide token again.`)});js.command("show").description("Show which GitHub token each repo and person would use (never prints tokens)").action(()=>{let t=le();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 Pc=Re.command("audit").description("Recurring specialist audits on this runner");Pc.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=le();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}],ge(r),y.info(`Scheduled: ${e} audit of "${t}" every ${s}h. Restart the runner to apply.`)});Pc.command("schedules").description("List scheduled audits").action(()=>{let t=le();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`)});Pc.command("unschedule <repoName> <role>").description("Remove a scheduled audit").action((t,e)=>{let n=le(),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");ge(n),y.info("Removed. Restart the runner to apply.")});var jc=Re.command("deploy").description("Deployment settings for this machine");jc.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=le();t.deploy={enabled:!0},ge(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."),sn()});jc.command("disable").description("Stop this runner from executing any deploy steps").action(()=>{let t=le();t.deploy={enabled:!1},ge(t),y.info("deployments DISABLED on this runner"),sn()});jc.command("status").description("Show whether deployments are enabled here, and which env secrets are stored").action(()=>{let t=le();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 Yo=Re.command("env").description("Per-environment deploy secrets. Values stay on this machine, like your Jira token.");Yo.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=le(),s=Ri(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,ge(r),y.info(`stored ${o.length} secret(s) for ${s}: ${o.join(", ")}`),y.info(`Saved to ${qt()} (mode 600, this machine only)`),sn()});Yo.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=le().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(()=>(Gf(),Hf));await o({repoName:t,envName:e,dir:rn.default.resolve(i.replace(/^~(?=\/|$)/,fi.default.homedir())),port:n.port?Number(n.port):void 0,publicUrl:n.url,dryRun:!!n.dryRun})});Yo.command("unset <repoName> <envName> <names...>").description("Remove stored secrets for an environment").action((t,e,n)=>{let r=le(),s=Ri(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,ge(r),y.info(`removed ${n.join(", ")} from ${s}`)});Yo.command("list").description("Show which environments have secrets stored here (names only, never values)").action(()=>{let t=le(),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)"}`)});Re.command("export [file]").description("Back up ALL runner state (config+secrets, knowledge, audits, chats) to one tarball").action(t=>{try{let e=cu(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 ${rn.default.basename(e.file)}`)}catch(e){y.error(e instanceof Error?e.message:String(e)),process.exitCode=1}});Re.command("import <file>").description("Restore runner state from an `export` tarball (existing config is kept as a .bak dir)").action(t=>{let e=Vn();if(e&&Jn(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=uu(t);y.info(`Restored ${n.restored.length} entries into ${oe()}`),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}});Re.command("test").alias("doctor").description("Check local setup: Jira auth, repo mappings, Claude Code binary").action(async()=>{let t=le(),e=Object.keys(t.repos),n=Ei(t);n&&y.warn("no Jira credentials on this runner - it polls no board. Expected on a deploy-only server; add them any time with `allwright jira set-default`.");let r=e.length?e.map(i=>({jiraProjectKey:"*",repoName:i})):[{jiraProjectKey:"*",repoName:"(none mapped)"}],s=!0;for(let i of r){let o=await Zo(t,i),l=!Ii(t,i.repoName);for(let c of o){if(i.jiraProjectKey==="*"&&c.name==="jira-project")continue;if(l&&c.name==="jira-credentials"){n||y.warn(`[WARN] jira-credentials: nothing covers "${i.repoName}" - add a runner-wide credential with \`allwright jira set-default\`, or one for this repo with \`allwright jira set "${i.repoName}"\`.`);continue}let u=c.ok?"PASS":"FAIL";(c.ok?y.info:y.error)(`[${u}] ${c.name}: ${c.detail}`),s&&=c.ok}}s||(process.exitCode=1)});function sn(){let t=Vn()??ts();if(t&&Jn(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?bu(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 o_(t){if(!t.runnerToken)throw new Error("runner not enrolled - run `allwright init`");let e=yu();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",Sa);let n=t.jira?new Pe(t.jira):Za(),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=td(we()??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 R=`${g.creds.baseUrl}:${g.creds.email}:${g.creds.apiToken.slice(-6)}`,j=i.get(R);return j||(j=new Pe(g.creds),i.set(R,j)),{jira:j,authored:!0}}}},l=new URL("/api/runner/ws",t.controlPlaneUrl);l.protocol=l.protocol==="https:"?"wss:":"ws:";let c=[],u=[],p=[],f,w=null,b={cfg:t,jiraFor:s,transport:null},k=new Set,x=d=>{let m=c.find(R=>R.id===d),g=m&&t.repos[m.repoName];return m&&g?{project:m,repoPath:g.path}:null},A=d=>{let m=c.find(j=>j.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 R=Object.keys(t.repos).join(", ")||"(none)";return`${g} has no local checkout for "${m.name}" (repo "${m.repoName}"). Repos mapped here: ${R}. 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`},$={cfg:t,jiraFor:s,get transport(){return b.transport},lookup:(d,m)=>{let g=x(d),R=p.find(j=>j.projectId===d&&j.name===m);return g&&R?{...g,environment:R}:null}},z=new Map,v=new Ko(l.toString(),t.runnerToken,{runnerVersion:Fi},{onConfig:d=>{c=d.projects,bp(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){v.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:A(d.projectId)});return}let g=Me(t,m.project,"assist");if("error"in g){v.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:g.error});return}y.info(`investigating failed deploy of "${d.environmentName}" (step: ${d.failedStep||"?"})`);let R=await Hh({agent:g,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,steps:d.steps,failedStep:d.failedStep,errorText:d.errorText,cfg:t});v.sendDeploySuggestResult(d.requestId,R)},onProjectTest:async d=>{let m=c.find(R=>R.id===d.projectId);if(!m){v.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 Zo(we()??t,m,p.filter(R=>R.projectId===m.id),u.filter(R=>R.projectId===m.id).map(R=>"agent"in R.action?R.action.agent:"").filter(Boolean));v.sendProjectTestResult(d.requestId,g.every(R=>R.ok),g)},onRuleDiagnose:async d=>{let m=u.find(B=>B.id===d.ruleId),g=m&&c.find(B=>B.id===m.projectId);if(!m||!g){v.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 R=await Zo(we()??t,g,m.action.type==="deploy"?p.filter(B=>B.projectId===g.id):[]),j=m.action.type==="implement"?R:R.filter(B=>B.name!=="github-token"),{matchedCount:G,excludedCount:X,excludedSample:U}=await f.diagnoseRule(m,g);v.sendRuleDiagnoseResult(d.requestId,{checks:j,matchedCount:G,excludedCount:X,excludedSample:U})},onCancel:d=>{ah(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(zl(d)){Lh($,d).catch(g=>y.error(`deploy approval crashed for ${d}: ${g instanceof Error?g.stack:g}`));return}Ys(b,d,m).catch(g=>y.error(`approval handling crashed for ${d}: ${g instanceof Error?g.stack:g}`))},onRetryPush:d=>{let m=io(d),g=()=>yh(b,d).catch(R=>y.error(`retry push crashed for ${d}: ${R instanceof Error?R.stack:R}`));m?f.runOnRepoQueue(m.baseRepoPath,g):g()},onRejected:d=>{if(zl(d)){Uh($,d).catch(m=>y.error(`deploy rejection crashed for ${d}: ${m instanceof Error?m.stack:m}`));return}gh(b,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(k.has(m))return;k.add(m);let g=x(d.projectId);if(!g){let R=A(d.projectId);y.error(`deploy ${d.runId}: ${R}`),v.send({type:"run.status",runId:d.runId,status:"failed",error:R});return}y.info(`deploy ${d.runId} requested from the dashboard: ${d.issueKey} \u2192 ${d.environment.name}`),f.runOnEnvironmentQueue(d.environment.id,()=>wo({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:v,requestedBy:d.requestedBy}).catch(R=>y.error(`deploy crashed for ${d.runId}: ${R instanceof Error?R.stack:R}`)))},onDeploySuggest:async d=>{let m=x(d.projectId);if(!m){v.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:A(d.projectId)});return}let g=Me(t,m.project,"assist");if("error"in g){v.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 R=await Gh({agent:g,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,notes:d.notes,timeoutSeconds:d.timeoutSeconds,cfg:t});v.sendDeploySuggestResult(d.requestId,R)},onEnvPreflight:async d=>{let m=x(d.projectId);if(!m){v.sendEnvPreflightResult(d.requestId,{ok:!1,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project"}]});return}let g=await Kh({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});v.sendEnvPreflightResult(d.requestId,g)},onSelfMigrationApply:async d=>{let m=x(d.projectId);if(!m){v.sendSelfMigrationApplyResult(d.requestId,{ok:!1,file:d.file,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project",fix:[]}],output:"",error:A(d.projectId)});return}y.info(`applying migration ${d.file} for "${d.environmentName}"`);let g=await kp({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}`),v.sendSelfMigrationApplyResult(d.requestId,g)},onAutopilotPlan:async d=>{try{let m=x(d.projectId);if(!m){v.sendAutopilotPlanResult(d.requestId,{ok:!1,error:A(d.projectId)});return}let g=s(m.project.repoName),R=[];for(let q of d.issueKeys)try{let se=await g.getIssue(q);R.push(`${q}: ${se.summary}
1017
+ ${(se.description||"").slice(0,500)}`)}catch{R.push(`${q}: (could not read from Jira)`)}let j=Me(t,m.project,"assist");if("error"in j){v.sendAutopilotPlanResult(d.requestId,{ok:!1,error:j.error});return}let G=`You are planning a work queue. Below are tickets about ONE repository. Do not open any files - the summaries are your whole input, and speed matters.
1016
1018
 
1017
1019
  `+R.join(`
1018
1020
 
@@ -1025,15 +1027,23 @@ Rules:
1025
1027
  - "order": every key exactly once. Prerequisites before the work that needs them.
1026
1028
  - "chains": tickets one engineer would do in one sitting, in the same part of the code, ADJACENT in your order. Chained tickets share a warm agent session, so group real neighbours - and leave a ticket out of every chain when unsure. Solo tickets appear in no chain.
1027
1029
  - "dependencies": ONLY hard prerequisites, where the blocked ticket CANNOT pass if the other failed. An empty list is the normal answer.
1028
- - "reasoning": 2-3 short lines a person can check your plan against.`,X=await j.adapter.run({repoPath:m.repoPath,prompt:G,timeoutSeconds:90,bin:j.bin,mode:"read_only",maxTurns:3,model:j.adapter.fastModel,sessionId:(0,qr.randomUUID)(),onLog:()=>{}}),U=Ff(X.resultText,d.issueKeys);if(!U){v.sendAutopilotPlanResult(d.requestId,{ok:!1,error:"the planner's answer could not be parsed - the queue keeps its given order"});return}let{saveBatchPlan:B}=await Promise.resolve().then(()=>(Ll(),Uh));B({batchId:d.batchId,projectId:d.projectId,order:U.order,chains:U.chains,dependencies:U.dependencies,reasoning:U.reasoning}),v.sendAutopilotPlanResult(d.requestId,{ok:!0,...U})}catch(m){v.sendAutopilotPlanResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onChatCancel:d=>{let m=z.get(d.turnId);m&&(m.abort(),g.info(`chat turn ${d.turnId} stopped from the dashboard`))},onChatTurn:async d=>{let m=x(d.projectId);if(!m){v.sendChatTurnResult(d.requestId,{ok:!1,sessionId:d.sessionId??"",reply:"",error:A(d.projectId)});return}let y=d.sessionId||(0,qr.randomUUID)(),R=!d.sessionId,j=R?0:ei(y)?.messages.length??0,G=!1,X=0,U="";if(!R&&j>=Xh){let me=await tp(m,y,t);if(me)G=!0,X=j,U=me,y=(0,qr.randomUUID)(),R=!0,g.info(`chat compacted: ${j} message(s) summarized into a fresh session`);else if(j>=Qh){v.sendChatTurnResult(d.requestId,{ok:!1,sessionId:y,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 B=d.files.length?su(m.repoPath,d.requestId,d.files):null,q=(0,Je.replyPreferenceAppendix)({language:d.replyLanguage,languageInstruction:d.replyLanguageInstruction,style:d.replyStyle})+(0,Je.pendingMigrationsAppendix)(d.pendingMigrations),ie="```",Z=R?`You are the project assistant for "${m.project.name}" - this working directory is its repository, and you have read-only access.
1030
+ - "reasoning": 2-3 short lines a person can check your plan against.`,X=await j.adapter.run({repoPath:m.repoPath,prompt:G,timeoutSeconds:90,bin:j.bin,mode:"read_only",maxTurns:3,model:j.adapter.fastModel,sessionId:(0,Fr.randomUUID)(),onLog:()=>{}}),U=Kl(X.resultText,d.issueKeys);if(!U){v.sendAutopilotPlanResult(d.requestId,{ok:!1,error:"the planner's answer could not be parsed - the queue keeps its given order"});return}let{saveBatchPlan:B}=await Promise.resolve().then(()=>(Ro(),Vh));B({batchId:d.batchId,projectId:d.projectId,order:U.order,chains:U.chains,dependencies:U.dependencies,reasoning:U.reasoning}),v.sendAutopilotPlanResult(d.requestId,{ok:!0,...U})}catch(m){v.sendAutopilotPlanResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onChatDiagnostic:async d=>{try{let{runDiagnostic:m}=await Promise.resolve().then(()=>(Ec(),Nf)),g=await m({command:d.command,args:d.args});y.info(`chat diagnostic (user-approved): ${g.commandLine}`),v.sendChatDiagnosticResult(d.requestId,g)}catch(m){v.sendChatDiagnosticResult(d.requestId,{ok:!1,output:m instanceof Error?m.message:String(m)})}},onChatCancel:d=>{let m=z.get(d.turnId);m&&(m.abort(),y.info(`chat turn ${d.turnId} stopped from the dashboard`))},onChatTurn:async d=>{let m=x(d.projectId);if(!m){v.sendChatTurnResult(d.requestId,{ok:!1,sessionId:d.sessionId??"",reply:"",error:A(d.projectId)});return}let g=d.sessionId||(0,Fr.randomUUID)(),R=!d.sessionId,j=R?0:ti(g)?.messages.length??0,G=!1,X=0,U="";if(!R&&j>=ap){let me=await up(m,g,t);if(me)G=!0,X=j,U=me,g=(0,Fr.randomUUID)(),R=!0,y.info(`chat compacted: ${j} message(s) summarized into a fresh session`);else if(j>=lp){v.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 B=d.files.length?pu(m.repoPath,d.requestId,d.files):null,q=(0,Je.replyPreferenceAppendix)({language:d.replyLanguage,languageInstruction:d.replyLanguageInstruction,style:d.replyStyle})+(0,Je.pendingMigrationsAppendix)(d.pendingMigrations),se="```",Z=R?`You are the project assistant for "${m.project.name}" - this working directory is its repository, and you have read-only access.
1029
1031
 
1030
1032
  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.
1031
1033
  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.
1032
1034
 
1035
+ You cannot run commands - but you can ASK to. When the answer genuinely needs machine state (is a service up, what is in its log, what is listening), request ONE read-only diagnostic by ending your reply with:
1036
+ ${se}diagnose
1037
+ {"command": "<id>", "args": {...}, "why": "one line the user reads before approving"}
1038
+ ${se}
1039
+ Catalogue (nothing else exists):
1040
+ ${Ic()}
1041
+ The user approves or denies each request - never assume the answer; wait for the output, which arrives as the next message. Ask only when reading the repo cannot answer, and ask for the single most informative command first.
1042
+
1033
1043
  ONLY when the user explicitly asks for a ticket, propose it by ending your reply with EXACTLY one fenced block in this shape:
1034
- ${ie}ticket
1044
+ ${se}ticket
1035
1045
  {"summary": "\u2026", "description": "\u2026"}
1036
- ${ie}
1046
+ ${se}
1037
1047
  Before drafting, re-read this ENTIRE conversation from its first message and fold in every decision, constraint, and correction agreed along the way - the ticket reflects the final state of the whole discussion, not just the last message.
1038
1048
  GROUP, do not fragment. When the conversation holds SEVERAL tasks, apply this test: would one engineer do them in one sitting, in the same part of the code? If yes they are ONE ticket - a checklist of "- [ ]" items inside the Description, not many tickets. Only genuinely separate work areas get separate tickets (and then say so, and draft them one at a time, asking which to create first). Every extra ticket is an extra cold agent run that re-reads this repository from nothing: fragmenting one sitting's work into five tickets quintuples its cost and loses the shared context. If the user explicitly asks to split or to merge, their word wins.
1039
1049
  Write the description in plain human language, structured with these Markdown section headings in this order:
@@ -1043,30 +1053,30 @@ Expected Flow: - the flow once this ticket is done, as numbered steps.
1043
1053
  Current Flow: - how it behaves today; include ONLY when current behavior exists.
1044
1054
  Acceptance Criteria: - testable bullet points a reviewer can check off one by one.
1045
1055
  Include a section only when it carries real content, and add extra sections (Out of Scope, Notes, \u2026) when the work genuinely needs them. Use as many bullets as the work needs - no artificial length cap, but no padding either. It must stay concrete enough that a developer (or an agent) can implement it without asking questions. NEVER paste the conversation into the description; distill it. Refine the draft over further turns if the user asks.
1046
- EXCEPTION - verbatim payloads: when the user supplies literal content that must land in the ticket exactly (file contents, error logs, specs, commands), include it in the description IN FULL inside a fenced code block - the word budget applies to your own prose around it, never to the user's payload. Never summarize such content and never replace it with a placeholder like "[insert content here]": a placeholder makes the ticket unimplementable, because the implementing agent only ever sees the ticket. Inside the ${ie}ticket JSON, fence such payloads with ~~~ (tildes), NEVER with triple backticks - a nested ${ie} would end the outer block early and corrupt the draft.
1056
+ EXCEPTION - verbatim payloads: when the user supplies literal content that must land in the ticket exactly (file contents, error logs, specs, commands), include it in the description IN FULL inside a fenced code block - the word budget applies to your own prose around it, never to the user's payload. Never summarize such content and never replace it with a placeholder like "[insert content here]": a placeholder makes the ticket unimplementable, because the implementing agent only ever sees the ticket. Inside the ${se}ticket JSON, fence such payloads with ~~~ (tildes), NEVER with triple backticks - a nested ${se} would end the outer block early and corrupt the draft.
1047
1057
  EXCEPTION - big requirements: when the user asks for an epic with sub-tickets, or asks to ticket something clearly too large for one ticket, break it down instead and emit this shape in the \`\`\`ticket block:
1048
1058
  {"epic": {"summary": "\u2026", "description": "\u2026"}, "tickets": [{"summary": "\u2026", "description": "\u2026"}, \u2026]}
1049
1059
  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.
1050
1060
 
1051
- `+np+(U?`
1061
+ `+dp+(U?`
1052
1062
 
1053
1063
  This conversation was already running and has been compacted. Everything agreed so far, in summary form - treat it as established, do not re-ask:
1054
1064
  ${U}
1055
1065
  `:"")+q+`
1056
- ${d.userName||"The user"} says: ${d.message}`+(B?.section??""):q+`${d.userName||"The user"} says: ${d.message}`+(B?.section??""),he=0,De=[],ne;try{let me=Me(t,m.project,"chat");if("error"in me){v.sendChatTurnResult(d.requestId,{ok:!1,sessionId:y,reply:"",error:me.error});return}let we=new AbortController;z.set(d.requestId,we),ne=await me.adapter.run({repoPath:m.repoPath,prompt:Z,signal:we.signal,timeoutSeconds:180,bin:me.bin,mode:"read_only",maxTurns:25,model:d.model||me.adapter.fastModel,sessionId:y,resume:!R,onLog:(ut,jt)=>{ut==="agent"&&(De.push(jt.slice(0,4e3)),v.send({type:"chat.stream",requestId:d.requestId,seq:he++,text:jt.slice(0,8e3)}))},onUsage:ut=>{v.send({type:"chat.usage",requestId:d.requestId,inputTokens:Math.round(ut.inputTokens),outputTokens:Math.round(ut.outputTokens),cacheReadTokens:ut.cacheReadTokens===void 0?void 0:Math.round(ut.cacheReadTokens),turns:ut.turns})}})}finally{z.delete(d.requestId),B&&Ve.default.rmSync(B.dir,{recursive:!0,force:!0})}if(ne.cancelled){v.sendChatTurnResult(d.requestId,{ok:!1,sessionId:y,reply:"",error:"stopped by you - the reply was cut off and nothing was saved to this chat",inputTokens:ne.inputTokens,outputTokens:ne.outputTokens,cacheReadTokens:ne.cacheReadTokens});return}if(ne.ok){let me=De.filter(we=>we.trim()&&!ne.resultText.trim().startsWith(we.trim()));Jh(d.projectId,y,d.message,ne.resultText,me,d.files.map(we=>we.name))}let ct=(ne.inputTokens??0)+(ne.cacheReadTokens??0);v.sendChatTurnResult(d.requestId,{contextTokens:ct,contextLimit:ep(ne.model||d.model||""),compacted:G,compactedMessages:X,ok:ne.ok,sessionId:y,reply:ne.resultText,error:ne.ok?void 0:ne.error??"the agent produced no reply",inputTokens:ne.inputTokens,outputTokens:ne.outputTokens,cacheReadTokens:ne.cacheReadTokens,costUsd:ne.costUsd,model:ne.model??""})},onChatList:d=>{v.sendChatListResult(d.requestId,Yh(d.projectId))},onRepoDocs:d=>{let m=x(d.projectId);if(!m){v.sendRepoDocsResult(d.requestId,{ok:!1,docs:[],error:A(d.projectId)});return}v.sendRepoDocsResult(d.requestId,{ok:!0,docs:ip(m.repoPath)})},onRepoDocRead:d=>{let m=x(d.projectId);if(!m){v.sendRepoDocReadResult(d.requestId,{ok:!1,path:d.path,content:"",truncated:!1,error:A(d.projectId)});return}let y=op(m.repoPath,d.path);v.sendRepoDocReadResult(d.requestId,{ok:y.ok,path:y.ok?y.path:d.path,content:y.ok?y.content:"",truncated:y.ok?y.truncated:!1,error:y.ok?void 0:y.error})},onChatLoad:d=>{let m=ei(d.sessionId);v.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){v.sendBoardFetchResult(d.requestId,{ok:!1,columns:[],error:A(d.projectId)});return}try{let y=s(m.project.repoName),R;try{R=await y.searchBoard(`project = "${m.project.jiraProjectKey}" ORDER BY Rank ASC`,100)}catch{R=await y.searchBoard(`project = "${m.project.jiraProjectKey}" ORDER BY updated DESC`,100)}let j=await y.boardColumns(m.project.jiraProjectKey),G;if(j){G=j.map(B=>({name:B.name,issues:[]}));let U=new Map;for(let B of R){let q=j.findIndex(Z=>Z.statusIds.includes(B.statusId)),ie={key:B.key,summary:B.summary,labels:B.labels};if(q>=0)G[q].issues.push(ie);else{let Z=U.get(B.status)??[];Z.push(ie),U.set(B.status,Z)}}for(let[B,q]of U)G.push({name:B,issues:q})}else{let U=he=>he.trim().toLowerCase(),B=new Map,q=new Map;for(let he of R){let De=U(he.status);B.has(De)||B.set(De,he.status.trim());let ne=q.get(De)??[];ne.push({key:he.key,summary:he.summary,labels:he.labels}),q.set(De,ne)}let ie=[];try{ie=await y.projectStatuses(m.project.jiraProjectKey)}catch{}let Z=[];for(let he of ie){let De=U(he);!Z.includes(De)&&q.has(De)&&Z.push(De)}for(let he of q.keys())Z.includes(he)||Z.push(he);G=Z.map(he=>({name:B.get(he)??he,issues:q.get(he)??[]}))}let X=t.repos[m.project.repoName]?.jira??t.jira;v.sendBoardFetchResult(d.requestId,{ok:!0,browseBaseUrl:(X?.baseUrl??"").replace(/\/+$/,""),columns:G})}catch(y){v.sendBoardFetchResult(d.requestId,{ok:!1,columns:[],error:y instanceof Error?y.message:String(y)})}},onBoardTrigger:async d=>{let m=x(d.projectId);if(!m){v.sendBoardTriggerResult(d.requestId,{ok:!1,error:A(d.projectId)});return}try{let y=s(m.project.repoName),R=d.comment.trim()?o(m.project.repoName,d.requestedByEmail):{jira:y,authored:!1};if(R.error!==void 0){v.sendBoardTriggerResult(d.requestId,{ok:!1,error:R.error});return}if(d.reimplement){let j=await y.getIssue(d.issueKey),G=j.comments.filter(B=>Rt(B.body)),X=G.length?Math.max(...G.map(B=>new Date(B.created).getTime())):0;if(!j.comments.some(B=>!Rt(B.body)&&new Date(B.created).getTime()>X)){v.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 y.editLabels(d.issueKey,{remove:["agent-implemented"]})}d.removeLabel.trim()&&await y.editLabels(d.issueKey,{remove:[d.removeLabel.trim()]}),d.comment.trim()&&await R.jira.addTriggerComment(d.issueKey,`${d.comment.trim()}`+(!R.authored&&d.requestedBy?`
1066
+ ${d.userName||"The user"} says: ${d.message}`+(B?.section??""):q+`${d.userName||"The user"} says: ${d.message}`+(B?.section??""),he=0,De=[],ne;try{let me=Me(t,m.project,"chat");if("error"in me){v.sendChatTurnResult(d.requestId,{ok:!1,sessionId:g,reply:"",error:me.error});return}let ve=new AbortController;z.set(d.requestId,ve),ne=await me.adapter.run({repoPath:m.repoPath,prompt:Z,signal:ve.signal,timeoutSeconds:180,bin:me.bin,mode:"read_only",maxTurns:25,model:d.model||me.adapter.fastModel,sessionId:g,resume:!R,onLog:(dt,Nt)=>{dt==="agent"&&(De.push(Nt.slice(0,4e3)),v.send({type:"chat.stream",requestId:d.requestId,seq:he++,text:Nt.slice(0,8e3)}))},onUsage:dt=>{v.send({type:"chat.usage",requestId:d.requestId,inputTokens:Math.round(dt.inputTokens),outputTokens:Math.round(dt.outputTokens),cacheReadTokens:dt.cacheReadTokens===void 0?void 0:Math.round(dt.cacheReadTokens),turns:dt.turns})}})}finally{z.delete(d.requestId),B&&Ve.default.rmSync(B.dir,{recursive:!0,force:!0})}if(ne.cancelled){v.sendChatTurnResult(d.requestId,{ok:!1,sessionId:g,reply:"",error:"stopped by you - the reply was cut off and nothing was saved to this chat",inputTokens:ne.inputTokens,outputTokens:ne.outputTokens,cacheReadTokens:ne.cacheReadTokens});return}if(ne.ok){let me=De.filter(ve=>ve.trim()&&!ne.resultText.trim().startsWith(ve.trim()));ip(d.projectId,g,d.message,ne.resultText,me,d.files.map(ve=>ve.name))}let ut=(ne.inputTokens??0)+(ne.cacheReadTokens??0);v.sendChatTurnResult(d.requestId,{contextTokens:ut,contextLimit:cp(ne.model||d.model||""),compacted:G,compactedMessages:X,ok:ne.ok,sessionId:g,reply:ne.resultText,error:ne.ok?void 0:ne.error??"the agent produced no reply",inputTokens:ne.inputTokens,outputTokens:ne.outputTokens,cacheReadTokens:ne.cacheReadTokens,costUsd:ne.costUsd,model:ne.model??""})},onChatList:d=>{v.sendChatListResult(d.requestId,op(d.projectId))},onRepoDocs:d=>{let m=x(d.projectId);if(!m){v.sendRepoDocsResult(d.requestId,{ok:!1,docs:[],error:A(d.projectId)});return}v.sendRepoDocsResult(d.requestId,{ok:!0,docs:fp(m.repoPath)})},onRepoDocRead:d=>{let m=x(d.projectId);if(!m){v.sendRepoDocReadResult(d.requestId,{ok:!1,path:d.path,content:"",truncated:!1,error:A(d.projectId)});return}let g=mp(m.repoPath,d.path);v.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=ti(d.sessionId);v.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){v.sendBoardFetchResult(d.requestId,{ok:!1,columns:[],error:A(d.projectId)});return}try{let g=s(m.project.repoName),R;try{R=await g.searchBoard(`project = "${m.project.jiraProjectKey}" ORDER BY Rank ASC`,100)}catch{R=await g.searchBoard(`project = "${m.project.jiraProjectKey}" ORDER BY updated DESC`,100)}let j=await g.boardColumns(m.project.jiraProjectKey),G;if(j){G=j.map(B=>({name:B.name,issues:[]}));let U=new Map;for(let B of R){let q=j.findIndex(Z=>Z.statusIds.includes(B.statusId)),se={key:B.key,summary:B.summary,labels:B.labels};if(q>=0)G[q].issues.push(se);else{let Z=U.get(B.status)??[];Z.push(se),U.set(B.status,Z)}}for(let[B,q]of U)G.push({name:B,issues:q})}else{let U=he=>he.trim().toLowerCase(),B=new Map,q=new Map;for(let he of R){let De=U(he.status);B.has(De)||B.set(De,he.status.trim());let ne=q.get(De)??[];ne.push({key:he.key,summary:he.summary,labels:he.labels}),q.set(De,ne)}let se=[];try{se=await g.projectStatuses(m.project.jiraProjectKey)}catch{}let Z=[];for(let he of se){let De=U(he);!Z.includes(De)&&q.has(De)&&Z.push(De)}for(let he of q.keys())Z.includes(he)||Z.push(he);G=Z.map(he=>({name:B.get(he)??he,issues:q.get(he)??[]}))}let X=t.repos[m.project.repoName]?.jira??t.jira;v.sendBoardFetchResult(d.requestId,{ok:!0,browseBaseUrl:(X?.baseUrl??"").replace(/\/+$/,""),columns:G})}catch(g){v.sendBoardFetchResult(d.requestId,{ok:!1,columns:[],error:g instanceof Error?g.message:String(g)})}},onBoardTrigger:async d=>{let m=x(d.projectId);if(!m){v.sendBoardTriggerResult(d.requestId,{ok:!1,error:A(d.projectId)});return}try{let g=s(m.project.repoName),R=d.comment.trim()?o(m.project.repoName,d.requestedByEmail):{jira:g,authored:!1};if(R.error!==void 0){v.sendBoardTriggerResult(d.requestId,{ok:!1,error:R.error});return}if(d.reimplement){let j=await g.getIssue(d.issueKey),G=j.comments.filter(B=>It(B.body)),X=G.length?Math.max(...G.map(B=>new Date(B.created).getTime())):0;if(!j.comments.some(B=>!It(B.body)&&new Date(B.created).getTime()>X)){v.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 R.jira.addTriggerComment(d.issueKey,`${d.comment.trim()}`+(!R.authored&&d.requestedBy?`
1057
1067
 
1058
- _(requested by ${d.requestedBy} via Allwright)_`:"")),g.info(`Board action on ${d.issueKey}`+(d.comment?` comment "${d.comment.trim()}"`:"")+(d.removeLabel?` -label ${d.removeLabel}`:"")+(d.requestedBy?` by ${d.requestedBy}`:"")),v.sendBoardTriggerResult(d.requestId,{ok:!0})}catch(y){v.sendBoardTriggerResult(d.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onChatCreateTicket:async d=>{let m=x(d.projectId);if(!m){v.sendChatCreateTicketResult(d.requestId,{ok:!1,issueKey:"",error:A(d.projectId)});return}try{let y=o(m.project.repoName,d.requestedByEmail);if(y.error!==void 0){v.sendChatCreateTicketResult(d.requestId,{ok:!1,issueKey:"",error:y.error});return}let R=`
1068
+ _(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}`:"")),v.sendBoardTriggerResult(d.requestId,{ok:!0})}catch(g){v.sendBoardTriggerResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onChatCreateTicket:async d=>{let m=x(d.projectId);if(!m){v.sendChatCreateTicketResult(d.requestId,{ok:!1,issueKey:"",error:A(d.projectId)});return}try{let g=o(m.project.repoName,d.requestedByEmail);if(g.error!==void 0){v.sendChatCreateTicketResult(d.requestId,{ok:!1,issueKey:"",error:g.error});return}let R=`
1059
1069
 
1060
1070
  ---
1061
- _Created via Allwright Compose`+(!y.authored&&d.requestedBy?` by ${d.requestedBy}`:"")+", drafted with the project agent._";if(d.asEpic&&d.createAs!=="epic_with_children"&&d.children.length){let X=d.createAs==="separate_epics"?"Epic":"Task",U=[];for(let B of d.children){let q=await y.jira.createIssue(m.project.jiraProjectKey,B.summary,(B.description||"(no description)")+R,X);U.push(q.key)}g.info(`Compose created ${U.length} standalone ${X.toLowerCase()}(s)`),v.sendChatCreateTicketResult(d.requestId,{ok:!0,issueKey:U[0]??"",childKeys:U});return}let{key:j}=await y.jira.createIssue(m.project.jiraProjectKey,d.summary,(d.description||"(no description)")+R,d.asEpic?"Epic":"Task");d.files.length&&await y.jira.addAttachments(j,d.files.map(X=>({name:X.name,content:Buffer.from(X.contentBase64,"base64")}))).then(()=>g.info(`Compose attached ${d.files.length} file(s) to ${j}`)).catch(X=>g.warn(`Compose could not attach files to ${j}: ${X instanceof Error?X.message:X}`));let G=[];if(d.asEpic){for(let X of d.children){let U=await y.jira.createIssue(m.project.jiraProjectKey,X.summary,X.description||"(no description)","Task",j);G.push(U.key)}g.info(`Compose created epic ${j} with ${G.length} child ticket(s)`),v.sendChatCreateTicketResult(d.requestId,{ok:!0,issueKey:j,childKeys:G});return}d.triggerComment.trim()&&await y.jira.addTriggerComment(j,`${d.triggerComment.trim()}`+(!y.authored&&d.requestedBy?`
1071
+ _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 X=d.createAs==="separate_epics"?"Epic":"Task",U=[];for(let B of d.children){let q=await g.jira.createIssue(m.project.jiraProjectKey,B.summary,(B.description||"(no description)")+R,X);U.push(q.key)}y.info(`Compose created ${U.length} standalone ${X.toLowerCase()}(s)`),v.sendChatCreateTicketResult(d.requestId,{ok:!0,issueKey:U[0]??"",childKeys:U});return}let{key:j}=await g.jira.createIssue(m.project.jiraProjectKey,d.summary,(d.description||"(no description)")+R,d.asEpic?"Epic":"Task");d.files.length&&await g.jira.addAttachments(j,d.files.map(X=>({name:X.name,content:Buffer.from(X.contentBase64,"base64")}))).then(()=>y.info(`Compose attached ${d.files.length} file(s) to ${j}`)).catch(X=>y.warn(`Compose could not attach files to ${j}: ${X instanceof Error?X.message:X}`));let G=[];if(d.asEpic){for(let X of d.children){let U=await g.jira.createIssue(m.project.jiraProjectKey,X.summary,X.description||"(no description)","Task",j);G.push(U.key)}y.info(`Compose created epic ${j} with ${G.length} child ticket(s)`),v.sendChatCreateTicketResult(d.requestId,{ok:!0,issueKey:j,childKeys:G});return}d.triggerComment.trim()&&await g.jira.addTriggerComment(j,`${d.triggerComment.trim()}`+(!g.authored&&d.requestedBy?`
1062
1072
 
1063
- _(requested by ${d.requestedBy} via Allwright)_`:"")),g.info(`Compose created ${j}`+(d.requestedBy?` for ${d.requestedBy}`:"")+(d.triggerComment?` with trigger "${d.triggerComment.trim()}"`:"")),v.sendChatCreateTicketResult(d.requestId,{ok:!0,issueKey:j})}catch(y){v.sendChatCreateTicketResult(d.requestId,{ok:!1,issueKey:"",error:y instanceof Error?y.message:String(y)})}},onAuditStart:async d=>{let m=x(d.projectId);if(!m){v.sendAuditStartResult(d.requestId,{ok:!1,error:A(d.projectId)});return}try{g.info(`Audit (${d.role}) starting on ${m.project.repoName}`+(d.scope.kind!=="repo"?` scoped to ${d.scope.kind}:${d.scope.ref}`:""));let y=Me(t,m.project,"assist");if("error"in y){v.sendAuditStartResult(d.requestId,{ok:!1,error:y.error});return}let R=await ms({projectId:d.projectId,repoPath:m.repoPath,role:d.role,scope:d.scope,detailLevel:d.detailLevel,model:d.model,agent:y,jira:s(m.project.repoName),baseUrl:d.baseUrl});if(!R.ok){v.sendAuditStartResult(d.requestId,{ok:!1,error:R.error});return}v.sendAuditStartResult(d.requestId,{ok:!0,audit:R.audit})}catch(y){v.sendAuditStartResult(d.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onAuditList:async d=>{try{v.sendAuditListResult(d.requestId,{ok:!0,audits:hd(d.projectId)})}catch(m){v.sendAuditListResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditExplain:async d=>{try{let m=tl(d.projectId,d.auditId),y=m?.findings.find(B=>B.id===d.findingId);if(!m||!y){v.sendAuditExplainResult(d.requestId,{ok:!1,error:"that finding is not on this runner any more"});return}let R=x(d.projectId);if(!R){v.sendAuditExplainResult(d.requestId,{ok:!1,error:A(d.projectId)});return}let j=Me(t,R.project,"assist");if("error"in j){v.sendAuditExplainResult(d.requestId,{ok:!1,error:j.error});return}let G=`Explain ONE audit finding to a smart person who is not a programmer - they have to decide whether to fix it now, later, or accept the risk, and the finding below was written for engineers.
1073
+ _(requested by ${d.requestedBy} via Allwright)_`:"")),y.info(`Compose created ${j}`+(d.requestedBy?` for ${d.requestedBy}`:"")+(d.triggerComment?` with trigger "${d.triggerComment.trim()}"`:"")),v.sendChatCreateTicketResult(d.requestId,{ok:!0,issueKey:j})}catch(g){v.sendChatCreateTicketResult(d.requestId,{ok:!1,issueKey:"",error:g instanceof Error?g.message:String(g)})}},onAuditStart:async d=>{let m=x(d.projectId);if(!m){v.sendAuditStartResult(d.requestId,{ok:!1,error:A(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=Me(t,m.project,"assist");if("error"in g){v.sendAuditStartResult(d.requestId,{ok:!1,error:g.error});return}let R=await gs({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),baseUrl:d.baseUrl});if(!R.ok){v.sendAuditStartResult(d.requestId,{ok:!1,error:R.error});return}v.sendAuditStartResult(d.requestId,{ok:!0,audit:R.audit})}catch(g){v.sendAuditStartResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onAuditList:async d=>{try{v.sendAuditListResult(d.requestId,{ok:!0,audits:kd(d.projectId)})}catch(m){v.sendAuditListResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditExplain:async d=>{try{let m=sl(d.projectId,d.auditId),g=m?.findings.find(B=>B.id===d.findingId);if(!m||!g){v.sendAuditExplainResult(d.requestId,{ok:!1,error:"that finding is not on this runner any more"});return}let R=x(d.projectId);if(!R){v.sendAuditExplainResult(d.requestId,{ok:!1,error:A(d.projectId)});return}let j=Me(t,R.project,"assist");if("error"in j){v.sendAuditExplainResult(d.requestId,{ok:!1,error:j.error});return}let G=`Explain ONE audit finding to a smart person who is not a programmer - they have to decide whether to fix it now, later, or accept the risk, and the finding below was written for engineers.
1064
1074
 
1065
- FINDING (${y.severity}${y.ruleId?`, rule ${y.ruleId}`:""}):
1066
- ${y.title}
1067
- `+y.evidence.map(B=>`- ${B.file}${B.line?`:${B.line}`:""} ${B.note}`.trim()).join(`
1068
- `)+(y.fix?`
1069
- Proposed fix: ${y.fix}`:"")+`
1075
+ FINDING (${g.severity}${g.ruleId?`, rule ${g.ruleId}`:""}):
1076
+ ${g.title}
1077
+ `+g.evidence.map(B=>`- ${B.file}${B.line?`:${B.line}`:""} ${B.note}`.trim()).join(`
1078
+ `)+(g.fix?`
1079
+ Proposed fix: ${g.fix}`:"")+`
1070
1080
 
1071
1081
  You may Read the cited files to understand the context - do NOT search for new problems; you are explaining this one, not auditing.
1072
1082
 
@@ -1075,7 +1085,7 @@ Answer in EXACTLY these four short sections, plain words, no jargon without an i
1075
1085
  **What can happen if ignored:** a concrete story, not a category ("someone could..." with the actual consequence), and how LIKELY that is for this project.
1076
1086
  **How urgent:** now / before the next release / when convenient - and why.
1077
1087
  **What fixing it takes:** rough size (an hour, a day, a project) and whether anything visible to users changes.
1078
- Nothing else - no preamble, no code.`,X=await j.adapter.run({repoPath:R.repoPath,prompt:G,timeoutSeconds:120,bin:j.bin,mode:"read_only",maxTurns:8,sessionId:(0,qr.randomUUID)(),onLog:()=>{}}),U=X.resultText.trim();if(!X.ok||!U){v.sendAuditExplainResult(d.requestId,{ok:!1,error:X.error??"the agent returned nothing - try again"});return}v.sendAuditExplainResult(d.requestId,{ok:!0,explanation:U})}catch(m){v.sendAuditExplainResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditGet:async d=>{try{let m=tl(d.projectId,d.auditId);if(!m){v.sendAuditGetResult(d.requestId,{ok:!1,error:"audit not found on this runner"});return}v.sendAuditGetResult(d.requestId,{ok:!0,audit:m})}catch(m){v.sendAuditGetResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditReview:async d=>{try{let m=el(d.projectId,d.auditId,{selected:d.selected,ticketed:d.ticketed,verdicts:d.verdicts,verdictBy:d.verdictBy});if(!m){v.sendAuditReviewResult(d.requestId,{ok:!1,error:"audit not found on this runner"});return}let y=x(d.projectId);if(y&&d.verdicts.length){let R=[];for(let j of d.verdicts){if(j.verdict==="valid"||m.lessonsWritten.includes(j.findingId))continue;let G=m.findings.find(X=>X.id===j.findingId);G&&(ol(y.repoPath,m.role,kd(G,j.verdict,j.note,d.verdictBy)),R.push(j.findingId),g.info(`Lesson written (${m.role}): ${j.verdict} - ${G.title.slice(0,60)}`))}R.length&&(m=el(d.projectId,d.auditId,{markLessonsWritten:R})??m)}v.sendAuditReviewResult(d.requestId,{ok:!0,audit:m})}catch(m){v.sendAuditReviewResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onKnowledgeList:async d=>{let m=x(d.projectId);if(!m){v.sendKnowledgeListResult(d.requestId,{ok:!1,error:A(d.projectId)});return}try{v.sendKnowledgeListResult(d.requestId,{ok:!0,files:Sd(m.repoPath)})}catch(y){v.sendKnowledgeListResult(d.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onKnowledgeSave:async d=>{let m=x(d.projectId);if(!m){v.sendKnowledgeSaveResult(d.requestId,{ok:!1,error:A(d.projectId)});return}try{d.append?ol(m.repoPath,d.role,_d(d.content,d.by),d.level):Td(m.repoPath,d.role,d.level,d.source,d.name,d.content),g.info(`Knowledge ${d.append?"taught":"saved"}: ${d.role}/${d.level}/${d.name}`),v.sendKnowledgeSaveResult(d.requestId,{ok:!0})}catch(y){v.sendKnowledgeSaveResult(d.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onEpicList:async d=>{let m=x(d.projectId);if(!m){v.sendEpicListResult(d.requestId,{ok:!1,error:A(d.projectId)});return}try{let y=s(m.project.repoName);if(d.epicKey){let R=await y.epicChildren(d.epicKey);v.sendEpicListResult(d.requestId,{ok:!0,children:R})}else{let R=await y.searchEpics(m.project.jiraProjectKey);v.sendEpicListResult(d.requestId,{ok:!0,epics:R})}}catch(y){v.sendEpicListResult(d.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onEpicSuggest:async d=>{let m=x(d.projectId);if(!m){v.sendEpicSuggestResult(d.requestId,{ok:!1,error:A(d.projectId)});return}try{let y=s(m.project.repoName),R=await y.epicChildren(d.epicKey),j=td(R);if(!j.length){v.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(j.length===1){v.sendEpicSuggestResult(d.requestId,{ok:!0,issueKey:j[0].key,reason:"It's the only pending ticket left in this epic.",considered:1});return}let G=await Promise.all(j.slice(0,12).map(async ie=>{try{let Z=await y.getIssue(ie.key);return{...ie,description:Z.description}}catch{return{...ie,description:""}}})),X=(await y.getIssue(d.epicKey).catch(()=>null))?.summary??"";g.info(`Epic suggest: weighing ${G.length} pending children of ${d.epicKey}`);let U=Me(t,m.project,"assist");if("error"in U){v.sendEpicSuggestResult(d.requestId,{ok:!1,error:U.error});return}let B=await U.adapter.run({repoPath:m.repoPath,prompt:nd(d.epicKey,X,G),timeoutSeconds:150,bin:U.bin,mode:"read_only",maxTurns:20,sessionId:(0,qr.randomUUID)(),model:d.model||"claude-sonnet-5",onLog:()=>{}}),q=rd(B.resultText,G.map(ie=>ie.key));if("error"in q){v.sendEpicSuggestResult(d.requestId,{ok:!1,error:q.error});return}g.info(`Epic suggest: ${d.epicKey} -> do ${q.issueKey} first`),v.sendEpicSuggestResult(d.requestId,{ok:!0,issueKey:q.issueKey,reason:q.reason,considered:G.length})}catch(y){v.sendEpicSuggestResult(d.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onTeamCreds:async d=>{try{let m=be()??t;if(m.github?.token&&!m.github.login)try{let{GitHubClient:R}=await Promise.resolve().then(()=>(mt(),wr));m.github.login=await new R(m.github.token).whoami(),ge(m)}catch{}let y=Vu(m,d.emails);v.sendTeamCredsResult(d.requestId,{ok:!0,...y})}catch(m){v.sendTeamCredsResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRepoUnmap:d=>{try{let m=be();if(!m){v.sendRepoUnmapResult(d.requestId,{ok:!1,error:"this runner has no config file"});return}let y=m.repos[d.repoName];if(!y){v.sendRepoUnmapResult(d.requestId,{ok:!0,removedPath:""});return}let R=y.path;delete m.repos[d.repoName];for(let j of Object.keys(m.environments).filter(G=>G.startsWith(`${d.repoName}:`)))delete m.environments[j];m.auditSchedules=m.auditSchedules.filter(j=>j.repoName!==d.repoName),ge(m),rn(),g.info(`Unmapped "${d.repoName}" (was ${R}) - its project was deleted on the dashboard. The checkout on disk was NOT touched.`),v.sendRepoUnmapResult(d.requestId,{ok:!0,removedPath:R})}catch(m){v.sendRepoUnmapResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupRecheck:d=>{try{let m=x(d.projectId);if(!m){v.sendSetupRecheckResult(d.requestId,{ok:!1,error:A(d.projectId)});return}v.sendSetupRecheckResult(d.requestId,{ok:!0,checks:yh({repoPath:m.repoPath,environments:d.environments})})}catch(m){v.sendSetupRecheckResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupStatus:async d=>{try{let m=be()??t,{buildSetupReport:y}=await Promise.resolve().then(()=>(Uf(),Lf)),R=await y(m,d.repoNames,t);v.sendSetupStatusResult(d.requestId,{ok:!0,...R})}catch(m){v.sendSetupStatusResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdGenerate:async d=>{try{let m=x(d.projectId);if(!m){v.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let y=d.kind==="deploy"?"DEPLOY.md":d.kind==="design"?"DESIGN.md":"CLAUDE.md";g.info(`Setup: drafting ${y} for ${m.project.repoName}`);let R="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.",j=`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.
1088
+ Nothing else - no preamble, no code.`,X=await j.adapter.run({repoPath:R.repoPath,prompt:G,timeoutSeconds:120,bin:j.bin,mode:"read_only",maxTurns:8,sessionId:(0,Fr.randomUUID)(),onLog:()=>{}}),U=X.resultText.trim();if(!X.ok||!U){v.sendAuditExplainResult(d.requestId,{ok:!1,error:X.error??"the agent returned nothing - try again"});return}v.sendAuditExplainResult(d.requestId,{ok:!0,explanation:U})}catch(m){v.sendAuditExplainResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditGet:async d=>{try{let m=sl(d.projectId,d.auditId);if(!m){v.sendAuditGetResult(d.requestId,{ok:!1,error:"audit not found on this runner"});return}v.sendAuditGetResult(d.requestId,{ok:!0,audit:m})}catch(m){v.sendAuditGetResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditReview:async d=>{try{let m=rl(d.projectId,d.auditId,{selected:d.selected,ticketed:d.ticketed,verdicts:d.verdicts,verdictBy:d.verdictBy});if(!m){v.sendAuditReviewResult(d.requestId,{ok:!1,error:"audit not found on this runner"});return}let g=x(d.projectId);if(g&&d.verdicts.length){let R=[];for(let j of d.verdicts){if(j.verdict==="valid"||m.lessonsWritten.includes(j.findingId))continue;let G=m.findings.find(X=>X.id===j.findingId);G&&(cl(g.repoPath,m.role,Cd(G,j.verdict,j.note,d.verdictBy)),R.push(j.findingId),y.info(`Lesson written (${m.role}): ${j.verdict} - ${G.title.slice(0,60)}`))}R.length&&(m=rl(d.projectId,d.auditId,{markLessonsWritten:R})??m)}v.sendAuditReviewResult(d.requestId,{ok:!0,audit:m})}catch(m){v.sendAuditReviewResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onKnowledgeList:async d=>{let m=x(d.projectId);if(!m){v.sendKnowledgeListResult(d.requestId,{ok:!1,error:A(d.projectId)});return}try{v.sendKnowledgeListResult(d.requestId,{ok:!0,files:Pd(m.repoPath)})}catch(g){v.sendKnowledgeListResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onKnowledgeSave:async d=>{let m=x(d.projectId);if(!m){v.sendKnowledgeSaveResult(d.requestId,{ok:!1,error:A(d.projectId)});return}try{d.append?cl(m.repoPath,d.role,$d(d.content,d.by),d.level):jd(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}`),v.sendKnowledgeSaveResult(d.requestId,{ok:!0})}catch(g){v.sendKnowledgeSaveResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onEpicList:async d=>{let m=x(d.projectId);if(!m){v.sendEpicListResult(d.requestId,{ok:!1,error:A(d.projectId)});return}try{let g=s(m.project.repoName);if(d.epicKey){let R=await g.epicChildren(d.epicKey);v.sendEpicListResult(d.requestId,{ok:!0,children:R})}else{let R=await g.searchEpics(m.project.jiraProjectKey);v.sendEpicListResult(d.requestId,{ok:!0,epics:R})}}catch(g){v.sendEpicListResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onEpicSuggest:async d=>{let m=x(d.projectId);if(!m){v.sendEpicSuggestResult(d.requestId,{ok:!1,error:A(d.projectId)});return}try{let g=s(m.project.repoName),R=await g.epicChildren(d.epicKey),j=ud(R);if(!j.length){v.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(j.length===1){v.sendEpicSuggestResult(d.requestId,{ok:!0,issueKey:j[0].key,reason:"It's the only pending ticket left in this epic.",considered:1});return}let G=await Promise.all(j.slice(0,12).map(async se=>{try{let Z=await g.getIssue(se.key);return{...se,description:Z.description}}catch{return{...se,description:""}}})),X=(await g.getIssue(d.epicKey).catch(()=>null))?.summary??"";y.info(`Epic suggest: weighing ${G.length} pending children of ${d.epicKey}`);let U=Me(t,m.project,"assist");if("error"in U){v.sendEpicSuggestResult(d.requestId,{ok:!1,error:U.error});return}let B=await U.adapter.run({repoPath:m.repoPath,prompt:dd(d.epicKey,X,G),timeoutSeconds:150,bin:U.bin,mode:"read_only",maxTurns:20,sessionId:(0,Fr.randomUUID)(),model:d.model||"claude-sonnet-5",onLog:()=>{}}),q=hd(B.resultText,G.map(se=>se.key));if("error"in q){v.sendEpicSuggestResult(d.requestId,{ok:!1,error:q.error});return}y.info(`Epic suggest: ${d.epicKey} -> do ${q.issueKey} first`),v.sendEpicSuggestResult(d.requestId,{ok:!0,issueKey:q.issueKey,reason:q.reason,considered:G.length})}catch(g){v.sendEpicSuggestResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onTeamCreds:async d=>{try{let m=we()??t;if(m.github?.token&&!m.github.login)try{let{GitHubClient:R}=await Promise.resolve().then(()=>(gt(),vr));m.github.login=await new R(m.github.token).whoami(),ge(m)}catch{}let g=sd(m,d.emails);v.sendTeamCredsResult(d.requestId,{ok:!0,...g})}catch(m){v.sendTeamCredsResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRepoUnmap:d=>{try{let m=we();if(!m){v.sendRepoUnmapResult(d.requestId,{ok:!1,error:"this runner has no config file"});return}let g=m.repos[d.repoName];if(!g){v.sendRepoUnmapResult(d.requestId,{ok:!0,removedPath:""});return}let R=g.path;delete m.repos[d.repoName];for(let j of Object.keys(m.environments).filter(G=>G.startsWith(`${d.repoName}:`)))delete m.environments[j];m.auditSchedules=m.auditSchedules.filter(j=>j.repoName!==d.repoName),ge(m),sn(),y.info(`Unmapped "${d.repoName}" (was ${R}) - its project was deleted on the dashboard. The checkout on disk was NOT touched.`),v.sendRepoUnmapResult(d.requestId,{ok:!0,removedPath:R})}catch(m){v.sendRepoUnmapResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupRecheck:d=>{try{let m=x(d.projectId);if(!m){v.sendSetupRecheckResult(d.requestId,{ok:!1,error:A(d.projectId)});return}v.sendSetupRecheckResult(d.requestId,{ok:!0,checks:Rh({repoPath:m.repoPath,environments:d.environments})})}catch(m){v.sendSetupRecheckResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupStatus:async d=>{try{let m=we()??t,{buildSetupReport:g}=await Promise.resolve().then(()=>(Qf(),Xf)),R=await g(m,d.repoNames,t);v.sendSetupStatusResult(d.requestId,{ok:!0,...R})}catch(m){v.sendSetupStatusResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdGenerate:async d=>{try{let m=x(d.projectId);if(!m){v.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 R="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.",j=`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.
1079
1089
 
1080
1090
  Ten things decide whether this document can actually be run:
1081
1091
  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.
@@ -1094,7 +1104,7 @@ Reply with ONLY the file content - no preamble, no fences around the whole thing
1094
1104
  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:
1095
1105
  `+d.environments.map(Z=>`- ${Z.name}`+(Z.branch?` (branch ${Z.branch})`:"")+(Z.publicUrl?` serves ${Z.publicUrl}`:" - no URL given")+(Z.onThisRunner?", its deploy commands run ON THIS MACHINE, in "+(Z.workdir?`${Z.workdir}`:Z.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(`
1096
1106
  `)+`
1097
- 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"?xl({repoPath:m.repoPath,urls:d.environments.map(Z=>Z.publicUrl).filter(Boolean)})+ks(m.repoPath):""),G=`Explore this repository's UI code and draft the content of a DESIGN.md file for its repo root - the design guidelines AI agents will follow for anything user-facing here. This is a SEED DRAFT: extract only what the code proves, and leave taste to the humans. Cover, from real evidence (tailwind/theme configs, design tokens, CSS, component libraries, existing screens): the color palette actually in use (names + hex), typography (families, the size scale), spacing and layout conventions, the component idiom (which library, how buttons/forms/cards are built, naming), dark mode, responsive breakpoints, and accessibility patterns already present. For everything code cannot prove - brand intent, tone of voice, look-and-feel references, what to never do - write a line starting with "VERIFY:" phrased as a question for the human to answer during review, instead of guessing. If the project has no UI at all, say exactly that in one line and stop. Under 120 lines, factual, no marketing language. Reply with ONLY the file content - no preamble, no fences around the whole thing.`,X=`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.
1107
+ 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"?El({repoPath:m.repoPath,urls:d.environments.map(Z=>Z.publicUrl).filter(Boolean)})+_s(m.repoPath):""),G=`Explore this repository's UI code and draft the content of a DESIGN.md file for its repo root - the design guidelines AI agents will follow for anything user-facing here. This is a SEED DRAFT: extract only what the code proves, and leave taste to the humans. Cover, from real evidence (tailwind/theme configs, design tokens, CSS, component libraries, existing screens): the color palette actually in use (names + hex), typography (families, the size scale), spacing and layout conventions, the component idiom (which library, how buttons/forms/cards are built, naming), dark mode, responsive breakpoints, and accessibility patterns already present. For everything code cannot prove - brand intent, tone of voice, look-and-feel references, what to never do - write a line starting with "VERIFY:" phrased as a question for the human to answer during review, instead of guessing. If the project has no UI at all, say exactly that in one line and stop. Under 120 lines, factual, no marketing language. Reply with ONLY the file content - no preamble, no fences around the whole thing.`,X=`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.
1098
1108
 
1099
1109
  BLOCKERS AS REPORTED:
1100
1110
  `+d.blockers.map((Z,he)=>`${he+1}. ${Z}`).join(`
@@ -1134,4 +1144,4 @@ Reply with ONLY the guide - no preamble.`+(d.environments.length?`
1134
1144
 
1135
1145
  THE ENVIRONMENTS AS ALLWRIGHT HAS THEM TODAY - your instructions have to end with these matching reality:
1136
1146
  `+d.environments.map(Z=>`- ${Z.name}`+(Z.branch?` (branch ${Z.branch})`:"")+(Z.publicUrl?` serves ${Z.publicUrl}`:"")+(Z.onThisRunner?", deploy commands run ON THIS MACHINE, in "+(Z.workdir?Z.workdir:Z.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(`
1137
- `):"")+xl({repoPath:m.repoPath,urls:d.environments.map(Z=>Z.publicUrl).filter(Boolean)})+ks(m.repoPath),U=Me(t,m.project,"assist");if("error"in U){v.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,content:"",error:U.error});return}let B=0,ie=(await U.adapter.run({repoPath:m.repoPath,prompt:d.kind==="deploy"?j:d.kind==="design"?G:d.kind==="unblock"?X:R,timeoutSeconds:600,bin:U.bin,mode:"read_only",maxTurns:40,sessionId:(0,qr.randomUUID)(),onLog:(Z,he)=>{Z==="agent"&&d.streamId&&v.send({type:"chat.stream",requestId:d.streamId,seq:B++,text:he.slice(0,8e3)})}})).resultText.trim();if(!ie){v.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:"the agent returned no content - try again"});return}v.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!0,content:ie})}catch(m){v.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdSave:async d=>{try{let m=x(d.projectId);if(!m){v.sendSetupClaudeMdSaveResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let y=d.kind==="deploy"?"DEPLOY.md":d.kind==="design"?"DESIGN.md":"CLAUDE.md",R=await yc({repoPath:m.repoPath,relPath:y,content:d.content,overwrite:d.overwrite,commitMessage:`Add ${y} (agent-drafted, human-approved via Allwright)`});R.ok&&g.info(`Setup: wrote human-approved ${y} to ${m.repoPath} - ${R.note}`),v.sendSetupClaudeMdSaveResult(d.requestId,R)}catch(m){v.sendSetupClaudeMdSaveResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRepoDocSave:async d=>{try{let m=x(d.projectId);if(!m){v.sendRepoDocSaveResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let y=await yc({repoPath:m.repoPath,relPath:d.relPath,content:d.content,overwrite:d.overwrite,commitMessage:`Add ${d.relPath.trim()} (written in Allwright Compose, human-approved)`});y.ok&&g.info(`Saved approved doc ${d.relPath} into ${m.repoPath}`),v.sendRepoDocSaveResult(d.requestId,y)}catch(m){v.sendRepoDocSaveResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditStats:d=>{try{v.sendAuditStatsResult(d.requestId,{ok:!0,byProject:pd(d.projectIds,d.since)})}catch(m){v.sendAuditStatsResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRunnerUpdate:async d=>{if(!process.env.INVOCATION_ID){v.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=()=>{g.info("Installing allwright@latest");let R=nn.default.dirname(process.execPath),j=Ve.default.existsSync(nn.default.join(R,"npm"))?nn.default.join(R,"npm"):"npm";(0,sn.execFile)(j,["install","-g","allwright@latest"],{timeout:18e4,env:{...process.env,PATH:`${R}:${process.env.PATH??""}`}},(G,X,U)=>{if(G){v.sendRunnerUpdateResult(d.requestId,{ok:!1,error:`npm install failed: ${(U||G.message).slice(0,300)} - on the machine run: allwright update && sudo systemctl restart allwright`});return}v.sendRunnerUpdateResult(d.requestId,{ok:!0,note:"updated - restarting now, back in a few seconds"}),g.info("Update installed; exiting so systemd restarts on the new version"),setTimeout(()=>process.exit(0),1500)})};if(f.idle){m();return}if(w){v.sendRunnerUpdateResult(d.requestId,{ok:!0,scheduled:!0,note:"an update is already scheduled and will install once the current work finishes"});return}let y=f.busyCount;v.sendRunnerUpdateResult(d.requestId,{ok:!0,scheduled:!0,note:`scheduled - ${y} run(s)/deploy(s) active right now. Nothing is refused meanwhile; the install runs automatically as soon as this machine goes idle.`}),g.info(`Update scheduled: waiting for ${y} active run(s)/deploy(s) to finish`),w=setInterval(()=>{f.idle&&(clearInterval(w),w=null,m())},5e3)},onRunnerUninstall:d=>{if(!f.idle){v.sendRunnerUninstallResult(d.requestId,{ok:!1,error:`${f.busyCount} run(s)/deploy(s) are executing on this machine right now - nothing was uninstalled.`});return}let m;try{m=Ya()}catch(R){v.sendRunnerUninstallResult(d.requestId,{ok:!1,error:R instanceof Error?R.message:String(R)});return}let y=m.problems.length===0;if(v.sendRunnerUninstallResult(d.requestId,{ok:y,error:y?void 0:m.problems.join("; "),note:y?[m.serviceRemoved?"service stopped and removed":"no systemd service was installed here",m.configRemoved?`config deleted (${m.removedPaths.join(", ")}) - the Jira and GitHub tokens went with it`:"no runner config was left to delete","checkouts untouched"].join("; "):"",serviceRemoved:m.serviceRemoved||m.serviceAbsent,configRemoved:m.configRemoved}),!y){g.info("Uninstall requested from the dashboard, but it could not complete here");return}g.info("Uninstalled from the dashboard - stopping now. Checkouts were not touched."),setTimeout(()=>{Ja(),process.exit(0)},1500)},onTestFix:async d=>{let m=y=>v.sendTestFixResult(d.requestId,{ok:!1,note:y});try{let y=ys(d.runId);if(!y){m("this runner no longer has that PR on file - it may have been decided already");return}let R=t.repos[y.repoName];if(!R){m(`no local checkout mapped for "${y.repoName}" on this machine`);return}let j=je(t,y.repoName);if(!j){m("no GitHub token on this runner for that repo");return}let G=await new Ne(j).getPullRequest(y.owner,y.repo,y.prNumber);if(!G){m("that pull request no longer exists on GitHub");return}if(G.merged||G.state==="closed"){m("that pull request is already merged or closed - there is nothing left to fix");return}let X=c.find(ie=>ie.repoName===y.repoName),U=y.nextDecisionSeq??1e5,B=(ie,Z)=>{v.send({type:"run.log",runId:d.runId,seq:U++,ts:new Date().toISOString(),level:ie,message:Z}),y.nextDecisionSeq=U,gt(y)},q=await Gh({cfg:t,repoPath:R.path,branch:y.branch,baseBranch:G.baseRef||"main",issueKey:y.issueKey,agentId:X?.defaultAgent||Je.DEFAULT_AGENT_ID,configDir:y.agentConfigDir,failedTests:d.failedTests,timeoutSeconds:900,onLog:B});q.ok&&q.headSha&&(y.headSha=q.headSha,gt(y),v.send({type:"run.status",runId:d.runId,status:"awaiting_approval",headSha:q.headSha,failedTests:q.remaining??[],...q.testsPassed!==void 0?{testsPassed:q.testsPassed}:{},...q.testsTotal!==void 0?{testsTotal:q.testsTotal}:{},...q.costUsd!==void 0?{costUsd:q.costUsd}:{},...q.inputTokens!==void 0?{inputTokens:q.inputTokens}:{},...q.outputTokens!==void 0?{outputTokens:q.outputTokens}:{}})),ft(R.path,{issueKey:y.issueKey,runId:d.runId,title:q.ok?q.headSha?(q.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:q.note.slice(0,500)}),v.sendTestFixResult(d.requestId,q)}catch(y){m(y instanceof Error?y.message.slice(0,300):String(y))}},onRunAnswer:async d=>{try{let m=await f.answerPendingInput(d.runId,d.text,d.answeredBy);v.sendRunAnswerResult(d.requestId,m)}catch(m){v.sendRunAnswerResult(d.requestId,{ok:!1,error:m instanceof Error?m.message.slice(0,300):String(m)})}},onResolveConflict:async d=>{let m=y=>v.sendResolveConflictResult(d.requestId,{ok:!1,note:y});try{let y=ys(d.runId);if(!y){m("this runner no longer has that PR on file - it may have been decided already");return}let R=t.repos[y.repoName];if(!R){m(`no local checkout mapped for "${y.repoName}" on this machine`);return}let j=je(t,y.repoName);if(!j){m("no GitHub token on this runner for that repo");return}let G=await new Ne(j).getPullRequest(y.owner,y.repo,y.prNumber);if(!G){m("that pull request no longer exists on GitHub");return}if(!G.baseRef){m("GitHub did not report the PR's base branch, so there is nothing to merge in");return}let X=c.find(ie=>ie.repoName===y.repoName),U=y.nextDecisionSeq??1e5,B=(ie,Z)=>{v.send({type:"run.log",runId:d.runId,seq:U++,ts:new Date().toISOString(),level:ie,message:Z}),y.nextDecisionSeq=U,gt(y)},q=await Kh({cfg:t,repoPath:R.path,branch:y.branch,baseBranch:G.baseRef,issueKey:y.issueKey,agentId:X?.defaultAgent||Je.DEFAULT_AGENT_ID,configDir:y.agentConfigDir,timeoutSeconds:900,onLog:B});q.ok&&q.headSha&&(y.headSha=q.headSha,y.conflictNotified=!1,gt(y),v.send({type:"run.pr.conflict",runId:d.runId,conflicted:!1}),v.send({type:"run.status",runId:d.runId,status:"awaiting_approval",headSha:q.headSha,...q.costUsd!==void 0?{costUsd:q.costUsd}:{},...q.inputTokens!==void 0?{inputTokens:q.inputTokens}:{},...q.outputTokens!==void 0?{outputTokens:q.outputTokens}:{}})),v.sendResolveConflictResult(d.requestId,q)}catch(y){m(y instanceof Error?y.message.slice(0,300):String(y))}},onAgentProfiles:d=>{try{let m=R=>{try{return Ve.default.existsSync(R)&&Ve.default.readdirSync(R).length>0}catch{return!1}},y=Object.entries(t.claudeProfiles).map(([R,j])=>({agent:"claude-code",name:R,loggedIn:m(j.configDir)}));v.sendAgentProfilesResult(d.requestId,{ok:!0,profiles:y,defaultLoggedIn:m(nn.default.join(pi.default.homedir(),".claude")),agentsWithoutProfiles:Je.REGISTERED_AGENTS.filter(R=>!R.capabilities.loginProfiles).map(R=>R.id)})}catch(m){v.sendAgentProfilesResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onJiraUsers:async d=>{try{let m=await n.searchUsers(d.query);v.sendJiraUsersResult(d.requestId,{ok:!0,users:m})}catch(m){v.sendJiraUsersResult(d.requestId,{ok:!1,users:[],error:m instanceof Error?m.message:String(m)})}}});b.transport=v,f=new Io(t,s,v);let L=Object.values(kr()).filter(d=>d.kind==="implement").map(d=>d.repoPath);ja(Object.values(t.repos).map(d=>d.path),L).catch(()=>{}),v.start(),f.start();let O=()=>{g.info("shutting down"),w&&clearInterval(w),v.stop(),au(process.pid),va(),process.exit(0)},Y=!1,M=()=>{if(Y){g.warn("second stop signal - exiting NOW; the interrupted run will be marked failed"),O();return}if(Y=!0,f.stop(),f.idle){O();return}g.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",M),process.on("SIGTERM",M),process.on("SIGHUP",()=>{try{let d=le();for(let m of Object.keys(t))delete t[m];Object.assign(t,d),n=d.jira?new Pe(d.jira):Ka(),r.clear(),g.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){g.error(`config reload failed - keeping the running config: ${d instanceof Error?d.message:String(d)}`)}})}Re.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=le();if(t.foreground){Hk(e);return}let n=Wn();if(n&&Vn(n)){g.info(`already running in the background (pid ${n}). Use \`allwright status\` or \`stop\`.`);return}let r=es();if(r){g.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=iu(),i=(0,sn.spawn)(process.execPath,[process.argv[1],"start","--foreground"],{detached:!0,stdio:["ignore",s,s]});i.unref(),ou(i.pid),g.info(`Runner started in the background (pid ${i.pid}).`),g.info(`Logs: ${Pi()}`),g.info("It will keep polling Jira until you run `allwright stop` - closing this terminal is fine.")});Re.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=Wn();if(!e||!Vn(e)){g.info("no background runner is running"),e&&Ve.default.rmSync(Qr(),{force:!0});return}if(t.force){process.kill(e,"SIGKILL"),Ve.default.rmSync(Qr(),{force:!0}),g.info(`killed (pid ${e}) - any interrupted run will show as failed on the dashboard`);return}process.kill(e,"SIGTERM"),g.info(`stop signal sent (pid ${e}) - it stops polling now and exits once active work finishes (watch \`allwright status\`). Use --force to kill immediately.`)});Re.command("status").description("Check whether the background runner is running").action(()=>{let t=Wn();t&&Vn(t)?g.info(`running in the background (pid ${t})`):g.info("not running")});Re.parseAsync().catch(t=>{g.error(t instanceof Error?t.message:String(t)),process.exit(1)});0&&(module.exports={parsePlanAnswer});
1147
+ `):"")+El({repoPath:m.repoPath,urls:d.environments.map(Z=>Z.publicUrl).filter(Boolean)})+_s(m.repoPath),U=Me(t,m.project,"assist");if("error"in U){v.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,content:"",error:U.error});return}let B=0,se=(await U.adapter.run({repoPath:m.repoPath,prompt:d.kind==="deploy"?j:d.kind==="design"?G:d.kind==="unblock"?X:R,timeoutSeconds:600,bin:U.bin,mode:"read_only",maxTurns:40,sessionId:(0,Fr.randomUUID)(),onLog:(Z,he)=>{Z==="agent"&&d.streamId&&v.send({type:"chat.stream",requestId:d.streamId,seq:B++,text:he.slice(0,8e3)})}})).resultText.trim();if(!se){v.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:"the agent returned no content - try again"});return}v.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!0,content:se})}catch(m){v.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdSave:async d=>{try{let m=x(d.projectId);if(!m){v.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",R=await _c({repoPath:m.repoPath,relPath:g,content:d.content,overwrite:d.overwrite,commitMessage:`Add ${g} (agent-drafted, human-approved via Allwright)`});R.ok&&y.info(`Setup: wrote human-approved ${g} to ${m.repoPath} - ${R.note}`),v.sendSetupClaudeMdSaveResult(d.requestId,R)}catch(m){v.sendSetupClaudeMdSaveResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRepoDocSave:async d=>{try{let m=x(d.projectId);if(!m){v.sendRepoDocSaveResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=await _c({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}`),v.sendRepoDocSaveResult(d.requestId,g)}catch(m){v.sendRepoDocSaveResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditStats:d=>{try{v.sendAuditStatsResult(d.requestId,{ok:!0,byProject:_d(d.projectIds,d.since)})}catch(m){v.sendAuditStatsResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRunnerUpdate:async d=>{if(!process.env.INVOCATION_ID){v.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 R=rn.default.dirname(process.execPath),j=Ve.default.existsSync(rn.default.join(R,"npm"))?rn.default.join(R,"npm"):"npm";(0,on.execFile)(j,["install","-g","allwright@latest"],{timeout:18e4,env:{...process.env,PATH:`${R}:${process.env.PATH??""}`}},(G,X,U)=>{if(G){v.sendRunnerUpdateResult(d.requestId,{ok:!1,error:`npm install failed: ${(U||G.message).slice(0,300)} - on the machine run: allwright update && sudo systemctl restart allwright`});return}v.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(w){v.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;v.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`),w=setInterval(()=>{f.idle&&(clearInterval(w),w=null,m())},5e3)},onRunnerUninstall:d=>{if(!f.idle){v.sendRunnerUninstallResult(d.requestId,{ok:!1,error:`${f.busyCount} run(s)/deploy(s) are executing on this machine right now - nothing was uninstalled.`});return}let m;try{m=el()}catch(R){v.sendRunnerUninstallResult(d.requestId,{ok:!1,error:R instanceof Error?R.message:String(R)});return}let g=m.problems.length===0;if(v.sendRunnerUninstallResult(d.requestId,{ok:g,error:g?void 0:m.problems.join("; "),note:g?[m.serviceRemoved?"service stopped and removed":"no systemd service was installed here",m.configRemoved?`config deleted (${m.removedPaths.join(", ")}) - the Jira and GitHub tokens went with it`:"no runner config was left to delete","checkouts untouched"].join("; "):"",serviceRemoved:m.serviceRemoved||m.serviceAbsent,configRemoved:m.configRemoved}),!g){y.info("Uninstall requested from the dashboard, but it could not complete here");return}y.info("Uninstalled from the dashboard - stopping now. Checkouts were not touched."),setTimeout(()=>{Qa(),process.exit(0)},1500)},onTestFix:async d=>{let m=g=>v.sendTestFixResult(d.requestId,{ok:!1,note:g});try{let g=bs(d.runId);if(!g){m("this runner no longer has that PR on file - it may have been decided already");return}let R=t.repos[g.repoName];if(!R){m(`no local checkout mapped for "${g.repoName}" on this machine`);return}let j=je(t,g.repoName);if(!j){m("no GitHub token on this runner for that repo");return}let G=await new Ne(j).getPullRequest(g.owner,g.repo,g.prNumber);if(!G){m("that pull request no longer exists on GitHub");return}if(G.merged||G.state==="closed"){m("that pull request is already merged or closed - there is nothing left to fix");return}let X=c.find(se=>se.repoName===g.repoName),U=g.nextDecisionSeq??1e5,B=(se,Z)=>{v.send({type:"run.log",runId:d.runId,seq:U++,ts:new Date().toISOString(),level:se,message:Z}),g.nextDecisionSeq=U,yt(g)},q=await tp({cfg:t,repoPath:R.path,branch:g.branch,baseBranch:G.baseRef||"main",issueKey:g.issueKey,agentId:X?.defaultAgent||Je.DEFAULT_AGENT_ID,configDir:g.agentConfigDir,failedTests:d.failedTests,timeoutSeconds:900,onLog:B});q.ok&&q.headSha&&(g.headSha=q.headSha,yt(g),v.send({type:"run.status",runId:d.runId,status:"awaiting_approval",headSha:q.headSha,failedTests:q.remaining??[],...q.testsPassed!==void 0?{testsPassed:q.testsPassed}:{},...q.testsTotal!==void 0?{testsTotal:q.testsTotal}:{},...q.costUsd!==void 0?{costUsd:q.costUsd}:{},...q.inputTokens!==void 0?{inputTokens:q.inputTokens}:{},...q.outputTokens!==void 0?{outputTokens:q.outputTokens}:{}})),mt(R.path,{issueKey:g.issueKey,runId:d.runId,title:q.ok?q.headSha?(q.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:q.note.slice(0,500)}),v.sendTestFixResult(d.requestId,q)}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);v.sendRunAnswerResult(d.requestId,m)}catch(m){v.sendRunAnswerResult(d.requestId,{ok:!1,error:m instanceof Error?m.message.slice(0,300):String(m)})}},onResolveConflict:async d=>{let m=g=>v.sendResolveConflictResult(d.requestId,{ok:!1,note:g});try{let g=bs(d.runId);if(!g){m("this runner no longer has that PR on file - it may have been decided already");return}let R=t.repos[g.repoName];if(!R){m(`no local checkout mapped for "${g.repoName}" on this machine`);return}let j=je(t,g.repoName);if(!j){m("no GitHub token on this runner for that repo");return}let G=await new Ne(j).getPullRequest(g.owner,g.repo,g.prNumber);if(!G){m("that pull request no longer exists on GitHub");return}if(!G.baseRef){m("GitHub did not report the PR's base branch, so there is nothing to merge in");return}let X=c.find(se=>se.repoName===g.repoName),U=g.nextDecisionSeq??1e5,B=(se,Z)=>{v.send({type:"run.log",runId:d.runId,seq:U++,ts:new Date().toISOString(),level:se,message:Z}),g.nextDecisionSeq=U,yt(g)},q=await Qh({cfg:t,repoPath:R.path,branch:g.branch,baseBranch:G.baseRef,issueKey:g.issueKey,agentId:X?.defaultAgent||Je.DEFAULT_AGENT_ID,configDir:g.agentConfigDir,timeoutSeconds:900,onLog:B});q.ok&&q.headSha&&(g.headSha=q.headSha,g.conflictNotified=!1,yt(g),v.send({type:"run.pr.conflict",runId:d.runId,conflicted:!1}),v.send({type:"run.status",runId:d.runId,status:"awaiting_approval",headSha:q.headSha,...q.costUsd!==void 0?{costUsd:q.costUsd}:{},...q.inputTokens!==void 0?{inputTokens:q.inputTokens}:{},...q.outputTokens!==void 0?{outputTokens:q.outputTokens}:{}})),v.sendResolveConflictResult(d.requestId,q)}catch(g){m(g instanceof Error?g.message.slice(0,300):String(g))}},onAgentProfiles:d=>{try{let m=R=>{try{return Ve.default.existsSync(R)&&Ve.default.readdirSync(R).length>0}catch{return!1}},g=Object.entries(t.claudeProfiles).map(([R,j])=>({agent:"claude-code",name:R,loggedIn:m(j.configDir)}));v.sendAgentProfilesResult(d.requestId,{ok:!0,profiles:g,defaultLoggedIn:m(rn.default.join(fi.default.homedir(),".claude")),agentsWithoutProfiles:Je.REGISTERED_AGENTS.filter(R=>!R.capabilities.loginProfiles).map(R=>R.id)})}catch(m){v.sendAgentProfilesResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onJiraUsers:async d=>{try{let m=await n.searchUsers(d.query);v.sendJiraUsersResult(d.requestId,{ok:!0,users:m})}catch(m){v.sendJiraUsersResult(d.requestId,{ok:!1,users:[],error:m instanceof Error?m.message:String(m)})}}});b.transport=v,f=new Eo(t,s,v);let L=Object.values(_r()).filter(d=>d.kind==="implement").map(d=>d.repoPath);Ma(Object.values(t.repos).map(d=>d.path),L).catch(()=>{}),v.start(),f.start();let O=()=>{y.info("shutting down"),w&&clearInterval(w),v.stop(),gu(process.pid),Sa(),process.exit(0)},Y=!1,M=()=>{if(Y){y.warn("second stop signal - exiting NOW; the interrupted run will be marked failed"),O();return}if(Y=!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",M),process.on("SIGTERM",M),process.on("SIGHUP",()=>{try{let d=le();for(let m of Object.keys(t))delete t[m];Object.assign(t,d),n=d.jira?new Pe(d.jira):Za(),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)}`)}})}Re.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=le();if(t.foreground){o_(e);return}let n=Vn();if(n&&Jn(n)){y.info(`already running in the background (pid ${n}). Use \`allwright status\` or \`stop\`.`);return}let r=ts();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=fu(),i=(0,on.spawn)(process.execPath,[process.argv[1],"start","--foreground"],{detached:!0,stdio:["ignore",s,s]});i.unref(),mu(i.pid),y.info(`Runner started in the background (pid ${i.pid}).`),y.info(`Logs: ${Pi()}`),y.info("It will keep polling Jira until you run `allwright stop` - closing this terminal is fine.")});Re.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=Vn();if(!e||!Jn(e)){y.info("no background runner is running"),e&&Ve.default.rmSync(es(),{force:!0});return}if(t.force){process.kill(e,"SIGKILL"),Ve.default.rmSync(es(),{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.`)});Re.command("status").description("Check whether the background runner is running").action(()=>{let t=Vn();t&&Jn(t)?y.info(`running in the background (pid ${t})`):y.info("not running")});Re.parseAsync().catch(t=>{y.error(t instanceof Error?t.message:String(t)),process.exit(1)});