allwright 1.81.0 → 1.83.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 +269 -254
  2. package/package.json +1 -1
package/bin/allwright.js CHANGED
@@ -1,42 +1,42 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Kg=Object.create;var Na=Object.defineProperty;var Gg=Object.getOwnPropertyDescriptor;var Wg=Object.getOwnPropertyNames;var Zg=Object.getPrototypeOf,Vg=Object.prototype.hasOwnProperty;var ne=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var de=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}},Kt=(t,e)=>{for(var n in e)Na(t,n,{get:e[n],enumerable:!0})},Yg=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Wg(e))!Vg.call(t,s)&&s!==n&&Na(t,s,{get:()=>e[s],enumerable:!(r=Gg(e,s))||r.enumerable});return t};var R=(t,e,n)=>(n=t!=null?Kg(Zg(t)):{},Yg(e||!t||!t.__esModule?Na(n,"default",{value:t,enumerable:!0}):n,t));var Vs=de(ja=>{var Gi=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}},Oa=class extends Gi{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};ja.CommanderError=Gi;ja.InvalidArgumentError=Oa});var Wi=de(za=>{var{InvalidArgumentError:Jg}=Vs(),Ma=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 Jg(`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 Xg(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}za.Argument=Ma;za.humanReadableArgName=Xg});var La=de(Fu=>{var{humanReadableArgName:Qg}=Wi(),Da=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=>Qg(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(_,I){if(I){let E=`${_.padEnd(r+o)}${I}`;return n.wrap(E,s-i,r+o)}return _}function c(_){return _.join(`
2
+ "use strict";var vy=Object.create;var Ba=Object.defineProperty;var ky=Object.getOwnPropertyDescriptor;var _y=Object.getOwnPropertyNames;var Sy=Object.getPrototypeOf,Ty=Object.prototype.hasOwnProperty;var te=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var he=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}},$t=(t,e)=>{for(var n in e)Ba(t,n,{get:e[n],enumerable:!0})},xy=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of _y(e))!Ty.call(t,s)&&s!==n&&Ba(t,s,{get:()=>e[s],enumerable:!(r=ky(e,s))||r.enumerable});return t};var E=(t,e,n)=>(n=t!=null?vy(Sy(t)):{},xy(e||!t||!t.__esModule?Ba(n,"default",{value:t,enumerable:!0}):n,t));var Xs=he(Ka=>{var Vi=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}},Ha=class extends Vi{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Ka.CommanderError=Vi;Ka.InvalidArgumentError=Ha});var Ji=he(Wa=>{var{InvalidArgumentError:Iy}=Xs(),Ga=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 Iy(`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 Ry(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}Wa.Argument=Ga;Wa.humanReadableArgName=Ry});var Va=he(Yu=>{var{humanReadableArgName:Ey}=Ji(),Za=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=>Ey(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(_,I){if(I){let R=`${_.padEnd(r+o)}${I}`;return n.wrap(R,s-i,r+o)}return _}function c(_){return _.join(`
3
3
  `).replace(/^/gm," ".repeat(i))}let d=[`Usage: ${n.commandUsage(e)}`,""],p=n.commandDescription(e);p.length>0&&(d=d.concat([n.wrap(p,s,0),""]));let f=n.visibleArguments(e).map(_=>l(n.argumentTerm(_),n.argumentDescription(_)));f.length>0&&(d=d.concat(["Arguments:",c(f),""]));let w=n.visibleOptions(e).map(_=>l(n.optionTerm(_),n.optionDescription(_)));if(w.length>0&&(d=d.concat(["Options:",c(w),""])),this.showGlobalOptions){let _=n.visibleGlobalOptions(e).map(I=>l(n.optionTerm(I),n.optionDescription(I)));_.length>0&&(d=d.concat(["Global Options:",c(_),""]))}let v=n.visibleCommands(e).map(_=>l(n.subcommandTerm(_),n.subcommandDescription(_)));return v.length>0&&(d=d.concat(["Commands:",c(v),""])),d.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),d=e.slice(r).replace(`\r
5
5
  `,`
6
6
  `),p=" ".repeat(r),w="\\s\u200B",v=new RegExp(`
7
- |.{1,${l-1}}([${w}]|$)|[^${w}]+?([${w}]|$)`,"g"),_=d.match(v)||[];return c+_.map((I,E)=>I===`
8
- `?"":(E>0?p:"")+I.trimEnd()).join(`
9
- `)}};Fu.Help=Da});var Ba=de(Fa=>{var{InvalidArgumentError:ey}=Vs(),Ua=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=ny(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 ey(`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 ty(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},qa=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 ty(t){return t.split("-").reduce((e,n)=>e+n[0].toUpperCase()+n.slice(1))}function ny(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}}Fa.Option=Ua;Fa.DualOptions=qa});var Hu=de(Bu=>{function ry(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 sy(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=ry(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?`
7
+ |.{1,${l-1}}([${w}]|$)|[^${w}]+?([${w}]|$)`,"g"),_=d.match(v)||[];return c+_.map((I,R)=>I===`
8
+ `?"":(R>0?p:"")+I.trimEnd()).join(`
9
+ `)}};Yu.Help=Za});var Qa=he(Xa=>{var{InvalidArgumentError:Ay}=Xs(),Ja=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=$y(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 Ay(`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 Cy(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Ya=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 Cy(t){return t.split("-").reduce((e,n)=>e+n[0].toUpperCase()+n.slice(1))}function $y(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}}Xa.Option=Ja;Xa.DualOptions=Ya});var Qu=he(Xu=>{function Py(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 Ny(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=Py(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]}?)`:""}Bu.suggestSimilar=sy});var Vu=de(Zu=>{var iy=require("node:events").EventEmitter,Ha=require("node:child_process"),Gt=require("node:path"),Ka=require("node:fs"),ve=require("node:process"),{Argument:oy,humanReadableArgName:ay}=Wi(),{CommanderError:Ga}=Vs(),{Help:ly}=La(),{Option:Ku,DualOptions:cy}=Ba(),{suggestSimilar:Gu}=Hu(),Wa=class t extends iy{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=>ve.stdout.write(n),writeErr:n=>ve.stderr.write(n),getOutHelpWidth:()=>ve.stdout.isTTY?ve.stdout.columns:void 0,getErrHelpWidth:()=>ve.stderr.isTTY?ve.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 ly,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 oy(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 Ga(e,n,r)),ve.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 Ku(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 Ku)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,d)=>{let p=l.exec(c);return p?p[0]:d},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){ve.versions?.electron&&(n.from="electron");let s=ve.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(n.from="eval")}e===void 0&&(e=ve.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":ve.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=Gt.resolve(p,f);if(Ka.existsSync(w))return w;if(s.includes(Gt.extname(f)))return;let v=s.find(_=>Ka.existsSync(`${w}${_}`));if(v)return`${w}${v}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,l=this._executableDir||"";if(this._scriptPath){let p;try{p=Ka.realpathSync(this._scriptPath)}catch{p=this._scriptPath}l=Gt.resolve(Gt.dirname(p),l)}if(l){let p=i(l,o);if(!p&&!e._executableFile&&this._scriptPath){let f=Gt.basename(this._scriptPath,Gt.extname(this._scriptPath));f!==this._name&&(p=i(l,`${f}-${e._name}`))}o=p||o}r=s.includes(Gt.extname(o));let c;ve.platform!=="win32"?r?(n.unshift(o),n=Wu(ve.execArgv).concat(n),c=Ha.spawn(ve.argv[0],n,{stdio:"inherit"})):c=Ha.spawn(o,n,{stdio:"inherit"}):(n.unshift(o),n=Wu(ve.execArgv).concat(n),c=Ha.spawn(ve.execPath,n,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{ve.on(f,()=>{c.killed===!1&&c.exitCode===null&&c.kill(f)})});let d=this._exitCallback;c.on("close",p=>{p=p??1,d?d(new Ga(p,"commander.executeSubCommandAsync","(close)")):ve.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]}?)`:""}Xu.suggestSimilar=Ny});var sd=he(rd=>{var jy=require("node:events").EventEmitter,el=require("node:child_process"),Jt=require("node:path"),tl=require("node:fs"),_e=require("node:process"),{Argument:Oy,humanReadableArgName:My}=Ji(),{CommanderError:nl}=Xs(),{Help:zy}=Va(),{Option:ed,DualOptions:Dy}=Qa(),{suggestSimilar:td}=Qu(),rl=class t extends jy{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=>_e.stdout.write(n),writeErr:n=>_e.stderr.write(n),getOutHelpWidth:()=>_e.stdout.isTTY?_e.stdout.columns:void 0,getErrHelpWidth:()=>_e.stderr.isTTY?_e.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 zy,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 Oy(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 nl(e,n,r)),_e.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 ed(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 ed)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,d)=>{let p=l.exec(c);return p?p[0]:d},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){_e.versions?.electron&&(n.from="electron");let s=_e.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(n.from="eval")}e===void 0&&(e=_e.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":_e.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=Jt.resolve(p,f);if(tl.existsSync(w))return w;if(s.includes(Jt.extname(f)))return;let v=s.find(_=>tl.existsSync(`${w}${_}`));if(v)return`${w}${v}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,l=this._executableDir||"";if(this._scriptPath){let p;try{p=tl.realpathSync(this._scriptPath)}catch{p=this._scriptPath}l=Jt.resolve(Jt.dirname(p),l)}if(l){let p=i(l,o);if(!p&&!e._executableFile&&this._scriptPath){let f=Jt.basename(this._scriptPath,Jt.extname(this._scriptPath));f!==this._name&&(p=i(l,`${f}-${e._name}`))}o=p||o}r=s.includes(Jt.extname(o));let c;_e.platform!=="win32"?r?(n.unshift(o),n=nd(_e.execArgv).concat(n),c=el.spawn(_e.argv[0],n,{stdio:"inherit"})):c=el.spawn(o,n,{stdio:"inherit"}):(n.unshift(o),n=nd(_e.execArgv).concat(n),c=el.spawn(_e.execPath,n,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{_e.on(f,()=>{c.killed===!1&&c.exitCode===null&&c.kill(f)})});let d=this._exitCallback;c.on("close",p=>{p=p??1,d?d(new nl(p,"commander.executeSubCommandAsync","(close)")):_e.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(!d)ve.exit(1);else{let f=new Ga(1,"commander.executeSubCommandAsync","(error)");f.nestedError=p,d(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 d=this._findOption(c);if(d){if(d.required){let p=i.shift();p===void 0&&this.optionMissingArgument(d),this.emit(`option:${d.name()}`,p)}else if(d.optional){let p=null;i.length>0&&!o(i[0])&&(p=i.shift()),this.emit(`option:${d.name()}`,p)}else this.emit(`option:${d.name()}`);l=d.variadic?d:null;continue}}if(c.length>2&&c[0]==="-"&&c[1]!=="-"){let d=this._findOption(`-${c[1]}`);if(d){d.required||d.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${d.name()}`,c.slice(2)):(this.emit(`option:${d.name()}`),i.unshift(`-${c.slice(2)}`));continue}}if(/^--[^=]+=/.test(c)){let d=c.indexOf("="),p=this._findOption(c.slice(0,d));if(p&&(p.required||p.optional)){this.emit(`option:${p.name()}`,c.slice(d+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(!d)_e.exit(1);else{let f=new nl(1,"commander.executeSubCommandAsync","(error)");f.nestedError=p,d(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 d=this._findOption(c);if(d){if(d.required){let p=i.shift();p===void 0&&this.optionMissingArgument(d),this.emit(`option:${d.name()}`,p)}else if(d.optional){let p=null;i.length>0&&!o(i[0])&&(p=i.shift()),this.emit(`option:${d.name()}`,p)}else this.emit(`option:${d.name()}`);l=d.variadic?d:null;continue}}if(c.length>2&&c[0]==="-"&&c[1]!=="-"){let d=this._findOption(`-${c[1]}`);if(d){d.required||d.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${d.name()}`,c.slice(2)):(this.emit(`option:${d.name()}`),i.unshift(`-${c.slice(2)}`));continue}}if(/^--[^=]+=/.test(c)){let d=c.indexOf("="),p=this._findOption(c.slice(0,d));if(p&&(p.required||p.optional)){this.emit(`option:${p.name()}`,c.slice(d+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 ve.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()}`,ve.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new cy(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),d=this.options.find(f=>f.negate&&l===f.attributeName()),p=this.options.find(f=>!f.negate&&l===f.attributeName());return d&&(d.presetArg===void 0&&c===!1||d.presetArg!==void 0&&c===d.presetArg)?d: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=Gu(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=Gu(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=>ay(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=Gt.basename(e,Gt.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=ve.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 _e.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()}`,_e.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Dy(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),d=this.options.find(f=>f.negate&&l===f.attributeName()),p=this.options.find(f=>!f.negate&&l===f.attributeName());return d&&(d.presetArg===void 0&&c===!1||d.presetArg!==void 0&&c===d.presetArg)?d: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=td(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=td(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=>My(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=Jt.basename(e,Jt.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=_e.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 Wu(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})}Zu.Command=Wa});var Qu=de(ot=>{var{Argument:Yu}=Wi(),{Command:Za}=Vu(),{CommanderError:uy,InvalidArgumentError:Ju}=Vs(),{Help:dy}=La(),{Option:Xu}=Ba();ot.program=new Za;ot.createCommand=t=>new Za(t);ot.createOption=(t,e)=>new Xu(t,e);ot.createArgument=(t,e)=>new Yu(t,e);ot.Command=Za;ot.Option=Xu;ot.Argument=Yu;ot.Help=dy;ot.CommanderError=uy;ot.InvalidArgumentError=Ju;ot.InvalidOptionArgumentError=Ju});var ce,Va,L,Rt,Ys=ne(()=>{(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function n(s){throw new Error}t.assertNever=n,t.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},t.getValidEnumValues=s=>{let i=t.objectKeys(s).filter(l=>typeof s[s[l]]!="number"),o={};for(let l of i)o[l]=s[l];return t.objectValues(o)},t.objectValues=s=>t.objectKeys(s).map(function(i){return s[i]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},t.find=(s,i)=>{for(let o of s)if(i(o))return o},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(ce||(ce={}));(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Va||(Va={}));L=ce.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Rt=t=>{switch(typeof t){case"undefined":return L.undefined;case"string":return L.string;case"number":return Number.isNaN(t)?L.nan:L.number;case"boolean":return L.boolean;case"function":return L.function;case"bigint":return L.bigint;case"symbol":return L.symbol;case"object":return Array.isArray(t)?L.array:t===null?L.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?L.promise:typeof Map<"u"&&t instanceof Map?L.map:typeof Set<"u"&&t instanceof Set?L.set:typeof Date<"u"&&t instanceof Date?L.date:L.object;default:return L.unknown}}});var A,hy,Ge,Zi=ne(()=>{Ys();A=ce.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"]),hy=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ge=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 d=o.path[c];c===o.path.length-1?(l[d]=l[d]||{_errors:[]},l[d]._errors.push(n(o))):l[d]=l[d]||{_errors:[]},l=l[d],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,ce.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()}};Ge.create=t=>new Ge(t)});var py,Wt,Ya=ne(()=>{Zi();Ys();py=(t,e)=>{let n;switch(t.code){case A.invalid_type:t.received===L.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case A.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,ce.jsonStringifyReplacer)}`;break;case A.unrecognized_keys:n=`Unrecognized key(s) in object: ${ce.joinValues(t.keys,", ")}`;break;case A.invalid_union:n="Invalid input";break;case A.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ce.joinValues(t.options)}`;break;case A.invalid_enum_value:n=`Invalid enum value. Expected ${ce.joinValues(t.options)}, received '${t.received}'`;break;case A.invalid_arguments:n="Invalid function arguments";break;case A.invalid_return_type:n="Invalid function return type";break;case A.invalid_date:n="Invalid date";break;case A.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}"`:ce.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case A.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 A.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 A.custom:n="Invalid input";break;case A.invalid_intersection_types:n="Intersection results could not be merged";break;case A.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case A.not_finite:n="Number must be finite";break;default:n=e.defaultError,ce.assertNever(t)}return{message:n}},Wt=py});function fy(t){nd=t}function es(){return nd}var nd,Vi=ne(()=>{Ya();nd=Wt});function z(t,e){let n=es(),r=Js({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Wt?void 0:Wt].filter(s=>!!s)});t.common.issues.push(r)}var Js,my,Oe,Q,Kn,Me,Yi,Ji,gn,ts,Ja=ne(()=>{Vi();Ya();Js=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(d=>!!d).slice().reverse();for(let d of c)l=d(o,{data:e,defaultError:l}).message;return{...s,path:i,message:l}},my=[];Oe=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 Q;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 Q;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}}},Q=Object.freeze({status:"aborted"}),Kn=t=>({status:"dirty",value:t}),Me=t=>({status:"valid",value:t}),Yi=t=>t.status==="aborted",Ji=t=>t.status==="dirty",gn=t=>t.status==="valid",ts=t=>typeof Promise<"u"&&t instanceof Promise});var rd=ne(()=>{});var K,sd=ne(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(K||(K={}))});function re(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 ld(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 Py(t){return new RegExp(`^${ld(t)}$`)}function cd(t){let e=`${ad}T${ld(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 Ny(t,e){return!!((e==="v4"||!e)&&xy.test(t)||(e==="v6"||!e)&&Ey.test(t))}function Oy(t,e){if(!ky.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 jy(t,e){return!!((e==="v4"||!e)&&Iy.test(t)||(e==="v6"||!e)&&Ry.test(t))}function My(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 ns(t){if(t instanceof We){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=at.create(ns(r))}return new We({...t._def,shape:()=>e})}else return t instanceof Yt?new Yt({...t._def,type:ns(t.element)}):t instanceof at?at.create(ns(t.unwrap())):t instanceof Ct?Ct.create(ns(t.unwrap())):t instanceof At?At.create(t.items.map(e=>ns(e))):t}function Qa(t,e){let n=Rt(t),r=Rt(e);if(t===e)return{valid:!0,data:t};if(n===L.object&&r===L.object){let s=ce.objectKeys(e),i=ce.objectKeys(t).filter(l=>s.indexOf(l)!==-1),o={...t,...e};for(let l of i){let c=Qa(t[l],e[l]);if(!c.valid)return{valid:!1};o[l]=c.data}return{valid:!0,data:o}}else if(n===L.array&&r===L.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=Qa(o,l);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===L.date&&r===L.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function ud(t,e){return new nr({values:t,typeName:ee.ZodEnum,...re(e)})}function od(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function dd(t,e={},n){return t?bn.create().superRefine((r,s)=>{let i=t(r);if(i instanceof Promise)return i.then(o=>{if(!o){let l=od(e,r),c=l.fatal??n??!0;s.addIssue({code:"custom",...l,fatal:c})}});if(!i){let o=od(e,r),l=o.fatal??n??!0;s.addIssue({code:"custom",...o,fatal:l})}}):bn.create()}var lt,id,le,gy,yy,by,wy,vy,ky,_y,Sy,Ty,Xa,xy,Iy,Ey,Ry,Ay,Cy,ad,$y,yn,Gn,Wn,Zn,Vn,rs,Yn,Jn,bn,Vt,vt,ss,Yt,We,Xn,Zt,Xi,Qn,At,Qi,is,os,eo,er,tr,nr,rr,wn,ct,at,Ct,sr,ir,as,zy,Xs,Qs,or,Dy,ee,Ly,hd,pd,Uy,qy,fd,Fy,By,Hy,Ky,Gy,Wy,Zy,Vy,Yy,Jy,Xy,Qy,eb,tb,nb,rb,sb,ib,ob,ab,lb,cb,ub,db,hb,pb,fb,mb,gb,yb,bb,wb,vb,kb,md=ne(()=>{Zi();Vi();sd();Ja();Ys();lt=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}},id=(t,e)=>{if(gn(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 Ge(t.common.issues);return this._error=n,this._error}}};le=class{get description(){return this._def.description}_getType(e){return Rt(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:Rt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Oe,ctx:{common:e.parent.common,data:e.data,parsedType:Rt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(ts(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:Rt(e)},s=this._parseSync({data:e,path:r.path,parent:r});return id(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Rt(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return gn(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=>gn(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:Rt(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(ts(s)?s:Promise.resolve(s));return id(r,i)}refine(e,n){let r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,i)=>{let o=e(s),l=()=>i.addIssue({code:A.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 ct({schema:this,typeName:ee.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 at.create(this,this._def)}nullable(){return Ct.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Yt.create(this)}promise(){return wn.create(this,this._def)}or(e){return Xn.create([this,e],this._def)}and(e){return Qn.create(this,e,this._def)}transform(e){return new ct({...re(this._def),schema:this,typeName:ee.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new sr({...re(this._def),innerType:this,defaultValue:n,typeName:ee.ZodDefault})}brand(){return new Xs({typeName:ee.ZodBranded,type:this,...re(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new ir({...re(this._def),innerType:this,catchValue:n,typeName:ee.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Qs.create(this,e)}readonly(){return or.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},gy=/^c[^\s-]{8,}$/i,yy=/^[0-9a-z]+$/,by=/^[0-9A-HJKMNP-TV-Z]{26}$/i,wy=/^[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,vy=/^[a-z0-9_-]{21}$/i,ky=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,_y=/^[-+]?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)?)??$/,Sy=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ty="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",xy=/^(?:(?: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])$/,Iy=/^(?:(?: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])$/,Ey=/^(([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]))$/,Ry=/^(([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])$/,Ay=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Cy=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ad="((\\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])))",$y=new RegExp(`^${ad}$`);yn=class t extends le{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==L.string){let i=this._getOrReturnCtx(e);return z(i,{code:A.invalid_type,expected:L.string,received:i.parsedType}),Q}let r=new Oe,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),z(s,{code:A.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),z(s,{code:A.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?z(s,{code:A.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):l&&z(s,{code:A.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")Sy.test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"email",code:A.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Xa||(Xa=new RegExp(Ty,"u")),Xa.test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"emoji",code:A.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")wy.test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"uuid",code:A.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")vy.test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"nanoid",code:A.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")gy.test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"cuid",code:A.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")yy.test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"cuid2",code:A.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")by.test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"ulid",code:A.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),z(s,{validation:"url",code:A.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),z(s,{validation:"regex",code:A.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),z(s,{code:A.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),z(s,{code:A.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),z(s,{code:A.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?cd(i).test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{code:A.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?$y.test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{code:A.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Py(i).test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{code:A.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?_y.test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"duration",code:A.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?Ny(e.data,i.version)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"ip",code:A.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?Oy(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"jwt",code:A.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?jy(e.data,i.version)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"cidr",code:A.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?Ay.test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"base64",code:A.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?Cy.test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"base64url",code:A.invalid_string,message:i.message}),r.dirty()):ce.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:A.invalid_string,...K.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...K.errToObj(e)})}url(e){return this._addCheck({kind:"url",...K.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...K.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...K.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...K.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...K.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...K.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...K.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...K.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...K.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...K.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...K.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...K.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,...K.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,...K.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...K.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...K.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...K.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...K.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...K.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...K.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...K.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...K.errToObj(n)})}nonempty(e){return this.min(1,K.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}};yn.create=t=>new yn({checks:[],typeName:ee.ZodString,coerce:t?.coerce??!1,...re(t)});Gn=class t extends le{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)!==L.number){let i=this._getOrReturnCtx(e);return z(i,{code:A.invalid_type,expected:L.number,received:i.parsedType}),Q}let r,s=new Oe;for(let i of this._def.checks)i.kind==="int"?ce.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),z(r,{code:A.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),z(r,{code:A.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),z(r,{code:A.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?My(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),z(r,{code:A.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),z(r,{code:A.not_finite,message:i.message}),s.dirty()):ce.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,K.toString(n))}gt(e,n){return this.setLimit("min",e,!1,K.toString(n))}lte(e,n){return this.setLimit("max",e,!0,K.toString(n))}lt(e,n){return this.setLimit("max",e,!1,K.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:K.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:K.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:K.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:K.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:K.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:K.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:K.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:K.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:K.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:K.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"&&ce.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)}};Gn.create=t=>new Gn({checks:[],typeName:ee.ZodNumber,coerce:t?.coerce||!1,...re(t)});Wn=class t extends le{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)!==L.bigint)return this._getInvalidInput(e);let r,s=new Oe;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),z(r,{code:A.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),z(r,{code:A.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),z(r,{code:A.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):ce.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return z(n,{code:A.invalid_type,expected:L.bigint,received:n.parsedType}),Q}gte(e,n){return this.setLimit("min",e,!0,K.toString(n))}gt(e,n){return this.setLimit("min",e,!1,K.toString(n))}lte(e,n){return this.setLimit("max",e,!0,K.toString(n))}lt(e,n){return this.setLimit("max",e,!1,K.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:K.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:K.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:K.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:K.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:K.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:K.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}};Wn.create=t=>new Wn({checks:[],typeName:ee.ZodBigInt,coerce:t?.coerce??!1,...re(t)});Zn=class extends le{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==L.boolean){let r=this._getOrReturnCtx(e);return z(r,{code:A.invalid_type,expected:L.boolean,received:r.parsedType}),Q}return Me(e.data)}};Zn.create=t=>new Zn({typeName:ee.ZodBoolean,coerce:t?.coerce||!1,...re(t)});Vn=class t extends le{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==L.date){let i=this._getOrReturnCtx(e);return z(i,{code:A.invalid_type,expected:L.date,received:i.parsedType}),Q}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return z(i,{code:A.invalid_date}),Q}let r=new Oe,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),z(s,{code:A.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),z(s,{code:A.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):ce.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:K.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:K.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}};Vn.create=t=>new Vn({checks:[],coerce:t?.coerce||!1,typeName:ee.ZodDate,...re(t)});rs=class extends le{_parse(e){if(this._getType(e)!==L.symbol){let r=this._getOrReturnCtx(e);return z(r,{code:A.invalid_type,expected:L.symbol,received:r.parsedType}),Q}return Me(e.data)}};rs.create=t=>new rs({typeName:ee.ZodSymbol,...re(t)});Yn=class extends le{_parse(e){if(this._getType(e)!==L.undefined){let r=this._getOrReturnCtx(e);return z(r,{code:A.invalid_type,expected:L.undefined,received:r.parsedType}),Q}return Me(e.data)}};Yn.create=t=>new Yn({typeName:ee.ZodUndefined,...re(t)});Jn=class extends le{_parse(e){if(this._getType(e)!==L.null){let r=this._getOrReturnCtx(e);return z(r,{code:A.invalid_type,expected:L.null,received:r.parsedType}),Q}return Me(e.data)}};Jn.create=t=>new Jn({typeName:ee.ZodNull,...re(t)});bn=class extends le{constructor(){super(...arguments),this._any=!0}_parse(e){return Me(e.data)}};bn.create=t=>new bn({typeName:ee.ZodAny,...re(t)});Vt=class extends le{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Me(e.data)}};Vt.create=t=>new Vt({typeName:ee.ZodUnknown,...re(t)});vt=class extends le{_parse(e){let n=this._getOrReturnCtx(e);return z(n,{code:A.invalid_type,expected:L.never,received:n.parsedType}),Q}};vt.create=t=>new vt({typeName:ee.ZodNever,...re(t)});ss=class extends le{_parse(e){if(this._getType(e)!==L.undefined){let r=this._getOrReturnCtx(e);return z(r,{code:A.invalid_type,expected:L.void,received:r.parsedType}),Q}return Me(e.data)}};ss.create=t=>new ss({typeName:ee.ZodVoid,...re(t)});Yt=class t extends le{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==L.array)return z(n,{code:A.invalid_type,expected:L.array,received:n.parsedType}),Q;if(s.exactLength!==null){let o=n.data.length>s.exactLength.value,l=n.data.length<s.exactLength.value;(o||l)&&(z(n,{code:o?A.too_big:A.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&&(z(n,{code:A.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&&(z(n,{code:A.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 lt(n,o,n.path,l)))).then(o=>Oe.mergeArray(r,o));let i=[...n.data].map((o,l)=>s.type._parseSync(new lt(n,o,n.path,l)));return Oe.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:K.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:K.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:K.toString(n)}})}nonempty(e){return this.min(1,e)}};Yt.create=(t,e)=>new Yt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:ee.ZodArray,...re(e)});We=class t extends le{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=ce.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==L.object){let d=this._getOrReturnCtx(e);return z(d,{code:A.invalid_type,expected:L.object,received:d.parsedType}),Q}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),l=[];if(!(this._def.catchall instanceof vt&&this._def.unknownKeys==="strip"))for(let d in s.data)o.includes(d)||l.push(d);let c=[];for(let d of o){let p=i[d],f=s.data[d];c.push({key:{status:"valid",value:d},value:p._parse(new lt(s,f,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof vt){let d=this._def.unknownKeys;if(d==="passthrough")for(let p of l)c.push({key:{status:"valid",value:p},value:{status:"valid",value:s.data[p]}});else if(d==="strict")l.length>0&&(z(s,{code:A.unrecognized_keys,keys:l}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let p of l){let f=s.data[p];c.push({key:{status:"valid",value:p},value:d._parse(new lt(s,f,s.path,p)),alwaysSet:p in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let d=[];for(let p of c){let f=await p.key,w=await p.value;d.push({key:f,value:w,alwaysSet:p.alwaysSet})}return d}).then(d=>Oe.mergeObjectSync(r,d)):Oe.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return K.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:K.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:ee.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 ce.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 ce.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 ce.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 ce.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof at;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return ud(ce.objectKeys(this.shape))}};We.create=(t,e)=>new We({shape:()=>t,unknownKeys:"strip",catchall:vt.create(),typeName:ee.ZodObject,...re(e)});We.strictCreate=(t,e)=>new We({shape:()=>t,unknownKeys:"strict",catchall:vt.create(),typeName:ee.ZodObject,...re(e)});We.lazycreate=(t,e)=>new We({shape:t,unknownKeys:"strip",catchall:vt.create(),typeName:ee.ZodObject,...re(e)});Xn=class extends le{_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 Ge(l.ctx.common.issues));return z(n,{code:A.invalid_union,unionErrors:o}),Q}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 d={...n,common:{...n.common,issues:[]},parent:null},p=c._parseSync({data:n.data,path:n.path,parent:d});if(p.status==="valid")return p;p.status==="dirty"&&!i&&(i={result:p,ctx:d}),d.common.issues.length&&o.push(d.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let l=o.map(c=>new Ge(c));return z(n,{code:A.invalid_union,unionErrors:l}),Q}}get options(){return this._def.options}};Xn.create=(t,e)=>new Xn({options:t,typeName:ee.ZodUnion,...re(e)});Zt=t=>t instanceof er?Zt(t.schema):t instanceof ct?Zt(t.innerType()):t instanceof tr?[t.value]:t instanceof nr?t.options:t instanceof rr?ce.objectValues(t.enum):t instanceof sr?Zt(t._def.innerType):t instanceof Yn?[void 0]:t instanceof Jn?[null]:t instanceof at?[void 0,...Zt(t.unwrap())]:t instanceof Ct?[null,...Zt(t.unwrap())]:t instanceof Xs||t instanceof or?Zt(t.unwrap()):t instanceof ir?Zt(t._def.innerType):[],Xi=class t extends le{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==L.object)return z(n,{code:A.invalid_type,expected:L.object,received:n.parsedType}),Q;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}):(z(n,{code:A.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Q)}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:ee.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...re(r)})}};Qn=class extends le{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=(i,o)=>{if(Yi(i)||Yi(o))return Q;let l=Qa(i.value,o.value);return l.valid?((Ji(i)||Ji(o))&&n.dirty(),{status:n.value,value:l.data}):(z(r,{code:A.invalid_intersection_types}),Q)};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:ee.ZodIntersection,...re(n)});At=class t extends le{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==L.array)return z(r,{code:A.invalid_type,expected:L.array,received:r.parsedType}),Q;if(r.data.length<this._def.items.length)return z(r,{code:A.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Q;!this._def.rest&&r.data.length>this._def.items.length&&(z(r,{code:A.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 lt(r,o,r.path,l)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>Oe.mergeArray(n,o)):Oe.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};At.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new At({items:t,typeName:ee.ZodTuple,rest:null,...re(e)})};Qi=class t extends le{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!==L.object)return z(r,{code:A.invalid_type,expected:L.object,received:r.parsedType}),Q;let s=[],i=this._def.keyType,o=this._def.valueType;for(let l in r.data)s.push({key:i._parse(new lt(r,l,r.path,l)),value:o._parse(new lt(r,r.data[l],r.path,l)),alwaysSet:l in r.data});return r.common.async?Oe.mergeObjectAsync(n,s):Oe.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof le?new t({keyType:e,valueType:n,typeName:ee.ZodRecord,...re(r)}):new t({keyType:yn.create(),valueType:e,typeName:ee.ZodRecord,...re(n)})}},is=class extends le{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!==L.map)return z(r,{code:A.invalid_type,expected:L.map,received:r.parsedType}),Q;let s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([l,c],d)=>({key:s._parse(new lt(r,l,r.path,[d,"key"])),value:i._parse(new lt(r,c,r.path,[d,"value"]))}));if(r.common.async){let l=new Map;return Promise.resolve().then(async()=>{for(let c of o){let d=await c.key,p=await c.value;if(d.status==="aborted"||p.status==="aborted")return Q;(d.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(d.value,p.value)}return{status:n.value,value:l}})}else{let l=new Map;for(let c of o){let d=c.key,p=c.value;if(d.status==="aborted"||p.status==="aborted")return Q;(d.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(d.value,p.value)}return{status:n.value,value:l}}}};is.create=(t,e,n)=>new is({valueType:e,keyType:t,typeName:ee.ZodMap,...re(n)});os=class t extends le{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==L.set)return z(r,{code:A.invalid_type,expected:L.set,received:r.parsedType}),Q;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(z(r,{code:A.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&&(z(r,{code:A.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 d=new Set;for(let p of c){if(p.status==="aborted")return Q;p.status==="dirty"&&n.dirty(),d.add(p.value)}return{status:n.value,value:d}}let l=[...r.data.values()].map((c,d)=>i._parse(new lt(r,c,r.path,d)));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:K.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:K.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};os.create=(t,e)=>new os({valueType:t,minSize:null,maxSize:null,typeName:ee.ZodSet,...re(e)});eo=class t extends le{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==L.function)return z(n,{code:A.invalid_type,expected:L.function,received:n.parsedType}),Q;function r(l,c){return Js({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,es(),Wt].filter(d=>!!d),issueData:{code:A.invalid_arguments,argumentsError:c}})}function s(l,c){return Js({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,es(),Wt].filter(d=>!!d),issueData:{code:A.invalid_return_type,returnTypeError:c}})}let i={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof wn){let l=this;return Me(async function(...c){let d=new Ge([]),p=await l._def.args.parseAsync(c,i).catch(v=>{throw d.addIssue(r(c,v)),d}),f=await Reflect.apply(o,this,p);return await l._def.returns._def.type.parseAsync(f,i).catch(v=>{throw d.addIssue(s(f,v)),d})})}else{let l=this;return Me(function(...c){let d=l._def.args.safeParse(c,i);if(!d.success)throw new Ge([r(c,d.error)]);let p=Reflect.apply(o,this,d.data),f=l._def.returns.safeParse(p,i);if(!f.success)throw new Ge([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:At.create(e).rest(Vt.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||At.create([]).rest(Vt.create()),returns:n||Vt.create(),typeName:ee.ZodFunction,...re(r)})}},er=class extends le{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})}};er.create=(t,e)=>new er({getter:t,typeName:ee.ZodLazy,...re(e)});tr=class extends le{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return z(n,{received:n.data,code:A.invalid_literal,expected:this._def.value}),Q}return{status:"valid",value:e.data}}get value(){return this._def.value}};tr.create=(t,e)=>new tr({value:t,typeName:ee.ZodLiteral,...re(e)});nr=class t extends le{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return z(n,{expected:ce.joinValues(r),received:n.parsedType,code:A.invalid_type}),Q}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 z(n,{received:n.data,code:A.invalid_enum_value,options:r}),Q}return Me(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})}};nr.create=ud;rr=class extends le{_parse(e){let n=ce.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==L.string&&r.parsedType!==L.number){let s=ce.objectValues(n);return z(r,{expected:ce.joinValues(s),received:r.parsedType,code:A.invalid_type}),Q}if(this._cache||(this._cache=new Set(ce.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=ce.objectValues(n);return z(r,{received:r.data,code:A.invalid_enum_value,options:s}),Q}return Me(e.data)}get enum(){return this._def.values}};rr.create=(t,e)=>new rr({values:t,typeName:ee.ZodNativeEnum,...re(e)});wn=class extends le{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==L.promise&&n.common.async===!1)return z(n,{code:A.invalid_type,expected:L.promise,received:n.parsedType}),Q;let r=n.parsedType===L.promise?n.data:Promise.resolve(n.data);return Me(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};wn.create=(t,e)=>new wn({type:t,typeName:ee.ZodPromise,...re(e)});ct=class extends le{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ee.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=>{z(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 Q;let c=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return c.status==="aborted"?Q:c.status==="dirty"?Kn(c.value):n.value==="dirty"?Kn(c.value):c});{if(n.value==="aborted")return Q;let l=this._def.schema._parseSync({data:o,path:r.path,parent:r});return l.status==="aborted"?Q:l.status==="dirty"?Kn(l.value):n.value==="dirty"?Kn(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"?Q:(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"?Q:(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(!gn(o))return Q;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=>gn(o)?Promise.resolve(s.transform(o.value,i)).then(l=>({status:n.value,value:l})):Q);ce.assertNever(s)}};ct.create=(t,e,n)=>new ct({schema:t,typeName:ee.ZodEffects,effect:e,...re(n)});ct.createWithPreprocess=(t,e,n)=>new ct({schema:e,effect:{type:"preprocess",transform:t},typeName:ee.ZodEffects,...re(n)});at=class extends le{_parse(e){return this._getType(e)===L.undefined?Me(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};at.create=(t,e)=>new at({innerType:t,typeName:ee.ZodOptional,...re(e)});Ct=class extends le{_parse(e){return this._getType(e)===L.null?Me(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ct.create=(t,e)=>new Ct({innerType:t,typeName:ee.ZodNullable,...re(e)});sr=class extends le{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===L.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};sr.create=(t,e)=>new sr({innerType:t,typeName:ee.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...re(e)});ir=class extends le{_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 ts(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Ge(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ge(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};ir.create=(t,e)=>new ir({innerType:t,typeName:ee.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...re(e)});as=class extends le{_parse(e){if(this._getType(e)!==L.nan){let r=this._getOrReturnCtx(e);return z(r,{code:A.invalid_type,expected:L.nan,received:r.parsedType}),Q}return{status:"valid",value:e.data}}};as.create=t=>new as({typeName:ee.ZodNaN,...re(t)});zy=Symbol("zod_brand"),Xs=class extends le{_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}},Qs=class t extends le{_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"?Q:i.status==="dirty"?(n.dirty(),Kn(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"?Q: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:ee.ZodPipeline})}},or=class extends le{_parse(e){let n=this._def.innerType._parse(e),r=s=>(gn(s)&&(s.value=Object.freeze(s.value)),s);return ts(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};or.create=(t,e)=>new or({innerType:t,typeName:ee.ZodReadonly,...re(e)});Dy={object:We.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"})(ee||(ee={}));Ly=(t,e={message:`Input not instance of ${t.name}`})=>dd(n=>n instanceof t,e),hd=yn.create,pd=Gn.create,Uy=as.create,qy=Wn.create,fd=Zn.create,Fy=Vn.create,By=rs.create,Hy=Yn.create,Ky=Jn.create,Gy=bn.create,Wy=Vt.create,Zy=vt.create,Vy=ss.create,Yy=Yt.create,Jy=We.create,Xy=We.strictCreate,Qy=Xn.create,eb=Xi.create,tb=Qn.create,nb=At.create,rb=Qi.create,sb=is.create,ib=os.create,ob=eo.create,ab=er.create,lb=tr.create,cb=nr.create,ub=rr.create,db=wn.create,hb=ct.create,pb=at.create,fb=Ct.create,mb=ct.createWithPreprocess,gb=Qs.create,yb=()=>hd().optional(),bb=()=>pd().optional(),wb=()=>fd().optional(),vb={string:(t=>yn.create({...t,coerce:!0})),number:(t=>Gn.create({...t,coerce:!0})),boolean:(t=>Zn.create({...t,coerce:!0})),bigint:(t=>Wn.create({...t,coerce:!0})),date:(t=>Vn.create({...t,coerce:!0}))},kb=Q});var k={};Kt(k,{BRAND:()=>zy,DIRTY:()=>Kn,EMPTY_PATH:()=>my,INVALID:()=>Q,NEVER:()=>kb,OK:()=>Me,ParseStatus:()=>Oe,Schema:()=>le,ZodAny:()=>bn,ZodArray:()=>Yt,ZodBigInt:()=>Wn,ZodBoolean:()=>Zn,ZodBranded:()=>Xs,ZodCatch:()=>ir,ZodDate:()=>Vn,ZodDefault:()=>sr,ZodDiscriminatedUnion:()=>Xi,ZodEffects:()=>ct,ZodEnum:()=>nr,ZodError:()=>Ge,ZodFirstPartyTypeKind:()=>ee,ZodFunction:()=>eo,ZodIntersection:()=>Qn,ZodIssueCode:()=>A,ZodLazy:()=>er,ZodLiteral:()=>tr,ZodMap:()=>is,ZodNaN:()=>as,ZodNativeEnum:()=>rr,ZodNever:()=>vt,ZodNull:()=>Jn,ZodNullable:()=>Ct,ZodNumber:()=>Gn,ZodObject:()=>We,ZodOptional:()=>at,ZodParsedType:()=>L,ZodPipeline:()=>Qs,ZodPromise:()=>wn,ZodReadonly:()=>or,ZodRecord:()=>Qi,ZodSchema:()=>le,ZodSet:()=>os,ZodString:()=>yn,ZodSymbol:()=>rs,ZodTransformer:()=>ct,ZodTuple:()=>At,ZodType:()=>le,ZodUndefined:()=>Yn,ZodUnion:()=>Xn,ZodUnknown:()=>Vt,ZodVoid:()=>ss,addIssueToContext:()=>z,any:()=>Gy,array:()=>Yy,bigint:()=>qy,boolean:()=>fd,coerce:()=>vb,custom:()=>dd,date:()=>Fy,datetimeRegex:()=>cd,defaultErrorMap:()=>Wt,discriminatedUnion:()=>eb,effect:()=>hb,enum:()=>cb,function:()=>ob,getErrorMap:()=>es,getParsedType:()=>Rt,instanceof:()=>Ly,intersection:()=>tb,isAborted:()=>Yi,isAsync:()=>ts,isDirty:()=>Ji,isValid:()=>gn,late:()=>Dy,lazy:()=>ab,literal:()=>lb,makeIssue:()=>Js,map:()=>sb,nan:()=>Uy,nativeEnum:()=>ub,never:()=>Zy,null:()=>Ky,nullable:()=>fb,number:()=>pd,object:()=>Jy,objectUtil:()=>Va,oboolean:()=>wb,onumber:()=>bb,optional:()=>pb,ostring:()=>yb,pipeline:()=>gb,preprocess:()=>mb,promise:()=>db,quotelessJson:()=>hy,record:()=>rb,set:()=>ib,setErrorMap:()=>fy,strictObject:()=>Xy,string:()=>hd,symbol:()=>By,transformer:()=>hb,tuple:()=>nb,undefined:()=>Hy,union:()=>Qy,unknown:()=>Wy,util:()=>ce,void:()=>Vy});var el=ne(()=>{Vi();Ja();rd();Ys();md();Zi()});var vn=ne(()=>{el();el()});function se(){let t=process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR;if(t)return t;let e=no.default.join(to.default.homedir(),".config","allwright"),n=no.default.join(to.default.homedir(),".config","ticketpilot");return!Jt.default.existsSync(e)&&Jt.default.existsSync(n)?n:e}function Xt(){return no.default.join(se(),"runner.json")}function ke(){let t=Xt();if(!Jt.default.existsSync(t))return null;let e=JSON.parse(Jt.default.readFileSync(t,"utf8"));return tl.parse(e)}function we(t){let e=se();Jt.default.mkdirSync(e,{recursive:!0,mode:448});let n=Xt(),r=n+".tmp";Jt.default.writeFileSync(r,JSON.stringify(t,null,2)+`
24
- `,{mode:384}),Jt.default.renameSync(r,n),Jt.default.chmodSync(n,384)}function ro(t,e){return`${t}:${e}`}function $t(t,e,n){return t.environments[ro(e,n)]?.secrets??{}}function so(t,e){return t.repos[e]?.jira??t.jira}function io(t){return!t.jira&&!Object.values(t.repos).some(e=>e.jira)}function he(){let t=ke();if(!t)throw new Error(`No runner config found at ${Xt()}. Run \`allwright init\` first.`);return t}var Jt,to,no,gd,tl,Ee=ne(()=>{"use strict";Jt=R(require("node:fs"),1),to=R(require("node:os"),1),no=R(require("node:path"),1);vn();gd=k.object({baseUrl:k.string().url(),email:k.string().email(),apiToken:k.string().min(1)}),tl=k.object({controlPlaneUrl:k.string().url(),runnerId:k.string().optional(),runnerToken:k.string().optional(),runnerName:k.string().default(to.default.hostname()),jira:gd.optional(),repos:k.record(k.object({path:k.string(),jira:gd.optional(),github:k.object({token:k.string().min(1),login:k.string().optional()}).optional()})).default({}),github:k.object({token:k.string().min(1),login:k.string().optional()}).optional(),githubUsers:k.record(k.object({token:k.string().min(1),login:k.string().optional()})).default({}),deploy:k.object({enabled:k.boolean().default(!1)}).default({enabled:!1}),environments:k.record(k.object({secrets:k.record(k.string()).default({})})).default({}),claudeProfiles:k.record(k.object({configDir:k.string()})).default({}),claudeBin:k.string().default("claude"),agents:k.record(k.object({bin:k.string()})).default({}),jiraUsers:k.record(k.object({email:k.string().email(),apiToken:k.string().min(1)})).default({}),auditSchedules:k.array(k.object({repoName:k.string(),role:k.enum(["security","testing"]),intervalHours:k.number().int().min(6).max(720)})).default([]),pollIntervalSeconds:k.number().int().min(10).max(600).default(30),operatorEnabled:k.boolean().default(!1)})});function vd(t,e){let n=kn.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 cs(t,e,n,r){if(!e.length)return"";let s=kn.default.join(n,lo);ls.default.mkdirSync(s,{recursive:!0});let i=new Set,o=[],l=0;for(let c of e){if(o.length>=wd){r("warn",`attachment cap reached (${wd} files) - skipping the rest`);break}if(c.size>Tb){r("warn",`skipping attachment "${c.filename}" - ${Rb(c.size)} MB exceeds the 15 MB limit`);continue}if(l+c.size>xb){r("warn",`attachment size budget reached - skipping "${c.filename}" and the rest`);break}try{let d=await t.downloadAttachment(c.contentUrl),p=vd(c.filename,i);ls.default.writeFileSync(kn.default.join(s,p),d),l+=d.length,o.push(`- ${lo}/${p} (${c.mimeType||"unknown type"}, ${nl(d.length)} KB)`),r("info",`Downloaded attachment "${c.filename}" (${nl(d.length)} KB)`)}catch(d){r("warn",`could not download attachment "${c.filename}": ${d instanceof Error?d.message:d}`)}}return o.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 nd(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})}rd.Command=rl});var ld=he(at=>{var{Argument:id}=Ji(),{Command:sl}=sd(),{CommanderError:Ly,InvalidArgumentError:od}=Xs(),{Help:Uy}=Va(),{Option:ad}=Qa();at.program=new sl;at.createCommand=t=>new sl(t);at.createOption=(t,e)=>new ad(t,e);at.createArgument=(t,e)=>new id(t,e);at.Command=sl;at.Option=ad;at.Argument=id;at.Help=Uy;at.CommanderError=Ly;at.InvalidArgumentError=od;at.InvalidOptionArgumentError=od});var ue,il,L,Pt,Qs=te(()=>{(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})(ue||(ue={}));(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(il||(il={}));L=ue.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Pt=t=>{switch(typeof t){case"undefined":return L.undefined;case"string":return L.string;case"number":return Number.isNaN(t)?L.nan:L.number;case"boolean":return L.boolean;case"function":return L.function;case"bigint":return L.bigint;case"symbol":return L.symbol;case"object":return Array.isArray(t)?L.array:t===null?L.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?L.promise:typeof Map<"u"&&t instanceof Map?L.map:typeof Set<"u"&&t instanceof Set?L.set:typeof Date<"u"&&t instanceof Date?L.date:L.object;default:return L.unknown}}});var A,qy,Ve,Yi=te(()=>{Qs();A=ue.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"]),qy=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ve=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 d=o.path[c];c===o.path.length-1?(l[d]=l[d]||{_errors:[]},l[d]._errors.push(n(o))):l[d]=l[d]||{_errors:[]},l=l[d],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,ue.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()}};Ve.create=t=>new Ve(t)});var Fy,Yt,ol=te(()=>{Yi();Qs();Fy=(t,e)=>{let n;switch(t.code){case A.invalid_type:t.received===L.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case A.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,ue.jsonStringifyReplacer)}`;break;case A.unrecognized_keys:n=`Unrecognized key(s) in object: ${ue.joinValues(t.keys,", ")}`;break;case A.invalid_union:n="Invalid input";break;case A.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ue.joinValues(t.options)}`;break;case A.invalid_enum_value:n=`Invalid enum value. Expected ${ue.joinValues(t.options)}, received '${t.received}'`;break;case A.invalid_arguments:n="Invalid function arguments";break;case A.invalid_return_type:n="Invalid function return type";break;case A.invalid_date:n="Invalid date";break;case A.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}"`:ue.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case A.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 A.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 A.custom:n="Invalid input";break;case A.invalid_intersection_types:n="Intersection results could not be merged";break;case A.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case A.not_finite:n="Number must be finite";break;default:n=e.defaultError,ue.assertNever(t)}return{message:n}},Yt=Fy});function By(t){dd=t}function ns(){return dd}var dd,Xi=te(()=>{ol();dd=Yt});function z(t,e){let n=ns(),r=ei({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Yt?void 0:Yt].filter(s=>!!s)});t.common.issues.push(r)}var ei,Hy,Oe,X,Wn,ze,Qi,eo,vn,rs,al=te(()=>{Xi();ol();ei=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(d=>!!d).slice().reverse();for(let d of c)l=d(o,{data:e,defaultError:l}).message;return{...s,path:i,message:l}},Hy=[];Oe=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 X;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 X;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}}},X=Object.freeze({status:"aborted"}),Wn=t=>({status:"dirty",value:t}),ze=t=>({status:"valid",value:t}),Qi=t=>t.status==="aborted",eo=t=>t.status==="dirty",vn=t=>t.status==="valid",rs=t=>typeof Promise<"u"&&t instanceof Promise});var hd=te(()=>{});var G,pd=te(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(G||(G={}))});function se(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 yd(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 ab(t){return new RegExp(`^${yd(t)}$`)}function bd(t){let e=`${gd}T${yd(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 lb(t,e){return!!((e==="v4"||!e)&&eb.test(t)||(e==="v6"||!e)&&nb.test(t))}function cb(t,e){if(!Jy.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 ub(t,e){return!!((e==="v4"||!e)&&tb.test(t)||(e==="v6"||!e)&&rb.test(t))}function db(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 ss(t){if(t instanceof Je){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=lt.create(ss(r))}return new Je({...t._def,shape:()=>e})}else return t instanceof en?new en({...t._def,type:ss(t.element)}):t instanceof lt?lt.create(ss(t.unwrap())):t instanceof jt?jt.create(ss(t.unwrap())):t instanceof Nt?Nt.create(t.items.map(e=>ss(e))):t}function cl(t,e){let n=Pt(t),r=Pt(e);if(t===e)return{valid:!0,data:t};if(n===L.object&&r===L.object){let s=ue.objectKeys(e),i=ue.objectKeys(t).filter(l=>s.indexOf(l)!==-1),o={...t,...e};for(let l of i){let c=cl(t[l],e[l]);if(!c.valid)return{valid:!1};o[l]=c.data}return{valid:!0,data:o}}else if(n===L.array&&r===L.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=cl(o,l);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===L.date&&r===L.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function wd(t,e){return new sr({values:t,typeName:Q.ZodEnum,...se(e)})}function md(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function vd(t,e={},n){return t?_n.create().superRefine((r,s)=>{let i=t(r);if(i instanceof Promise)return i.then(o=>{if(!o){let l=md(e,r),c=l.fatal??n??!0;s.addIssue({code:"custom",...l,fatal:c})}});if(!i){let o=md(e,r),l=o.fatal??n??!0;s.addIssue({code:"custom",...o,fatal:l})}}):_n.create()}var ct,fd,le,Ky,Gy,Wy,Zy,Vy,Jy,Yy,Xy,Qy,ll,eb,tb,nb,rb,sb,ib,gd,ob,kn,Zn,Vn,Jn,Yn,is,Xn,Qn,_n,Qt,kt,os,en,Je,er,Xt,to,tr,Nt,no,as,ls,ro,nr,rr,sr,ir,Sn,ut,lt,jt,or,ar,cs,hb,ti,ni,lr,pb,Q,fb,kd,_d,mb,gb,Sd,yb,bb,wb,vb,kb,_b,Sb,Tb,xb,Ib,Rb,Eb,Ab,Cb,$b,Pb,Nb,jb,Ob,Mb,zb,Db,Lb,Ub,qb,Fb,Bb,Hb,Kb,Gb,Wb,Zb,Vb,Jb,Td=te(()=>{Yi();Xi();pd();al();Qs();ct=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}},fd=(t,e)=>{if(vn(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 Ve(t.common.issues);return this._error=n,this._error}}};le=class{get description(){return this._def.description}_getType(e){return Pt(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:Pt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Oe,ctx:{common:e.parent.common,data:e.data,parsedType:Pt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(rs(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:Pt(e)},s=this._parseSync({data:e,path:r.path,parent:r});return fd(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Pt(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return vn(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=>vn(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:Pt(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(rs(s)?s:Promise.resolve(s));return fd(r,i)}refine(e,n){let r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,i)=>{let o=e(s),l=()=>i.addIssue({code:A.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 ut({schema:this,typeName:Q.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 lt.create(this,this._def)}nullable(){return jt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return en.create(this)}promise(){return Sn.create(this,this._def)}or(e){return er.create([this,e],this._def)}and(e){return tr.create(this,e,this._def)}transform(e){return new ut({...se(this._def),schema:this,typeName:Q.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new or({...se(this._def),innerType:this,defaultValue:n,typeName:Q.ZodDefault})}brand(){return new ti({typeName:Q.ZodBranded,type:this,...se(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new ar({...se(this._def),innerType:this,catchValue:n,typeName:Q.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return ni.create(this,e)}readonly(){return lr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Ky=/^c[^\s-]{8,}$/i,Gy=/^[0-9a-z]+$/,Wy=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Zy=/^[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,Vy=/^[a-z0-9_-]{21}$/i,Jy=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Yy=/^[-+]?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)?)??$/,Xy=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Qy="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",eb=/^(?:(?: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])$/,tb=/^(?:(?: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])$/,nb=/^(([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]))$/,rb=/^(([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])$/,sb=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ib=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,gd="((\\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])))",ob=new RegExp(`^${gd}$`);kn=class t extends le{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==L.string){let i=this._getOrReturnCtx(e);return z(i,{code:A.invalid_type,expected:L.string,received:i.parsedType}),X}let r=new Oe,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),z(s,{code:A.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),z(s,{code:A.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?z(s,{code:A.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):l&&z(s,{code:A.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")Xy.test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"email",code:A.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")ll||(ll=new RegExp(Qy,"u")),ll.test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"emoji",code:A.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")Zy.test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"uuid",code:A.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")Vy.test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"nanoid",code:A.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")Ky.test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"cuid",code:A.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")Gy.test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"cuid2",code:A.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")Wy.test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"ulid",code:A.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),z(s,{validation:"url",code:A.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),z(s,{validation:"regex",code:A.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),z(s,{code:A.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),z(s,{code:A.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),z(s,{code:A.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?bd(i).test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{code:A.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?ob.test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{code:A.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?ab(i).test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{code:A.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?Yy.test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"duration",code:A.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?lb(e.data,i.version)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"ip",code:A.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?cb(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"jwt",code:A.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?ub(e.data,i.version)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"cidr",code:A.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?sb.test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"base64",code:A.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?ib.test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"base64url",code:A.invalid_string,message:i.message}),r.dirty()):ue.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:A.invalid_string,...G.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...G.errToObj(e)})}url(e){return this._addCheck({kind:"url",...G.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...G.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...G.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...G.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...G.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...G.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...G.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...G.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...G.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...G.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...G.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...G.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,...G.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,...G.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...G.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...G.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...G.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...G.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...G.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...G.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...G.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...G.errToObj(n)})}nonempty(e){return this.min(1,G.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}};kn.create=t=>new kn({checks:[],typeName:Q.ZodString,coerce:t?.coerce??!1,...se(t)});Zn=class t extends le{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)!==L.number){let i=this._getOrReturnCtx(e);return z(i,{code:A.invalid_type,expected:L.number,received:i.parsedType}),X}let r,s=new Oe;for(let i of this._def.checks)i.kind==="int"?ue.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),z(r,{code:A.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),z(r,{code:A.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),z(r,{code:A.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?db(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),z(r,{code:A.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),z(r,{code:A.not_finite,message:i.message}),s.dirty()):ue.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,G.toString(n))}gt(e,n){return this.setLimit("min",e,!1,G.toString(n))}lte(e,n){return this.setLimit("max",e,!0,G.toString(n))}lt(e,n){return this.setLimit("max",e,!1,G.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:G.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:G.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:G.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:G.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:G.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:G.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:G.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:G.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:G.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:G.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"&&ue.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)}};Zn.create=t=>new Zn({checks:[],typeName:Q.ZodNumber,coerce:t?.coerce||!1,...se(t)});Vn=class t extends le{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)!==L.bigint)return this._getInvalidInput(e);let r,s=new Oe;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),z(r,{code:A.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),z(r,{code:A.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),z(r,{code:A.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):ue.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return z(n,{code:A.invalid_type,expected:L.bigint,received:n.parsedType}),X}gte(e,n){return this.setLimit("min",e,!0,G.toString(n))}gt(e,n){return this.setLimit("min",e,!1,G.toString(n))}lte(e,n){return this.setLimit("max",e,!0,G.toString(n))}lt(e,n){return this.setLimit("max",e,!1,G.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:G.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:G.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:G.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:G.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:G.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:G.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}};Vn.create=t=>new Vn({checks:[],typeName:Q.ZodBigInt,coerce:t?.coerce??!1,...se(t)});Jn=class extends le{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==L.boolean){let r=this._getOrReturnCtx(e);return z(r,{code:A.invalid_type,expected:L.boolean,received:r.parsedType}),X}return ze(e.data)}};Jn.create=t=>new Jn({typeName:Q.ZodBoolean,coerce:t?.coerce||!1,...se(t)});Yn=class t extends le{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==L.date){let i=this._getOrReturnCtx(e);return z(i,{code:A.invalid_type,expected:L.date,received:i.parsedType}),X}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return z(i,{code:A.invalid_date}),X}let r=new Oe,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),z(s,{code:A.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),z(s,{code:A.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):ue.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:G.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:G.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}};Yn.create=t=>new Yn({checks:[],coerce:t?.coerce||!1,typeName:Q.ZodDate,...se(t)});is=class extends le{_parse(e){if(this._getType(e)!==L.symbol){let r=this._getOrReturnCtx(e);return z(r,{code:A.invalid_type,expected:L.symbol,received:r.parsedType}),X}return ze(e.data)}};is.create=t=>new is({typeName:Q.ZodSymbol,...se(t)});Xn=class extends le{_parse(e){if(this._getType(e)!==L.undefined){let r=this._getOrReturnCtx(e);return z(r,{code:A.invalid_type,expected:L.undefined,received:r.parsedType}),X}return ze(e.data)}};Xn.create=t=>new Xn({typeName:Q.ZodUndefined,...se(t)});Qn=class extends le{_parse(e){if(this._getType(e)!==L.null){let r=this._getOrReturnCtx(e);return z(r,{code:A.invalid_type,expected:L.null,received:r.parsedType}),X}return ze(e.data)}};Qn.create=t=>new Qn({typeName:Q.ZodNull,...se(t)});_n=class extends le{constructor(){super(...arguments),this._any=!0}_parse(e){return ze(e.data)}};_n.create=t=>new _n({typeName:Q.ZodAny,...se(t)});Qt=class extends le{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ze(e.data)}};Qt.create=t=>new Qt({typeName:Q.ZodUnknown,...se(t)});kt=class extends le{_parse(e){let n=this._getOrReturnCtx(e);return z(n,{code:A.invalid_type,expected:L.never,received:n.parsedType}),X}};kt.create=t=>new kt({typeName:Q.ZodNever,...se(t)});os=class extends le{_parse(e){if(this._getType(e)!==L.undefined){let r=this._getOrReturnCtx(e);return z(r,{code:A.invalid_type,expected:L.void,received:r.parsedType}),X}return ze(e.data)}};os.create=t=>new os({typeName:Q.ZodVoid,...se(t)});en=class t extends le{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==L.array)return z(n,{code:A.invalid_type,expected:L.array,received:n.parsedType}),X;if(s.exactLength!==null){let o=n.data.length>s.exactLength.value,l=n.data.length<s.exactLength.value;(o||l)&&(z(n,{code:o?A.too_big:A.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&&(z(n,{code:A.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&&(z(n,{code:A.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 ct(n,o,n.path,l)))).then(o=>Oe.mergeArray(r,o));let i=[...n.data].map((o,l)=>s.type._parseSync(new ct(n,o,n.path,l)));return Oe.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:G.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:G.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:G.toString(n)}})}nonempty(e){return this.min(1,e)}};en.create=(t,e)=>new en({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Q.ZodArray,...se(e)});Je=class t extends le{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=ue.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==L.object){let d=this._getOrReturnCtx(e);return z(d,{code:A.invalid_type,expected:L.object,received:d.parsedType}),X}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),l=[];if(!(this._def.catchall instanceof kt&&this._def.unknownKeys==="strip"))for(let d in s.data)o.includes(d)||l.push(d);let c=[];for(let d of o){let p=i[d],f=s.data[d];c.push({key:{status:"valid",value:d},value:p._parse(new ct(s,f,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof kt){let d=this._def.unknownKeys;if(d==="passthrough")for(let p of l)c.push({key:{status:"valid",value:p},value:{status:"valid",value:s.data[p]}});else if(d==="strict")l.length>0&&(z(s,{code:A.unrecognized_keys,keys:l}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let p of l){let f=s.data[p];c.push({key:{status:"valid",value:p},value:d._parse(new ct(s,f,s.path,p)),alwaysSet:p in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let d=[];for(let p of c){let f=await p.key,w=await p.value;d.push({key:f,value:w,alwaysSet:p.alwaysSet})}return d}).then(d=>Oe.mergeObjectSync(r,d)):Oe.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return G.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:G.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:Q.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 ue.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 ue.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return ss(this)}partial(e){let n={};for(let r of ue.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 ue.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof lt;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return wd(ue.objectKeys(this.shape))}};Je.create=(t,e)=>new Je({shape:()=>t,unknownKeys:"strip",catchall:kt.create(),typeName:Q.ZodObject,...se(e)});Je.strictCreate=(t,e)=>new Je({shape:()=>t,unknownKeys:"strict",catchall:kt.create(),typeName:Q.ZodObject,...se(e)});Je.lazycreate=(t,e)=>new Je({shape:t,unknownKeys:"strip",catchall:kt.create(),typeName:Q.ZodObject,...se(e)});er=class extends le{_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 Ve(l.ctx.common.issues));return z(n,{code:A.invalid_union,unionErrors:o}),X}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 d={...n,common:{...n.common,issues:[]},parent:null},p=c._parseSync({data:n.data,path:n.path,parent:d});if(p.status==="valid")return p;p.status==="dirty"&&!i&&(i={result:p,ctx:d}),d.common.issues.length&&o.push(d.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let l=o.map(c=>new Ve(c));return z(n,{code:A.invalid_union,unionErrors:l}),X}}get options(){return this._def.options}};er.create=(t,e)=>new er({options:t,typeName:Q.ZodUnion,...se(e)});Xt=t=>t instanceof nr?Xt(t.schema):t instanceof ut?Xt(t.innerType()):t instanceof rr?[t.value]:t instanceof sr?t.options:t instanceof ir?ue.objectValues(t.enum):t instanceof or?Xt(t._def.innerType):t instanceof Xn?[void 0]:t instanceof Qn?[null]:t instanceof lt?[void 0,...Xt(t.unwrap())]:t instanceof jt?[null,...Xt(t.unwrap())]:t instanceof ti||t instanceof lr?Xt(t.unwrap()):t instanceof ar?Xt(t._def.innerType):[],to=class t extends le{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==L.object)return z(n,{code:A.invalid_type,expected:L.object,received:n.parsedType}),X;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}):(z(n,{code:A.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),X)}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=Xt(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:Q.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...se(r)})}};tr=class extends le{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=(i,o)=>{if(Qi(i)||Qi(o))return X;let l=cl(i.value,o.value);return l.valid?((eo(i)||eo(o))&&n.dirty(),{status:n.value,value:l.data}):(z(r,{code:A.invalid_intersection_types}),X)};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}))}};tr.create=(t,e,n)=>new tr({left:t,right:e,typeName:Q.ZodIntersection,...se(n)});Nt=class t extends le{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==L.array)return z(r,{code:A.invalid_type,expected:L.array,received:r.parsedType}),X;if(r.data.length<this._def.items.length)return z(r,{code:A.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),X;!this._def.rest&&r.data.length>this._def.items.length&&(z(r,{code:A.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 ct(r,o,r.path,l)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>Oe.mergeArray(n,o)):Oe.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Nt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Nt({items:t,typeName:Q.ZodTuple,rest:null,...se(e)})};no=class t extends le{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!==L.object)return z(r,{code:A.invalid_type,expected:L.object,received:r.parsedType}),X;let s=[],i=this._def.keyType,o=this._def.valueType;for(let l in r.data)s.push({key:i._parse(new ct(r,l,r.path,l)),value:o._parse(new ct(r,r.data[l],r.path,l)),alwaysSet:l in r.data});return r.common.async?Oe.mergeObjectAsync(n,s):Oe.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof le?new t({keyType:e,valueType:n,typeName:Q.ZodRecord,...se(r)}):new t({keyType:kn.create(),valueType:e,typeName:Q.ZodRecord,...se(n)})}},as=class extends le{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!==L.map)return z(r,{code:A.invalid_type,expected:L.map,received:r.parsedType}),X;let s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([l,c],d)=>({key:s._parse(new ct(r,l,r.path,[d,"key"])),value:i._parse(new ct(r,c,r.path,[d,"value"]))}));if(r.common.async){let l=new Map;return Promise.resolve().then(async()=>{for(let c of o){let d=await c.key,p=await c.value;if(d.status==="aborted"||p.status==="aborted")return X;(d.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(d.value,p.value)}return{status:n.value,value:l}})}else{let l=new Map;for(let c of o){let d=c.key,p=c.value;if(d.status==="aborted"||p.status==="aborted")return X;(d.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(d.value,p.value)}return{status:n.value,value:l}}}};as.create=(t,e,n)=>new as({valueType:e,keyType:t,typeName:Q.ZodMap,...se(n)});ls=class t extends le{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==L.set)return z(r,{code:A.invalid_type,expected:L.set,received:r.parsedType}),X;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(z(r,{code:A.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&&(z(r,{code:A.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 d=new Set;for(let p of c){if(p.status==="aborted")return X;p.status==="dirty"&&n.dirty(),d.add(p.value)}return{status:n.value,value:d}}let l=[...r.data.values()].map((c,d)=>i._parse(new ct(r,c,r.path,d)));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:G.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:G.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};ls.create=(t,e)=>new ls({valueType:t,minSize:null,maxSize:null,typeName:Q.ZodSet,...se(e)});ro=class t extends le{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==L.function)return z(n,{code:A.invalid_type,expected:L.function,received:n.parsedType}),X;function r(l,c){return ei({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,ns(),Yt].filter(d=>!!d),issueData:{code:A.invalid_arguments,argumentsError:c}})}function s(l,c){return ei({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,ns(),Yt].filter(d=>!!d),issueData:{code:A.invalid_return_type,returnTypeError:c}})}let i={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof Sn){let l=this;return ze(async function(...c){let d=new Ve([]),p=await l._def.args.parseAsync(c,i).catch(v=>{throw d.addIssue(r(c,v)),d}),f=await Reflect.apply(o,this,p);return await l._def.returns._def.type.parseAsync(f,i).catch(v=>{throw d.addIssue(s(f,v)),d})})}else{let l=this;return ze(function(...c){let d=l._def.args.safeParse(c,i);if(!d.success)throw new Ve([r(c,d.error)]);let p=Reflect.apply(o,this,d.data),f=l._def.returns.safeParse(p,i);if(!f.success)throw new Ve([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:Nt.create(e).rest(Qt.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||Nt.create([]).rest(Qt.create()),returns:n||Qt.create(),typeName:Q.ZodFunction,...se(r)})}},nr=class extends le{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})}};nr.create=(t,e)=>new nr({getter:t,typeName:Q.ZodLazy,...se(e)});rr=class extends le{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return z(n,{received:n.data,code:A.invalid_literal,expected:this._def.value}),X}return{status:"valid",value:e.data}}get value(){return this._def.value}};rr.create=(t,e)=>new rr({value:t,typeName:Q.ZodLiteral,...se(e)});sr=class t extends le{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return z(n,{expected:ue.joinValues(r),received:n.parsedType,code:A.invalid_type}),X}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 z(n,{received:n.data,code:A.invalid_enum_value,options:r}),X}return ze(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})}};sr.create=wd;ir=class extends le{_parse(e){let n=ue.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==L.string&&r.parsedType!==L.number){let s=ue.objectValues(n);return z(r,{expected:ue.joinValues(s),received:r.parsedType,code:A.invalid_type}),X}if(this._cache||(this._cache=new Set(ue.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=ue.objectValues(n);return z(r,{received:r.data,code:A.invalid_enum_value,options:s}),X}return ze(e.data)}get enum(){return this._def.values}};ir.create=(t,e)=>new ir({values:t,typeName:Q.ZodNativeEnum,...se(e)});Sn=class extends le{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==L.promise&&n.common.async===!1)return z(n,{code:A.invalid_type,expected:L.promise,received:n.parsedType}),X;let r=n.parsedType===L.promise?n.data:Promise.resolve(n.data);return ze(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Sn.create=(t,e)=>new Sn({type:t,typeName:Q.ZodPromise,...se(e)});ut=class extends le{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Q.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=>{z(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 X;let c=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return c.status==="aborted"?X:c.status==="dirty"?Wn(c.value):n.value==="dirty"?Wn(c.value):c});{if(n.value==="aborted")return X;let l=this._def.schema._parseSync({data:o,path:r.path,parent:r});return l.status==="aborted"?X:l.status==="dirty"?Wn(l.value):n.value==="dirty"?Wn(l.value):l}}if(s.type==="refinement"){let o=l=>{let c=s.refinement(l,i);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){let l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?X:(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"?X:(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(!vn(o))return X;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=>vn(o)?Promise.resolve(s.transform(o.value,i)).then(l=>({status:n.value,value:l})):X);ue.assertNever(s)}};ut.create=(t,e,n)=>new ut({schema:t,typeName:Q.ZodEffects,effect:e,...se(n)});ut.createWithPreprocess=(t,e,n)=>new ut({schema:e,effect:{type:"preprocess",transform:t},typeName:Q.ZodEffects,...se(n)});lt=class extends le{_parse(e){return this._getType(e)===L.undefined?ze(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};lt.create=(t,e)=>new lt({innerType:t,typeName:Q.ZodOptional,...se(e)});jt=class extends le{_parse(e){return this._getType(e)===L.null?ze(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};jt.create=(t,e)=>new jt({innerType:t,typeName:Q.ZodNullable,...se(e)});or=class extends le{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===L.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};or.create=(t,e)=>new or({innerType:t,typeName:Q.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...se(e)});ar=class extends le{_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 rs(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Ve(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ve(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};ar.create=(t,e)=>new ar({innerType:t,typeName:Q.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...se(e)});cs=class extends le{_parse(e){if(this._getType(e)!==L.nan){let r=this._getOrReturnCtx(e);return z(r,{code:A.invalid_type,expected:L.nan,received:r.parsedType}),X}return{status:"valid",value:e.data}}};cs.create=t=>new cs({typeName:Q.ZodNaN,...se(t)});hb=Symbol("zod_brand"),ti=class extends le{_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}},ni=class t extends le{_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"?X:i.status==="dirty"?(n.dirty(),Wn(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?X: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:Q.ZodPipeline})}},lr=class extends le{_parse(e){let n=this._def.innerType._parse(e),r=s=>(vn(s)&&(s.value=Object.freeze(s.value)),s);return rs(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};lr.create=(t,e)=>new lr({innerType:t,typeName:Q.ZodReadonly,...se(e)});pb={object:Je.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"})(Q||(Q={}));fb=(t,e={message:`Input not instance of ${t.name}`})=>vd(n=>n instanceof t,e),kd=kn.create,_d=Zn.create,mb=cs.create,gb=Vn.create,Sd=Jn.create,yb=Yn.create,bb=is.create,wb=Xn.create,vb=Qn.create,kb=_n.create,_b=Qt.create,Sb=kt.create,Tb=os.create,xb=en.create,Ib=Je.create,Rb=Je.strictCreate,Eb=er.create,Ab=to.create,Cb=tr.create,$b=Nt.create,Pb=no.create,Nb=as.create,jb=ls.create,Ob=ro.create,Mb=nr.create,zb=rr.create,Db=sr.create,Lb=ir.create,Ub=Sn.create,qb=ut.create,Fb=lt.create,Bb=jt.create,Hb=ut.createWithPreprocess,Kb=ni.create,Gb=()=>kd().optional(),Wb=()=>_d().optional(),Zb=()=>Sd().optional(),Vb={string:(t=>kn.create({...t,coerce:!0})),number:(t=>Zn.create({...t,coerce:!0})),boolean:(t=>Jn.create({...t,coerce:!0})),bigint:(t=>Vn.create({...t,coerce:!0})),date:(t=>Yn.create({...t,coerce:!0}))},Jb=X});var k={};$t(k,{BRAND:()=>hb,DIRTY:()=>Wn,EMPTY_PATH:()=>Hy,INVALID:()=>X,NEVER:()=>Jb,OK:()=>ze,ParseStatus:()=>Oe,Schema:()=>le,ZodAny:()=>_n,ZodArray:()=>en,ZodBigInt:()=>Vn,ZodBoolean:()=>Jn,ZodBranded:()=>ti,ZodCatch:()=>ar,ZodDate:()=>Yn,ZodDefault:()=>or,ZodDiscriminatedUnion:()=>to,ZodEffects:()=>ut,ZodEnum:()=>sr,ZodError:()=>Ve,ZodFirstPartyTypeKind:()=>Q,ZodFunction:()=>ro,ZodIntersection:()=>tr,ZodIssueCode:()=>A,ZodLazy:()=>nr,ZodLiteral:()=>rr,ZodMap:()=>as,ZodNaN:()=>cs,ZodNativeEnum:()=>ir,ZodNever:()=>kt,ZodNull:()=>Qn,ZodNullable:()=>jt,ZodNumber:()=>Zn,ZodObject:()=>Je,ZodOptional:()=>lt,ZodParsedType:()=>L,ZodPipeline:()=>ni,ZodPromise:()=>Sn,ZodReadonly:()=>lr,ZodRecord:()=>no,ZodSchema:()=>le,ZodSet:()=>ls,ZodString:()=>kn,ZodSymbol:()=>is,ZodTransformer:()=>ut,ZodTuple:()=>Nt,ZodType:()=>le,ZodUndefined:()=>Xn,ZodUnion:()=>er,ZodUnknown:()=>Qt,ZodVoid:()=>os,addIssueToContext:()=>z,any:()=>kb,array:()=>xb,bigint:()=>gb,boolean:()=>Sd,coerce:()=>Vb,custom:()=>vd,date:()=>yb,datetimeRegex:()=>bd,defaultErrorMap:()=>Yt,discriminatedUnion:()=>Ab,effect:()=>qb,enum:()=>Db,function:()=>Ob,getErrorMap:()=>ns,getParsedType:()=>Pt,instanceof:()=>fb,intersection:()=>Cb,isAborted:()=>Qi,isAsync:()=>rs,isDirty:()=>eo,isValid:()=>vn,late:()=>pb,lazy:()=>Mb,literal:()=>zb,makeIssue:()=>ei,map:()=>Nb,nan:()=>mb,nativeEnum:()=>Lb,never:()=>Sb,null:()=>vb,nullable:()=>Bb,number:()=>_d,object:()=>Ib,objectUtil:()=>il,oboolean:()=>Zb,onumber:()=>Wb,optional:()=>Fb,ostring:()=>Gb,pipeline:()=>Kb,preprocess:()=>Hb,promise:()=>Ub,quotelessJson:()=>qy,record:()=>Pb,set:()=>jb,setErrorMap:()=>By,strictObject:()=>Rb,string:()=>kd,symbol:()=>bb,transformer:()=>qb,tuple:()=>$b,undefined:()=>wb,union:()=>Eb,unknown:()=>_b,util:()=>ue,void:()=>Tb});var ul=te(()=>{Xi();al();hd();Qs();Td();Yi()});var Tn=te(()=>{ul();ul()});function ie(){let t=process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR;if(t)return t;let e=io.default.join(so.default.homedir(),".config","allwright"),n=io.default.join(so.default.homedir(),".config","ticketpilot");return!tn.default.existsSync(e)&&tn.default.existsSync(n)?n:e}function nn(){return io.default.join(ie(),"runner.json")}function ve(){let t=nn();if(!tn.default.existsSync(t))return null;let e=JSON.parse(tn.default.readFileSync(t,"utf8"));return dl.parse(e)}function ye(t){let e=ie();tn.default.mkdirSync(e,{recursive:!0,mode:448});let n=nn(),r=n+".tmp";tn.default.writeFileSync(r,JSON.stringify(t,null,2)+`
24
+ `,{mode:384}),tn.default.renameSync(r,n),tn.default.chmodSync(n,384)}function oo(t,e){return`${t}:${e}`}function Ot(t,e,n){return t.environments[oo(e,n)]?.secrets??{}}function ao(t,e){return t.repos[e]?.jira??t.jira}function lo(t){return!t.jira&&!Object.values(t.repos).some(e=>e.jira)}function de(){let t=ve();if(!t)throw new Error(`No runner config found at ${nn()}. Run \`allwright init\` first.`);return t}var tn,so,io,xd,dl,Ae=te(()=>{"use strict";tn=E(require("node:fs"),1),so=E(require("node:os"),1),io=E(require("node:path"),1);Tn();xd=k.object({baseUrl:k.string().url(),email:k.string().email(),apiToken:k.string().min(1)}),dl=k.object({controlPlaneUrl:k.string().url(),runnerId:k.string().optional(),runnerToken:k.string().optional(),runnerName:k.string().default(so.default.hostname()),jira:xd.optional(),repos:k.record(k.object({path:k.string(),jira:xd.optional(),github:k.object({token:k.string().min(1),login:k.string().optional()}).optional()})).default({}),github:k.object({token:k.string().min(1),login:k.string().optional()}).optional(),githubUsers:k.record(k.object({token:k.string().min(1),login:k.string().optional()})).default({}),deploy:k.object({enabled:k.boolean().default(!1)}).default({enabled:!1}),environments:k.record(k.object({secrets:k.record(k.string()).default({})})).default({}),claudeProfiles:k.record(k.object({configDir:k.string()})).default({}),claudeBin:k.string().default("claude"),agents:k.record(k.object({bin:k.string()})).default({}),jiraUsers:k.record(k.object({email:k.string().email(),apiToken:k.string().min(1)})).default({}),auditSchedules:k.array(k.object({repoName:k.string(),role:k.enum(["security","testing"]),intervalHours:k.number().int().min(6).max(720)})).default([]),pollIntervalSeconds:k.number().int().min(10).max(600).default(30),operatorEnabled:k.boolean().default(!1)})});function Ad(t,e){let n=xn.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 ds(t,e,n,r){if(!e.length)return"";let s=xn.default.join(n,ho);us.default.mkdirSync(s,{recursive:!0});let i=new Set,o=[],l=0;for(let c of e){if(o.length>=Ed){r("warn",`attachment cap reached (${Ed} files) - skipping the rest`);break}if(c.size>Qb){r("warn",`skipping attachment "${c.filename}" - ${rw(c.size)} MB exceeds the 15 MB limit`);continue}if(l+c.size>ew){r("warn",`attachment size budget reached - skipping "${c.filename}" and the rest`);break}try{let d=await t.downloadAttachment(c.contentUrl),p=Ad(c.filename,i);us.default.writeFileSync(xn.default.join(s,p),d),l+=d.length,o.push(`- ${ho}/${p} (${c.mimeType||"unknown type"}, ${hl(d.length)} KB)`),r("info",`Downloaded attachment "${c.filename}" (${hl(d.length)} KB)`)}catch(d){r("warn",`could not download attachment "${c.filename}": ${d instanceof Error?d.message:d}`)}}return o.length?`
25
25
 
26
26
  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:
27
27
  ${o.join(`
28
28
  `)}
29
- Read them with the Read tool when relevant; images (screenshots) can be viewed directly.`:(_n(n),"")}function _n(t){ls.default.rmSync(kn.default.join(t,lo),{recursive:!0,force:!0})}function kd(t,e,n){let r=kn.default.join(t,lo,`chat-${e.replace(/[^\w-]/g,"")}`);if(!n.length)return{section:"",dir:r};ls.default.mkdirSync(r,{recursive:!0});let s=new Set,i=[],o=0,l=kn.default.relative(t,r);for(let d of n){let p=Buffer.from(d.contentBase64,"base64");if(p.length>Ib||o+p.length>Eb){i.push(`- (skipped "${d.name}" - over the upload size budget)`);continue}let f=vd(d.name,s);ls.default.writeFileSync(kn.default.join(r,f),p),o+=p.length,i.push(`- ${l}/${f} (${nl(p.length)} KB)`)}return{section:`
29
+ Read them with the Read tool when relevant; images (screenshots) can be viewed directly.`:(In(n),"")}function In(t){us.default.rmSync(xn.default.join(t,ho),{recursive:!0,force:!0})}function Cd(t,e,n){let r=xn.default.join(t,ho,`chat-${e.replace(/[^\w-]/g,"")}`);if(!n.length)return{section:"",dir:r};us.default.mkdirSync(r,{recursive:!0});let s=new Set,i=[],o=0,l=xn.default.relative(t,r);for(let d of n){let p=Buffer.from(d.contentBase64,"base64");if(p.length>tw||o+p.length>nw){i.push(`- (skipped "${d.name}" - over the upload size budget)`);continue}let f=Ad(d.name,s);us.default.writeFileSync(xn.default.join(r,f),p),o+=p.length,i.push(`- ${l}/${f} (${hl(p.length)} KB)`)}return{section:`
30
30
 
31
31
  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:
32
32
  ${i.join(`
33
33
  `)}
34
- Read them with the Read tool; images can be viewed directly.`,dir:r}}var ls,kn,lo,Tb,xb,wd,Ib,Eb,nl,Rb,rl=ne(()=>{"use strict";ls=R(require("node:fs"),1),kn=R(require("node:path"),1),lo=".ticketpilot-attachments",Tb=15*1024*1024,xb=50*1024*1024,wd=20;Ib=4*1024*1024,Eb=16*1024*1024;nl=t=>Math.max(1,Math.round(t/1024)),Rb=t=>Math.round(t/(1024*1024)*10)/10});var ei=de(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.getParsedType=me.ZodParsedType=me.objectUtil=me.util=void 0;var ol;(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})(ol||(me.util=ol={}));var Ad;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Ad||(me.objectUtil=Ad={}));me.ZodParsedType=ol.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var $b=t=>{switch(typeof t){case"undefined":return me.ZodParsedType.undefined;case"string":return me.ZodParsedType.string;case"number":return Number.isNaN(t)?me.ZodParsedType.nan:me.ZodParsedType.number;case"boolean":return me.ZodParsedType.boolean;case"function":return me.ZodParsedType.function;case"bigint":return me.ZodParsedType.bigint;case"symbol":return me.ZodParsedType.symbol;case"object":return Array.isArray(t)?me.ZodParsedType.array:t===null?me.ZodParsedType.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?me.ZodParsedType.promise:typeof Map<"u"&&t instanceof Map?me.ZodParsedType.map:typeof Set<"u"&&t instanceof Set?me.ZodParsedType.set:typeof Date<"u"&&t instanceof Date?me.ZodParsedType.date:me.ZodParsedType.object;default:return me.ZodParsedType.unknown}};me.getParsedType=$b});var ho=de(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.ZodError=Sn.quotelessJson=Sn.ZodIssueCode=void 0;var Cd=ei();Sn.ZodIssueCode=Cd.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 Pb=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");Sn.quotelessJson=Pb;var ti=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 d=o.path[c];c===o.path.length-1?(l[d]=l[d]||{_errors:[]},l[d]._errors.push(n(o))):l[d]=l[d]||{_errors:[]},l=l[d],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,Cd.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()}};Sn.ZodError=ti;ti.create=t=>new ti(t)});var ll=de(al=>{"use strict";Object.defineProperty(al,"__esModule",{value:!0});var De=ho(),cr=ei(),Nb=(t,e)=>{let n;switch(t.code){case De.ZodIssueCode.invalid_type:t.received===cr.ZodParsedType.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case De.ZodIssueCode.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,cr.util.jsonStringifyReplacer)}`;break;case De.ZodIssueCode.unrecognized_keys:n=`Unrecognized key(s) in object: ${cr.util.joinValues(t.keys,", ")}`;break;case De.ZodIssueCode.invalid_union:n="Invalid input";break;case De.ZodIssueCode.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${cr.util.joinValues(t.options)}`;break;case De.ZodIssueCode.invalid_enum_value:n=`Invalid enum value. Expected ${cr.util.joinValues(t.options)}, received '${t.received}'`;break;case De.ZodIssueCode.invalid_arguments:n="Invalid function arguments";break;case De.ZodIssueCode.invalid_return_type:n="Invalid function return type";break;case De.ZodIssueCode.invalid_date:n="Invalid date";break;case De.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}"`:cr.util.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case De.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 De.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 De.ZodIssueCode.custom:n="Invalid input";break;case De.ZodIssueCode.invalid_intersection_types:n="Intersection results could not be merged";break;case De.ZodIssueCode.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case De.ZodIssueCode.not_finite:n="Number must be finite";break;default:n=e.defaultError,cr.util.assertNever(t)}return{message:n}};al.default=Nb});var po=de(Tn=>{"use strict";var Ob=Tn&&Tn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Tn,"__esModule",{value:!0});Tn.defaultErrorMap=void 0;Tn.setErrorMap=jb;Tn.getErrorMap=Mb;var $d=Ob(ll());Tn.defaultErrorMap=$d.default;var Pd=$d.default;function jb(t){Pd=t}function Mb(){return Pd}});var ul=de(pe=>{"use strict";var zb=pe&&pe.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(pe,"__esModule",{value:!0});pe.isAsync=pe.isValid=pe.isDirty=pe.isAborted=pe.OK=pe.DIRTY=pe.INVALID=pe.ParseStatus=pe.EMPTY_PATH=pe.makeIssue=void 0;pe.addIssueToContext=Ub;var Db=po(),Nd=zb(ll()),Lb=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(d=>!!d).slice().reverse();for(let d of c)l=d(o,{data:e,defaultError:l}).message;return{...s,path:i,message:l}};pe.makeIssue=Lb;pe.EMPTY_PATH=[];function Ub(t,e){let n=(0,Db.getErrorMap)(),r=(0,pe.makeIssue)({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Nd.default?void 0:Nd.default].filter(s=>!!s)});t.common.issues.push(r)}var cl=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 pe.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 pe.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}}};pe.ParseStatus=cl;pe.INVALID=Object.freeze({status:"aborted"});var qb=t=>({status:"dirty",value:t});pe.DIRTY=qb;var Fb=t=>({status:"valid",value:t});pe.OK=Fb;var Bb=t=>t.status==="aborted";pe.isAborted=Bb;var Hb=t=>t.status==="dirty";pe.isDirty=Hb;var Kb=t=>t.status==="valid";pe.isValid=Kb;var Gb=t=>typeof Promise<"u"&&t instanceof Promise;pe.isAsync=Gb});var jd=de(Od=>{"use strict";Object.defineProperty(Od,"__esModule",{value:!0})});var zd=de(fo=>{"use strict";Object.defineProperty(fo,"__esModule",{value:!0});fo.errorUtil=void 0;var Md;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(Md||(fo.errorUtil=Md={}))});var Vd=de(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=Fd;S.custom=Hd;var N=ho(),mo=po(),G=zd(),T=ul(),M=ei(),dt=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}},Dd=(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 N.ZodError(t.common.issues);return this._error=n,this._error}}};function ie(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 oe=class{get description(){return this._def.description}_getType(e){return(0,M.getParsedType)(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:(0,M.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,M.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,M.getParsedType)(e)},s=this._parseSync({data:e,path:r.path,parent:r});return Dd(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,M.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,M.getParsedType)(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await((0,T.isAsync)(s)?s:Promise.resolve(s));return Dd(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:N.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 et({schema:this,typeName:te.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 ut.create(this,this._def)}nullable(){return Nt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return tn.create(this)}promise(){return En.create(this,this._def)}or(e){return gr.create([this,e],this._def)}and(e){return yr.create(this,e,this._def)}transform(e){return new et({...ie(this._def),schema:this,typeName:te.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new _r({...ie(this._def),innerType:this,defaultValue:n,typeName:te.ZodDefault})}brand(){return new ni({typeName:te.ZodBranded,type:this,...ie(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Sr({...ie(this._def),innerType:this,catchValue:n,typeName:te.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return ri.create(this,e)}readonly(){return Tr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};S.ZodType=oe;S.Schema=oe;S.ZodSchema=oe;var Wb=/^c[^\s-]{8,}$/i,Zb=/^[0-9a-z]+$/,Vb=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Yb=/^[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,Jb=/^[a-z0-9_-]{21}$/i,Xb=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Qb=/^[-+]?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)?)??$/,ew=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,tw="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",dl,nw=/^(?:(?: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])$/,rw=/^(?:(?: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])$/,sw=/^(([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]))$/,iw=/^(([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])$/,ow=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,aw=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ud="((\\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])))",lw=new RegExp(`^${Ud}$`);function qd(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 cw(t){return new RegExp(`^${qd(t)}$`)}function Fd(t){let e=`${Ud}T${qd(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 uw(t,e){return!!((e==="v4"||!e)&&nw.test(t)||(e==="v6"||!e)&&sw.test(t))}function dw(t,e){if(!Xb.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 hw(t,e){return!!((e==="v4"||!e)&&rw.test(t)||(e==="v6"||!e)&&iw.test(t))}var xn=class t extends oe{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==M.ZodParsedType.string){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:N.ZodIssueCode.invalid_type,expected:M.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:N.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:N.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:N.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):l&&(0,T.addIssueToContext)(s,{code:N.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")ew.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"email",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")dl||(dl=new RegExp(tw,"u")),dl.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"emoji",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")Yb.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"uuid",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")Jb.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"nanoid",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")Wb.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"cuid",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")Zb.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"cuid2",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")Vb.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"ulid",code:N.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:N.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:N.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:N.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:N.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:N.ZodIssueCode.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Fd(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:N.ZodIssueCode.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?lw.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:N.ZodIssueCode.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?cw(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:N.ZodIssueCode.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?Qb.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"duration",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?uw(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"ip",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?dw(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"jwt",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?hw(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"cidr",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?ow.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"base64",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?aw.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"base64url",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):M.util.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:N.ZodIssueCode.invalid_string,...G.errorUtil.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...G.errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...G.errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...G.errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...G.errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...G.errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...G.errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...G.errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...G.errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...G.errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...G.errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...G.errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...G.errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...G.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,...G.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,...G.errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...G.errorUtil.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...G.errorUtil.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...G.errorUtil.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...G.errorUtil.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...G.errorUtil.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...G.errorUtil.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...G.errorUtil.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...G.errorUtil.errToObj(n)})}nonempty(e){return this.min(1,G.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=xn;xn.create=t=>new xn({checks:[],typeName:te.ZodString,coerce:t?.coerce??!1,...ie(t)});function pw(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 ur=class t extends oe{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)!==M.ZodParsedType.number){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:N.ZodIssueCode.invalid_type,expected:M.ZodParsedType.number,received:i.parsedType}),T.INVALID}let r,s=new T.ParseStatus;for(let i of this._def.checks)i.kind==="int"?M.util.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:N.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:N.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:N.ZodIssueCode.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?pw(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:N.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:N.ZodIssueCode.not_finite,message:i.message}),s.dirty()):M.util.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,G.errorUtil.toString(n))}gt(e,n){return this.setLimit("min",e,!1,G.errorUtil.toString(n))}lte(e,n){return this.setLimit("max",e,!0,G.errorUtil.toString(n))}lt(e,n){return this.setLimit("max",e,!1,G.errorUtil.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:G.errorUtil.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:G.errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:G.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:G.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:G.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:G.errorUtil.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:G.errorUtil.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:G.errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:G.errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:G.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"&&M.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=ur;ur.create=t=>new ur({checks:[],typeName:te.ZodNumber,coerce:t?.coerce||!1,...ie(t)});var dr=class t extends oe{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)!==M.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:N.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:N.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:N.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):M.util.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(n,{code:N.ZodIssueCode.invalid_type,expected:M.ZodParsedType.bigint,received:n.parsedType}),T.INVALID}gte(e,n){return this.setLimit("min",e,!0,G.errorUtil.toString(n))}gt(e,n){return this.setLimit("min",e,!1,G.errorUtil.toString(n))}lte(e,n){return this.setLimit("max",e,!0,G.errorUtil.toString(n))}lt(e,n){return this.setLimit("max",e,!1,G.errorUtil.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:G.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:G.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:G.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:G.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:G.errorUtil.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:G.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=dr;dr.create=t=>new dr({checks:[],typeName:te.ZodBigInt,coerce:t?.coerce??!1,...ie(t)});var hr=class extends oe{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==M.ZodParsedType.boolean){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.invalid_type,expected:M.ZodParsedType.boolean,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};S.ZodBoolean=hr;hr.create=t=>new hr({typeName:te.ZodBoolean,coerce:t?.coerce||!1,...ie(t)});var pr=class t extends oe{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==M.ZodParsedType.date){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:N.ZodIssueCode.invalid_type,expected:M.ZodParsedType.date,received:i.parsedType}),T.INVALID}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:N.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:N.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:N.ZodIssueCode.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):M.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:G.errorUtil.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:G.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=pr;pr.create=t=>new pr({checks:[],coerce:t?.coerce||!1,typeName:te.ZodDate,...ie(t)});var ps=class extends oe{_parse(e){if(this._getType(e)!==M.ZodParsedType.symbol){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.invalid_type,expected:M.ZodParsedType.symbol,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};S.ZodSymbol=ps;ps.create=t=>new ps({typeName:te.ZodSymbol,...ie(t)});var fr=class extends oe{_parse(e){if(this._getType(e)!==M.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.invalid_type,expected:M.ZodParsedType.undefined,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};S.ZodUndefined=fr;fr.create=t=>new fr({typeName:te.ZodUndefined,...ie(t)});var mr=class extends oe{_parse(e){if(this._getType(e)!==M.ZodParsedType.null){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.invalid_type,expected:M.ZodParsedType.null,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};S.ZodNull=mr;mr.create=t=>new mr({typeName:te.ZodNull,...ie(t)});var In=class extends oe{constructor(){super(...arguments),this._any=!0}_parse(e){return(0,T.OK)(e.data)}};S.ZodAny=In;In.create=t=>new In({typeName:te.ZodAny,...ie(t)});var en=class extends oe{constructor(){super(...arguments),this._unknown=!0}_parse(e){return(0,T.OK)(e.data)}};S.ZodUnknown=en;en.create=t=>new en({typeName:te.ZodUnknown,...ie(t)});var kt=class extends oe{_parse(e){let n=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(n,{code:N.ZodIssueCode.invalid_type,expected:M.ZodParsedType.never,received:n.parsedType}),T.INVALID}};S.ZodNever=kt;kt.create=t=>new kt({typeName:te.ZodNever,...ie(t)});var fs=class extends oe{_parse(e){if(this._getType(e)!==M.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.invalid_type,expected:M.ZodParsedType.void,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};S.ZodVoid=fs;fs.create=t=>new fs({typeName:te.ZodVoid,...ie(t)});var tn=class t extends oe{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==M.ZodParsedType.array)return(0,T.addIssueToContext)(n,{code:N.ZodIssueCode.invalid_type,expected:M.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?N.ZodIssueCode.too_big:N.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:N.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:N.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 dt(n,o,n.path,l)))).then(o=>T.ParseStatus.mergeArray(r,o));let i=[...n.data].map((o,l)=>s.type._parseSync(new dt(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:G.errorUtil.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:G.errorUtil.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:G.errorUtil.toString(n)}})}nonempty(e){return this.min(1,e)}};S.ZodArray=tn;tn.create=(t,e)=>new tn({type:t,minLength:null,maxLength:null,exactLength:null,typeName:te.ZodArray,...ie(e)});function hs(t){if(t instanceof Ze){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=ut.create(hs(r))}return new Ze({...t._def,shape:()=>e})}else return t instanceof tn?new tn({...t._def,type:hs(t.element)}):t instanceof ut?ut.create(hs(t.unwrap())):t instanceof Nt?Nt.create(hs(t.unwrap())):t instanceof Pt?Pt.create(t.items.map(e=>hs(e))):t}var Ze=class t extends oe{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=M.util.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==M.ZodParsedType.object){let d=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(d,{code:N.ZodIssueCode.invalid_type,expected:M.ZodParsedType.object,received:d.parsedType}),T.INVALID}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),l=[];if(!(this._def.catchall instanceof kt&&this._def.unknownKeys==="strip"))for(let d in s.data)o.includes(d)||l.push(d);let c=[];for(let d of o){let p=i[d],f=s.data[d];c.push({key:{status:"valid",value:d},value:p._parse(new dt(s,f,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof kt){let d=this._def.unknownKeys;if(d==="passthrough")for(let p of l)c.push({key:{status:"valid",value:p},value:{status:"valid",value:s.data[p]}});else if(d==="strict")l.length>0&&((0,T.addIssueToContext)(s,{code:N.ZodIssueCode.unrecognized_keys,keys:l}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let p of l){let f=s.data[p];c.push({key:{status:"valid",value:p},value:d._parse(new dt(s,f,s.path,p)),alwaysSet:p in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let d=[];for(let p of c){let f=await p.key,w=await p.value;d.push({key:f,value:w,alwaysSet:p.alwaysSet})}return d}).then(d=>T.ParseStatus.mergeObjectSync(r,d)):T.ParseStatus.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return G.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:G.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:te.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 M.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 M.util.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return hs(this)}partial(e){let n={};for(let r of M.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 M.util.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof ut;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return Bd(M.util.objectKeys(this.shape))}};S.ZodObject=Ze;Ze.create=(t,e)=>new Ze({shape:()=>t,unknownKeys:"strip",catchall:kt.create(),typeName:te.ZodObject,...ie(e)});Ze.strictCreate=(t,e)=>new Ze({shape:()=>t,unknownKeys:"strict",catchall:kt.create(),typeName:te.ZodObject,...ie(e)});Ze.lazycreate=(t,e)=>new Ze({shape:t,unknownKeys:"strip",catchall:kt.create(),typeName:te.ZodObject,...ie(e)});var gr=class extends oe{_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 N.ZodError(l.ctx.common.issues));return(0,T.addIssueToContext)(n,{code:N.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 d={...n,common:{...n.common,issues:[]},parent:null},p=c._parseSync({data:n.data,path:n.path,parent:d});if(p.status==="valid")return p;p.status==="dirty"&&!i&&(i={result:p,ctx:d}),d.common.issues.length&&o.push(d.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let l=o.map(c=>new N.ZodError(c));return(0,T.addIssueToContext)(n,{code:N.ZodIssueCode.invalid_union,unionErrors:l}),T.INVALID}}get options(){return this._def.options}};S.ZodUnion=gr;gr.create=(t,e)=>new gr({options:t,typeName:te.ZodUnion,...ie(e)});var Qt=t=>t instanceof br?Qt(t.schema):t instanceof et?Qt(t.innerType()):t instanceof wr?[t.value]:t instanceof vr?t.options:t instanceof kr?M.util.objectValues(t.enum):t instanceof _r?Qt(t._def.innerType):t instanceof fr?[void 0]:t instanceof mr?[null]:t instanceof ut?[void 0,...Qt(t.unwrap())]:t instanceof Nt?[null,...Qt(t.unwrap())]:t instanceof ni||t instanceof Tr?Qt(t.unwrap()):t instanceof Sr?Qt(t._def.innerType):[],go=class t extends oe{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==M.ZodParsedType.object)return(0,T.addIssueToContext)(n,{code:N.ZodIssueCode.invalid_type,expected:M.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:N.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=Qt(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:te.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...ie(r)})}};S.ZodDiscriminatedUnion=go;function hl(t,e){let n=(0,M.getParsedType)(t),r=(0,M.getParsedType)(e);if(t===e)return{valid:!0,data:t};if(n===M.ZodParsedType.object&&r===M.ZodParsedType.object){let s=M.util.objectKeys(e),i=M.util.objectKeys(t).filter(l=>s.indexOf(l)!==-1),o={...t,...e};for(let l of i){let c=hl(t[l],e[l]);if(!c.valid)return{valid:!1};o[l]=c.data}return{valid:!0,data:o}}else if(n===M.ZodParsedType.array&&r===M.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=hl(o,l);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===M.ZodParsedType.date&&r===M.ZodParsedType.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var yr=class extends oe{_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=hl(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:N.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=yr;yr.create=(t,e,n)=>new yr({left:t,right:e,typeName:te.ZodIntersection,...ie(n)});var Pt=class t extends oe{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==M.ZodParsedType.array)return(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.invalid_type,expected:M.ZodParsedType.array,received:r.parsedType}),T.INVALID;if(r.data.length<this._def.items.length)return(0,T.addIssueToContext)(r,{code:N.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:N.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 dt(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=Pt;Pt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Pt({items:t,typeName:te.ZodTuple,rest:null,...ie(e)})};var yo=class t extends oe{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!==M.ZodParsedType.object)return(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.invalid_type,expected:M.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 dt(r,l,r.path,l)),value:o._parse(new dt(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 oe?new t({keyType:e,valueType:n,typeName:te.ZodRecord,...ie(r)}):new t({keyType:xn.create(),valueType:e,typeName:te.ZodRecord,...ie(n)})}};S.ZodRecord=yo;var ms=class extends oe{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!==M.ZodParsedType.map)return(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.invalid_type,expected:M.ZodParsedType.map,received:r.parsedType}),T.INVALID;let s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([l,c],d)=>({key:s._parse(new dt(r,l,r.path,[d,"key"])),value:i._parse(new dt(r,c,r.path,[d,"value"]))}));if(r.common.async){let l=new Map;return Promise.resolve().then(async()=>{for(let c of o){let d=await c.key,p=await c.value;if(d.status==="aborted"||p.status==="aborted")return T.INVALID;(d.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(d.value,p.value)}return{status:n.value,value:l}})}else{let l=new Map;for(let c of o){let d=c.key,p=c.value;if(d.status==="aborted"||p.status==="aborted")return T.INVALID;(d.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(d.value,p.value)}return{status:n.value,value:l}}}};S.ZodMap=ms;ms.create=(t,e,n)=>new ms({valueType:e,keyType:t,typeName:te.ZodMap,...ie(n)});var gs=class t extends oe{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==M.ZodParsedType.set)return(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.invalid_type,expected:M.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:N.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:N.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 d=new Set;for(let p of c){if(p.status==="aborted")return T.INVALID;p.status==="dirty"&&n.dirty(),d.add(p.value)}return{status:n.value,value:d}}let l=[...r.data.values()].map((c,d)=>i._parse(new dt(r,c,r.path,d)));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:G.errorUtil.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:G.errorUtil.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};S.ZodSet=gs;gs.create=(t,e)=>new gs({valueType:t,minSize:null,maxSize:null,typeName:te.ZodSet,...ie(e)});var bo=class t extends oe{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==M.ZodParsedType.function)return(0,T.addIssueToContext)(n,{code:N.ZodIssueCode.invalid_type,expected:M.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,mo.getErrorMap)(),mo.defaultErrorMap].filter(d=>!!d),issueData:{code:N.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,mo.getErrorMap)(),mo.defaultErrorMap].filter(d=>!!d),issueData:{code:N.ZodIssueCode.invalid_return_type,returnTypeError:c}})}let i={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof En){let l=this;return(0,T.OK)(async function(...c){let d=new N.ZodError([]),p=await l._def.args.parseAsync(c,i).catch(v=>{throw d.addIssue(r(c,v)),d}),f=await Reflect.apply(o,this,p);return await l._def.returns._def.type.parseAsync(f,i).catch(v=>{throw d.addIssue(s(f,v)),d})})}else{let l=this;return(0,T.OK)(function(...c){let d=l._def.args.safeParse(c,i);if(!d.success)throw new N.ZodError([r(c,d.error)]);let p=Reflect.apply(o,this,d.data),f=l._def.returns.safeParse(p,i);if(!f.success)throw new N.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:Pt.create(e).rest(en.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||Pt.create([]).rest(en.create()),returns:n||en.create(),typeName:te.ZodFunction,...ie(r)})}};S.ZodFunction=bo;var br=class extends oe{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=br;br.create=(t,e)=>new br({getter:t,typeName:te.ZodLazy,...ie(e)});var wr=class extends oe{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(n,{received:n.data,code:N.ZodIssueCode.invalid_literal,expected:this._def.value}),T.INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}};S.ZodLiteral=wr;wr.create=(t,e)=>new wr({value:t,typeName:te.ZodLiteral,...ie(e)});function Bd(t,e){return new vr({values:t,typeName:te.ZodEnum,...ie(e)})}var vr=class t extends oe{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return(0,T.addIssueToContext)(n,{expected:M.util.joinValues(r),received:n.parsedType,code:N.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:N.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=vr;vr.create=Bd;var kr=class extends oe{_parse(e){let n=M.util.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==M.ZodParsedType.string&&r.parsedType!==M.ZodParsedType.number){let s=M.util.objectValues(n);return(0,T.addIssueToContext)(r,{expected:M.util.joinValues(s),received:r.parsedType,code:N.ZodIssueCode.invalid_type}),T.INVALID}if(this._cache||(this._cache=new Set(M.util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=M.util.objectValues(n);return(0,T.addIssueToContext)(r,{received:r.data,code:N.ZodIssueCode.invalid_enum_value,options:s}),T.INVALID}return(0,T.OK)(e.data)}get enum(){return this._def.values}};S.ZodNativeEnum=kr;kr.create=(t,e)=>new kr({values:t,typeName:te.ZodNativeEnum,...ie(e)});var En=class extends oe{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==M.ZodParsedType.promise&&n.common.async===!1)return(0,T.addIssueToContext)(n,{code:N.ZodIssueCode.invalid_type,expected:M.ZodParsedType.promise,received:n.parsedType}),T.INVALID;let r=n.parsedType===M.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=En;En.create=(t,e)=>new En({type:t,typeName:te.ZodPromise,...ie(e)});var et=class extends oe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===te.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);M.util.assertNever(s)}};S.ZodEffects=et;S.ZodTransformer=et;et.create=(t,e,n)=>new et({schema:t,typeName:te.ZodEffects,effect:e,...ie(n)});et.createWithPreprocess=(t,e,n)=>new et({schema:e,effect:{type:"preprocess",transform:t},typeName:te.ZodEffects,...ie(n)});var ut=class extends oe{_parse(e){return this._getType(e)===M.ZodParsedType.undefined?(0,T.OK)(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};S.ZodOptional=ut;ut.create=(t,e)=>new ut({innerType:t,typeName:te.ZodOptional,...ie(e)});var Nt=class extends oe{_parse(e){return this._getType(e)===M.ZodParsedType.null?(0,T.OK)(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};S.ZodNullable=Nt;Nt.create=(t,e)=>new Nt({innerType:t,typeName:te.ZodNullable,...ie(e)});var _r=class extends oe{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===M.ZodParsedType.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};S.ZodDefault=_r;_r.create=(t,e)=>new _r({innerType:t,typeName:te.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ie(e)});var Sr=class extends oe{_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 N.ZodError(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new N.ZodError(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};S.ZodCatch=Sr;Sr.create=(t,e)=>new Sr({innerType:t,typeName:te.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ie(e)});var ys=class extends oe{_parse(e){if(this._getType(e)!==M.ZodParsedType.nan){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.invalid_type,expected:M.ZodParsedType.nan,received:r.parsedType}),T.INVALID}return{status:"valid",value:e.data}}};S.ZodNaN=ys;ys.create=t=>new ys({typeName:te.ZodNaN,...ie(t)});S.BRAND=Symbol("zod_brand");var ni=class extends oe{_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=ni;var ri=class t extends oe{_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:te.ZodPipeline})}};S.ZodPipeline=ri;var Tr=class extends oe{_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=Tr;Tr.create=(t,e)=>new Tr({innerType:t,typeName:te.ZodReadonly,...ie(e)});function Ld(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function Hd(t,e={},n){return t?In.create().superRefine((r,s)=>{let i=t(r);if(i instanceof Promise)return i.then(o=>{if(!o){let l=Ld(e,r),c=l.fatal??n??!0;s.addIssue({code:"custom",...l,fatal:c})}});if(!i){let o=Ld(e,r),l=o.fatal??n??!0;s.addIssue({code:"custom",...o,fatal:l})}}):In.create()}S.late={object:Ze.lazycreate};var te;(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"})(te||(S.ZodFirstPartyTypeKind=te={}));var fw=(t,e={message:`Input not instance of ${t.name}`})=>Hd(n=>n instanceof t,e);S.instanceof=fw;var Kd=xn.create;S.string=Kd;var Gd=ur.create;S.number=Gd;var mw=ys.create;S.nan=mw;var gw=dr.create;S.bigint=gw;var Wd=hr.create;S.boolean=Wd;var yw=pr.create;S.date=yw;var bw=ps.create;S.symbol=bw;var ww=fr.create;S.undefined=ww;var vw=mr.create;S.null=vw;var kw=In.create;S.any=kw;var _w=en.create;S.unknown=_w;var Sw=kt.create;S.never=Sw;var Tw=fs.create;S.void=Tw;var xw=tn.create;S.array=xw;var Iw=Ze.create;S.object=Iw;var Ew=Ze.strictCreate;S.strictObject=Ew;var Rw=gr.create;S.union=Rw;var Aw=go.create;S.discriminatedUnion=Aw;var Cw=yr.create;S.intersection=Cw;var $w=Pt.create;S.tuple=$w;var Pw=yo.create;S.record=Pw;var Nw=ms.create;S.map=Nw;var Ow=gs.create;S.set=Ow;var jw=bo.create;S.function=jw;var Mw=br.create;S.lazy=Mw;var zw=wr.create;S.literal=zw;var Dw=vr.create;S.enum=Dw;var Lw=kr.create;S.nativeEnum=Lw;var Uw=En.create;S.promise=Uw;var Zd=et.create;S.effect=Zd;S.transformer=Zd;var qw=ut.create;S.optional=qw;var Fw=Nt.create;S.nullable=Fw;var Bw=et.createWithPreprocess;S.preprocess=Bw;var Hw=ri.create;S.pipeline=Hw;var Kw=()=>Kd().optional();S.ostring=Kw;var Gw=()=>Gd().optional();S.onumber=Gw;var Ww=()=>Wd().optional();S.oboolean=Ww;S.coerce={string:(t=>xn.create({...t,coerce:!0})),number:(t=>ur.create({...t,coerce:!0})),boolean:(t=>hr.create({...t,coerce:!0})),bigint:(t=>dr.create({...t,coerce:!0})),date:(t=>pr.create({...t,coerce:!0}))};S.NEVER=T.INVALID});var pl=de(ht=>{"use strict";var Zw=ht&&ht.__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]})),bs=ht&&ht.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Zw(e,t,n)};Object.defineProperty(ht,"__esModule",{value:!0});bs(po(),ht);bs(ul(),ht);bs(jd(),ht);bs(ei(),ht);bs(Vd(),ht);bs(ho(),ht)});var Xd=de(Ve=>{"use strict";var Yd=Ve&&Ve.__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]})),Vw=Ve&&Ve.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Yw=Ve&&Ve.__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)&&Yd(e,t,n);return Vw(e,t),e},Jw=Ve&&Ve.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Yd(e,t,n)};Object.defineProperty(Ve,"__esModule",{value:!0});Ve.z=void 0;var Jd=Yw(pl());Ve.z=Jd;Jw(pl(),Ve);Ve.default=Jd});var Re=de(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.ChatListMsg=h.ChatSessionMsg=h.ChatActivityMsg=h.ChatUsageMsg=h.ChatStreamMsg=h.JiraUsersResultMsg=h.DeployClaimResultMsg=h.DeployClaimMsg=h.RuleDiagnoseResultMsg=h.ProjectTestResultMsg=h.RunStatusMsg=h.RunContextMsg=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.DEPLOY_DOC_CANDIDATES=h.RUNNER_UNINSTALL_COMMAND=h.PROTOCOL_VERSION=h.GITHUB_TOKEN_PERMISSIONS=void 0;h.KnowledgeFile=h.KnowledgeListMsg=h.AuditReviewResultMsg=h.AuditReviewMsg=h.AuditGetResultMsg=h.AuditGetMsg=h.AuditExplainResultMsg=h.AuditExplainMsg=h.ChatCancelMsg=h.ChatStepRunResultMsg=h.ChatStepRunMsg=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=h.TICKET_RULES_APPENDIX=h.COMPOSE_COMMANDS=h.MAX_FAILURE_CHARS=h.MAX_FAILURE_LINES=h.FAILURE_BLOCK_LINES=h.FAILURE_CONTEXT_LINES=h.REPLY_STYLES=h.BUILTIN_REPLY_LANGUAGES=h.ChatLoadMsg=h.ChatListResultMsg=void 0;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.SetupAskResultMsg=h.SetupAskMsg=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=h.EnvPreflightResultMsg=h.EnvPreflightMsg=h.ChatCreateTicketResultMsg=h.ChatCreateTicketMsg=h.ChatTurnResultMsg=h.ChatTurnMsg=h.ChatFile=h.TeamCredsResultMsg=h.TeamCredsMsg=h.KnowledgeSaveResultMsg=h.KnowledgeSaveMsg=h.KnowledgeListResultMsg=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.REVISION_PROMPT=h.FOCUSED_READING_PROMPT=h.NEEDS_INPUT_OPTIONS_PROMPT=h.DEFAULT_PLAN_PROMPT_TEMPLATE=h.EnrollResponse=h.EnrollRequest=h.ServerToRunnerMsg=h.JiraUsersMsg=h.DeploySuggestMsg=h.DeployFixMsg=h.DeployStartMsg=h.RunRetryPushMsg=h.RunRejectedMsg=h.RunApprovedMsg=h.RunCancelMsg=h.RuleDiagnoseMsg=h.ProjectTestMsg=h.RunClaimResultMsg=h.ConfigMsg=void 0;h.missingAgentCapabilities=Xw;h.replyPreferenceAppendix=ev;h.pendingMigrationsAppendix=tv;h.deployTargetsAppendix=nv;h.savedStepChecksAppendix=rv;h.failureCollector=Qd;h.failureLines=av;h.composeCommandAppendix=lv;h.isSelfMigrationFilename=cv;h.parseRunnerMsg=uv;h.parseServerMsg=dv;var a=Xd();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.84";h.RUNNER_UNINSTALL_COMMAND="sudo allwright service uninstall";h.DEPLOY_DOC_CANDIDATES=[".ticketpilot/deploy.md","DEPLOY.md","DEPLOYMENT.md","docs/DEPLOY.md","docs/deploy.md","docs/deployment.md"];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 Xw(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 Qw=t=>t.includes(h.NEEDS_INPUT_COMMENT_MARKER)||h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS.some(e=>t.includes(e));h.needsInputMarkerIn=Qw;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),maxCostUsd:a.z.number().positive().optional(),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(""),servePath: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.RunContextMsg=a.z.object({type:a.z.literal("run.context"),runId:a.z.string(),pieces:a.z.array(a.z.object({part:a.z.string().max(80),chars:a.z.number().int().nonnegative()})).max(30),totalChars:a.z.number().int().nonnegative(),sessionMode:a.z.enum(["fresh","chained","timeout-resume","preflight-resume"])});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.ChatActivityMsg=a.z.object({type:a.z.literal("chat.activity"),requestId:a.z.string(),seq:a.z.number().int().nonnegative(),verb:a.z.string().max(40),target:a.z.string().max(200).default("")});h.ChatSessionMsg=a.z.object({type:a.z.literal("chat.session"),requestId:a.z.string(),sessionId:a.z.string()});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),ownerUserId:a.z.string().default("")})).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 ev(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?`
34
+ Read them with the Read tool; images can be viewed directly.`,dir:r}}var us,xn,ho,Qb,ew,Ed,tw,nw,hl,rw,pl=te(()=>{"use strict";us=E(require("node:fs"),1),xn=E(require("node:path"),1),ho=".ticketpilot-attachments",Qb=15*1024*1024,ew=50*1024*1024,Ed=20;tw=4*1024*1024,nw=16*1024*1024;hl=t=>Math.max(1,Math.round(t/1024)),rw=t=>Math.round(t/(1024*1024)*10)/10});var ri=he(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.getParsedType=me.ZodParsedType=me.objectUtil=me.util=void 0;var gl;(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})(gl||(me.util=gl={}));var Dd;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Dd||(me.objectUtil=Dd={}));me.ZodParsedType=gl.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var ow=t=>{switch(typeof t){case"undefined":return me.ZodParsedType.undefined;case"string":return me.ZodParsedType.string;case"number":return Number.isNaN(t)?me.ZodParsedType.nan:me.ZodParsedType.number;case"boolean":return me.ZodParsedType.boolean;case"function":return me.ZodParsedType.function;case"bigint":return me.ZodParsedType.bigint;case"symbol":return me.ZodParsedType.symbol;case"object":return Array.isArray(t)?me.ZodParsedType.array:t===null?me.ZodParsedType.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?me.ZodParsedType.promise:typeof Map<"u"&&t instanceof Map?me.ZodParsedType.map:typeof Set<"u"&&t instanceof Set?me.ZodParsedType.set:typeof Date<"u"&&t instanceof Date?me.ZodParsedType.date:me.ZodParsedType.object;default:return me.ZodParsedType.unknown}};me.getParsedType=ow});var mo=he(Rn=>{"use strict";Object.defineProperty(Rn,"__esModule",{value:!0});Rn.ZodError=Rn.quotelessJson=Rn.ZodIssueCode=void 0;var Ld=ri();Rn.ZodIssueCode=Ld.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 aw=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");Rn.quotelessJson=aw;var si=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 d=o.path[c];c===o.path.length-1?(l[d]=l[d]||{_errors:[]},l[d]._errors.push(n(o))):l[d]=l[d]||{_errors:[]},l=l[d],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,Ld.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()}};Rn.ZodError=si;si.create=t=>new si(t)});var bl=he(yl=>{"use strict";Object.defineProperty(yl,"__esModule",{value:!0});var Le=mo(),dr=ri(),lw=(t,e)=>{let n;switch(t.code){case Le.ZodIssueCode.invalid_type:t.received===dr.ZodParsedType.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case Le.ZodIssueCode.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,dr.util.jsonStringifyReplacer)}`;break;case Le.ZodIssueCode.unrecognized_keys:n=`Unrecognized key(s) in object: ${dr.util.joinValues(t.keys,", ")}`;break;case Le.ZodIssueCode.invalid_union:n="Invalid input";break;case Le.ZodIssueCode.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${dr.util.joinValues(t.options)}`;break;case Le.ZodIssueCode.invalid_enum_value:n=`Invalid enum value. Expected ${dr.util.joinValues(t.options)}, received '${t.received}'`;break;case Le.ZodIssueCode.invalid_arguments:n="Invalid function arguments";break;case Le.ZodIssueCode.invalid_return_type:n="Invalid function return type";break;case Le.ZodIssueCode.invalid_date:n="Invalid date";break;case Le.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}"`:dr.util.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case Le.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 Le.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 Le.ZodIssueCode.custom:n="Invalid input";break;case Le.ZodIssueCode.invalid_intersection_types:n="Intersection results could not be merged";break;case Le.ZodIssueCode.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case Le.ZodIssueCode.not_finite:n="Number must be finite";break;default:n=e.defaultError,dr.util.assertNever(t)}return{message:n}};yl.default=lw});var go=he(En=>{"use strict";var cw=En&&En.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(En,"__esModule",{value:!0});En.defaultErrorMap=void 0;En.setErrorMap=uw;En.getErrorMap=dw;var Ud=cw(bl());En.defaultErrorMap=Ud.default;var qd=Ud.default;function uw(t){qd=t}function dw(){return qd}});var vl=he(pe=>{"use strict";var hw=pe&&pe.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(pe,"__esModule",{value:!0});pe.isAsync=pe.isValid=pe.isDirty=pe.isAborted=pe.OK=pe.DIRTY=pe.INVALID=pe.ParseStatus=pe.EMPTY_PATH=pe.makeIssue=void 0;pe.addIssueToContext=mw;var pw=go(),Fd=hw(bl()),fw=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(d=>!!d).slice().reverse();for(let d of c)l=d(o,{data:e,defaultError:l}).message;return{...s,path:i,message:l}};pe.makeIssue=fw;pe.EMPTY_PATH=[];function mw(t,e){let n=(0,pw.getErrorMap)(),r=(0,pe.makeIssue)({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Fd.default?void 0:Fd.default].filter(s=>!!s)});t.common.issues.push(r)}var wl=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 pe.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 pe.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}}};pe.ParseStatus=wl;pe.INVALID=Object.freeze({status:"aborted"});var gw=t=>({status:"dirty",value:t});pe.DIRTY=gw;var yw=t=>({status:"valid",value:t});pe.OK=yw;var bw=t=>t.status==="aborted";pe.isAborted=bw;var ww=t=>t.status==="dirty";pe.isDirty=ww;var vw=t=>t.status==="valid";pe.isValid=vw;var kw=t=>typeof Promise<"u"&&t instanceof Promise;pe.isAsync=kw});var Hd=he(Bd=>{"use strict";Object.defineProperty(Bd,"__esModule",{value:!0})});var Gd=he(yo=>{"use strict";Object.defineProperty(yo,"__esModule",{value:!0});yo.errorUtil=void 0;var Kd;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(Kd||(yo.errorUtil=Kd={}))});var sh=he(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=Yd;S.custom=Qd;var N=mo(),bo=go(),W=Gd(),T=vl(),O=ri(),ht=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}},Wd=(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 N.ZodError(t.common.issues);return this._error=n,this._error}}};function oe(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 ae=class{get description(){return this._def.description}_getType(e){return(0,O.getParsedType)(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:(0,O.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,O.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,O.getParsedType)(e)},s=this._parseSync({data:e,path:r.path,parent:r});return Wd(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,O.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,O.getParsedType)(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await((0,T.isAsync)(s)?s:Promise.resolve(s));return Wd(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:N.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 nt({schema:this,typeName:ee.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 dt.create(this,this._def)}nullable(){return zt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return on.create(this)}promise(){return $n.create(this,this._def)}or(e){return br.create([this,e],this._def)}and(e){return wr.create(this,e,this._def)}transform(e){return new nt({...oe(this._def),schema:this,typeName:ee.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new Tr({...oe(this._def),innerType:this,defaultValue:n,typeName:ee.ZodDefault})}brand(){return new ii({typeName:ee.ZodBranded,type:this,...oe(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new xr({...oe(this._def),innerType:this,catchValue:n,typeName:ee.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return oi.create(this,e)}readonly(){return Ir.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};S.ZodType=ae;S.Schema=ae;S.ZodSchema=ae;var _w=/^c[^\s-]{8,}$/i,Sw=/^[0-9a-z]+$/,Tw=/^[0-9A-HJKMNP-TV-Z]{26}$/i,xw=/^[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,Iw=/^[a-z0-9_-]{21}$/i,Rw=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ew=/^[-+]?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)?)??$/,Aw=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Cw="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",kl,$w=/^(?:(?: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])$/,Pw=/^(?:(?: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])$/,Nw=/^(([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]))$/,jw=/^(([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])$/,Ow=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Mw=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Vd="((\\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])))",zw=new RegExp(`^${Vd}$`);function Jd(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 Dw(t){return new RegExp(`^${Jd(t)}$`)}function Yd(t){let e=`${Vd}T${Jd(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 Lw(t,e){return!!((e==="v4"||!e)&&$w.test(t)||(e==="v6"||!e)&&Nw.test(t))}function Uw(t,e){if(!Rw.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 qw(t,e){return!!((e==="v4"||!e)&&Pw.test(t)||(e==="v6"||!e)&&jw.test(t))}var An=class t extends ae{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==O.ZodParsedType.string){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:N.ZodIssueCode.invalid_type,expected:O.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:N.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:N.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:N.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):l&&(0,T.addIssueToContext)(s,{code:N.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")Aw.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"email",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")kl||(kl=new RegExp(Cw,"u")),kl.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"emoji",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")xw.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"uuid",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")Iw.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"nanoid",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")_w.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"cuid",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")Sw.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"cuid2",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")Tw.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"ulid",code:N.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:N.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:N.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:N.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:N.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:N.ZodIssueCode.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Yd(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:N.ZodIssueCode.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?zw.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:N.ZodIssueCode.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Dw(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:N.ZodIssueCode.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?Ew.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"duration",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?Lw(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"ip",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?Uw(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"jwt",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?qw(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"cidr",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?Ow.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"base64",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?Mw.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"base64url",code:N.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):O.util.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:N.ZodIssueCode.invalid_string,...W.errorUtil.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...W.errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...W.errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...W.errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...W.errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...W.errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...W.errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...W.errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...W.errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...W.errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...W.errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...W.errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...W.errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...W.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,...W.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,...W.errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...W.errorUtil.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...W.errorUtil.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...W.errorUtil.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...W.errorUtil.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...W.errorUtil.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...W.errorUtil.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...W.errorUtil.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...W.errorUtil.errToObj(n)})}nonempty(e){return this.min(1,W.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=An;An.create=t=>new An({checks:[],typeName:ee.ZodString,coerce:t?.coerce??!1,...oe(t)});function Fw(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 hr=class t extends ae{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==O.ZodParsedType.number){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:N.ZodIssueCode.invalid_type,expected:O.ZodParsedType.number,received:i.parsedType}),T.INVALID}let r,s=new T.ParseStatus;for(let i of this._def.checks)i.kind==="int"?O.util.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:N.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:N.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:N.ZodIssueCode.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Fw(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:N.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:N.ZodIssueCode.not_finite,message:i.message}),s.dirty()):O.util.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,W.errorUtil.toString(n))}gt(e,n){return this.setLimit("min",e,!1,W.errorUtil.toString(n))}lte(e,n){return this.setLimit("max",e,!0,W.errorUtil.toString(n))}lt(e,n){return this.setLimit("max",e,!1,W.errorUtil.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:W.errorUtil.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:W.errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:W.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:W.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:W.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:W.errorUtil.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:W.errorUtil.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:W.errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:W.errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:W.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"&&O.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=hr;hr.create=t=>new hr({checks:[],typeName:ee.ZodNumber,coerce:t?.coerce||!1,...oe(t)});var pr=class t extends ae{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==O.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:N.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:N.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:N.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):O.util.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(n,{code:N.ZodIssueCode.invalid_type,expected:O.ZodParsedType.bigint,received:n.parsedType}),T.INVALID}gte(e,n){return this.setLimit("min",e,!0,W.errorUtil.toString(n))}gt(e,n){return this.setLimit("min",e,!1,W.errorUtil.toString(n))}lte(e,n){return this.setLimit("max",e,!0,W.errorUtil.toString(n))}lt(e,n){return this.setLimit("max",e,!1,W.errorUtil.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:W.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:W.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:W.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:W.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:W.errorUtil.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:W.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=pr;pr.create=t=>new pr({checks:[],typeName:ee.ZodBigInt,coerce:t?.coerce??!1,...oe(t)});var fr=class extends ae{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==O.ZodParsedType.boolean){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.invalid_type,expected:O.ZodParsedType.boolean,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};S.ZodBoolean=fr;fr.create=t=>new fr({typeName:ee.ZodBoolean,coerce:t?.coerce||!1,...oe(t)});var mr=class t extends ae{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==O.ZodParsedType.date){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:N.ZodIssueCode.invalid_type,expected:O.ZodParsedType.date,received:i.parsedType}),T.INVALID}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:N.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:N.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:N.ZodIssueCode.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):O.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:W.errorUtil.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:W.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=mr;mr.create=t=>new mr({checks:[],coerce:t?.coerce||!1,typeName:ee.ZodDate,...oe(t)});var ms=class extends ae{_parse(e){if(this._getType(e)!==O.ZodParsedType.symbol){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.invalid_type,expected:O.ZodParsedType.symbol,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};S.ZodSymbol=ms;ms.create=t=>new ms({typeName:ee.ZodSymbol,...oe(t)});var gr=class extends ae{_parse(e){if(this._getType(e)!==O.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.invalid_type,expected:O.ZodParsedType.undefined,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};S.ZodUndefined=gr;gr.create=t=>new gr({typeName:ee.ZodUndefined,...oe(t)});var yr=class extends ae{_parse(e){if(this._getType(e)!==O.ZodParsedType.null){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.invalid_type,expected:O.ZodParsedType.null,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};S.ZodNull=yr;yr.create=t=>new yr({typeName:ee.ZodNull,...oe(t)});var Cn=class extends ae{constructor(){super(...arguments),this._any=!0}_parse(e){return(0,T.OK)(e.data)}};S.ZodAny=Cn;Cn.create=t=>new Cn({typeName:ee.ZodAny,...oe(t)});var sn=class extends ae{constructor(){super(...arguments),this._unknown=!0}_parse(e){return(0,T.OK)(e.data)}};S.ZodUnknown=sn;sn.create=t=>new sn({typeName:ee.ZodUnknown,...oe(t)});var _t=class extends ae{_parse(e){let n=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(n,{code:N.ZodIssueCode.invalid_type,expected:O.ZodParsedType.never,received:n.parsedType}),T.INVALID}};S.ZodNever=_t;_t.create=t=>new _t({typeName:ee.ZodNever,...oe(t)});var gs=class extends ae{_parse(e){if(this._getType(e)!==O.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.invalid_type,expected:O.ZodParsedType.void,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};S.ZodVoid=gs;gs.create=t=>new gs({typeName:ee.ZodVoid,...oe(t)});var on=class t extends ae{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==O.ZodParsedType.array)return(0,T.addIssueToContext)(n,{code:N.ZodIssueCode.invalid_type,expected:O.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?N.ZodIssueCode.too_big:N.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:N.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:N.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 ht(n,o,n.path,l)))).then(o=>T.ParseStatus.mergeArray(r,o));let i=[...n.data].map((o,l)=>s.type._parseSync(new ht(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:W.errorUtil.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:W.errorUtil.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:W.errorUtil.toString(n)}})}nonempty(e){return this.min(1,e)}};S.ZodArray=on;on.create=(t,e)=>new on({type:t,minLength:null,maxLength:null,exactLength:null,typeName:ee.ZodArray,...oe(e)});function fs(t){if(t instanceof Ye){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=dt.create(fs(r))}return new Ye({...t._def,shape:()=>e})}else return t instanceof on?new on({...t._def,type:fs(t.element)}):t instanceof dt?dt.create(fs(t.unwrap())):t instanceof zt?zt.create(fs(t.unwrap())):t instanceof Mt?Mt.create(t.items.map(e=>fs(e))):t}var Ye=class t extends ae{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=O.util.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==O.ZodParsedType.object){let d=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(d,{code:N.ZodIssueCode.invalid_type,expected:O.ZodParsedType.object,received:d.parsedType}),T.INVALID}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),l=[];if(!(this._def.catchall instanceof _t&&this._def.unknownKeys==="strip"))for(let d in s.data)o.includes(d)||l.push(d);let c=[];for(let d of o){let p=i[d],f=s.data[d];c.push({key:{status:"valid",value:d},value:p._parse(new ht(s,f,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof _t){let d=this._def.unknownKeys;if(d==="passthrough")for(let p of l)c.push({key:{status:"valid",value:p},value:{status:"valid",value:s.data[p]}});else if(d==="strict")l.length>0&&((0,T.addIssueToContext)(s,{code:N.ZodIssueCode.unrecognized_keys,keys:l}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let p of l){let f=s.data[p];c.push({key:{status:"valid",value:p},value:d._parse(new ht(s,f,s.path,p)),alwaysSet:p in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let d=[];for(let p of c){let f=await p.key,w=await p.value;d.push({key:f,value:w,alwaysSet:p.alwaysSet})}return d}).then(d=>T.ParseStatus.mergeObjectSync(r,d)):T.ParseStatus.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return W.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:W.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:ee.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 O.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 O.util.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return fs(this)}partial(e){let n={};for(let r of O.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 O.util.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof dt;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return Xd(O.util.objectKeys(this.shape))}};S.ZodObject=Ye;Ye.create=(t,e)=>new Ye({shape:()=>t,unknownKeys:"strip",catchall:_t.create(),typeName:ee.ZodObject,...oe(e)});Ye.strictCreate=(t,e)=>new Ye({shape:()=>t,unknownKeys:"strict",catchall:_t.create(),typeName:ee.ZodObject,...oe(e)});Ye.lazycreate=(t,e)=>new Ye({shape:t,unknownKeys:"strip",catchall:_t.create(),typeName:ee.ZodObject,...oe(e)});var br=class extends ae{_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 N.ZodError(l.ctx.common.issues));return(0,T.addIssueToContext)(n,{code:N.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 d={...n,common:{...n.common,issues:[]},parent:null},p=c._parseSync({data:n.data,path:n.path,parent:d});if(p.status==="valid")return p;p.status==="dirty"&&!i&&(i={result:p,ctx:d}),d.common.issues.length&&o.push(d.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let l=o.map(c=>new N.ZodError(c));return(0,T.addIssueToContext)(n,{code:N.ZodIssueCode.invalid_union,unionErrors:l}),T.INVALID}}get options(){return this._def.options}};S.ZodUnion=br;br.create=(t,e)=>new br({options:t,typeName:ee.ZodUnion,...oe(e)});var rn=t=>t instanceof vr?rn(t.schema):t instanceof nt?rn(t.innerType()):t instanceof kr?[t.value]:t instanceof _r?t.options:t instanceof Sr?O.util.objectValues(t.enum):t instanceof Tr?rn(t._def.innerType):t instanceof gr?[void 0]:t instanceof yr?[null]:t instanceof dt?[void 0,...rn(t.unwrap())]:t instanceof zt?[null,...rn(t.unwrap())]:t instanceof ii||t instanceof Ir?rn(t.unwrap()):t instanceof xr?rn(t._def.innerType):[],wo=class t extends ae{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==O.ZodParsedType.object)return(0,T.addIssueToContext)(n,{code:N.ZodIssueCode.invalid_type,expected:O.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:N.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=rn(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:ee.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...oe(r)})}};S.ZodDiscriminatedUnion=wo;function _l(t,e){let n=(0,O.getParsedType)(t),r=(0,O.getParsedType)(e);if(t===e)return{valid:!0,data:t};if(n===O.ZodParsedType.object&&r===O.ZodParsedType.object){let s=O.util.objectKeys(e),i=O.util.objectKeys(t).filter(l=>s.indexOf(l)!==-1),o={...t,...e};for(let l of i){let c=_l(t[l],e[l]);if(!c.valid)return{valid:!1};o[l]=c.data}return{valid:!0,data:o}}else if(n===O.ZodParsedType.array&&r===O.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=_l(o,l);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===O.ZodParsedType.date&&r===O.ZodParsedType.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var wr=class extends ae{_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=_l(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:N.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=wr;wr.create=(t,e,n)=>new wr({left:t,right:e,typeName:ee.ZodIntersection,...oe(n)});var Mt=class t extends ae{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==O.ZodParsedType.array)return(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.invalid_type,expected:O.ZodParsedType.array,received:r.parsedType}),T.INVALID;if(r.data.length<this._def.items.length)return(0,T.addIssueToContext)(r,{code:N.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:N.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 ht(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=Mt;Mt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Mt({items:t,typeName:ee.ZodTuple,rest:null,...oe(e)})};var vo=class t extends ae{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!==O.ZodParsedType.object)return(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.invalid_type,expected:O.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 ht(r,l,r.path,l)),value:o._parse(new ht(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 ae?new t({keyType:e,valueType:n,typeName:ee.ZodRecord,...oe(r)}):new t({keyType:An.create(),valueType:e,typeName:ee.ZodRecord,...oe(n)})}};S.ZodRecord=vo;var ys=class extends ae{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!==O.ZodParsedType.map)return(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.invalid_type,expected:O.ZodParsedType.map,received:r.parsedType}),T.INVALID;let s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([l,c],d)=>({key:s._parse(new ht(r,l,r.path,[d,"key"])),value:i._parse(new ht(r,c,r.path,[d,"value"]))}));if(r.common.async){let l=new Map;return Promise.resolve().then(async()=>{for(let c of o){let d=await c.key,p=await c.value;if(d.status==="aborted"||p.status==="aborted")return T.INVALID;(d.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(d.value,p.value)}return{status:n.value,value:l}})}else{let l=new Map;for(let c of o){let d=c.key,p=c.value;if(d.status==="aborted"||p.status==="aborted")return T.INVALID;(d.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(d.value,p.value)}return{status:n.value,value:l}}}};S.ZodMap=ys;ys.create=(t,e,n)=>new ys({valueType:e,keyType:t,typeName:ee.ZodMap,...oe(n)});var bs=class t extends ae{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==O.ZodParsedType.set)return(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.invalid_type,expected:O.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:N.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:N.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 d=new Set;for(let p of c){if(p.status==="aborted")return T.INVALID;p.status==="dirty"&&n.dirty(),d.add(p.value)}return{status:n.value,value:d}}let l=[...r.data.values()].map((c,d)=>i._parse(new ht(r,c,r.path,d)));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:W.errorUtil.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:W.errorUtil.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};S.ZodSet=bs;bs.create=(t,e)=>new bs({valueType:t,minSize:null,maxSize:null,typeName:ee.ZodSet,...oe(e)});var ko=class t extends ae{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==O.ZodParsedType.function)return(0,T.addIssueToContext)(n,{code:N.ZodIssueCode.invalid_type,expected:O.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,bo.getErrorMap)(),bo.defaultErrorMap].filter(d=>!!d),issueData:{code:N.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,bo.getErrorMap)(),bo.defaultErrorMap].filter(d=>!!d),issueData:{code:N.ZodIssueCode.invalid_return_type,returnTypeError:c}})}let i={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof $n){let l=this;return(0,T.OK)(async function(...c){let d=new N.ZodError([]),p=await l._def.args.parseAsync(c,i).catch(v=>{throw d.addIssue(r(c,v)),d}),f=await Reflect.apply(o,this,p);return await l._def.returns._def.type.parseAsync(f,i).catch(v=>{throw d.addIssue(s(f,v)),d})})}else{let l=this;return(0,T.OK)(function(...c){let d=l._def.args.safeParse(c,i);if(!d.success)throw new N.ZodError([r(c,d.error)]);let p=Reflect.apply(o,this,d.data),f=l._def.returns.safeParse(p,i);if(!f.success)throw new N.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:Mt.create(e).rest(sn.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new t({args:e||Mt.create([]).rest(sn.create()),returns:n||sn.create(),typeName:ee.ZodFunction,...oe(r)})}};S.ZodFunction=ko;var vr=class extends ae{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=vr;vr.create=(t,e)=>new vr({getter:t,typeName:ee.ZodLazy,...oe(e)});var kr=class extends ae{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(n,{received:n.data,code:N.ZodIssueCode.invalid_literal,expected:this._def.value}),T.INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}};S.ZodLiteral=kr;kr.create=(t,e)=>new kr({value:t,typeName:ee.ZodLiteral,...oe(e)});function Xd(t,e){return new _r({values:t,typeName:ee.ZodEnum,...oe(e)})}var _r=class t extends ae{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return(0,T.addIssueToContext)(n,{expected:O.util.joinValues(r),received:n.parsedType,code:N.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:N.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=_r;_r.create=Xd;var Sr=class extends ae{_parse(e){let n=O.util.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==O.ZodParsedType.string&&r.parsedType!==O.ZodParsedType.number){let s=O.util.objectValues(n);return(0,T.addIssueToContext)(r,{expected:O.util.joinValues(s),received:r.parsedType,code:N.ZodIssueCode.invalid_type}),T.INVALID}if(this._cache||(this._cache=new Set(O.util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=O.util.objectValues(n);return(0,T.addIssueToContext)(r,{received:r.data,code:N.ZodIssueCode.invalid_enum_value,options:s}),T.INVALID}return(0,T.OK)(e.data)}get enum(){return this._def.values}};S.ZodNativeEnum=Sr;Sr.create=(t,e)=>new Sr({values:t,typeName:ee.ZodNativeEnum,...oe(e)});var $n=class extends ae{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==O.ZodParsedType.promise&&n.common.async===!1)return(0,T.addIssueToContext)(n,{code:N.ZodIssueCode.invalid_type,expected:O.ZodParsedType.promise,received:n.parsedType}),T.INVALID;let r=n.parsedType===O.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=$n;$n.create=(t,e)=>new $n({type:t,typeName:ee.ZodPromise,...oe(e)});var nt=class extends ae{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ee.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);O.util.assertNever(s)}};S.ZodEffects=nt;S.ZodTransformer=nt;nt.create=(t,e,n)=>new nt({schema:t,typeName:ee.ZodEffects,effect:e,...oe(n)});nt.createWithPreprocess=(t,e,n)=>new nt({schema:e,effect:{type:"preprocess",transform:t},typeName:ee.ZodEffects,...oe(n)});var dt=class extends ae{_parse(e){return this._getType(e)===O.ZodParsedType.undefined?(0,T.OK)(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};S.ZodOptional=dt;dt.create=(t,e)=>new dt({innerType:t,typeName:ee.ZodOptional,...oe(e)});var zt=class extends ae{_parse(e){return this._getType(e)===O.ZodParsedType.null?(0,T.OK)(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};S.ZodNullable=zt;zt.create=(t,e)=>new zt({innerType:t,typeName:ee.ZodNullable,...oe(e)});var Tr=class extends ae{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===O.ZodParsedType.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};S.ZodDefault=Tr;Tr.create=(t,e)=>new Tr({innerType:t,typeName:ee.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...oe(e)});var xr=class extends ae{_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 N.ZodError(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new N.ZodError(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};S.ZodCatch=xr;xr.create=(t,e)=>new xr({innerType:t,typeName:ee.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...oe(e)});var ws=class extends ae{_parse(e){if(this._getType(e)!==O.ZodParsedType.nan){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:N.ZodIssueCode.invalid_type,expected:O.ZodParsedType.nan,received:r.parsedType}),T.INVALID}return{status:"valid",value:e.data}}};S.ZodNaN=ws;ws.create=t=>new ws({typeName:ee.ZodNaN,...oe(t)});S.BRAND=Symbol("zod_brand");var ii=class extends ae{_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=ii;var oi=class t extends ae{_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:ee.ZodPipeline})}};S.ZodPipeline=oi;var Ir=class extends ae{_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=Ir;Ir.create=(t,e)=>new Ir({innerType:t,typeName:ee.ZodReadonly,...oe(e)});function Zd(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function Qd(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=Zd(e,r),c=l.fatal??n??!0;s.addIssue({code:"custom",...l,fatal:c})}});if(!i){let o=Zd(e,r),l=o.fatal??n??!0;s.addIssue({code:"custom",...o,fatal:l})}}):Cn.create()}S.late={object:Ye.lazycreate};var ee;(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"})(ee||(S.ZodFirstPartyTypeKind=ee={}));var Bw=(t,e={message:`Input not instance of ${t.name}`})=>Qd(n=>n instanceof t,e);S.instanceof=Bw;var eh=An.create;S.string=eh;var th=hr.create;S.number=th;var Hw=ws.create;S.nan=Hw;var Kw=pr.create;S.bigint=Kw;var nh=fr.create;S.boolean=nh;var Gw=mr.create;S.date=Gw;var Ww=ms.create;S.symbol=Ww;var Zw=gr.create;S.undefined=Zw;var Vw=yr.create;S.null=Vw;var Jw=Cn.create;S.any=Jw;var Yw=sn.create;S.unknown=Yw;var Xw=_t.create;S.never=Xw;var Qw=gs.create;S.void=Qw;var ev=on.create;S.array=ev;var tv=Ye.create;S.object=tv;var nv=Ye.strictCreate;S.strictObject=nv;var rv=br.create;S.union=rv;var sv=wo.create;S.discriminatedUnion=sv;var iv=wr.create;S.intersection=iv;var ov=Mt.create;S.tuple=ov;var av=vo.create;S.record=av;var lv=ys.create;S.map=lv;var cv=bs.create;S.set=cv;var uv=ko.create;S.function=uv;var dv=vr.create;S.lazy=dv;var hv=kr.create;S.literal=hv;var pv=_r.create;S.enum=pv;var fv=Sr.create;S.nativeEnum=fv;var mv=$n.create;S.promise=mv;var rh=nt.create;S.effect=rh;S.transformer=rh;var gv=dt.create;S.optional=gv;var yv=zt.create;S.nullable=yv;var bv=nt.createWithPreprocess;S.preprocess=bv;var wv=oi.create;S.pipeline=wv;var vv=()=>eh().optional();S.ostring=vv;var kv=()=>th().optional();S.onumber=kv;var _v=()=>nh().optional();S.oboolean=_v;S.coerce={string:(t=>An.create({...t,coerce:!0})),number:(t=>hr.create({...t,coerce:!0})),boolean:(t=>fr.create({...t,coerce:!0})),bigint:(t=>pr.create({...t,coerce:!0})),date:(t=>mr.create({...t,coerce:!0}))};S.NEVER=T.INVALID});var Sl=he(pt=>{"use strict";var Sv=pt&&pt.__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]})),vs=pt&&pt.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Sv(e,t,n)};Object.defineProperty(pt,"__esModule",{value:!0});vs(go(),pt);vs(vl(),pt);vs(Hd(),pt);vs(ri(),pt);vs(sh(),pt);vs(mo(),pt)});var ah=he(Xe=>{"use strict";var ih=Xe&&Xe.__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]})),Tv=Xe&&Xe.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),xv=Xe&&Xe.__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)&&ih(e,t,n);return Tv(e,t),e},Iv=Xe&&Xe.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&ih(e,t,n)};Object.defineProperty(Xe,"__esModule",{value:!0});Xe.z=void 0;var oh=xv(Sl());Xe.z=oh;Iv(Sl(),Xe);Xe.default=oh});var Re=he(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.ChatListMsg=h.ChatSessionMsg=h.ChatActivityMsg=h.ChatUsageMsg=h.ChatStreamMsg=h.JiraUsersResultMsg=h.DeployClaimResultMsg=h.DeployClaimMsg=h.RuleDiagnoseResultMsg=h.ProjectTestResultMsg=h.RunStatusMsg=h.RunContextMsg=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.DEPLOY_DOC_CANDIDATES=h.RUNNER_UNINSTALL_COMMAND=h.PROTOCOL_VERSION=h.GITHUB_TOKEN_PERMISSIONS=void 0;h.KnowledgeFile=h.KnowledgeListMsg=h.AuditReviewResultMsg=h.AuditReviewMsg=h.AuditGetResultMsg=h.AuditGetMsg=h.AuditExplainResultMsg=h.AuditExplainMsg=h.ChatCancelMsg=h.ChatStepRunResultMsg=h.ChatStepRunMsg=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=h.TICKET_RULES_APPENDIX=h.COMPOSE_COMMANDS=h.MAX_FAILURE_CHARS=h.MAX_FAILURE_LINES=h.FAILURE_BLOCK_LINES=h.FAILURE_CONTEXT_LINES=h.REPLY_STYLES=h.BUILTIN_REPLY_LANGUAGES=h.ChatLoadMsg=h.ChatListResultMsg=void 0;h.ServerInventoryResultMsg=h.ServerInventoryMsg=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.SetupAskResultMsg=h.SetupAskMsg=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=h.EnvPreflightResultMsg=h.EnvPreflightMsg=h.ChatCreateTicketResultMsg=h.ChatCreateTicketMsg=h.ChatTurnResultMsg=h.ChatTurnMsg=h.ChatFile=h.TeamCredsResultMsg=h.TeamCredsMsg=h.KnowledgeSaveResultMsg=h.KnowledgeSaveMsg=h.KnowledgeListResultMsg=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.REVISION_PROMPT=h.FOCUSED_READING_PROMPT=h.NEEDS_INPUT_OPTIONS_PROMPT=h.DEFAULT_PLAN_PROMPT_TEMPLATE=h.EnrollResponse=h.EnrollRequest=h.ServerToRunnerMsg=h.JiraUsersMsg=h.DeploySuggestMsg=h.DeployFixMsg=h.DeployStartMsg=h.RunRetryPushMsg=h.RunRejectedMsg=h.RunApprovedMsg=h.RunCancelMsg=h.RuleDiagnoseMsg=h.ProjectTestMsg=h.RunClaimResultMsg=h.ConfigMsg=h.HelloAckMsg=h.RunnerToServerMsg=void 0;h.missingAgentCapabilities=Rv;h.replyPreferenceAppendix=Av;h.pendingMigrationsAppendix=Cv;h.deployTargetsAppendix=$v;h.savedStepChecksAppendix=Pv;h.failureCollector=lh;h.failureLines=Mv;h.composeCommandAppendix=zv;h.isSelfMigrationFilename=Dv;h.parseRunnerMsg=Lv;h.parseServerMsg=Uv;var a=ah();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.89";h.RUNNER_UNINSTALL_COMMAND="sudo allwright service uninstall";h.DEPLOY_DOC_CANDIDATES=[".ticketpilot/deploy.md","DEPLOY.md","DEPLOYMENT.md","docs/DEPLOY.md","docs/deploy.md","docs/deployment.md"];h.REGISTERED_AGENTS=[{id:"claude-code",displayName:"Claude Code",capabilities:{readOnlyJail:!0,editNoShellJail:!0,sessionResume:!0,costReporting:!0,modelSelection:!0,loginProfiles:!0,fullAccess:!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,fullAccess:!1},suggestedModels:[],experimental:!0},{id:"kimi",displayName:"Moonshot Kimi Code CLI",capabilities:{readOnlyJail:!0,editNoShellJail:!1,sessionResume:!0,costReporting:!1,modelSelection:!0,loginProfiles:!1,fullAccess:!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"],operator:["fullAccess","sessionResume"]};function Rv(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 Ev=t=>t.includes(h.NEEDS_INPUT_COMMENT_MARKER)||h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS.some(e=>t.includes(e));h.needsInputMarkerIn=Ev;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),allowWeb:a.z.boolean().default(!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),maxCostUsd:a.z.number().positive().optional(),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),allowWeb: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(""),servePath: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.RunContextMsg=a.z.object({type:a.z.literal("run.context"),runId:a.z.string(),pieces:a.z.array(a.z.object({part:a.z.string().max(80),chars:a.z.number().int().nonnegative()})).max(30),totalChars:a.z.number().int().nonnegative(),sessionMode:a.z.enum(["fresh","chained","timeout-resume","preflight-resume"])});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.ChatActivityMsg=a.z.object({type:a.z.literal("chat.activity"),requestId:a.z.string(),seq:a.z.number().int().nonnegative(),verb:a.z.string().max(40),target:a.z.string().max(200).default("")});h.ChatSessionMsg=a.z.object({type:a.z.literal("chat.session"),requestId:a.z.string(),sessionId:a.z.string()});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),ownerUserId:a.z.string().default(""),agentId:a.z.string().default("")})).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 Av(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?`
35
35
 
36
36
  HOW TO WRITE THE REPLY - the person you are answering chose this, so it applies to every reply in this conversation:
37
37
  - ${e.join(`
38
38
  - `)}
39
- `:""}function tv(t){if(!t.length)return"";let e="```";return`
39
+ `:""}function Cv(t){if(!t.length)return"";let e="```";return`
40
40
 
41
41
  PENDING DATABASE MIGRATIONS (fact, read from this database's own ledger just now):
42
42
  `+t.map(n=>`- ${h.SELF_MIGRATION_DIR}/${n}`).join(`
@@ -45,7 +45,7 @@ These files are checked in but NOT applied to the database this control plane ru
45
45
  ${e}action
46
46
  {"type": "apply-migration", "file": "<one filename from the list above>"}
47
47
  ${e}
48
- That is an action block - there is no free-form command form of any action. Never mention the block itself in your prose.`}function nv(t){if(!t.length)return"";let e="```";return`
48
+ That is an action block - there is no free-form command form of any action. Never mention the block itself in your prose.`}function $v(t){if(!t.length)return"";let e="```";return`
49
49
 
50
50
  DEPLOY TARGETS (fact: this project's environments, in promotion order):
51
51
  `+t.map(n=>`- ${n}`).join(`
@@ -54,7 +54,7 @@ When your diagnosis concludes that one of these environments is running old code
54
54
  ${e}action
55
55
  {"type": "deploy", "environment": "<one name from the list above>"}
56
56
  ${e}
57
- The dashboard turns that into a Deploy button for the user - subject to their own permissions, which you cannot see; never promise the deploy will be allowed. Offer it only when a deploy is genuinely the fix, never as a routine suggestion, and never name an environment that is not in the list. Never mention the block itself in your prose.`}function rv(t){let e=t.filter(r=>r.steps.length);if(!e.length)return"";let n="```";return`
57
+ The dashboard turns that into a Deploy button for the user - subject to their own permissions, which you cannot see; never promise the deploy will be allowed. Offer it only when a deploy is genuinely the fix, never as a routine suggestion, and never name an environment that is not in the list. Never mention the block itself in your prose.`}function Pv(t){let e=t.filter(r=>r.steps.length);if(!e.length)return"";let n="```";return`
58
58
 
59
59
  RE-RUNNABLE CHECKS (fact: the saved deploy steps of this project's environments):
60
60
  `+e.map(r=>`- ${r.environment}: ${r.steps.map(s=>`"${s}"`).join(", ")}`).join(`
@@ -63,13 +63,13 @@ When answering would genuinely be settled by running one of these again - the ga
63
63
  ${n}check
64
64
  {"environment": "<one name above>", "step": "<one step name of that environment, exactly>", "why": "one line the user reads before approving"}
65
65
  ${n}
66
- Rules, and they are hard ones. Only ask for a step that CHECKS something - a test suite, a build, a lint. NEVER a step that changes anything: no deploy, no restart, no migration, no install, no file it writes outside a build directory. If you are not certain which kind a step is, do not ask for it. Ask for ONE, and only when reading the code and the log cannot settle the question - it runs on a real machine and takes real minutes. The user approves or denies; wait for the output, which arrives as the next message, and never assume it ran. Never mention the block itself in your prose.`}var sv=/^\s*(not ok\b|fail(ed|ure|s)?\b|✗|✖|×|✘|error[: ]|exception\b)/i,iv=/\berror [A-Z]{2,}\d|AssertionError|Traceback \(most recent|panic: |\bFAILED\b/,ov=/^\s*(ok \d|PASS\b|✓|√|# (pass|fail|tests|suites|skipped|todo|cancelled|duration)|\.\.\.\s*$)/;h.FAILURE_CONTEXT_LINES=6;h.FAILURE_BLOCK_LINES=16;h.MAX_FAILURE_LINES=60;h.MAX_FAILURE_CHARS=2500;function Qd(){let t=[],e=-1;return{push(n){if(t.length>=h.MAX_FAILURE_LINES)return;if(sv.test(n)||iv.test(n)){t.push(n),e=0;return}if(e<0)return;if(ov.test(n)){e=-1;return}let s=/^\s+\S/.test(n)?h.FAILURE_BLOCK_LINES:h.FAILURE_CONTEXT_LINES;if(e>=s){e=-1;return}t.push(n),e++},text(){return t.join(`
67
- `).slice(0,h.MAX_FAILURE_CHARS)}}}function av(t){let e=Qd();for(let n of t.split(`
68
- `))e.push(n);return e.text()}h.COMPOSE_COMMANDS=[{id:"ticket",name:"ticket",label:"Draft a Jira ticket",hint:"Turn what we have discussed into a ticket draft",instruction:'THIS TURN IS AN EXPLICIT TICKET REQUEST. The user is asking, in so many words, for a ticket - so draft one now, by the ticket rules above, and end your reply with the ```ticket block. Use the conversation so far as the source; do not re-investigate from scratch. If something essential is genuinely missing - which part of the codebase, or what "done" means - ask ONE short question instead of inventing it.'},{id:"investigate",name:"investigate",label:"Investigate",hint:"Read the code and find the cause, with evidence",instruction:"THIS TURN IS AN INVESTIGATION. Read the actual code before you answer - this is one of the few turns where opening files is the point, not a detour. Report three things in this order: what you checked (name the files, and the lines that matter), what you found, and the most likely cause with the evidence for it. Where the evidence does not settle it, say so and say what would - a log line, a command, a file you cannot see. Do NOT draft a ticket: end with the two or three moves you would make next, and let the user pick one."},{id:"plan",name:"plan",label:"Plan the work",hint:"Break it into steps, smallest first - no ticket yet",instruction:"THIS TURN IS A PLAN. Break the work into numbered steps in the order you would do them, smallest and most certain first, each one a thing a person could finish in a sitting. Name the files each step touches where you know them, and say plainly which steps you are unsure about and why. Do NOT draft a ticket - the user will ask for that when the plan is right."},{id:"explain",name:"explain",label:"Explain how it works",hint:"Plain-language walkthrough of a part of this repo",instruction:"THIS TURN IS AN EXPLANATION. Walk through how this actually works in this repository, in plain language, naming the files and functions so the reader can follow along. Start with the shape of it in two or three sentences, then the detail. Prefer what the code does today over what it was designed to do, and say when the two differ. No ticket."},{id:"review",name:"review",label:"Review the code",hint:"Read a file or area and list what is actually wrong",instruction:'THIS TURN IS A CODE REVIEW. Read what the user named and list the concrete problems you can point at, most serious first, each with the file and line and what goes wrong in practice. Separate "this is a bug" from "this is taste" and label which is which - a review that mixes them gets ignored. You are read-only: describe the fix, do not pretend to have made it. No ticket unless the user asks for one.'}];function lv(t){let e=h.COMPOSE_COMMANDS.find(n=>n.id===t);return e?`
66
+ Rules, and they are hard ones. Only ask for a step that CHECKS something - a test suite, a build, a lint. NEVER a step that changes anything: no deploy, no restart, no migration, no install, no file it writes outside a build directory. If you are not certain which kind a step is, do not ask for it. Ask for ONE, and only when reading the code and the log cannot settle the question - it runs on a real machine and takes real minutes. The user approves or denies; wait for the output, which arrives as the next message, and never assume it ran. Never mention the block itself in your prose.`}var Nv=/^\s*(not ok\b|fail(ed|ure|s)?\b|✗|✖|×|✘|error[: ]|exception\b)/i,jv=/\berror [A-Z]{2,}\d|AssertionError|Traceback \(most recent|panic: |\bFAILED\b/,Ov=/^\s*(ok \d|PASS\b|✓|√|# (pass|fail|tests|suites|skipped|todo|cancelled|duration)|\.\.\.\s*$)/;h.FAILURE_CONTEXT_LINES=6;h.FAILURE_BLOCK_LINES=16;h.MAX_FAILURE_LINES=60;h.MAX_FAILURE_CHARS=2500;function lh(){let t=[],e=-1;return{push(n){if(t.length>=h.MAX_FAILURE_LINES)return;if(Nv.test(n)||jv.test(n)){t.push(n),e=0;return}if(e<0)return;if(Ov.test(n)){e=-1;return}let s=/^\s+\S/.test(n)?h.FAILURE_BLOCK_LINES:h.FAILURE_CONTEXT_LINES;if(e>=s){e=-1;return}t.push(n),e++},text(){return t.join(`
67
+ `).slice(0,h.MAX_FAILURE_CHARS)}}}function Mv(t){let e=lh();for(let n of t.split(`
68
+ `))e.push(n);return e.text()}h.COMPOSE_COMMANDS=[{id:"ticket",name:"ticket",label:"Draft a Jira ticket",hint:"Turn what we have discussed into a ticket draft",instruction:'THIS TURN IS AN EXPLICIT TICKET REQUEST. The user is asking, in so many words, for a ticket - so draft one now, by the ticket rules above, and end your reply with the ```ticket block. Use the conversation so far as the source; do not re-investigate from scratch. If something essential is genuinely missing - which part of the codebase, or what "done" means - ask ONE short question instead of inventing it.'},{id:"investigate",name:"investigate",label:"Investigate",hint:"Read the code and find the cause, with evidence",instruction:"THIS TURN IS AN INVESTIGATION. Read the actual code before you answer - this is one of the few turns where opening files is the point, not a detour. Report three things in this order: what you checked (name the files, and the lines that matter), what you found, and the most likely cause with the evidence for it. Where the evidence does not settle it, say so and say what would - a log line, a command, a file you cannot see. Do NOT draft a ticket: end with the two or three moves you would make next, and let the user pick one."},{id:"plan",name:"plan",label:"Plan the work",hint:"Break it into steps, smallest first - no ticket yet",instruction:"THIS TURN IS A PLAN. Break the work into numbered steps in the order you would do them, smallest and most certain first, each one a thing a person could finish in a sitting. Name the files each step touches where you know them, and say plainly which steps you are unsure about and why. Do NOT draft a ticket - the user will ask for that when the plan is right."},{id:"explain",name:"explain",label:"Explain how it works",hint:"Plain-language walkthrough of a part of this repo",instruction:"THIS TURN IS AN EXPLANATION. Walk through how this actually works in this repository, in plain language, naming the files and functions so the reader can follow along. Start with the shape of it in two or three sentences, then the detail. Prefer what the code does today over what it was designed to do, and say when the two differ. No ticket."},{id:"review",name:"review",label:"Review the code",hint:"Read a file or area and list what is actually wrong",instruction:'THIS TURN IS A CODE REVIEW. Read what the user named and list the concrete problems you can point at, most serious first, each with the file and line and what goes wrong in practice. Separate "this is a bug" from "this is taste" and label which is which - a review that mixes them gets ignored. You are read-only: describe the fix, do not pretend to have made it. No ticket unless the user asks for one.'}];function zv(t){let e=h.COMPOSE_COMMANDS.find(n=>n.id===t);return e?`
69
69
 
70
70
  WHAT THIS TURN IS FOR (the user chose "/${e.name}"):
71
71
  ${e.instruction}
72
- `:""}h.TICKET_RULES_APPENDIX='\n\nONLY when the user explicitly asks for a ticket, propose it by ending your reply with EXACTLY one fenced block in this shape:\n```ticket\n{"summary": "\u2026", "description": "\u2026"}\n```\nBefore 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.\nRIGHT-SIZE every ticket - it is a work order for ONE agent run. One ticket = one concern: a single feature, fix or change an engineer would land as one reviewable PR. The test for TOO BIG: the summary needs an "and", the Expected Flow forks into unrelated flows, or the acceptance criteria span unrelated screens or modules - split there, into an epic batch if the pieces belong together. Queued tickets share a warm agent session and one branch, so splitting is cheap; an oversized ticket is the single biggest driver of runaway agent cost and un-reviewable diffs. Trivial same-file touches (a rename plus its comment) stay together - splitting has to buy a smaller review, not ceremony. If the user explicitly asks to split or to merge, their word wins.\nWrite the description in plain human language, structured with these Markdown section headings in this order:\nStory: - one or two sentences: who needs this and why.\nDescription: - what to build and WHERE, as bullet points that name exact files, directories or symbols whenever the conversation or repo makes them known - the implementing agent starts cold, and every named path saves it a paid search.\nExpected Flow: - the flow once this ticket is done, as numbered steps.\nCurrent Flow: - how it behaves today; include ONLY when current behavior exists.\nAcceptance Criteria: - testable bullet points a reviewer can check off one by one.\nInclude 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.\nTHE READER IS A COLD AGENT: whoever implements this sees the ticket alone, never this conversation. Anything that is obvious only from the chat must be written into the ticket; anything the repo already documents is referenced by path, not restated.\nEXCEPTION - 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 ```ticket JSON, fence such payloads with ~~~ (tildes), NEVER with triple backticks - a nested ``` would end the outer block early and corrupt the draft.\nEXCEPTION - several tickets at once: when the user asks for more than one ticket, asks for an epic with sub-tickets, or asks to ticket something clearly too large for one ticket, break it down and emit ONE ```ticket block of this shape:\n{"tickets": [{"summary": "\u2026", "description": "\u2026"}, \u2026]}\nAdd an "epic" key ONLY when the pieces genuinely belong under one parent goal:\n{"epic": {"summary": "\u2026", "description": "\u2026"}, "tickets": [ \u2026 ]}\nNever invent a parent to hold tickets that are simply independent - "make these three tickets" means three tickets, and the person chooses in the dashboard whether they become tasks, epics, or one epic with children. NEVER emit a second ```ticket block to add more tickets: only the last block in a reply is read, so a second one silently discards the first.\n3-8 tickets, each sized for ONE short agent run 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. When one ticket needs another from the SAME batch, reference it as "Ticket #N" (its position in the list) - Allwright rewrites those into the real Jira keys at creation, and any other phrasing survives as a dangling reference nobody can follow.\nRE-EMIT, never refer back: when the user asks for the ticket again, says it did not appear, or a quick action repeats the request, emit the COMPLETE ```ticket block again in that reply. The dashboard only acts on a block in the NEWEST reply, and a long earlier reply can be cut off in transport without you ever knowing - so "I already sent it" is never a valid answer, and explaining your capabilities instead of re-emitting the block is never what was asked.\nSIZE: a reply that outgrows the transport is cut off mid-block and creates NOTHING - and you cannot tell it happened, because your own memory holds the text you meant to send. So when several tickets will not fit, emit FEWER entries, complete, and say which ones you left out for a follow-up turn; never open a block you cannot finish, and never spend the budget on prose before it - the block comes last, so prose is what pushes it over the edge. A payload that lives in the repo is referenced by exact path, never inlined - the implementing agent has the checkout. A pasted payload too large to inline safely (more than ~200 lines) is distilled into the description sections instead; say plainly that you distilled it and ask the user to attach the original file to the ticket so nothing is lost.\n\nA MACHINE ACTION IS NOT A TICKET. When the answer is an action ON A MACHINE rather than a change to this repository - installing a package, restarting or enabling a service, a DNS record, storing a credential, a permissions or sudoers change - do NOT propose a ticket for it. An implement run has NO SHELL and is path-jailed to this checkout, so no agent can carry a machine action out: such a ticket sits in the backlog forever or fails its run. What the person needs is the exact command and which machine to run it on, so end your reply with EXACTLY one fenced block:\n```command\n{"server": "<machine name if known, else empty>", "why": "<one line: what this fixes>", "commands": ["<exact shell command>", "\u2026"]}\n```\nCommands are EXACT and copy-pasteable - no placeholders, no prose, at most 5. NEVER include a secret VALUE: write $NAMES and let the person supply them.\nNEVER invent a server name - leave "server" empty when you are not sure which machine it is. When part of the fix is a code change and part is a machine action, emit BOTH blocks - the ```ticket block for the code half, the ```command block for the machine half - and say in ONE line which half is which.';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(""),ownerUserId: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([]),tokens:a.z.number().int().nonnegative().default(0),files:a.z.array(a.z.string()).default([]),at:a.z.string().default(""),ms:a.z.number().int().nonnegative().default(0)})).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","compose"]);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.ChatStepRunMsg=a.z.object({type:a.z.literal("chat.step.run"),requestId:a.z.string(),projectId:a.z.string(),environmentName:a.z.string(),stepIndex:a.z.number().int().nonnegative(),stepName:a.z.string()});h.ChatStepRunResultMsg=a.z.object({type:a.z.literal("chat.step.run.result"),requestId:a.z.string(),ok:a.z.boolean().default(!0),stepName:a.z.string().default(""),commandLine:a.z.string().default(""),exitCode:a.z.number().int().default(0),timedOut:a.z.boolean().default(!1),output:a.z.string().default(""),error: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(""),userId:a.z.string().max(80).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(""),command:a.z.string().max(40).default(""),pendingMigrations:a.z.array(a.z.string().max(200)).max(50).default([]),environments:a.z.array(a.z.string().max(60)).max(20).default([]),environmentSteps:a.z.array(a.z.object({environment:a.z.string().max(60),steps:a.z.array(a.z.string().max(120)).max(40).default([])})).max(20).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),outputTruncated:a.z.boolean().default(!1)});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 cv(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(""),fixTicketSummary:a.z.string().max(250).default(""),fixTicketDescription:a.z.string().max(2e4).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(""),servePath: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(""),truncated:a.z.boolean().default(!1)});h.SetupAskMsg=a.z.object({type:a.z.literal("setup.ask"),requestId:a.z.string(),projectId:a.z.string(),subject:a.z.string().max(600).default(""),command:a.z.string().max(2e3).default(""),machineState:a.z.array(a.z.string().max(400)).max(40).default([]),history:a.z.array(a.z.object({role:a.z.enum(["user","agent"]),text:a.z.string().max(4e3)})).max(8).default([]),question:a.z.string().max(4e3)});h.SetupAskResultMsg=a.z.object({type:a.z.literal("setup.ask.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),answer: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),remainingInBatch:a.z.number().int().min(0).default(0)}).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.RunContextMsg,h.RunUsageMsg,h.RunStatusMsg,h.ProjectTestResultMsg,h.RuleDiagnoseResultMsg,h.DeployClaimMsg,h.DeploySuggestResultMsg,h.EnvPreflightResultMsg,h.SelfMigrationApplyResultMsg,h.ChatTurnResultMsg,h.ChatStreamMsg,h.ChatUsageMsg,h.ChatSessionMsg,h.ChatActivityMsg,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.SetupAskResultMsg,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.ChatStepRunResultMsg]);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),publicIp:a.z.string().default("")});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.ChatStepRunMsg,h.AuditReviewMsg,h.KnowledgeListMsg,h.KnowledgeSaveMsg,h.EpicListMsg,h.EpicSuggestMsg,h.JiraUsersMsg,h.SetupStatusMsg,h.SetupClaudeMdGenerateMsg,h.SetupAskMsg,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 uv(t){return h.RunnerToServerMsg.parse(t)}function dv(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.
72
+ `:""}h.TICKET_RULES_APPENDIX='\n\nONLY when the user explicitly asks for a ticket, propose it by ending your reply with EXACTLY one fenced block in this shape:\n```ticket\n{"summary": "\u2026", "description": "\u2026"}\n```\nBefore 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.\nRIGHT-SIZE every ticket - it is a work order for ONE agent run. One ticket = one concern: a single feature, fix or change an engineer would land as one reviewable PR. The test for TOO BIG: the summary needs an "and", the Expected Flow forks into unrelated flows, or the acceptance criteria span unrelated screens or modules - split there, into an epic batch if the pieces belong together. Queued tickets share a warm agent session and one branch, so splitting is cheap; an oversized ticket is the single biggest driver of runaway agent cost and un-reviewable diffs. Trivial same-file touches (a rename plus its comment) stay together - splitting has to buy a smaller review, not ceremony. If the user explicitly asks to split or to merge, their word wins.\nWrite the description in plain human language, structured with these Markdown section headings in this order:\nStory: - one or two sentences: who needs this and why.\nDescription: - what to build and WHERE, as bullet points that name exact files, directories or symbols whenever the conversation or repo makes them known - the implementing agent starts cold, and every named path saves it a paid search.\nExpected Flow: - the flow once this ticket is done, as numbered steps.\nCurrent Flow: - how it behaves today; include ONLY when current behavior exists.\nAcceptance Criteria: - testable bullet points a reviewer can check off one by one.\nInclude 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.\nTHE READER IS A COLD AGENT: whoever implements this sees the ticket alone, never this conversation. Anything that is obvious only from the chat must be written into the ticket; anything the repo already documents is referenced by path, not restated.\nEXCEPTION - 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 ```ticket JSON, fence such payloads with ~~~ (tildes), NEVER with triple backticks - a nested ``` would end the outer block early and corrupt the draft.\nEXCEPTION - several tickets at once: when the user asks for more than one ticket, asks for an epic with sub-tickets, or asks to ticket something clearly too large for one ticket, break it down and emit ONE ```ticket block of this shape:\n{"tickets": [{"summary": "\u2026", "description": "\u2026"}, \u2026]}\nAdd an "epic" key ONLY when the pieces genuinely belong under one parent goal:\n{"epic": {"summary": "\u2026", "description": "\u2026"}, "tickets": [ \u2026 ]}\nNever invent a parent to hold tickets that are simply independent - "make these three tickets" means three tickets, and the person chooses in the dashboard whether they become tasks, epics, or one epic with children. NEVER emit a second ```ticket block to add more tickets: only the last block in a reply is read, so a second one silently discards the first.\n3-8 tickets, each sized for ONE short agent run 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. When one ticket needs another from the SAME batch, reference it as "Ticket #N" (its position in the list) - Allwright rewrites those into the real Jira keys at creation, and any other phrasing survives as a dangling reference nobody can follow.\nRE-EMIT, never refer back: when the user asks for the ticket again, says it did not appear, or a quick action repeats the request, emit the COMPLETE ```ticket block again in that reply. The dashboard only acts on a block in the NEWEST reply, and a long earlier reply can be cut off in transport without you ever knowing - so "I already sent it" is never a valid answer, and explaining your capabilities instead of re-emitting the block is never what was asked.\nSIZE: a reply that outgrows the transport is cut off mid-block and creates NOTHING - and you cannot tell it happened, because your own memory holds the text you meant to send. So when several tickets will not fit, emit FEWER entries, complete, and say which ones you left out for a follow-up turn; never open a block you cannot finish, and never spend the budget on prose before it - the block comes last, so prose is what pushes it over the edge. A payload that lives in the repo is referenced by exact path, never inlined - the implementing agent has the checkout. A pasted payload too large to inline safely (more than ~200 lines) is distilled into the description sections instead; say plainly that you distilled it and ask the user to attach the original file to the ticket so nothing is lost.\n\nA MACHINE ACTION IS NOT A TICKET. When the answer is an action ON A MACHINE rather than a change to this repository - installing a package, restarting or enabling a service, a DNS record, storing a credential, a permissions or sudoers change - do NOT propose a ticket for it. An implement run has NO SHELL and is path-jailed to this checkout, so no agent can carry a machine action out: such a ticket sits in the backlog forever or fails its run. What the person needs is the exact command and which machine to run it on, so end your reply with EXACTLY one fenced block:\n```command\n{"server": "<machine name if known, else empty>", "why": "<one line: what this fixes>", "commands": ["<exact shell command>", "\u2026"]}\n```\nCommands are EXACT and copy-pasteable - no placeholders, no prose, at most 5. NEVER include a secret VALUE: write $NAMES and let the person supply them.\nNEVER invent a server name - leave "server" empty when you are not sure which machine it is. When part of the fix is a code change and part is a machine action, emit BOTH blocks - the ```ticket block for the code half, the ```command block for the machine half - and say in ONE line which half is which.';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(""),ownerUserId:a.z.string().default(""),agentId: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([]),tokens:a.z.number().int().nonnegative().default(0),files:a.z.array(a.z.string()).default([]),at:a.z.string().default(""),ms:a.z.number().int().nonnegative().default(0)})).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","compose"]);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.ChatStepRunMsg=a.z.object({type:a.z.literal("chat.step.run"),requestId:a.z.string(),projectId:a.z.string(),environmentName:a.z.string(),stepIndex:a.z.number().int().nonnegative(),stepName:a.z.string()});h.ChatStepRunResultMsg=a.z.object({type:a.z.literal("chat.step.run.result"),requestId:a.z.string(),ok:a.z.boolean().default(!0),stepName:a.z.string().default(""),commandLine:a.z.string().default(""),exitCode:a.z.number().int().default(0),timedOut:a.z.boolean().default(!1),output:a.z.string().default(""),error: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(""),userId:a.z.string().max(80).default(""),model:a.z.string().default(""),agentId:a.z.string().max(60).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(""),command:a.z.string().max(40).default(""),pendingMigrations:a.z.array(a.z.string().max(200)).max(50).default([]),operator:a.z.boolean().default(!1),environments:a.z.array(a.z.string().max(60)).max(20).default([]),environmentSteps:a.z.array(a.z.object({environment:a.z.string().max(60),steps:a.z.array(a.z.string().max(120)).max(40).default([])})).max(20).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),outputTruncated:a.z.boolean().default(!1)});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([]),chatSessionId:a.z.string().max(64).default(""),userId:a.z.string().max(80).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 Dv(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(""),fixTicketSummary:a.z.string().max(250).default(""),fixTicketDescription:a.z.string().max(2e4).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(""),agents:a.z.record(a.z.object({installed:a.z.boolean(),version:a.z.string().default(""),loggedIn:a.z.boolean()})).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),architecture:a.z.object({languages:a.z.array(a.z.string()).max(4).default([]),frameworks:a.z.array(a.z.string()).max(6).default([]),databases:a.z.array(a.z.string()).max(4).default([]),docker:a.z.boolean().default(!1),dockerCompose:a.z.boolean().default(!1),packageManager:a.z.string().default(""),monorepo:a.z.string().default("")}).optional()})).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(""),servePath: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(""),truncated:a.z.boolean().default(!1)});h.SetupAskMsg=a.z.object({type:a.z.literal("setup.ask"),requestId:a.z.string(),projectId:a.z.string(),subject:a.z.string().max(600).default(""),command:a.z.string().max(2e3).default(""),machineState:a.z.array(a.z.string().max(400)).max(40).default([]),history:a.z.array(a.z.object({role:a.z.enum(["user","agent"]),text:a.z.string().max(4e3)})).max(8).default([]),question:a.z.string().max(4e3)});h.SetupAskResultMsg=a.z.object({type:a.z.literal("setup.ask.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),answer: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),remainingInBatch:a.z.number().int().min(0).default(0)}).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.ServerInventoryMsg=a.z.object({type:a.z.literal("server.inventory"),requestId:a.z.string()});h.ServerInventoryResultMsg=a.z.object({type:a.z.literal("server.inventory.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),checkouts:a.z.array(a.z.object({path:a.z.string(),repoName:a.z.string().default(""),remoteUrl:a.z.string().default(""),branch:a.z.string().default("")})).max(60).default([]),services:a.z.array(a.z.object({name:a.z.string(),description:a.z.string().default(""),active:a.z.string().default("")})).max(150).default([]),containers:a.z.array(a.z.object({name:a.z.string(),image:a.z.string().default(""),status:a.z.string().default(""),ports:a.z.string().default("")})).max(60).default([]),ports:a.z.array(a.z.object({port:a.z.number().int().nonnegative(),process:a.z.string().default(""),pid:a.z.number().int().nonnegative().default(0)})).max(150).default([]),processes:a.z.array(a.z.object({pid:a.z.number().int().nonnegative(),user:a.z.string().default(""),cpuPct:a.z.number().default(0),memPct:a.z.number().default(0),command:a.z.string().default("")})).max(40).default([])});h.RunnerToServerMsg=a.z.discriminatedUnion("type",[h.HelloMsg,h.HeartbeatMsg,h.RunClaimMsg,h.RunLogMsg,h.RunContextMsg,h.RunUsageMsg,h.RunStatusMsg,h.ProjectTestResultMsg,h.RuleDiagnoseResultMsg,h.DeployClaimMsg,h.DeploySuggestResultMsg,h.EnvPreflightResultMsg,h.SelfMigrationApplyResultMsg,h.ChatTurnResultMsg,h.ChatStreamMsg,h.ChatUsageMsg,h.ChatSessionMsg,h.ChatActivityMsg,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.SetupAskResultMsg,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.ChatStepRunResultMsg,h.ServerInventoryResultMsg]);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),publicIp:a.z.string().default("")});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.ServerInventoryMsg,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.ChatStepRunMsg,h.AuditReviewMsg,h.KnowledgeListMsg,h.KnowledgeSaveMsg,h.EpicListMsg,h.EpicSuggestMsg,h.JiraUsersMsg,h.SetupStatusMsg,h.SetupClaudeMdGenerateMsg,h.SetupAskMsg,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 Lv(t){return h.RunnerToServerMsg.parse(t)}function Uv(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.
73
73
 
74
74
  Ticket {{issueKey}}: {{summary}}
75
75
 
@@ -345,38 +345,38 @@ Rules for the steps:
345
345
  - Prefer commands that are safe to re-run; a deploy may be retried.
346
346
  - A check that fails SILENTLY is only half a check. A pre-check chaining five bare \`test\`/\`grep -q\` guards with && dies as an uninvestigable "exit code 1" - the operator retries blind, twice, and then stops trusting the deploy (this happened; the culprit was a \`test -f\` with no message four conditions deep). Every guard that can fail must SAY what it found: \`test -f apps/api/.env || { echo "apps/api/.env is missing"; exit 1; }\` - the echo is not decoration, it is the entire difference between a five-second fix and a lost evening.
347
347
  - Order matters: install, build, test (if cheap), then release.
348
- - If you genuinely cannot tell how this repo is deployed, return an empty "steps" array and explain what is missing in "notes".`});var ch={};Kt(ch,{DELETE_MANIFEST_FILE:()=>nn,MAX_CHANGED_FILES:()=>Rn,MAX_CHANGED_LINES:()=>An,abortMerge:()=>Pn,applyDeleteManifest:()=>ws,branchForIssue:()=>Sl,branchSha:()=>To,branchesDiffer:()=>$l,checkDiffSafety:()=>$n,checkoutBranchInWorktree:()=>Tl,commitAll:()=>Ir,commitMergeResolution:()=>Rl,commitsBetween:()=>kl,deleteStaleBranch:()=>bl,diffAgainstDefault:()=>xo,envCheckoutPath:()=>lh,envCheckoutsRoot:()=>ah,fetchBase:()=>Cn,findConflictMarkers:()=>Io,headSha:()=>Ye,mergeBaseIntoWorktree:()=>El,mergeTicketBranch:()=>Il,originUrl:()=>Rr,parseOwnerRepo:()=>_t,prepareEnvCheckout:()=>xl,previousDeliveryForIssue:()=>gl,pruneWorktrees:()=>_l,pushBranch:()=>Er,pushEnvBranch:()=>Cl,pushWipBranch:()=>fl,remoteBranchExists:()=>yl,removeWorktree:()=>Ot,resetHard:()=>vs,servedBranchTip:()=>vl,statusSnapshot:()=>ml,unresolvedAmong:()=>Al,worktreeAdd:()=>wl,worktreeAddExisting:()=>ii,worktreeFingerprint:()=>So,worktreesRoot:()=>rn});async function F(t,e,n={}){try{let{stdout:r}=await ih("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 ws(t){let e={deleted:[],refused:[]},n=ge.default.join(t,nn);if(!Ae.default.existsSync(n))return e;let r=ge.default.resolve(t),s=Ae.default.readFileSync(n,"utf8").split(`
349
- `).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#"));for(let i of s.slice(0,200)){if(ge.default.isAbsolute(i)){e.refused.push(`${i} - absolute paths are not allowed`);continue}let o=ge.default.resolve(r,i);if(o!==r&&!o.startsWith(r+ge.default.sep)){e.refused.push(`${i} - escapes the worktree`);continue}let l=ge.default.relative(r,o).split(ge.default.sep).join("/");if(l===nn)continue;if(oh.some(d=>d.test(l))){e.refused.push(`${i} - protected path (CI/hook files are never touched)`);continue}let c;try{c=Ae.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{Ae.default.rmSync(o),e.deleted.push(l)}catch(d){e.refused.push(`${i} - ${d instanceof Error?d.message:"delete failed"}`)}}return Ae.default.rmSync(n,{force:!0}),e}async function fl(t,e){await F(t,["push","--force","origin",`HEAD:refs/heads/${e}`],{timeoutMs:3e5})}async function So(t){let e=await F(t,["status","--porcelain"]),n=await F(t,["diff","--numstat"]),r=e.split(`
350
- `).filter(s=>s.startsWith("??")).map(s=>s.slice(3).trim()).slice(0,500).map(s=>{try{let i=Ae.default.statSync(ge.default.join(t,s));return`${s}:${i.size}:${i.mtimeMs}`}catch{return s}}).join(`
348
+ - If you genuinely cannot tell how this repo is deployed, return an empty "steps" array and explain what is missing in "notes".`});var bh={};$t(bh,{DELETE_MANIFEST_FILE:()=>an,MAX_CHANGED_FILES:()=>Pn,MAX_CHANGED_LINES:()=>Nn,abortMerge:()=>Mn,applyDeleteManifest:()=>ks,branchForIssue:()=>Nl,branchSha:()=>Ro,branchesDiffer:()=>ql,checkDiffSafety:()=>On,checkoutBranchInWorktree:()=>jl,commitAll:()=>Er,commitMergeResolution:()=>Dl,commitsBetween:()=>$l,deleteStaleBranch:()=>El,diffAgainstDefault:()=>Eo,envCheckoutPath:()=>yh,envCheckoutsRoot:()=>gh,fetchBase:()=>jn,findConflictMarkers:()=>Ao,headSha:()=>Qe,mergeBaseIntoWorktree:()=>zl,mergeTicketBranch:()=>Ml,originUrl:()=>Cr,parseOwnerRepo:()=>St,prepareEnvCheckout:()=>Ol,previousDeliveryForIssue:()=>Il,pruneWorktrees:()=>Pl,pushBranch:()=>Ar,pushEnvBranch:()=>Ul,pushWipBranch:()=>Tl,remoteBranchExists:()=>Rl,removeWorktree:()=>Dt,resetHard:()=>_s,servedBranchTip:()=>Cl,statusSnapshot:()=>xl,unresolvedAmong:()=>Ll,worktreeAdd:()=>Al,worktreeAddExisting:()=>li,worktreeFingerprint:()=>Io,worktreesRoot:()=>ln});async function H(t,e,n={}){try{let{stdout:r}=await fh("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 ks(t){let e={deleted:[],refused:[]},n=ge.default.join(t,an);if(!Ne.default.existsSync(n))return e;let r=ge.default.resolve(t),s=Ne.default.readFileSync(n,"utf8").split(`
349
+ `).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#"));for(let i of s.slice(0,200)){if(ge.default.isAbsolute(i)){e.refused.push(`${i} - absolute paths are not allowed`);continue}let o=ge.default.resolve(r,i);if(o!==r&&!o.startsWith(r+ge.default.sep)){e.refused.push(`${i} - escapes the worktree`);continue}let l=ge.default.relative(r,o).split(ge.default.sep).join("/");if(l===an)continue;if(mh.some(d=>d.test(l))){e.refused.push(`${i} - protected path (CI/hook files are never touched)`);continue}let c;try{c=Ne.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{Ne.default.rmSync(o),e.deleted.push(l)}catch(d){e.refused.push(`${i} - ${d instanceof Error?d.message:"delete failed"}`)}}return Ne.default.rmSync(n,{force:!0}),e}async function Tl(t,e){await H(t,["push","--force","origin",`HEAD:refs/heads/${e}`],{timeoutMs:3e5})}async function Io(t){let e=await H(t,["status","--porcelain"]),n=await H(t,["diff","--numstat"]),r=e.split(`
350
+ `).filter(s=>s.startsWith("??")).map(s=>s.slice(3).trim()).slice(0,500).map(s=>{try{let i=Ne.default.statSync(ge.default.join(t,s));return`${s}:${i.size}:${i.mtimeMs}`}catch{return s}}).join(`
351
351
  `);return`${e}
352
352
  --
353
353
  ${n}
354
354
  --
355
- ${r}`}async function ml(t){let e=(await F(t,["rev-parse","--abbrev-ref","HEAD"])).trim(),n=(await F(t,["log","--oneline","-1"])).trim(),r=(await F(t,["status","--porcelain"])).trim(),s=r?r.split(`
355
+ ${r}`}async function xl(t){let e=(await H(t,["rev-parse","--abbrev-ref","HEAD"])).trim(),n=(await H(t,["log","--oneline","-1"])).trim(),r=(await H(t,["status","--porcelain"])).trim(),s=r?r.split(`
356
356
  `):[],i=s.slice(0,15).join(`
357
357
  `),o=s.length>15?`
358
358
  (\u2026 ${s.length-15} more)`:"";return`branch ${e} @ ${n}
359
359
  working tree: ${s.length?`
360
- ${i}${o}`:"clean"}`}function rn(){let t=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(Ae.default.existsSync(ge.default.join(xr.default.homedir(),".cache","ticketpilot"))?ge.default.join(xr.default.homedir(),".cache","ticketpilot"):ge.default.join(xr.default.homedir(),".cache","allwright"));return ge.default.join(t,"worktrees")}async function gl(t,e,n,r=40){if(!n.trim()||!e.trim())return null;let s=await F(t,["log",`origin/${e}`,"-n","1","--format=%H%x00%s","--fixed-strings",`--grep=${n}`]).then(c=>c.trim()).catch(()=>"");if(!s)return null;let[i,o=""]=s.split("\0");if(!i)return null;let l=await F(t,["show","--name-only","--format=",i]).then(c=>c.split(`
361
- `).map(d=>d.trim()).filter(Boolean)).catch(()=>[]);return{sha:i,subject:o,files:l.slice(0,r),more:Math.max(0,l.length-r)}}async function yl(t,e){try{return(await F(t,["ls-remote","--heads","origin",e])).trim().length>0}catch{return null}}async function Cn(t,e){try{await F(t,["fetch","origin",e])}catch(n){throw new Error(`could not fetch base branch "${e}" from origin - check the rule's base branch and that this machine can reach the remote (${n instanceof Error?n.message:n})`)}}async function bl(t,e){try{let n=await F(t,["worktree","list","--porcelain"]),r=rn(),s=null;for(let i of n.split(`
362
- `))i.startsWith("worktree ")&&(s=i.slice(9).trim()),i===`branch refs/heads/${e}`&&s&&s.startsWith(r)&&await F(t,["worktree","remove","--force",s]);await F(t,["worktree","prune"])}catch{}try{await F(t,["branch","-D",e])}catch{}}async function wl(t,e,n,r){Ae.default.mkdirSync(ge.default.dirname(e),{recursive:!0,mode:448}),await F(t,["worktree","add","-b",n,e,`origin/${r}`])}async function Ir(t,e){if(await F(t,["add","-A"]),!(await F(t,["status","--porcelain"])).trim())throw new Error("Claude wrote no changes - nothing to commit");await F(t,["-c",`user.name=${ko}`,"-c",`user.email=${_o}`,"commit","-m",e])}async function $n(t,e){let r=(await F(t,["diff","--name-only",`origin/${e}...HEAD`])).split(`
363
- `).filter(Boolean),s=r.filter(d=>oh.some(p=>p.test(d))),i=await F(t,["diff","--shortstat",`origin/${e}...HEAD`]),o=Number(/(\d+) insertion/.exec(i)?.[1]??0),l=Number(/(\d+) deletion/.exec(i)?.[1]??0);return{ok:s.length===0&&r.length<=Rn&&o+l<=An,files:r.length,insertions:o,deletions:l,forbidden:s}}async function Er(t,e){await F(t,["fetch","--prune","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],{timeoutMs:12e4}).catch(()=>F(t,["update-ref","-d",`refs/remotes/origin/${e}`]).catch(()=>{})),await F(t,["push","--force-with-lease","-u","origin",e],{timeoutMs:3e5})}async function Ye(t){return(await F(t,["rev-parse","HEAD"])).trim()}async function vl(t,e){let n=await F(t,["fetch","origin",e],{timeoutMs:12e4}).then(()=>!0).catch(()=>!1),r=async s=>F(t,["rev-parse","--verify",s]).then(i=>i.trim()).catch(()=>"");if(n){let s=await r("FETCH_HEAD");if(s)return s}return r(`refs/remotes/origin/${e}`)}async function kl(t,e,n){return F(t,["rev-list","--count",`${e}..${n}`]).then(r=>r.trim()).catch(()=>"")}async function To(t,e){try{return(await F(t,["rev-parse","--verify",`refs/heads/${e}`])).trim()}catch{return null}}async function vs(t,e){await F(t,["reset","--hard",e])}async function Ot(t,e){try{await F(t,["worktree","remove","--force",e])}catch{Ae.default.rmSync(e,{recursive:!0,force:!0})}}async function _l(t,e=[]){let n=new Set(e.map(s=>ge.default.basename(ge.default.resolve(s))).filter(s=>s.length>0)),r=rn();if(Ae.default.existsSync(r))for(let s of Ae.default.readdirSync(r))n.has(s)||Ae.default.rmSync(ge.default.join(r,s),{recursive:!0,force:!0});for(let s of t)try{await F(s,["worktree","prune"])}catch{}}async function Sl(t,e){return await F(t,["fetch","origin","--prune"]).catch(()=>{}),(await F(t,["branch","-r","--list",`*${e}*`])).split(`
364
- `).map(s=>s.trim()).filter(s=>s&&!s.includes("->"))[0]??null}async function xo(t,e,n=6e4){let s=(await F(t,["symbolic-ref","refs/remotes/origin/HEAD"]).catch(()=>"")).trim().replace("refs/remotes/","")||"origin/main",i=await F(t,["diff","--stat",`${s}...${e}`]),o=await F(t,["diff",`${s}...${e}`]);return{base:s,stat:i.slice(0,4e3),diff:o.slice(0,n)}}function ah(){let t=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(Ae.default.existsSync(ge.default.join(xr.default.homedir(),".cache","ticketpilot"))?ge.default.join(xr.default.homedir(),".cache","ticketpilot"):ge.default.join(xr.default.homedir(),".cache","allwright"));return ge.default.join(t,"env-checkouts")}function nh(t){return t.replace(/[^\w.-]+/g,"_")}async function Tl(t,e,n){await F(t,["fetch","origin"],{timeoutMs:3e5}),await F(t,["reset","--hard"]),await F(t,["checkout","-B",e,n])}function lh(t,e){return ge.default.join(ah(),nh(t),nh(e))}async function xl(t){let e=lh(t.repoName,t.envName);return await F(t.repoPath,["fetch","origin",t.branch],{timeoutMs:3e5}),Ae.default.existsSync(ge.default.join(e,".git"))?await F(e,["fetch","origin",t.branch],{timeoutMs:3e5}):(Ae.default.rmSync(e,{recursive:!0,force:!0}),Ae.default.mkdirSync(ge.default.dirname(e),{recursive:!0,mode:448}),await F(t.repoPath,["worktree","prune"]).catch(()=>{}),await F(t.repoPath,["worktree","add","--detach",e,`origin/${t.branch}`])),t.attached?await F(e,["checkout","-B",t.branch,`origin/${t.branch}`]):await F(e,["checkout","--force","--detach",`origin/${t.branch}`]),e}async function Il(t,e,n){try{await F(t,["fetch","origin",e],{timeoutMs:3e5})}catch{return{ok:!1,reason:`branch "${e}" does not exist on origin - nothing to promote. Check the environment's ticket branch template against the branch your implement rule creates.`}}try{return await F(t,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyMerged:!0}}catch{}try{return await F(t,["-c",`user.name=${ko}`,"-c",`user.email=${_o}`,"merge","--no-ff","-m",n,`origin/${e}`]),{ok:!0}}catch(r){return await F(t,["merge","--abort"]).catch(()=>{}),{ok:!1,reason:`could not merge "${e}" into the environment branch - ${r instanceof Error?r.message:r}. Resolve it manually and deploy again.`}}}async function El(t,e){await F(t,["fetch","origin",e],{timeoutMs:3e5});try{return await F(t,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyUpToDate:!0}}catch{}try{return await F(t,["-c",`user.name=${ko}`,"-c",`user.email=${_o}`,"merge","--no-edit",`origin/${e}`]),{ok:!0,alreadyUpToDate:!1}}catch(n){let s=(await F(t,["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
365
- `).filter(Boolean);return s.length?{ok:!1,conflicts:s}:(await F(t,["merge","--abort"]).catch(()=>{}),{ok:!1,conflicts:null,reason:n instanceof Error?n.message.slice(0,300):String(n)})}}async function Pn(t){await F(t,["merge","--abort"]).catch(()=>{})}async function Rl(t,e){await F(t,["add","-A"]),await F(t,["-c",`user.name=${ko}`,"-c",`user.email=${_o}`,"commit","--no-edit","-m",e])}async function Al(t,e){let n=new Set(await Io(t));return e.filter(r=>n.has(r))}async function Io(t){let e=new Set;try{let r=await F(t,["grep","-l","-I","-E","^(<{7}|>{7})( |$)"]);for(let s of r.split(`
366
- `).filter(Boolean))e.add(s)}catch{}let n=[];try{n=(await F(t,["grep","-l","-I","-E","^={7}$"])).split(`
367
- `).filter(Boolean).filter(s=>!e.has(s))}catch{}for(let r of n)try{let s=await F(t,["show",`HEAD:${r}`]);/^={7}$/m.test(s)||e.add(r)}catch{e.add(r)}return[...e]}async function ii(t,e,n){Ae.default.mkdirSync(ge.default.dirname(e),{recursive:!0,mode:448}),await F(t,["fetch","origin",n],{timeoutMs:3e5}),await F(t,["worktree","add","--detach",e,`origin/${n}`]),await F(e,["checkout","-B",n,`origin/${n}`])}async function Cl(t,e){try{await F(t,["push","origin",e],{timeoutMs:3e5})}catch(n){throw new Error(`could not push "${e}" - ${n instanceof Error?n.message:n}. Someone may have pushed to it since this deploy started; retry.`)}}async function $l(t,e,n){try{return await ih("git",["-C",t,"diff","--quiet",e,n,"--"],{timeout:12e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),!1}catch(r){let s=r;if(s.code===1)return!0;throw new Error(`git diff failed comparing ${e}..${n}: ${(s.stderr||s.message||"").trim().slice(0,500)}`)}}async function Rr(t){return(await F(t,["config","--get","remote.origin.url"])).trim()}function _t(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 Ae,xr,ge,rh,sh,ih,ko,_o,Rn,An,oh,nn,jt=ne(()=>{"use strict";Ae=R(require("node:fs"),1),xr=R(require("node:os"),1),ge=R(require("node:path"),1),rh=require("node:child_process"),sh=require("node:util"),ih=(0,sh.promisify)(rh.execFile),ko="Allwright Agent",_o="agent@ticketpilot.local",Rn=200,An=2e4,oh=[/^\.github\/workflows\//,/^\.git\b/,/(^|\/)\.githooks\//];nn=".ticketpilot-delete"});function fv(t){return t.length<=3e4?t:`${t.slice(0,3e4)}
368
-
369
- [description truncated by Allwright at 30,000 characters - read the rest on the ticket]`}function Nl(){return new Le({baseUrl:"",email:"",apiToken:""},!1)}function uh(t){if(!t)return"";let e=[],n=r=>{r.text&&e.push(r.text),r.type==="hardBreak"&&e.push(`
360
+ ${i}${o}`:"clean"}`}function ln(){let t=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(Ne.default.existsSync(ge.default.join(Rr.default.homedir(),".cache","ticketpilot"))?ge.default.join(Rr.default.homedir(),".cache","ticketpilot"):ge.default.join(Rr.default.homedir(),".cache","allwright"));return ge.default.join(t,"worktrees")}async function Il(t,e,n,r=40){if(!n.trim()||!e.trim())return null;let s=await H(t,["log",`origin/${e}`,"-n","1","--format=%H%x00%s","--fixed-strings",`--grep=${n}`]).then(c=>c.trim()).catch(()=>"");if(!s)return null;let[i,o=""]=s.split("\0");if(!i)return null;let l=await H(t,["show","--name-only","--format=",i]).then(c=>c.split(`
361
+ `).map(d=>d.trim()).filter(Boolean)).catch(()=>[]);return{sha:i,subject:o,files:l.slice(0,r),more:Math.max(0,l.length-r)}}async function Rl(t,e){try{return(await H(t,["ls-remote","--heads","origin",e])).trim().length>0}catch{return null}}async function jn(t,e){try{await H(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 El(t,e){try{let n=await H(t,["worktree","list","--porcelain"]),r=ln(),s=null;for(let i of n.split(`
362
+ `))i.startsWith("worktree ")&&(s=i.slice(9).trim()),i===`branch refs/heads/${e}`&&s&&s.startsWith(r)&&await H(t,["worktree","remove","--force",s]);await H(t,["worktree","prune"])}catch{}try{await H(t,["branch","-D",e])}catch{}}async function Al(t,e,n,r){Ne.default.mkdirSync(ge.default.dirname(e),{recursive:!0,mode:448}),await H(t,["worktree","add","-b",n,e,`origin/${r}`])}async function Er(t,e){if(await H(t,["add","-A"]),!(await H(t,["status","--porcelain"])).trim())throw new Error("Claude wrote no changes - nothing to commit");await H(t,["-c",`user.name=${To}`,"-c",`user.email=${xo}`,"commit","-m",e])}async function On(t,e){let r=(await H(t,["diff","--name-only",`origin/${e}...HEAD`])).split(`
363
+ `).filter(Boolean),s=r.filter(d=>mh.some(p=>p.test(d))),i=await H(t,["diff","--shortstat",`origin/${e}...HEAD`]),o=Number(/(\d+) insertion/.exec(i)?.[1]??0),l=Number(/(\d+) deletion/.exec(i)?.[1]??0);return{ok:s.length===0&&r.length<=Pn&&o+l<=Nn,files:r.length,insertions:o,deletions:l,forbidden:s}}async function Ar(t,e){await H(t,["fetch","--prune","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],{timeoutMs:12e4}).catch(()=>H(t,["update-ref","-d",`refs/remotes/origin/${e}`]).catch(()=>{})),await H(t,["push","--force-with-lease","-u","origin",e],{timeoutMs:3e5})}async function Qe(t){return(await H(t,["rev-parse","HEAD"])).trim()}async function Cl(t,e){let n=await H(t,["fetch","origin",e],{timeoutMs:12e4}).then(()=>!0).catch(()=>!1),r=async s=>H(t,["rev-parse","--verify",s]).then(i=>i.trim()).catch(()=>"");if(n){let s=await r("FETCH_HEAD");if(s)return s}return r(`refs/remotes/origin/${e}`)}async function $l(t,e,n){return H(t,["rev-list","--count",`${e}..${n}`]).then(r=>r.trim()).catch(()=>"")}async function Ro(t,e){try{return(await H(t,["rev-parse","--verify",`refs/heads/${e}`])).trim()}catch{return null}}async function _s(t,e){await H(t,["reset","--hard",e])}async function Dt(t,e){try{await H(t,["worktree","remove","--force",e])}catch{Ne.default.rmSync(e,{recursive:!0,force:!0})}}async function Pl(t,e=[]){let n=new Set(e.map(s=>ge.default.basename(ge.default.resolve(s))).filter(s=>s.length>0)),r=ln();if(Ne.default.existsSync(r))for(let s of Ne.default.readdirSync(r))n.has(s)||Ne.default.rmSync(ge.default.join(r,s),{recursive:!0,force:!0});for(let s of t)try{await H(s,["worktree","prune"])}catch{}}async function Nl(t,e){return await H(t,["fetch","origin","--prune"]).catch(()=>{}),(await H(t,["branch","-r","--list",`*${e}*`])).split(`
364
+ `).map(s=>s.trim()).filter(s=>s&&!s.includes("->"))[0]??null}async function Eo(t,e,n=6e4){let s=(await H(t,["symbolic-ref","refs/remotes/origin/HEAD"]).catch(()=>"")).trim().replace("refs/remotes/","")||"origin/main",i=await H(t,["diff","--stat",`${s}...${e}`]),o=await H(t,["diff",`${s}...${e}`]);return{base:s,stat:i.slice(0,4e3),diff:o.slice(0,n)}}function gh(){let t=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(Ne.default.existsSync(ge.default.join(Rr.default.homedir(),".cache","ticketpilot"))?ge.default.join(Rr.default.homedir(),".cache","ticketpilot"):ge.default.join(Rr.default.homedir(),".cache","allwright"));return ge.default.join(t,"env-checkouts")}function dh(t){return t.replace(/[^\w.-]+/g,"_")}async function jl(t,e,n){await H(t,["fetch","origin"],{timeoutMs:3e5}),await H(t,["reset","--hard"]),await H(t,["checkout","-B",e,n])}function yh(t,e){return ge.default.join(gh(),dh(t),dh(e))}async function Ol(t){let e=yh(t.repoName,t.envName);return await H(t.repoPath,["fetch","origin",t.branch],{timeoutMs:3e5}),Ne.default.existsSync(ge.default.join(e,".git"))?await H(e,["fetch","origin",t.branch],{timeoutMs:3e5}):(Ne.default.rmSync(e,{recursive:!0,force:!0}),Ne.default.mkdirSync(ge.default.dirname(e),{recursive:!0,mode:448}),await H(t.repoPath,["worktree","prune"]).catch(()=>{}),await H(t.repoPath,["worktree","add","--detach",e,`origin/${t.branch}`])),t.attached?await H(e,["checkout","-B",t.branch,`origin/${t.branch}`]):await H(e,["checkout","--force","--detach",`origin/${t.branch}`]),e}async function Ml(t,e,n){try{await H(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 H(t,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyMerged:!0}}catch{}try{return await H(t,["-c",`user.name=${To}`,"-c",`user.email=${xo}`,"merge","--no-ff","-m",n,`origin/${e}`]),{ok:!0}}catch(r){return await H(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 zl(t,e){await H(t,["fetch","origin",e],{timeoutMs:3e5});try{return await H(t,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyUpToDate:!0}}catch{}try{return await H(t,["-c",`user.name=${To}`,"-c",`user.email=${xo}`,"merge","--no-edit",`origin/${e}`]),{ok:!0,alreadyUpToDate:!1}}catch(n){let s=(await H(t,["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
365
+ `).filter(Boolean);return s.length?{ok:!1,conflicts:s}:(await H(t,["merge","--abort"]).catch(()=>{}),{ok:!1,conflicts:null,reason:n instanceof Error?n.message.slice(0,300):String(n)})}}async function Mn(t){await H(t,["merge","--abort"]).catch(()=>{})}async function Dl(t,e){await H(t,["add","-A"]),await H(t,["-c",`user.name=${To}`,"-c",`user.email=${xo}`,"commit","--no-edit","-m",e])}async function Ll(t,e){let n=new Set(await Ao(t));return e.filter(r=>n.has(r))}async function Ao(t){let e=new Set;try{let r=await H(t,["grep","-l","-I","-E","^(<{7}|>{7})( |$)"]);for(let s of r.split(`
366
+ `).filter(Boolean))e.add(s)}catch{}let n=[];try{n=(await H(t,["grep","-l","-I","-E","^={7}$"])).split(`
367
+ `).filter(Boolean).filter(s=>!e.has(s))}catch{}for(let r of n)try{let s=await H(t,["show",`HEAD:${r}`]);/^={7}$/m.test(s)||e.add(r)}catch{e.add(r)}return[...e]}async function li(t,e,n){Ne.default.mkdirSync(ge.default.dirname(e),{recursive:!0,mode:448}),await H(t,["fetch","origin",n],{timeoutMs:3e5}),await H(t,["worktree","add","--detach",e,`origin/${n}`]),await H(e,["checkout","-B",n,`origin/${n}`])}async function Ul(t,e){try{await H(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 ql(t,e,n){try{return await fh("git",["-C",t,"diff","--quiet",e,n,"--"],{timeout:12e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),!1}catch(r){let s=r;if(s.code===1)return!0;throw new Error(`git diff failed comparing ${e}..${n}: ${(s.stderr||s.message||"").trim().slice(0,500)}`)}}async function Cr(t){return(await H(t,["config","--get","remote.origin.url"])).trim()}function St(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 Ne,Rr,ge,hh,ph,fh,To,xo,Pn,Nn,mh,an,Lt=te(()=>{"use strict";Ne=E(require("node:fs"),1),Rr=E(require("node:os"),1),ge=E(require("node:path"),1),hh=require("node:child_process"),ph=require("node:util"),fh=(0,ph.promisify)(hh.execFile),To="Allwright Agent",xo="agent@ticketpilot.local",Pn=200,Nn=2e4,mh=[/^\.github\/workflows\//,/^\.git\b/,/(^|\/)\.githooks\//];an=".ticketpilot-delete"});function Bv(t){return t.length<=3e4?t:`${t.slice(0,3e4)}
368
+
369
+ [description truncated by Allwright at 30,000 characters - read the rest on the ticket]`}function Bl(){return new Ue({baseUrl:"",email:"",apiToken:""},!1)}function wh(t){if(!t)return"";let e=[],n=r=>{r.text&&e.push(r.text),r.type==="hardBreak"&&e.push(`
370
370
  `);for(let s of r.content??[])n(s);r.type&&["paragraph","heading","listItem","codeBlock","blockquote"].includes(r.type)&&e.push(`
371
371
  `)};return n(t),e.join("").replace(/\n{3,}/g,`
372
372
 
373
- `).trim()}function Eo(t){let e=t.replace(/\r\n/g,`
373
+ `).trim()}function Co(t){let e=t.replace(/\r\n/g,`
374
374
  `).split(`
375
375
  `),n=[],r=0,s=i=>{let o=[],l=/(\*\*[^*]+\*\*|`[^`]+`)/g,c=0,d;for(;(d=l.exec(i))!==null;){d.index>c&&o.push({type:"text",text:i.slice(c,d.index)});let p=d[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=d.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(`
376
- `)||" "}]});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}}var dh,pv,pt,Pl,mv,Le,oi=ne(()=>{"use strict";dh="Posted automatically by Allwright",pv=["Posted automatically by TicketPilot"],pt=t=>t.includes(dh)||pv.some(e=>t.includes(e));Pl=200,mv="no Jira credentials on this runner - add them with `allwright jira set-default`";Le=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(mv)}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,issuetype`),r;try{r=await this.listAllComments(e)}catch{r=n.fields.comment?.comments??[]}let s=r.map(l=>({id:l.id??"",author:l.author?.displayName??"unknown",authorAccountId:l.author?.accountId??null,created:l.created,body:uh(l.body)})),i=(n.fields.attachment??[]).filter(l=>l.id&&l.filename&&l.content).map(l=>({id:l.id,filename:l.filename,mimeType:l.mimeType??"",size:l.size??0,contentUrl:l.content})),o=fv(uh(n.fields.description));return{key:n.key,summary:n.fields.summary??"",description:o,labels:n.fields.labels??[],status:n.fields.status?.name??"",issueType:n.fields.issuetype?.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-Pl),i=s===0?[...n.comments]:[];for(;i.length<Math.min(r,Pl);){let o=await this.fetchCommentPage(e,s+i.length);if(!o.comments.length)break;i.push(...o.comments)}return i.slice(-Pl)}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:Eo(r),...i?{parent:{key:i}}:{}}})).key}}async updateDescription(e,n){await this.request("PUT",`/rest/api/3/issue/${encodeURIComponent(e)}`,{fields:{description:Eo(n)}})}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:Eo(n)})}async addComment(e,n){let r=`${n}
376
+ `)||" "}]});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}}var vh,Fv,ft,Fl,Hv,Ue,ci=te(()=>{"use strict";vh="Posted automatically by Allwright",Fv=["Posted automatically by TicketPilot"],ft=t=>t.includes(vh)||Fv.some(e=>t.includes(e));Fl=200,Hv="no Jira credentials on this runner - add them with `allwright jira set-default`";Ue=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(Hv)}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,issuetype`),r;try{r=await this.listAllComments(e)}catch{r=n.fields.comment?.comments??[]}let s=r.map(l=>({id:l.id??"",author:l.author?.displayName??"unknown",authorAccountId:l.author?.accountId??null,created:l.created,body:wh(l.body)})),i=(n.fields.attachment??[]).filter(l=>l.id&&l.filename&&l.content).map(l=>({id:l.id,filename:l.filename,mimeType:l.mimeType??"",size:l.size??0,contentUrl:l.content})),o=Bv(wh(n.fields.description));return{key:n.key,summary:n.fields.summary??"",description:o,labels:n.fields.labels??[],status:n.fields.status?.name??"",issueType:n.fields.issuetype?.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-Fl),i=s===0?[...n.comments]:[];for(;i.length<Math.min(r,Fl);){let o=await this.fetchCommentPage(e,s+i.length);if(!o.comments.length)break;i.push(...o.comments)}return i.slice(-Fl)}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:Co(r),...i?{parent:{key:i}}:{}}})).key}}async updateDescription(e,n){await this.request("PUT",`/rest/api/3/issue/${encodeURIComponent(e)}`,{fields:{description:Co(n)}})}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:Co(n)})}async addComment(e,n){let r=`${n}
377
377
 
378
378
  ---
379
- _${dh} - never treated as a trigger._`;await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/comment`,{body:Eo(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 Ro(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 Ue(t,e){return t.repos[e]?.github?.token??t.github?.token??null}function mh(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(),d=t.jiraUsers[c]?"own":r.has(c)?"runner-account":"missing",p=d==="own"?t.jiraUsers[c].email:d==="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:d,jiraAs:p,github:f,githubAs:w}});return{githubShared:s,sharedGithubLogin:i,entries:o}}var Ar=ne(()=>{"use strict"});function Ih(t,e,n,r={}){let s=e.map(p=>`### Pack: ${p.name}
379
+ _${vh} - never treated as a trigger._`;await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/comment`,{body:Co(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 $o(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 qe(t,e){return t.repos[e]?.github?.token??t.github?.token??null}function Th(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(),d=t.jiraUsers[c]?"own":r.has(c)?"runner-account":"missing",p=d==="own"?t.jiraUsers[c].email:d==="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:d,jiraAs:p,github:f,githubAs:w}});return{githubShared:s,sharedGithubLogin:i,entries:o}}var $r=te(()=>{"use strict"});function Oh(t,e,n,r={}){let s=e.map(p=>`### Pack: ${p.name}
380
380
 
381
381
  ${p.content}`).join(`
382
382
 
@@ -405,7 +405,7 @@ This transcript is your PRIMARY evidence. A URL with issues becomes a finding; t
405
405
  ### WRITING STYLE - plain language
406
406
 
407
407
  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.
408
- 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`${_v[t]}
408
+ 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`${Yv[t]}
409
409
 
410
410
  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.
411
411
 
@@ -419,36 +419,36 @@ Explore the repository first - entry points, routes, storage, tests - then audit
419
419
  "evidence": [{"file": "<repo-relative path>", "line": <number, omit if n/a>, "note": "<what is there>"}],
420
420
  "fix": "<2-4 sentences: concrete fix, specific to this code>"}]}
421
421
  \`\`\`
422
- 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.`+d}function Eh(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=Sv(l),d=c?Po.AuditFinding.safeParse(c):null;if(!d?.success){i++;continue}let p=d.data.id;for(;o.has(p);)p=`${p}-2`;o.add(p),s.push({...d.data,id:p})}return{summary:typeof r.summary=="string"?r.summary.trim().slice(0,2e3):"",findings:s,dropped:i}}function Sv(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:"",...xh(i.line)?{line:xh(i.line)}:{},note:typeof i.note=="string"?i.note:""})).filter(i=>i.file):[],s=typeof e.ruleId=="string"?e.ruleId.trim().toUpperCase():"";return{id:Tv(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:Po.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 xh(t){let e=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):NaN;return Number.isInteger(e)&&e>0?e:void 0}function Tv(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"finding"}function xv(t){try{let e=ql.default.readFileSync(t,"utf8");return e?e.split(`
423
- `).length:0}catch{return null}}function Rh(t,e){let n=$o.default.resolve(t),r=[],s=[],i=0;for(let o of e){let l=[];for(let c of o.evidence){let d=c.file.trim().replace(/^\.\//,""),p=$o.default.resolve(n,d);if(p!==n&&!p.startsWith(n+$o.default.sep))continue;let f;try{f=ql.default.statSync(p)}catch{continue}if(f.isFile()){if(c.line!==void 0){let w=xv(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 ql,$o,Po,_v,Ah=ne(()=>{"use strict";ql=R(require("node:fs"),1),$o=R(require("node:path"),1),Po=R(Re(),1),_v={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 $h(){return Fl.default.join(se(),"audits.json")}function Ss(){try{return{byProject:JSON.parse(ai.default.readFileSync($h(),"utf8")).byProject??{}}}catch{return{byProject:{}}}}function Ph(t){let e=$h();ai.default.mkdirSync(Fl.default.dirname(e),{recursive:!0,mode:448});let n=e+".tmp";ai.default.writeFileSync(n,JSON.stringify(t,null,2),{mode:384}),ai.default.renameSync(n,e)}function Nh(t,e){let n=Ss(),r=n.byProject[t]??[];r.unshift(Ch.AuditRecord.parse(e)),n.byProject[t]=r.slice(0,Iv),Ph(n)}function Oh(t){return(Ss().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 jh(t,e){let n=Ss(),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 d of c.findings){let p=c.verdicts[d.id]?.verdict;p==="valid"?l.valid++:p==="false-positive"?l.falsePositive++:p==="wont-fix"?l.wontFix++:l.unreviewed++}}s[i]=l}return s}function Bl(t,e,n){let r=Ss(),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 Ph(r),i}function Mh(t,e){return(Ss().byProject[t]??[]).find(s=>s.role===e&&(s.scope?.kind??"repo")==="repo")?.createdAt??null}function Hl(t,e){return(Ss().byProject[t]??[]).find(n=>n.id===e)??null}var ai,Fl,Ch,Iv,No=ne(()=>{"use strict";ai=R(require("node:fs"),1),Fl=R(require("node:path"),1),Ch=R(Re(),1);Ee();Iv=20});function Av(t){let e=St.default.join(t,".git"),n;try{n=qe.default.statSync(e)}catch{return null}if(n.isDirectory())return St.default.join(e,"info");let r=/^gitdir:\s*(.+)$/m.exec(qe.default.readFileSync(e,"utf8"));if(!r?.[1])return null;let s=St.default.resolve(t,r[1].trim());try{let i=qe.default.readFileSync(St.default.join(s,"commondir"),"utf8").trim();return St.default.join(St.default.resolve(s,i),"info")}catch{return St.default.join(s,"info")}}function Cv(t){try{let e=Av(t);if(!e)return;let n=St.default.join(e,"exclude"),r="";try{r=qe.default.readFileSync(n,"utf8")}catch{}if(r.split(`
424
- `).some(i=>i.trim()===zh))return;qe.default.mkdirSync(e,{recursive:!0});let s=r&&!r.endsWith(`
422
+ 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.`+d}function Mh(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=Xv(l),d=c?Oo.AuditFinding.safeParse(c):null;if(!d?.success){i++;continue}let p=d.data.id;for(;o.has(p);)p=`${p}-2`;o.add(p),s.push({...d.data,id:p})}return{summary:typeof r.summary=="string"?r.summary.trim().slice(0,2e3):"",findings:s,dropped:i}}function Xv(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:"",...jh(i.line)?{line:jh(i.line)}:{},note:typeof i.note=="string"?i.note:""})).filter(i=>i.file):[],s=typeof e.ruleId=="string"?e.ruleId.trim().toUpperCase():"";return{id:Qv(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:Oo.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 jh(t){let e=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):NaN;return Number.isInteger(e)&&e>0?e:void 0}function Qv(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"finding"}function ek(t){try{let e=Yl.default.readFileSync(t,"utf8");return e?e.split(`
423
+ `).length:0}catch{return null}}function zh(t,e){let n=jo.default.resolve(t),r=[],s=[],i=0;for(let o of e){let l=[];for(let c of o.evidence){let d=c.file.trim().replace(/^\.\//,""),p=jo.default.resolve(n,d);if(p!==n&&!p.startsWith(n+jo.default.sep))continue;let f;try{f=Yl.default.statSync(p)}catch{continue}if(f.isFile()){if(c.line!==void 0){let w=ek(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 Yl,jo,Oo,Yv,Dh=te(()=>{"use strict";Yl=E(require("node:fs"),1),jo=E(require("node:path"),1),Oo=E(Re(),1),Yv={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 Uh(){return Xl.default.join(ie(),"audits.json")}function xs(){try{return{byProject:JSON.parse(ui.default.readFileSync(Uh(),"utf8")).byProject??{}}}catch{return{byProject:{}}}}function qh(t){let e=Uh();ui.default.mkdirSync(Xl.default.dirname(e),{recursive:!0,mode:448});let n=e+".tmp";ui.default.writeFileSync(n,JSON.stringify(t,null,2),{mode:384}),ui.default.renameSync(n,e)}function Fh(t,e){let n=xs(),r=n.byProject[t]??[];r.unshift(Lh.AuditRecord.parse(e)),n.byProject[t]=r.slice(0,tk),qh(n)}function Bh(t){return(xs().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 Hh(t,e){let n=xs(),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 d of c.findings){let p=c.verdicts[d.id]?.verdict;p==="valid"?l.valid++:p==="false-positive"?l.falsePositive++:p==="wont-fix"?l.wontFix++:l.unreviewed++}}s[i]=l}return s}function Ql(t,e,n){let r=xs(),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 qh(r),i}function Kh(t,e){return(xs().byProject[t]??[]).find(s=>s.role===e&&(s.scope?.kind??"repo")==="repo")?.createdAt??null}function ec(t,e){return(xs().byProject[t]??[]).find(n=>n.id===e)??null}var ui,Xl,Lh,tk,Mo=te(()=>{"use strict";ui=E(require("node:fs"),1),Xl=E(require("node:path"),1),Lh=E(Re(),1);Ae();tk=20});function sk(t){let e=Tt.default.join(t,".git"),n;try{n=Fe.default.statSync(e)}catch{return null}if(n.isDirectory())return Tt.default.join(e,"info");let r=/^gitdir:\s*(.+)$/m.exec(Fe.default.readFileSync(e,"utf8"));if(!r?.[1])return null;let s=Tt.default.resolve(t,r[1].trim());try{let i=Fe.default.readFileSync(Tt.default.join(s,"commondir"),"utf8").trim();return Tt.default.join(Tt.default.resolve(s,i),"info")}catch{return Tt.default.join(s,"info")}}function ik(t){try{let e=sk(t);if(!e)return;let n=Tt.default.join(e,"exclude"),r="";try{r=Fe.default.readFileSync(n,"utf8")}catch{}if(r.split(`
424
+ `).some(i=>i.trim()===Gh))return;Fe.default.mkdirSync(e,{recursive:!0});let s=r&&!r.endsWith(`
425
425
  `)?`
426
- `:"";qe.default.appendFileSync(n,`${s}# Allwright runner scratch - see .ticketpilot/memory/
427
- ${zh}
428
- `)}catch{}}function Kl(t){return St.default.join(t,".ticketpilot","memory","incidents.md")}function ft(t,e){try{let n=Kl(t),r=St.default.dirname(n);qe.default.existsSync(r)||(qe.default.mkdirSync(r,{recursive:!0}),Cv(t));let s=qe.default.existsSync(n)?"":Dh,i=new Date().toISOString().slice(0,10),o=e.detail?.trim();qe.default.appendFileSync(n,s+`## ${i} \xB7 ${e.issueKey} \xB7 ${e.title} (run ${e.runId})
426
+ `:"";Fe.default.appendFileSync(n,`${s}# Allwright runner scratch - see .ticketpilot/memory/
427
+ ${Gh}
428
+ `)}catch{}}function tc(t){return Tt.default.join(t,".ticketpilot","memory","incidents.md")}function mt(t,e){try{let n=tc(t),r=Tt.default.dirname(n);Fe.default.existsSync(r)||(Fe.default.mkdirSync(r,{recursive:!0}),ik(t));let s=Fe.default.existsSync(n)?"":Wh,i=new Date().toISOString().slice(0,10),o=e.detail?.trim();Fe.default.appendFileSync(n,s+`## ${i} \xB7 ${e.issueKey} \xB7 ${e.title} (run ${e.runId})
429
429
  `+(o?`${o.slice(0,1500)}
430
430
  `:"")+`
431
- `),$v(n)}catch{}}function li(t,e){try{return qe.default.readFileSync(Kl(t),"utf8").includes(`\xB7 ${e} \xB7`)}catch{return!1}}function $v(t){if(qe.default.statSync(t).size<=Ev)return;let r=qe.default.readFileSync(t,"utf8").slice(-Rv),s=r.indexOf(`
432
- ## `),i=s===-1?r:r.slice(s+1);qe.default.writeFileSync(t,Dh+`*(older entries were rotated out)*
431
+ `),ok(n)}catch{}}function di(t,e){try{return Fe.default.readFileSync(tc(t),"utf8").includes(`\xB7 ${e} \xB7`)}catch{return!1}}function ok(t){if(Fe.default.statSync(t).size<=nk)return;let r=Fe.default.readFileSync(t,"utf8").slice(-rk),s=r.indexOf(`
432
+ ## `),i=s===-1?r:r.slice(s+1);Fe.default.writeFileSync(t,Wh+`*(older entries were rotated out)*
433
433
 
434
- `+i)}function Lh(t){try{return qe.default.readFileSync(Kl(t),"utf8")}catch{return null}}var qe,St,Ev,Rv,zh,Dh,ci=ne(()=>{"use strict";qe=R(require("node:fs"),1),St=R(require("node:path"),1),Ev=25e4,Rv=2e5,zh="/.ticketpilot/memory/";Dh=`# Incident ledger
434
+ `+i)}function Zh(t){try{return Fe.default.readFileSync(tc(t),"utf8")}catch{return null}}var Fe,Tt,nk,rk,Gh,Wh,hi=te(()=>{"use strict";Fe=E(require("node:fs"),1),Tt=E(require("node:path"),1),nk=25e4,rk=2e5,Gh="/.ticketpilot/memory/";Wh=`# Incident ledger
435
435
 
436
436
  Machine-written facts about this repository's runs: what failed, what
437
437
  resolved it. Appended by the Allwright runner; humans may edit freely.
438
438
  Newest entries are at the bottom.
439
439
 
440
- `});function Gl(t){return Mt.default.join(se(),"knowledge",t)}function Fh(t,e){return Mt.default.join(t,".ticketpilot","knowledge",`${e}.md`)}function Wl(t,e){return Mt.default.join(t,".ticketpilot","lessons",`${e}.md`)}function Bh(t,e){let n=[],r=Gl(t),s=[];if(He.default.existsSync(r)){for(let c of He.default.readdirSync(r)){if(!c.endsWith(".md"))continue;let d=Mt.default.join(r,c),p=He.default.readFileSync(d,"utf8");if(Mv.some(f=>p.includes(f))&&Uh[t].map(w=>w.name).includes(c)&&!p.includes("SEC-0")&&!p.includes("TEST-0")&&!p.includes("GDPR-0")){He.default.rmSync(d);continue}s.push(c)}s.sort()}let i=new Set(s);for(let c of Uh[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:He.default.readFileSync(Mt.default.join(r,c),"utf8").slice(0,3e4),editable:!0});let o=Fh(e,t);He.default.existsSync(o)&&n.push({level:"project",source:"pack",name:`${t}.md`,content:He.default.readFileSync(o,"utf8").slice(0,3e4),editable:!0});let l=Wl(e,t);return He.default.existsSync(l)&&n.push({level:"project",source:"lessons",name:`${t}.md`,content:He.default.readFileSync(l,"utf8").slice(0,2e4),editable:!0}),n}function Ts(t,e){let n=Bh(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 Zl(t,e,n,r="project"){let s=r==="org"?Mt.default.join(Gl(e),"org-lessons.md"):Wl(t,e);He.default.mkdirSync(Mt.default.dirname(s),{recursive:!0});let i=He.default.existsSync(s)?"":`# ${e} lessons (${r} level)
440
+ `});function nc(t){return Ut.default.join(ie(),"knowledge",t)}function Yh(t,e){return Ut.default.join(t,".ticketpilot","knowledge",`${e}.md`)}function rc(t,e){return Ut.default.join(t,".ticketpilot","lessons",`${e}.md`)}function Xh(t,e){let n=[],r=nc(t),s=[];if(Ge.default.existsSync(r)){for(let c of Ge.default.readdirSync(r)){if(!c.endsWith(".md"))continue;let d=Ut.default.join(r,c),p=Ge.default.readFileSync(d,"utf8");if(dk.some(f=>p.includes(f))&&Vh[t].map(w=>w.name).includes(c)&&!p.includes("SEC-0")&&!p.includes("TEST-0")&&!p.includes("GDPR-0")){Ge.default.rmSync(d);continue}s.push(c)}s.sort()}let i=new Set(s);for(let c of Vh[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:Ge.default.readFileSync(Ut.default.join(r,c),"utf8").slice(0,3e4),editable:!0});let o=Yh(e,t);Ge.default.existsSync(o)&&n.push({level:"project",source:"pack",name:`${t}.md`,content:Ge.default.readFileSync(o,"utf8").slice(0,3e4),editable:!0});let l=rc(e,t);return Ge.default.existsSync(l)&&n.push({level:"project",source:"lessons",name:`${t}.md`,content:Ge.default.readFileSync(l,"utf8").slice(0,2e4),editable:!0}),n}function Is(t,e){let n=Xh(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 sc(t,e,n,r="project"){let s=r==="org"?Ut.default.join(nc(e),"org-lessons.md"):rc(t,e);Ge.default.mkdirSync(Ut.default.dirname(s),{recursive:!0});let i=Ge.default.existsSync(s)?"":`# ${e} lessons (${r} level)
441
441
 
442
442
  Human-confirmed corrections and rules. `+(e==="implement"?`Every implement run on this repo reads this BEFORE starting work.
443
443
 
444
444
  `:`Every ${e} audit reads this FIRST. Reference rule ids (SEC-001 style) when overriding a rule.
445
445
 
446
- `);He.default.appendFileSync(s,i+n.trimEnd()+`
446
+ `);Ge.default.appendFileSync(s,i+n.trimEnd()+`
447
447
 
448
- `)}function Hh(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}
448
+ `)}function Qh(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}
449
449
  Finding \`${t.id}\` [${t.severity}] was marked **${e}**`+(r?` by ${r}`:"")+`.${n?` Reason: ${n}`:""}
450
- `+(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 Kh(t,e){return`## ${new Date().toISOString().slice(0,10)} \xB7 taught${e?` by ${e}`:""}
451
- ${t.trim()}`}function Gh(t){let e=[];for(let r of qh.KnowledgeRole.options)for(let s of Bh(r,t))e.push({role:r,...s});let n=Lh(t);return n&&e.push({role:"implement",level:"project",source:"memory",name:"incidents.md",content:n.slice(-3e4),editable:!1}),e}function Wh(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"?Mt.default.join(Gl(e),s):r==="lessons"?Wl(t,e):Fh(t,e);He.default.mkdirSync(Mt.default.dirname(o),{recursive:!0}),He.default.writeFileSync(o,i,{mode:n==="org"?384:420})}var He,Mt,qh,Pv,Nv,Ov,jv,Uh,Mv,Oo=ne(()=>{"use strict";He=R(require("node:fs"),1),Mt=R(require("node:path"),1),qh=R(Re(),1);ci();Ee();Pv=`# Security baseline - what to check in any repo
450
+ `+(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 ep(t,e){return`## ${new Date().toISOString().slice(0,10)} \xB7 taught${e?` by ${e}`:""}
451
+ ${t.trim()}`}function tp(t){let e=[];for(let r of Jh.KnowledgeRole.options)for(let s of Xh(r,t))e.push({role:r,...s});let n=Zh(t);return n&&e.push({role:"implement",level:"project",source:"memory",name:"incidents.md",content:n.slice(-3e4),editable:!1}),e}function np(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"?Ut.default.join(nc(e),s):r==="lessons"?rc(t,e):Yh(t,e);Ge.default.mkdirSync(Ut.default.dirname(o),{recursive:!0}),Ge.default.writeFileSync(o,i,{mode:n==="org"?384:420})}var Ge,Ut,Jh,ak,lk,ck,uk,Vh,dk,zo=te(()=>{"use strict";Ge=E(require("node:fs"),1),Ut=E(require("node:path"),1),Jh=E(Re(),1);hi();Ae();ak=`# Security baseline - what to check in any repo
452
452
 
453
453
  Every rule has a stable id. Findings must cite the id they violate.
454
454
 
@@ -491,7 +491,7 @@ Every rule has a stable id. Findings must cite the id they violate.
491
491
  - **SEC-042** TLS/redirect handling that downgrades to http.
492
492
 
493
493
  Prioritize by real exploitability in THIS codebase, not by rule order.
494
- `,Nv=`# Test gaps - what to check in any repo
494
+ `,lk=`# Test gaps - what to check in any repo
495
495
 
496
496
  Every rule has a stable id. Findings must cite the id they violate.
497
497
 
@@ -521,7 +521,7 @@ Every rule has a stable id. Findings must cite the id they violate.
521
521
  flaky suspects.
522
522
 
523
523
  Report the GAP and why it is risky here, not generic coverage philosophy.
524
- `,Ov=`# GDPR readiness - data-protection audit for repos with EU exposure
524
+ `,ck=`# GDPR readiness - data-protection audit for repos with EU exposure
525
525
 
526
526
  FIRST decide exposure: if this product clearly has no EU users, no personal
527
527
  data, or is a purely static/internal tool, say so in ONE summary sentence and
@@ -565,7 +565,7 @@ rules below. Cite the rule id AND map the area to the closest GDPR article
565
565
 
566
566
  Severity: many users' data exposed or a missing legal-basis mechanism is
567
567
  high/critical; hygiene and documentation gaps are medium/low.
568
- `,jv=`# Architecture health - is this repository structurally sound?
568
+ `,uk=`# Architecture health - is this repository structurally sound?
569
569
 
570
570
  Every rule has a stable id. Findings must cite the id they violate. Judge
571
571
  against what THIS codebase is trying to be (a static site does not need
@@ -604,72 +604,73 @@ deviations.
604
604
 
605
605
  Summarize with an overall verdict: is this repository HEALTHY for its
606
606
  purpose, and what are the 2-3 structural moves with the best payoff?
607
- `,Uh={security:[{name:"baseline.md",content:Pv},{name:"gdpr.md",content:Ov}],testing:[{name:"test-gaps.md",content:Nv}],architecture:[{name:"architecture-health.md",content:jv}],functional:[],implement:[],compose:[]},Mv=["You are auditing code you can READ but never run or change.","You are auditing test coverage by READING code and tests","\\`area\\`"]});var Vl,y,zt=ne(()=>{"use strict";Vl=()=>new Date().toISOString(),y={info:t=>console.log(`${Vl()} [info] ${t}`),warn:t=>console.warn(`${Vl()} [warn] ${t}`),error:t=>console.error(`${Vl()} [error] ${t}`)}});function xs(t){for(let e of["TEST.md","TESTING.md","docs/TEST.md"]){let n=Yh.default.join(t,e);if(Vh.default.existsSync(n))return n}return null}function Is(t){let e=[];for(let n of t.matchAll(/```(?:bash|sh|shell)?\s*\n([\s\S]*?)```/g)){let r=n[1],s=r.split(`
608
- `).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#"));if(s.length){if(zv.test(r)){e.push(r.trim());continue}e.push(...s)}}return e.slice(0,10)}async function Cr(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 d=(0,Zh.spawn)("bash",["-lc",i],{cwd:t,env:{...process.env,CI:"1",FORCE_COLOR:"0"}}),p="",f=v=>{p+=v.toString(),p.length>2e5&&(p=p.slice(-1e5))};d.stdout.on("data",f),d.stderr.on("data",f);let w=setTimeout(()=>{d.kill("SIGKILL"),p+=`
609
- [killed: timed out]`},s);d.on("close",v=>{clearTimeout(w),c({command:i,exitCode:v??-1,durationMs:Date.now()-o,tail:p.slice(-4e3)})}),d.on("error",v=>{clearTimeout(w),c({command:i,exitCode:-1,durationMs:Date.now()-o,tail:String(v)})})});n.onProgress?.(`exit ${l.exitCode} in ${Math.round(l.durationMs/1e3)}s: ${i}`),r.push(l)}return r}var Zh,Vh,Yh,zv,jo=ne(()=>{"use strict";Zh=require("node:child_process"),Vh=R(require("node:fs"),1),Yh=R(require("node:path"),1);zv=/(^|\n)\s*(if|for|while|case|until)\s|\{\s*$|\)\s*\{|<<[-~]?\s*['"]?\w+|\\\s*$/});var Qh={};Kt(Qh,{crawlSite:()=>Dv,extractLinks:()=>Jh,formatCrawlReport:()=>Lv,pageIssues:()=>Xh});function Jh(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 Xh(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 Dv(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,d=async w=>{let v=Date.now();try{let _=await fetch(w,{redirect:"follow",signal:AbortSignal.timeout(15e3),headers:{"user-agent":"Allwright-functional-audit (reads pages, changes nothing)"}}),I=await _.arrayBuffer(),E=I.byteLength,C=new TextDecoder().decode(I.slice(0,3e6));return{status:_.status,html:C,ms:Date.now()-v,bytes:E}}catch{return{status:0,html:"",ms:Date.now()-v,bytes:0}}};for(;o.length&&s.pages.length<30&&Date.now()-r<12e4;){let w=o.shift(),{status:v,html:_,ms:I,bytes:E}=await d(w),C=/<title[^>]*>([\s\S]*?)<\/title>/i.exec(_)?.[1]?.trim()??"",Y=Xh({status:v,html:_,url:w,ms:I});if(v===0&&Y.push("did not respond at all (timeout or connection failure)"),s.pages.push({url:w,status:v,ms:I,bytes:E,title:C,linkedFrom:[...i.get(w)??[]].slice(0,3),issues:Y}),C&&c.set(C,[...c.get(C)??[],w]),v===200&&_)for(let X of Jh(_,w,n))i.has(X)||i.set(X,new Set),i.get(X).add(w),l.has(X)||(l.add(X),o.push(X))}let p=[...c.entries()].filter(([,w])=>w.length>1);for(let[w,v]of p.slice(0,5))s.notes.push(`${v.length} pages share the title "${w.slice(0,60)}" (${v.slice(0,3).join(", ")})`);return(await d(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 Lv(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(`
607
+ `,Vh={security:[{name:"baseline.md",content:ak},{name:"gdpr.md",content:ck}],testing:[{name:"test-gaps.md",content:lk}],architecture:[{name:"architecture-health.md",content:uk}],functional:[],implement:[],compose:[]},dk=["You are auditing code you can READ but never run or change.","You are auditing test coverage by READING code and tests","\\`area\\`"]});var ic,g,qt=te(()=>{"use strict";ic=()=>new Date().toISOString(),g={info:t=>console.log(`${ic()} [info] ${t}`),warn:t=>console.warn(`${ic()} [warn] ${t}`),error:t=>console.error(`${ic()} [error] ${t}`)}});function Rs(t){for(let e of["TEST.md","TESTING.md","docs/TEST.md"]){let n=ip.default.join(t,e);if(sp.default.existsSync(n))return n}return null}function Es(t){let e=[];for(let n of t.matchAll(/```(?:bash|sh|shell)?\s*\n([\s\S]*?)```/g)){let r=n[1],s=r.split(`
608
+ `).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#"));if(s.length){if(hk.test(r)){e.push(r.trim());continue}e.push(...s)}}return e.slice(0,10)}async function Pr(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 d=(0,rp.spawn)("bash",["-lc",i],{cwd:t,env:{...process.env,CI:"1",FORCE_COLOR:"0"}}),p="",f=v=>{p+=v.toString(),p.length>2e5&&(p=p.slice(-1e5))};d.stdout.on("data",f),d.stderr.on("data",f);let w=setTimeout(()=>{d.kill("SIGKILL"),p+=`
609
+ [killed: timed out]`},s);d.on("close",v=>{clearTimeout(w),c({command:i,exitCode:v??-1,durationMs:Date.now()-o,tail:p.slice(-4e3)})}),d.on("error",v=>{clearTimeout(w),c({command:i,exitCode:-1,durationMs:Date.now()-o,tail:String(v)})})});n.onProgress?.(`exit ${l.exitCode} in ${Math.round(l.durationMs/1e3)}s: ${i}`),r.push(l)}return r}var rp,sp,ip,hk,Do=te(()=>{"use strict";rp=require("node:child_process"),sp=E(require("node:fs"),1),ip=E(require("node:path"),1);hk=/(^|\n)\s*(if|for|while|case|until)\s|\{\s*$|\)\s*\{|<<[-~]?\s*['"]?\w+|\\\s*$/});var lp={};$t(lp,{crawlSite:()=>pk,extractLinks:()=>op,formatCrawlReport:()=>fk,pageIssues:()=>ap});function op(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 ap(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 pk(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,d=async w=>{let v=Date.now();try{let _=await fetch(w,{redirect:"follow",signal:AbortSignal.timeout(15e3),headers:{"user-agent":"Allwright-functional-audit (reads pages, changes nothing)"}}),I=await _.arrayBuffer(),R=I.byteLength,C=new TextDecoder().decode(I.slice(0,3e6));return{status:_.status,html:C,ms:Date.now()-v,bytes:R}}catch{return{status:0,html:"",ms:Date.now()-v,bytes:0}}};for(;o.length&&s.pages.length<30&&Date.now()-r<12e4;){let w=o.shift(),{status:v,html:_,ms:I,bytes:R}=await d(w),C=/<title[^>]*>([\s\S]*?)<\/title>/i.exec(_)?.[1]?.trim()??"",V=ap({status:v,html:_,url:w,ms:I});if(v===0&&V.push("did not respond at all (timeout or connection failure)"),s.pages.push({url:w,status:v,ms:I,bytes:R,title:C,linkedFrom:[...i.get(w)??[]].slice(0,3),issues:V}),C&&c.set(C,[...c.get(C)??[],w]),v===200&&_)for(let J of op(_,w,n))i.has(J)||i.set(J,new Set),i.get(J).add(w),l.has(J)||(l.add(J),o.push(J))}let p=[...c.entries()].filter(([,w])=>w.length>1);for(let[w,v]of p.slice(0,5))s.notes.push(`${v.length} pages share the title "${w.slice(0,60)}" (${v.slice(0,3).join(", ")})`);return(await d(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 fk(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(`
610
610
  `);return`CRAWL OF THE RUNNING SITE (${t.baseUrl}) - gathered by the runner just now, GET only, same-origin only:
611
611
  ${e}
612
612
 
613
613
  SITE-WIDE:
614
614
  ${t.notes.map(n=>`- ${n}`).join(`
615
- `)}`}var ep=ne(()=>{"use strict"});async function Es(t){let{packs:e,lessons:n}=Ts(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:v,formatCrawlReport:_}=await Promise.resolve().then(()=>(ep(),Qh));try{r=_(await v(t.baseUrl.trim()))}catch(I){return{ok:!1,error:`could not crawl ${t.baseUrl}: ${I instanceof Error?I.message:"unreachable"}`}}}let s="";if(t.scope.kind==="ticket"&&t.scope.ref){let v=t.scope.ref,_="";try{let E=await t.jira.getIssue(v);_=`Ticket ${v}: ${E.summary}
615
+ `)}`}var cp=te(()=>{"use strict"});async function As(t){let{packs:e,lessons:n}=Is(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:v,formatCrawlReport:_}=await Promise.resolve().then(()=>(cp(),lp));try{r=_(await v(t.baseUrl.trim()))}catch(I){return{ok:!1,error:`could not crawl ${t.baseUrl}: ${I instanceof Error?I.message:"unreachable"}`}}}let s="";if(t.scope.kind==="ticket"&&t.scope.ref){let v=t.scope.ref,_="";try{let R=await t.jira.getIssue(v);_=`Ticket ${v}: ${R.summary}
616
616
 
617
- ${E.description}`.slice(0,4e3)}catch{_=`Ticket ${v} (could not fetch its text from Jira).`}let I=await Sl(t.repoPath,v).catch(()=>null);if(I){let{base:E,stat:C,diff:Y}=await xo(t.repoPath,I).catch(()=>({base:"",stat:"",diff:""}));s=`${_}
617
+ ${R.description}`.slice(0,4e3)}catch{_=`Ticket ${v} (could not fetch its text from Jira).`}let I=await Nl(t.repoPath,v).catch(()=>null);if(I){let{base:R,stat:C,diff:V}=await Eo(t.repoPath,I).catch(()=>({base:"",stat:"",diff:""}));s=`${_}
618
618
 
619
- Its implementation branch \`${I}\` vs \`${E}\`:
619
+ Its implementation branch \`${I}\` vs \`${R}\`:
620
620
  \`\`\`
621
621
  ${C}\`\`\`
622
622
  \`\`\`diff
623
- ${Y}
623
+ ${V}
624
624
  \`\`\``}else s=`${_}
625
625
 
626
- No implementation branch found for ${v} - audit the parts of the codebase this ticket touches or would touch.`}else if(t.scope.kind==="branch"&&t.scope.ref){let{base:v,stat:_,diff:I}=await xo(t.repoPath,t.scope.ref);s=`The diff of \`${t.scope.ref}\` vs \`${v}\`:
626
+ No implementation branch found for ${v} - audit the parts of the codebase this ticket touches or would touch.`}else if(t.scope.kind==="branch"&&t.scope.ref){let{base:v,stat:_,diff:I}=await Eo(t.repoPath,t.scope.ref);s=`The diff of \`${t.scope.ref}\` vs \`${v}\`:
627
627
  \`\`\`
628
628
  ${_}\`\`\`
629
629
  \`\`\`diff
630
630
  ${I}
631
- \`\`\``}let i,o;if(t.role==="testing"){let v=xs(t.repoPath),_=v?Is(tp.default.readFileSync(v,"utf8")):[];_.length&&(y.info(`Audit (testing): executing ${_.length} TEST.md command(s)`),o=await Cr(t.repoPath,_,{onProgress:I=>y.info(`[test-run] ${I}`)}),i=o.map(I=>`$ ${I.command}
631
+ \`\`\``}let i,o;if(t.role==="testing"){let v=Rs(t.repoPath),_=v?Es(up.default.readFileSync(v,"utf8")):[];_.length&&(g.info(`Audit (testing): executing ${_.length} TEST.md command(s)`),o=await Pr(t.repoPath,_,{onProgress:I=>g.info(`[test-run] ${I}`)}),i=o.map(I=>`$ ${I.command}
632
632
  (exit ${I.exitCode}, ${Math.round(I.durationMs/1e3)}s)
633
633
  ${I.tail.slice(-2e3)}`).join(`
634
634
 
635
635
  ---
636
636
 
637
- `))}let l=t.model||t.agent.adapter.deepModel,c=t.detailLevel??"technical",d=await t.agent.adapter.run({repoPath:t.repoPath,prompt:Ih(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,Yl.randomUUID)(),model:l,onLog:(v,_)=>{v==="agent"&&y.info(`[audit:${t.role}] ${_.slice(0,160)}`)}}),p=Eh(d.resultText);if("error"in p)return{ok:!1,error:p.error};let f=Rh(t.repoPath,p.findings);for(let v of f.droppedFindings)y.warn(`[audit:${t.role}] dropped "${v.title}" - cited files do not exist: `+v.files.join(", "));let w={id:(0,Yl.randomUUID)(),role:t.role,createdAt:new Date().toISOString(),model:d.model||l,summary:p.summary,packNames:e.map(v=>v.name),findings:f.findings,costUsd:d.costUsd??0,ticketed:{},verdicts:{},lessonsWritten:[],scope:t.scope,detailLevel:c,...o?{testRun:o}:{}};return Nh(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 Yl,tp,Mo=ne(()=>{"use strict";Yl=require("node:crypto"),tp=R(require("node:fs"),1);Ah();No();jt();Oo();zt();jo()});function zo(t){return t==="operator"?`
637
+ `))}let l=t.model||t.agent.adapter.deepModel,c=t.detailLevel??"technical",d=await t.agent.adapter.run({repoPath:t.repoPath,prompt:Oh(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,oc.randomUUID)(),model:l,onLog:(v,_)=>{v==="agent"&&g.info(`[audit:${t.role}] ${_.slice(0,160)}`)}}),p=Mh(d.resultText);if("error"in p)return{ok:!1,error:p.error};let f=zh(t.repoPath,p.findings);for(let v of f.droppedFindings)g.warn(`[audit:${t.role}] dropped "${v.title}" - cited files do not exist: `+v.files.join(", "));let w={id:(0,oc.randomUUID)(),role:t.role,createdAt:new Date().toISOString(),model:d.model||l,summary:p.summary,packNames:e.map(v=>v.name),findings:f.findings,costUsd:d.costUsd??0,ticketed:{},verdicts:{},lessonsWritten:[],scope:t.scope,detailLevel:c,...o?{testRun:o}:{}};return Fh(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 oc,up,Lo=te(()=>{"use strict";oc=require("node:crypto"),up=E(require("node:fs"),1);Dh();Mo();Lt();zo();qt();Do()});function Uo(t){if(t==="operator")return`
638
638
 
639
639
  OPERATOR MODE - this run has FULL access: shell commands as this machine's runner user, and file edits anywhere. A person explicitly granted this for a limited window, every tool call is recorded, and they are watching live. Rules:
640
640
  - SAY WHAT YOU ARE ABOUT TO RUN and why, in one line, before commands that change state; read-only commands need no preamble.
641
641
  - Prefer the least destructive route: inspect before you modify, reload before you restart, never delete what you can rename.
642
642
  - NEVER print secret VALUES (tokens, keys, passwords, connection strings) into the conversation - name the file or variable instead.
643
643
  - Deploys still go through their own path: do not edit saved deploy recipes or re-implement a deploy by hand here; say so and point at the Deploy button instead.
644
- - End with a short list of every state-changing command you ran and what it did.`:`
644
+ - End with a short list of every state-changing command you ran and what it did.`;let e=`
645
645
 
646
646
  YOUR CAPABILITIES IN THIS RUN - state them accurately, never guess:
647
647
  - 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.
648
- `+(t==="edit_no_shell"?`- You CAN read files and CREATE or EDIT files inside this working directory.
648
+ `,n=t==="edit_no_shell"?`- You CAN read files and CREATE or EDIT files inside this working directory.
649
649
  `:`- You can ONLY read: Read, Glob and Grep inside this working directory. You cannot create or change a single file.
650
- `)+'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 Jl=ne(()=>{"use strict"});function Fv(t){if(process.env.ANTHROPIC_API_KEY)return"API key";let e=t??Do.default.join(np.default.homedir(),".claude");try{if(Xl.default.existsSync(Do.default.join(e,".credentials.json"))||Xl.default.existsSync(Do.default.join(e,"credentials.json")))return"subscription"}catch{}return"unknown"}function Bv(t,e,n){let r=o=>typeof e[o]=="string"?e[o]:"",i=(o=>o.startsWith(n+"/")?o.slice(n.length+1):o)(r("file_path")||r("path")||r("notebook_path"));switch(t){case"Read":return{verb:"Read",target:i};case"Glob":return{verb:"Looked for files",target:r("pattern")};case"Grep":return{verb:"Searched for",target:r("pattern")};case"Bash":return{verb:"Ran",target:r("description")||r("command")};case"Edit":case"MultiEdit":return{verb:"Edited",target:i};case"Write":return{verb:"Wrote",target:i};case"NotebookEdit":return{verb:"Edited",target:i};case"WebFetch":return{verb:"Fetched",target:r("url")};case"WebSearch":return{verb:"Searched the web for",target:r("query")};case"Task":return{verb:"Started a sub-agent",target:r("description")};case"TodoWrite":return{verb:"Updated its plan",target:""};default:return{verb:`Used ${t}`,target:r("description")}}}async function Hv(t){let e=["-p","--output-format","stream-json","--verbose","--allowedTools",qv[t.mode].join(","),"--max-turns",String(t.maxTurns??60),...t.model?["--model",t.model]:[],...t.resume?["--resume",t.sessionId]:["--session-id",t.sessionId]],n=Fv(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,rp.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=!1,c=0,d=0,p=0,f=0,w=()=>{if(!t.onUsage)return;let X=Date.now();X-f<Uv||(f=X,t.onUsage({inputTokens:c,outputTokens:d,cacheReadTokens:p,turns:o}))},v=!1,_=()=>{v||(v=!0,clearTimeout(E),t.signal?.removeEventListener("abort",I),r(i))},I=()=>{i.cancelled=!0,i.error="stopped from the dashboard",t.onLog("error",i.error),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),3e3).unref()};t.signal?.addEventListener("abort",I,{once:!0});let E=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+zo(t.mode)),s.stdin.end(),sp.default.createInterface({input:s.stdout}).on("line",X=>{if(!X.trim())return;let $;try{$=JSON.parse(X)}catch{t.onLog("agent",X.slice(0,1e3));return}if($.type==="system"&&$.subtype==="init")i.model=typeof $.model=="string"?$.model:void 0,t.onLog("info",`Claude Code session started (model: ${$.model??"default"})`);else if($.type==="assistant"){o+=1,l=$.message?.stop_reason==="max_tokens",l&&t.onLog("error","the agent hit its output limit mid-message - this reply is cut off, not finished");let b=$.message?.usage;if(b){c+=Number(b.input_tokens??0)+Number(b.cache_creation_input_tokens??0);let U=JSON.stringify($.message?.content??[]).length;d+=Math.max(Number(b.output_tokens??0),Math.round(U/4)),p+=Number(b.cache_read_input_tokens??0),w()}for(let U of $.message?.content??[])if(U.type==="text"&&U.text?.trim())t.onLog("agent",U.text.trim().slice(0,4e3));else if(U.type==="tool_use"){let j=U.input??{},H=["file_path","path","pattern","command","description","url"].map(u=>typeof j[u]=="string"?`${u}=${j[u]}`:null).filter(Boolean).join(" "),q=JSON.stringify(j).slice(0,400);if(t.onLog("info",`tool ${U.name} ${H?`${H} `:""}${q}`),t.onTool){let u=Bv(String(U.name??""),j,t.repoPath);t.onTool(u.verb,u.target.slice(0,200))}}}else $.type==="result"&&(i.costUsd=Number($.total_cost_usd??0),i.inputTokens=Number($.usage?.input_tokens??0)+Number($.usage?.cache_creation_input_tokens??0),i.outputTokens=Number($.usage?.output_tokens??0),c=Math.max(i.inputTokens,c),d=Math.max(i.outputTokens,d),i.inputTokens=c,i.outputTokens=d,p=Number($.usage?.cache_read_input_tokens??p),i.cacheReadTokens=p,t.onUsage&&(t.onUsage({inputTokens:c,outputTokens:d,cacheReadTokens:p,costUsd:i.costUsd,turns:o}),f=Date.now()),$.subtype==="success"&&!$.is_error?(i.ok=!0,i.resultText=String($.result??""),i.outputTruncated=l):$.subtype==="error_max_turns"?(i.turnLimitHit=!0,i.error=`hit the ${t.maxTurns??60}-turn limit before finishing`):i.error||(i.error=$.subtype==="error_during_execution"?"the agent stopped mid-work before it could finish - the session was interrupted or hit an internal limit":String($.result??$.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 Y="";s.stderr.on("data",X=>{Y=(Y+X.toString()).slice(-2e3)}),s.on("error",X=>{i.error=`failed to start ${t.bin}: ${X.message}`,t.onLog("error",i.error),_()}),s.on("close",X=>{!i.ok&&!i.error&&(i.error=i.timedOut?i.error:`claude exited with code ${X}${Y?`: ${Y.slice(-500)}`:""}`),_()})})}var Xl,np,Do,rp,sp,ip,Uv,qv,Lo,op=ne(()=>{"use strict";Xl=R(require("node:fs"),1),np=R(require("node:os"),1),Do=R(require("node:path"),1),rp=require("node:child_process"),sp=R(require("node:readline"),1),ip=R(Re(),1);Jl();Uv=4e3,qv={read_only:["Read(./**)","Glob(./**)","Grep(./**)"],edit_no_shell:["Read(./**)","Glob(./**)","Grep(./**)","Edit(./**)","Write(./**)"],operator:["Bash","Read","Glob","Grep","Edit","Write"]};Lo={id:"claude-code",displayName:"Claude Code",fastModel:"claude-sonnet-5",deepModel:"claude-fable-5",capabilities:ip.REGISTERED_AGENTS.find(t=>t.id==="claude-code").capabilities,run:Hv}});async function Kv(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,ap.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+zo(t.mode)),r.stdin.end(),lp.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 v=w.item??w.msg??w,_=v?.type??w.type,I=v?.text??v?.message??"";_==="agent_message"&&typeof I=="string"&&I.trim()?(i=I,t.onLog("agent",I.trim().slice(0,4e3))):_==="command_execution"||_==="exec_command_begin"?t.onLog("info",`tool ${String(v?.command??"").slice(0,300)}`):_==="error"&&typeof I=="string"&&I&&t.onLog("error",I.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 ap,lp,cp,Ql,up=ne(()=>{"use strict";ap=require("node:child_process"),lp=R(require("node:readline"),1),cp=R(Re(),1);Jl();Ql={id:"codex",fastModel:"",deepModel:"",displayName:"OpenAI Codex CLI (experimental)",capabilities:cp.REGISTERED_AGENTS.find(t=>t.id==="codex").capabilities,run:Kv}});function Je(t){return Gv[t||$r.DEFAULT_AGENT_ID]??null}function Xe(t,e){return!e||e===Lo.id?t.claudeBin:t.agents[e]?.bin??e}function jn(t,e){let n=Je(t);if(!n)return`no agent adapter named "${t}" on this runner - update the runner, or set the rule's agent to "${$r.DEFAULT_AGENT_ID}"`;let r=(0,$r.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 Ce(t,e,n){let r=e.defaultAgent||$r.DEFAULT_AGENT_ID,s=Je(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,$r.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:Xe(t,s.id)}}var $r,Gv,Dt=ne(()=>{"use strict";$r=R(Re(),1);op();up();Gv={[Lo.id]:Lo,[Ql.id]:Ql}});function sn(t,e){return t.replace(/\{\{(\w+)\}\}/g,(n,r)=>r in e?e[r]:n)}var ec=ne(()=>{"use strict"});function Xv(t){let e=[],n=(r,s)=>{if(s>4||e.length>=200)return;let i;try{i=tc.default.readdirSync(r,{withFileTypes:!0})}catch{return}for(let o of i){if(o.name.startsWith(".")||Jv.has(o.name))continue;let l=Uo.default.join(r,o.name);o.isDirectory()?n(l,s+1):o.isFile()&&/\.md$/i.test(o.name)&&e.push(l)}};return n(t,0),e}function qo(t){let e=[],n=0;for(let r of Xv(t)){if(n>=Wv||e.join(`
651
- `).length>Yv)break;let s=Uo.default.relative(t,r);if(Uo.default.basename(r).toUpperCase()==="CLAUDE.MD")continue;let i;try{i=tc.default.readFileSync(r,"utf8")}catch{continue}let o=i.split(`
652
- `);if(o.length<Zv)continue;let l=[],c=!1;for(let d=0;d<o.length;d++){let p=o[d];if(/^\s*(```|~~~)/.test(p)){c=!c;continue}if(!c&&/^#{1,3}\s+\S/.test(p)&&(l.push(` L${d+1} ${p.trim().slice(0,110)}`),l.length>=Vv)){l.push(" \u2026 more headings follow in the file");break}}l.length<2||(e.push(`${s} (${o.length} lines)`),e.push(...l),n++)}return e.length?`
650
+ `,r=t==="read_only_web"||t==="edit_no_shell_web"?`- You CAN search the public web (WebSearch) and fetch public pages (WebFetch) - use them for current documentation, error messages, versions and comparisons. Never put code from this repository, file paths, or anything secret into a query or URL, and never fetch private/internal addresses.
651
+ `:"";return e+n+r+'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 ac=te(()=>{"use strict"});function yk(t){if(process.env.ANTHROPIC_API_KEY)return"API key";let e=t??qo.default.join(dp.default.homedir(),".claude");try{if(lc.default.existsSync(qo.default.join(e,".credentials.json"))||lc.default.existsSync(qo.default.join(e,"credentials.json")))return"subscription"}catch{}return"unknown"}function bk(t,e,n){let r=o=>typeof e[o]=="string"?e[o]:"",i=(o=>o.startsWith(n+"/")?o.slice(n.length+1):o)(r("file_path")||r("path")||r("notebook_path"));switch(t){case"Read":return{verb:"Read",target:i};case"Glob":return{verb:"Looked for files",target:r("pattern")};case"Grep":return{verb:"Searched for",target:r("pattern")};case"Bash":return{verb:"Ran",target:r("description")||r("command")};case"Edit":case"MultiEdit":return{verb:"Edited",target:i};case"Write":return{verb:"Wrote",target:i};case"NotebookEdit":return{verb:"Edited",target:i};case"WebFetch":return{verb:"Fetched",target:r("url")};case"WebSearch":return{verb:"Searched the web for",target:r("query")};case"Task":return{verb:"Started a sub-agent",target:r("description")};case"TodoWrite":return{verb:"Updated its plan",target:""};default:return{verb:`Used ${t}`,target:r("description")}}}async function wk(t){let e=["-p","--output-format","stream-json","--verbose","--allowedTools",gk[t.mode].join(","),"--max-turns",String(t.maxTurns??60),...t.model?["--model",t.model]:[],...t.resume?["--resume",t.sessionId]:["--session-id",t.sessionId]],n=yk(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,hp.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=!1,c=0,d=0,p=0,f=0,w=()=>{if(!t.onUsage)return;let J=Date.now();J-f<mk||(f=J,t.onUsage({inputTokens:c,outputTokens:d,cacheReadTokens:p,turns:o}))},v=!1,_=()=>{v||(v=!0,clearTimeout(R),t.signal?.removeEventListener("abort",I),r(i))},I=()=>{i.cancelled=!0,i.error="stopped from the dashboard",t.onLog("error",i.error),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),3e3).unref()};t.signal?.addEventListener("abort",I,{once:!0});let R=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+Uo(t.mode)),s.stdin.end(),pp.default.createInterface({input:s.stdout}).on("line",J=>{if(!J.trim())return;let $;try{$=JSON.parse(J)}catch{t.onLog("agent",J.slice(0,1e3));return}if($.type==="system"&&$.subtype==="init")i.model=typeof $.model=="string"?$.model:void 0,t.onLog("info",`Claude Code session started (model: ${$.model??"default"})`);else if($.type==="assistant"){o+=1,l=$.message?.stop_reason==="max_tokens",l&&t.onLog("error","the agent hit its output limit mid-message - this reply is cut off, not finished");let b=$.message?.usage;if(b){c+=Number(b.input_tokens??0)+Number(b.cache_creation_input_tokens??0);let U=JSON.stringify($.message?.content??[]).length;d+=Math.max(Number(b.output_tokens??0),Math.round(U/4)),p+=Number(b.cache_read_input_tokens??0),w()}for(let U of $.message?.content??[])if(U.type==="text"&&U.text?.trim())t.onLog("agent",U.text.trim().slice(0,4e3));else if(U.type==="tool_use"){let j=U.input??{},K=["file_path","path","pattern","command","description","url"].map(u=>typeof j[u]=="string"?`${u}=${j[u]}`:null).filter(Boolean).join(" "),F=JSON.stringify(j).slice(0,400);if(t.onLog("info",`tool ${U.name} ${K?`${K} `:""}${F}`),t.onTool){let u=bk(String(U.name??""),j,t.repoPath);t.onTool(u.verb,u.target.slice(0,200))}}}else $.type==="result"&&(i.costUsd=Number($.total_cost_usd??0),i.inputTokens=Number($.usage?.input_tokens??0)+Number($.usage?.cache_creation_input_tokens??0),i.outputTokens=Number($.usage?.output_tokens??0),c=Math.max(i.inputTokens,c),d=Math.max(i.outputTokens,d),i.inputTokens=c,i.outputTokens=d,p=Number($.usage?.cache_read_input_tokens??p),i.cacheReadTokens=p,t.onUsage&&(t.onUsage({inputTokens:c,outputTokens:d,cacheReadTokens:p,costUsd:i.costUsd,turns:o}),f=Date.now()),$.subtype==="success"&&!$.is_error?(i.ok=!0,i.resultText=String($.result??""),i.outputTruncated=l):$.subtype==="error_max_turns"?(i.turnLimitHit=!0,i.error=`hit the ${t.maxTurns??60}-turn limit before finishing`):i.error||(i.error=$.subtype==="error_during_execution"?"the agent stopped mid-work before it could finish - the session was interrupted or hit an internal limit":String($.result??$.subtype??"unknown Claude Code error"),/rate.?limit|usage limit|limit (reached|exceeded)|overloaded/i.test(i.error)&&(i.error=`Claude usage limit hit for this account - the run will work again once the limit window resets. Original error: ${i.error.slice(0,400)}`)))});let V="";s.stderr.on("data",J=>{V=(V+J.toString()).slice(-2e3)}),s.on("error",J=>{i.error=`failed to start ${t.bin}: ${J.message}`,t.onLog("error",i.error),_()}),s.on("close",J=>{!i.ok&&!i.error&&(i.error=i.timedOut?i.error:`claude exited with code ${J}${V?`: ${V.slice(-500)}`:""}`),_()})})}var lc,dp,qo,hp,pp,fp,mk,gk,Fo,mp=te(()=>{"use strict";lc=E(require("node:fs"),1),dp=E(require("node:os"),1),qo=E(require("node:path"),1),hp=require("node:child_process"),pp=E(require("node:readline"),1),fp=E(Re(),1);ac();mk=4e3,gk={read_only:["Read(./**)","Glob(./**)","Grep(./**)"],edit_no_shell:["Read(./**)","Glob(./**)","Grep(./**)","Edit(./**)","Write(./**)"],read_only_web:["Read(./**)","Glob(./**)","Grep(./**)","WebSearch","WebFetch"],edit_no_shell_web:["Read(./**)","Glob(./**)","Grep(./**)","Edit(./**)","Write(./**)","WebSearch","WebFetch"],operator:["Bash","Read","Glob","Grep","Edit","Write"]};Fo={id:"claude-code",displayName:"Claude Code",fastModel:"claude-sonnet-5",deepModel:"claude-fable-5",capabilities:fp.REGISTERED_AGENTS.find(t=>t.id==="claude-code").capabilities,run:wk}});async function vk(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,gp.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+Uo(t.mode)),r.stdin.end(),yp.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 v=w.item??w.msg??w,_=v?.type??w.type,I=v?.text??v?.message??"";_==="agent_message"&&typeof I=="string"&&I.trim()?(i=I,t.onLog("agent",I.trim().slice(0,4e3))):_==="command_execution"||_==="exec_command_begin"?t.onLog("info",`tool ${String(v?.command??"").slice(0,300)}`):_==="error"&&typeof I=="string"&&I&&t.onLog("error",I.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 gp,yp,bp,cc,wp=te(()=>{"use strict";gp=require("node:child_process"),yp=E(require("node:readline"),1),bp=E(Re(),1);ac();cc={id:"codex",fastModel:"",deepModel:"",displayName:"OpenAI Codex CLI (experimental)",capabilities:bp.REGISTERED_AGENTS.find(t=>t.id==="codex").capabilities,run:vk}});function et(t){return kk[t||Nr.DEFAULT_AGENT_ID]??null}function Be(t,e){return!e||e===Fo.id?t.claudeBin:t.agents[e]?.bin??e}function Ln(t,e){let n=et(t);if(!n)return`no agent adapter named "${t}" on this runner - update the runner, or set the rule's agent to "${Nr.DEFAULT_AGENT_ID}"`;let r=(0,Nr.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 Ce(t,e,n,r){let s=(r??"").trim(),i=s||e.defaultAgent||Nr.DEFAULT_AGENT_ID,o=s?"the agent chosen for this chat":"this project's default agent",l=s?"Pick another agent for this chat":"Change the project's agent",c=et(i);if(!c)return{error:`${o} "${i}" is not on this runner - update the runner, or change the project's agent`};let d=(0,Nr.missingAgentCapabilities)(c.id,n);return d&&d.length?{error:`${o} "${c.displayName}" cannot power this - it lacks ${d.join(", ")}. ${l}, or use one that can.`}:{adapter:c,bin:Be(t,c.id)}}var Nr,kk,xt=te(()=>{"use strict";Nr=E(Re(),1);mp();wp();kk={[Fo.id]:Fo,[cc.id]:cc}});function cn(t,e){return t.replace(/\{\{(\w+)\}\}/g,(n,r)=>r in e?e[r]:n)}var uc=te(()=>{"use strict"});function Rk(t){let e=[],n=(r,s)=>{if(s>4||e.length>=200)return;let i;try{i=dc.default.readdirSync(r,{withFileTypes:!0})}catch{return}for(let o of i){if(o.name.startsWith(".")||Ik.has(o.name))continue;let l=Bo.default.join(r,o.name);o.isDirectory()?n(l,s+1):o.isFile()&&/\.md$/i.test(o.name)&&e.push(l)}};return n(t,0),e}function Ho(t){let e=[],n=0;for(let r of Rk(t)){if(n>=_k||e.join(`
652
+ `).length>xk)break;let s=Bo.default.relative(t,r);if(Bo.default.basename(r).toUpperCase()==="CLAUDE.MD")continue;let i;try{i=dc.default.readFileSync(r,"utf8")}catch{continue}let o=i.split(`
653
+ `);if(o.length<Sk)continue;let l=[],c=!1;for(let d=0;d<o.length;d++){let p=o[d];if(/^\s*(```|~~~)/.test(p)){c=!c;continue}if(!c&&/^#{1,3}\s+\S/.test(p)&&(l.push(` L${d+1} ${p.trim().slice(0,110)}`),l.length>=Tk)){l.push(" \u2026 more headings follow in the file");break}}l.length<2||(e.push(`${s} (${o.length} lines)`),e.push(...l),n++)}return e.length?`
653
654
 
654
655
  DOCUMENT INDEX - the repo's larger Markdown documents, with 1-based line numbers (generated; the files themselves are the truth):
655
656
  ${e.join(`
656
657
  `)}
657
- Read a document's relevant SECTION with Read offset/limit using these line numbers - read one end-to-end only when the task genuinely needs all of it.`:""}var tc,Uo,Wv,Zv,Vv,Yv,Jv,dp=ne(()=>{"use strict";tc=R(require("node:fs"),1),Uo=R(require("node:path"),1),Wv=24,Zv=120,Vv=30,Yv=6e3,Jv=new Set(["node_modules","dist","build","out","coverage","vendor","target"])});function mp(){return hp.default.join(se(),"repo-briefs.json")}function rc(){try{return ek.parse(JSON.parse(ui.default.readFileSync(mp(),"utf8")))}catch{return{}}}function nk(t){ui.default.mkdirSync(se(),{recursive:!0,mode:448});let e=mp();ui.default.writeFileSync(e+".tmp",JSON.stringify(t,null,2)+`
658
- `,{mode:384}),ui.default.renameSync(e+".tmp",e)}function rk(t){return new Promise(e=>{(0,pp.execFile)("git",["-C",t,"rev-parse","HEAD"],{timeout:1e4},(n,r)=>e(n?"":r.trim()))})}function di(t){let e=rc()[t];return e?.brief?`
658
+ Read a document's relevant SECTION with Read offset/limit using these line numbers - read one end-to-end only when the task genuinely needs all of it.`:""}var dc,Bo,_k,Sk,Tk,xk,Ik,vp=te(()=>{"use strict";dc=E(require("node:fs"),1),Bo=E(require("node:path"),1),_k=24,Sk=120,Tk=30,xk=6e3,Ik=new Set(["node_modules","dist","build","out","coverage","vendor","target"])});function Tp(){return kp.default.join(ie(),"repo-briefs.json")}function pc(){try{return Ak.parse(JSON.parse(pi.default.readFileSync(Tp(),"utf8")))}catch{return{}}}function $k(t){pi.default.mkdirSync(ie(),{recursive:!0,mode:448});let e=Tp();pi.default.writeFileSync(e+".tmp",JSON.stringify(t,null,2)+`
659
+ `,{mode:384}),pi.default.renameSync(e+".tmp",e)}function Pk(t){return new Promise(e=>{(0,_p.execFile)("git",["-C",t,"rev-parse","HEAD"],{timeout:1e4},(n,r)=>e(n?"":r.trim()))})}function fi(t){let e=pc()[t];return e?.brief?`
659
660
 
660
661
  REPO ORIENTATION (machine-generated from commit ${e.headCommit.slice(0,10)} - treat as hints and verify in code; where this disagrees with the repo or its CLAUDE.md, they win):
661
662
  ${e.brief}
662
- `:""}function Fo(t,e){let n=t.project.repoName;nc.has(n)||(nc.add(n),(async()=>{try{let r=await rk(t.repoPath);if(!r||rc()[n]?.headCommit===r)return;let s=Ce(e,t.project,"chat");if("error"in s)return;let i=await s.adapter.run({repoPath:t.repoPath,prompt:sk,timeoutSeconds:240,bin:s.bin,mode:"read_only",maxTurns:20,model:s.adapter.fastModel,sessionId:(0,fp.randomUUID)(),onLog:()=>{}}),o=i.ok?i.resultText.trim().slice(0,tk):"";if(!o)return;let l=rc();l[n]={brief:o,headCommit:r,generatedAt:new Date().toISOString()},nk(l),y.info(`repo brief refreshed for ${n} (${o.length} chars, HEAD ${r.slice(0,10)})`)}catch(r){y.warn(`repo brief refresh failed for ${n}: ${r instanceof Error?r.message:r}`)}finally{nc.delete(n)}})())}var ui,hp,pp,fp,Qv,ek,tk,sk,nc,sc=ne(()=>{"use strict";ui=R(require("node:fs"),1),hp=R(require("node:path"),1),pp=require("node:child_process"),fp=require("node:crypto");vn();Ee();Dt();zt();Qv=k.object({brief:k.string(),headCommit:k.string(),generatedAt:k.string()}),ek=k.record(Qv),tk=4e3;sk=`Write an orientation brief for an AI agent that will work in this repository cold. Under 450 words, plain statements, these headings:
663
+ `:""}function Ko(t,e){let n=t.project.repoName;hc.has(n)||(hc.add(n),(async()=>{try{let r=await Pk(t.repoPath);if(!r||pc()[n]?.headCommit===r)return;let s=Ce(e,t.project,"chat");if("error"in s)return;let i=await s.adapter.run({repoPath:t.repoPath,prompt:Nk,timeoutSeconds:240,bin:s.bin,mode:"read_only",maxTurns:20,model:s.adapter.fastModel,sessionId:(0,Sp.randomUUID)(),onLog:()=>{}}),o=i.ok?i.resultText.trim().slice(0,Ck):"";if(!o)return;let l=pc();l[n]={brief:o,headCommit:r,generatedAt:new Date().toISOString()},$k(l),g.info(`repo brief refreshed for ${n} (${o.length} chars, HEAD ${r.slice(0,10)})`)}catch(r){g.warn(`repo brief refresh failed for ${n}: ${r instanceof Error?r.message:r}`)}finally{hc.delete(n)}})())}var pi,kp,_p,Sp,Ek,Ak,Ck,Nk,hc,fc=te(()=>{"use strict";pi=E(require("node:fs"),1),kp=E(require("node:path"),1),_p=require("node:child_process"),Sp=require("node:crypto");Tn();Ae();xt();qt();Ek=k.object({brief:k.string(),headCommit:k.string(),generatedAt:k.string()}),Ak=k.record(Ek),Ck=4e3;Nk=`Write an orientation brief for an AI agent that will work in this repository cold. Under 450 words, plain statements, these headings:
663
664
  What this is: one or two lines.
664
665
  Layout: the directories that matter and what lives in each.
665
666
  Key files: the files most tasks touch or must not miss.
666
667
  Commands: how to build, test and run - only what you can verify from the repo.
667
668
  Gotchas: non-obvious facts that would waste an agent's time to rediscover.
668
- Do NOT repeat what CLAUDE.md already says - the agent reads that file itself; add what it lacks. Never include secrets, tokens or credential values. No preamble, no closing offer.`,nc=new Set});function bp(){try{return JSON.parse(hi.default.readFileSync(yp(),"utf8"))}catch{return{}}}function wp(t){hi.default.mkdirSync(se(),{recursive:!0,mode:448}),hi.default.writeFileSync(yp(),JSON.stringify(t,null,2),{mode:384})}function kp(t,e,n){let r=bp();r[vp(t,e)]={...n,at:new Date().toISOString()},wp(r)}function _p(t,e,n){let r=bp(),s=vp(t,e),i=r[s];return!i||(delete r[s],wp(r),i.branch!==n)||!hi.default.existsSync(i.worktreePath)?null:i}var hi,gp,ic,yp,vp,Sp=ne(()=>{"use strict";hi=R(require("node:fs"),1),gp=R(require("node:path"),1);Ee();ic=2,yp=()=>gp.default.join(se(),"timeout-sessions.json");vp=(t,e)=>`${t}:${e}`});var Pr={};Kt(Pr,{GitHubClient:()=>Fe});var ik,Fe,Tt=ne(()=>{"use strict";ik=process.env.TICKETPILOT_GITHUB_API??"https://api.github.com",Fe=class{constructor(e){this.token=e}token;async request(e,n,r){let s=await fetch(`${ik}${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 Tp(){return Rs.default.join(se(),"pending-runs.json")}function oc(){return Rs.default.join(se(),"pending-deploys.json")}function ac(){return Rs.default.join(se(),"pending-inputs.json")}function lc(){return Rs.default.join(se(),"merge-watch.json")}function cc(){return Rs.default.join(se(),"pending-pushes.json")}function uc(){let t=cc();if(!Ke.default.existsSync(t))return{};try{return hk.parse(JSON.parse(Ke.default.readFileSync(t,"utf8")))}catch{return{}}}function Bo(t){let e=uc();e[t.runId]=t,on(cc(),e)}function Ho(t){return uc()[t]??null}function dc(t){let e=uc();t in e&&(delete e[t],on(cc(),e))}function Ko(){let t=lc();if(!Ke.default.existsSync(t))return{};try{return fk.parse(JSON.parse(Ke.default.readFileSync(t,"utf8")))}catch{return{}}}function xp(t){let e=Ko();e[t.runId]=t,on(lc(),e)}function pi(t){let e=Ko();t in e&&(delete e[t],on(lc(),e))}function fi(){let t=Tp();if(!Ke.default.existsSync(t))return{};try{return ak.parse(JSON.parse(Ke.default.readFileSync(t,"utf8")))}catch{return{}}}function on(t,e){Ke.default.mkdirSync(se(),{recursive:!0,mode:448});let n=t+".tmp";Ke.default.writeFileSync(n,JSON.stringify(e,null,2)+`
669
- `,{mode:384}),Ke.default.renameSync(n,t),Ke.default.chmodSync(t,384)}function Ip(t){on(Tp(),t)}function xt(t){let e=fi();e[t.runId]=t,Ip(e)}function As(t){return fi()[t]??null}function Nr(t){let e=fi();t in e&&(delete e[t],Ip(e))}function hc(){let t=oc();if(!Ke.default.existsSync(t))return{};try{return ck.parse(JSON.parse(Ke.default.readFileSync(t,"utf8")))}catch{return{}}}function Ep(t){let e=hc();e[t.runId]=t,on(oc(),e)}function Go(t){return hc()[t]??null}function Wo(t){let e=hc();t in e&&(delete e[t],on(oc(),e))}function Or(){let t=ac();if(!Ke.default.existsSync(t))return{};try{return mk.parse(JSON.parse(Ke.default.readFileSync(t,"utf8")))}catch{return{}}}function Rp(t){let e=Or();e[t.runId]=t,on(ac(),e)}function Ap(t){return Or()[t]??null}function Lt(t){let e=Or();t in e&&(delete e[t],on(ac(),e))}var Ke,Rs,ok,ak,lk,ck,uk,dk,hk,pk,fk,mk,mi=ne(()=>{"use strict";Ke=R(require("node:fs"),1),Rs=R(require("node:path"),1);vn();Ee();ok=k.object({runId:k.string(),issueKey:k.string(),repoName:k.string(),owner:k.string(),repo:k.string(),prNumber:k.number().int(),prUrl:k.string(),branch:k.string(),headSha:k.string(),doneLabel:k.string(),failedLabel:k.string(),jiraTransition:k.string().optional(),mergeOnApprove:k.boolean().default(!1),mergeMethod:k.enum(["squash","merge","rebase"]).default("squash"),autoMerge:k.boolean().default(!1),nextDecisionSeq:k.number().int().default(1e5),changesRequestedNotified:k.boolean().optional(),conflictNotified:k.boolean().optional(),agentConfigDir:k.string().optional()}),ak=k.record(ok),lk=k.object({runId:k.string(),issueKey:k.string(),issueSummary:k.string().default(""),projectId:k.string(),repoName:k.string(),environmentName:k.string(),requestedBy:k.string().default(""),createdAt:k.string()}),ck=k.record(lk),uk=k.object({runId:k.string(),issueKey:k.string(),kind:k.enum(["plan","implement"]),repoPath:k.string(),sessionId:k.string(),doneLabel:k.string(),failedLabel:k.string(),timeoutSeconds:k.number(),createdAt:k.string(),questionsPostedAt:k.string(),rounds:k.number().int().default(1),nextLogSeq:k.number().int().nonnegative().default(0),baseRepoPath:k.string().optional(),repoName:k.string().optional(),branch:k.string().optional(),baseBranch:k.string().optional(),jiraTransition:k.string().optional(),jiraTransitionOnMerge:k.string().optional(),requireApproval:k.boolean().optional(),maxTurns:k.number().int().optional(),runTests:k.boolean().default(!0),mergeOnApprove:k.boolean().default(!1),mergeMethod:k.enum(["squash","merge","rebase"]).default("squash"),autoMerge:k.boolean().default(!1),issueSummary:k.string().default(""),claudeConfigDir:k.string().optional(),agent:k.string().optional(),model:k.string().optional(),actorEmail:k.string().optional(),preflight:k.enum(["epic-confirm"]).optional(),ruleId:k.string().optional()}),dk=k.object({runId:k.string(),issueKey:k.string(),issueSummary:k.string().default(""),repoName:k.string(),baseRepoPath:k.string(),branch:k.string(),baseBranch:k.string(),headSha:k.string(),requireApproval:k.boolean(),mergeOnApprove:k.boolean().default(!1),mergeMethod:k.enum(["squash","merge","rebase"]).default("squash"),autoMerge:k.boolean().default(!1),doneLabel:k.string(),failedLabel:k.string(),jiraTransition:k.string().optional(),jiraTransitionOnMerge:k.string().optional(),actorEmail:k.string().optional(),resultSummary:k.string().default(""),prSummary:k.string().default(""),costUsd:k.number().default(0),nextLogSeq:k.number().int().default(1e5),createdAt:k.string()}),hk=k.record(dk),pk=k.object({runId:k.string(),issueKey:k.string(),repoName:k.string(),owner:k.string(),repo:k.string(),prNumber:k.number().int(),prUrl:k.string(),jiraTransitionOnMerge:k.string().default(""),createdAt:k.string()}),fk=k.record(pk),mk=k.record(uk)});function Cp(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 $p(t){let e=`${t.exitCode===0?"PASS":"FAIL"} ${t.command} (exit ${t.exitCode})`;if(t.exitCode!==0)return`${e}
669
+ Do NOT repeat what CLAUDE.md already says - the agent reads that file itself; add what it lacks. Never include secrets, tokens or credential values. No preamble, no closing offer.`,hc=new Set});function Rp(){try{return JSON.parse(mi.default.readFileSync(Ip(),"utf8"))}catch{return{}}}function Ep(t){mi.default.mkdirSync(ie(),{recursive:!0,mode:448}),mi.default.writeFileSync(Ip(),JSON.stringify(t,null,2),{mode:384})}function Cp(t,e,n){let r=Rp();r[Ap(t,e)]={...n,at:new Date().toISOString()},Ep(r)}function $p(t,e,n){let r=Rp(),s=Ap(t,e),i=r[s];return!i||(delete r[s],Ep(r),i.branch!==n)||!mi.default.existsSync(i.worktreePath)?null:i}var mi,xp,mc,Ip,Ap,Pp=te(()=>{"use strict";mi=E(require("node:fs"),1),xp=E(require("node:path"),1);Ae();mc=2,Ip=()=>xp.default.join(ie(),"timeout-sessions.json");Ap=(t,e)=>`${t}:${e}`});var jr={};$t(jr,{GitHubClient:()=>He});var jk,He,It=te(()=>{"use strict";jk=process.env.TICKETPILOT_GITHUB_API??"https://api.github.com",He=class{constructor(e){this.token=e}token;async request(e,n,r){let s=await fetch(`${jk}${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 Np(){return Cs.default.join(ie(),"pending-runs.json")}function gc(){return Cs.default.join(ie(),"pending-deploys.json")}function yc(){return Cs.default.join(ie(),"pending-inputs.json")}function bc(){return Cs.default.join(ie(),"merge-watch.json")}function wc(){return Cs.default.join(ie(),"pending-pushes.json")}function vc(){let t=wc();if(!We.default.existsSync(t))return{};try{return qk.parse(JSON.parse(We.default.readFileSync(t,"utf8")))}catch{return{}}}function Go(t){let e=vc();e[t.runId]=t,un(wc(),e)}function Wo(t){return vc()[t]??null}function kc(t){let e=vc();t in e&&(delete e[t],un(wc(),e))}function Zo(){let t=bc();if(!We.default.existsSync(t))return{};try{return Bk.parse(JSON.parse(We.default.readFileSync(t,"utf8")))}catch{return{}}}function jp(t){let e=Zo();e[t.runId]=t,un(bc(),e)}function gi(t){let e=Zo();t in e&&(delete e[t],un(bc(),e))}function yi(){let t=Np();if(!We.default.existsSync(t))return{};try{return Mk.parse(JSON.parse(We.default.readFileSync(t,"utf8")))}catch{return{}}}function un(t,e){We.default.mkdirSync(ie(),{recursive:!0,mode:448});let n=t+".tmp";We.default.writeFileSync(n,JSON.stringify(e,null,2)+`
670
+ `,{mode:384}),We.default.renameSync(n,t),We.default.chmodSync(t,384)}function Op(t){un(Np(),t)}function Rt(t){let e=yi();e[t.runId]=t,Op(e)}function $s(t){return yi()[t]??null}function Or(t){let e=yi();t in e&&(delete e[t],Op(e))}function _c(){let t=gc();if(!We.default.existsSync(t))return{};try{return Dk.parse(JSON.parse(We.default.readFileSync(t,"utf8")))}catch{return{}}}function Mp(t){let e=_c();e[t.runId]=t,un(gc(),e)}function Vo(t){return _c()[t]??null}function Jo(t){let e=_c();t in e&&(delete e[t],un(gc(),e))}function Mr(){let t=yc();if(!We.default.existsSync(t))return{};try{return Hk.parse(JSON.parse(We.default.readFileSync(t,"utf8")))}catch{return{}}}function zp(t){let e=Mr();e[t.runId]=t,un(yc(),e)}function Dp(t){return Mr()[t]??null}function Ft(t){let e=Mr();t in e&&(delete e[t],un(yc(),e))}var We,Cs,Ok,Mk,zk,Dk,Lk,Uk,qk,Fk,Bk,Hk,bi=te(()=>{"use strict";We=E(require("node:fs"),1),Cs=E(require("node:path"),1);Tn();Ae();Ok=k.object({runId:k.string(),issueKey:k.string(),repoName:k.string(),owner:k.string(),repo:k.string(),prNumber:k.number().int(),prUrl:k.string(),branch:k.string(),headSha:k.string(),doneLabel:k.string(),failedLabel:k.string(),jiraTransition:k.string().optional(),mergeOnApprove:k.boolean().default(!1),mergeMethod:k.enum(["squash","merge","rebase"]).default("squash"),autoMerge:k.boolean().default(!1),nextDecisionSeq:k.number().int().default(1e5),changesRequestedNotified:k.boolean().optional(),conflictNotified:k.boolean().optional(),agentConfigDir:k.string().optional()}),Mk=k.record(Ok),zk=k.object({runId:k.string(),issueKey:k.string(),issueSummary:k.string().default(""),projectId:k.string(),repoName:k.string(),environmentName:k.string(),requestedBy:k.string().default(""),createdAt:k.string()}),Dk=k.record(zk),Lk=k.object({runId:k.string(),issueKey:k.string(),kind:k.enum(["plan","implement"]),repoPath:k.string(),sessionId:k.string(),doneLabel:k.string(),failedLabel:k.string(),timeoutSeconds:k.number(),createdAt:k.string(),questionsPostedAt:k.string(),rounds:k.number().int().default(1),nextLogSeq:k.number().int().nonnegative().default(0),baseRepoPath:k.string().optional(),repoName:k.string().optional(),branch:k.string().optional(),baseBranch:k.string().optional(),jiraTransition:k.string().optional(),jiraTransitionOnMerge:k.string().optional(),requireApproval:k.boolean().optional(),maxTurns:k.number().int().optional(),runTests:k.boolean().default(!0),allowWeb:k.boolean().default(!1),mergeOnApprove:k.boolean().default(!1),mergeMethod:k.enum(["squash","merge","rebase"]).default("squash"),autoMerge:k.boolean().default(!1),issueSummary:k.string().default(""),claudeConfigDir:k.string().optional(),agent:k.string().optional(),model:k.string().optional(),actorEmail:k.string().optional(),preflight:k.enum(["epic-confirm"]).optional(),ruleId:k.string().optional()}),Uk=k.object({runId:k.string(),issueKey:k.string(),issueSummary:k.string().default(""),repoName:k.string(),baseRepoPath:k.string(),branch:k.string(),baseBranch:k.string(),headSha:k.string(),requireApproval:k.boolean(),mergeOnApprove:k.boolean().default(!1),mergeMethod:k.enum(["squash","merge","rebase"]).default("squash"),autoMerge:k.boolean().default(!1),doneLabel:k.string(),failedLabel:k.string(),jiraTransition:k.string().optional(),jiraTransitionOnMerge:k.string().optional(),actorEmail:k.string().optional(),resultSummary:k.string().default(""),prSummary:k.string().default(""),costUsd:k.number().default(0),nextLogSeq:k.number().int().default(1e5),createdAt:k.string()}),qk=k.record(Uk),Fk=k.object({runId:k.string(),issueKey:k.string(),repoName:k.string(),owner:k.string(),repo:k.string(),prNumber:k.number().int(),prUrl:k.string(),jiraTransitionOnMerge:k.string().default(""),createdAt:k.string()}),Bk=k.record(Fk),Hk=k.record(Lk)});function Lp(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 Up(t){let e=`${t.exitCode===0?"PASS":"FAIL"} ${t.command} (exit ${t.exitCode})`;if(t.exitCode!==0)return`${e}
670
671
  ${t.tail.slice(-1500)}`;let n=t.tail.split(`
671
672
  `).map(r=>r.trim()).filter(Boolean).pop();return n?`${e}
672
- ${n.slice(0,200)}`:e}function wk(t){let e=t.map(n=>`$ ${n.command} (exit ${n.exitCode})
673
+ ${n.slice(0,200)}`:e}function Zk(t){let e=t.map(n=>`$ ${n.command} (exit ${n.exitCode})
673
674
  ${n.tail.slice(-2e3)}`).join(`
674
675
 
675
676
  `);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:
@@ -681,7 +682,7 @@ Fix what these failures point at, with the smallest change that makes them pass.
681
682
  - 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.
682
683
  - Do not ask questions; if you cannot fix something safely, say what you found and stop.
683
684
  - The runner re-runs every documented command after you finish, so a fix that breaks a previously passing command will be caught.
684
- 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 vk(t){try{let{packs:e,lessons:n}=Ts("implement",t),r="",s=e.map(o=>`### ${o.name}
685
+ 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 Vk(t){try{let{packs:e,lessons:n}=Is("implement",t),r="",s=e.map(o=>`### ${o.name}
685
686
  ${o.content}`).join(`
686
687
 
687
688
  `).trim();s&&(r+=`
@@ -691,48 +692,48 @@ This repository has working rules taught to Allwright - follow them:
691
692
  \u2026${i.slice(-6e3)}`:i;r+=`
692
693
 
693
694
  Lessons from earlier runs on this repository (human-confirmed - follow them BEFORE writing code, they exist because a run got this wrong once):
694
- `+o}return r}catch{return""}}function gc(t){return mc.default.existsSync(Zo.default.join(t,"DESIGN.md"))?`
695
+ `+o}return r}catch{return""}}function xc(t){return Yo.default.existsSync(Xo.default.join(t,"DESIGN.md"))?`
695
696
 
696
- 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.`:""}async function bi(t,e,n,r){let s=Date.now(),i="";r&&(i=await r().catch(()=>""));let o=await t.run(e),l=0,c="",d=r?kk:Pp,p=!1;for(;!o.ok&&o.turnLimitHit&&!o.cancelled&&t.capabilities.sessionResume;){if(e.maxCostUsd&&o.costUsd>=e.maxCostUsd){c=`the run's cost cap ($${e.maxCostUsd.toFixed(2)}) is spent ($${o.costUsd.toFixed(2)} so far)`,p=!0;break}if(l>=d){c=`resume cap (${d}) reached`;break}if(r&&l>=Pp){let w=await r().catch(()=>""),v=w!==""&&w!==i;if(i=w,!v){c="the last resume produced no new work";break}if(Date.now()-s>e.timeoutSeconds*Np*1e3){c=`wall-clock budget (${Np}x the rule's timeout) exhausted`;break}}l++,n("info",`Turn limit hit mid-work - auto-resuming the same session (resume ${l}, cap ${d})`);let f=await t.run({...e,prompt:Tk,resume:!0});f.costUsd+=o.costUsd,f.inputTokens+=o.inputTokens,f.outputTokens+=o.outputTokens,o=f}return!o.ok&&o.turnLimitHit&&t.capabilities.sessionResume&&(p&&(o.costCapped=!0),o.error=p?`stopped by the rule's cost cap: $${o.costUsd.toFixed(2)} spent of the $${(e.maxCostUsd??0).toFixed(2)} allowed, with the work unfinished after ${l} resume(s). This is the circuit breaker doing its job - split the ticket into smaller ones, or raise the rule's max cost if the scope really warrants it.`:`${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}function Mp(t){let e=gi.get(t);return e?(e.abort(),!0):!1}function zp(t){let e=new AbortController;return gi.set(t,e),e}function Dp(t){gi.delete(t)}async function $s(t,e,n,r,s){let i=new AbortController;gi.set(t,i);try{return await bi(e,{...n,signal:i.signal},r,s)}finally{gi.delete(t)}}function jr(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 wi(t){return Fo({project:t.project,repoPath:t.repoPath},t.cfg),t.rule.action.type==="implement"?Ek(t):t.rule.action.type==="respond"?Ik(t):xk(t)}async function xk(t){let{emit:e,setStatus:n,sendUsage:r,nextSeq:s}=jr(t.runId,t.transport),{trigger:i}=t.rule,o=t.rule.action;if(o.type!=="plan_only")return;let l=jn(o.agent,o.type);if(l){e("error",l),await Cs(t,l),n("failed",{error:l});return}let c=(0,Vo.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 d=await t.jira.getIssue(t.issueKey),p=sn(o.promptTemplate,{issueKey:d.key,summary:d.summary,description:d.description||"(no description)",comments:Mr(d.comments)})+await cs(t.jira,d.attachments,t.repoPath,e)+gc(t.repoPath)+qo(t.repoPath)+di(t.project.repoName)+Mn.FOCUSED_READING_PROMPT+Ie.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 $s(t.runId,Je(o.agent),{repoPath:t.repoPath,prompt:p,timeoutSeconds:o.timeoutSeconds,bin:Xe(t.cfg,o.agent),configDir:t.claudeConfigDir,mode:"read_only",model:o.model||void 0,sessionId:c,onLog:(_,I)=>e(_,I),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 _=f.error??"Claude Code produced no output";e("error",`Run failed: ${_}`),await Cs(t,_),n(f.timedOut?"timed_out":"failed",{error:_,...f.cancelled?{errorKind:"guard"}:{},...w});return}let v=ki(f.resultText);if(v){await yi({kind:"plan",runId:t.runId,issueKey:t.issueKey,repoPath:t.repoPath,sessionId:c,doneLabel:i.doneLabel,failedLabel:i.failedLabel,timeoutSeconds:o.timeoutSeconds,jira:t.jira,nextLogSeq:s(),rounds:1,claudeConfigDir:t.claudeConfigDir,agent:o.agent,model:o.model},v,e,n,w);return}await Lp({runId:t.runId,issueKey:t.issueKey,doneLabel:i.doneLabel,jira:t.jira,resultText:f.resultText,costFields:w,emit:e,setStatus:n})}catch(d){let p=d instanceof Error?d.message:String(d);e("error",`Run failed: ${p}`),await Cs(t,p),n("failed",{error:p})}finally{_n(t.repoPath)}}async function yc(t,e,n,r){let{emit:s,setStatus:i,sendUsage:o,nextSeq:l}=jr(t.runId,r.transport,t.nextLogSeq);try{i("running"),s("info",`Reply received on ${t.issueKey} - continuing run \`${t.runId}\``);let c=Vp(e)+await cs(r.jiraFor(t.repoName??""),n,t.repoPath,s),d=await $s(t.runId,Je(t.agent),{repoPath:t.repoPath,prompt:c,timeoutSeconds:t.timeoutSeconds,bin:Xe(r.cfg,t.agent??""),configDir:t.claudeConfigDir,mode:"read_only",model:t.model||void 0,sessionId:t.sessionId,resume:!0,onLog:(w,v)=>s(w,v),onUsage:o},s),p={costUsd:d.costUsd,inputTokens:d.inputTokens,outputTokens:d.outputTokens,billingMode:d.billingMode,model:d.model};if(!d.ok||!d.resultText.trim()){let w=d.error??"Claude Code produced no output";s("error",`Run failed: ${w}`),await Ut(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,w),Lt(t.runId),i(d.timedOut?"timed_out":"failed",{error:w,...d.cancelled?{errorKind:"guard"}:{},...p});return}let f=ki(d.resultText);if(f){if(t.rounds>=jp){await Yp(r.jiraFor(t.repoName??""),t,s,i,p);return}await yi({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 Lp({runId:t.runId,issueKey:t.issueKey,doneLabel:t.doneLabel,jira:r.jiraFor(t.repoName??""),resultText:d.resultText,costFields:p,emit:s,setStatus:i}),Lt(t.runId)}catch(c){let d=c instanceof Error?c.message:String(c);s("error",`Run failed: ${d}`),await Ut(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,d),Lt(t.runId),i("failed",{error:d})}finally{_n(t.repoPath)}}async function Lp(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 d=`
697
+ 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.`:""}async function ki(t,e,n,r){let s=Date.now(),i="";r&&(i=await r().catch(()=>""));let o=await t.run(e),l=0,c="",d=r?Jk:qp,p=!1;for(;!o.ok&&o.turnLimitHit&&!o.cancelled&&t.capabilities.sessionResume;){if(e.maxCostUsd&&o.costUsd>=e.maxCostUsd){c=`the run's cost cap ($${e.maxCostUsd.toFixed(2)}) is spent ($${o.costUsd.toFixed(2)} so far)`,p=!0;break}if(l>=d){c=`resume cap (${d}) reached`;break}if(r&&l>=qp){let w=await r().catch(()=>""),v=w!==""&&w!==i;if(i=w,!v){c="the last resume produced no new work";break}if(Date.now()-s>e.timeoutSeconds*Fp*1e3){c=`wall-clock budget (${Fp}x the rule's timeout) exhausted`;break}}l++,n("info",`Turn limit hit mid-work - auto-resuming the same session (resume ${l}, cap ${d})`);let f=await t.run({...e,prompt:Qk,resume:!0});f.costUsd+=o.costUsd,f.inputTokens+=o.inputTokens,f.outputTokens+=o.outputTokens,o=f}return!o.ok&&o.turnLimitHit&&t.capabilities.sessionResume&&(p&&(o.costCapped=!0),o.error=p?`stopped by the rule's cost cap: $${o.costUsd.toFixed(2)} spent of the $${(e.maxCostUsd??0).toFixed(2)} allowed, with the work unfinished after ${l} resume(s). This is the circuit breaker doing its job - split the ticket into smaller ones, or raise the rule's max cost if the scope really warrants it.`:`${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}function Kp(t){let e=wi.get(t);return e?(e.abort(),!0):!1}function Gp(t){let e=new AbortController;return wi.set(t,e),e}function Wp(t){wi.delete(t)}async function Ns(t,e,n,r,s){let i=new AbortController;wi.set(t,i);try{return await ki(e,{...n,signal:i.signal},r,s)}finally{wi.delete(t)}}function zr(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 _i(t){return Ko({project:t.project,repoPath:t.repoPath},t.cfg),t.rule.action.type==="implement"?n_(t):t.rule.action.type==="respond"?t_(t):e_(t)}async function e_(t){let{emit:e,setStatus:n,sendUsage:r,nextSeq:s}=zr(t.runId,t.transport),{trigger:i}=t.rule,o=t.rule.action;if(o.type!=="plan_only")return;let l=Ln(o.agent,o.type);if(l){e("error",l),await Ps(t,l),n("failed",{error:l});return}let c=(0,Qo.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 d=await t.jira.getIssue(t.issueKey),p=cn(o.promptTemplate,{issueKey:d.key,summary:d.summary,description:d.description||"(no description)",comments:Dr(d.comments)})+await ds(t.jira,d.attachments,t.repoPath,e)+xc(t.repoPath)+Ho(t.repoPath)+fi(t.project.repoName)+Un.FOCUSED_READING_PROMPT+Ee.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 Ns(t.runId,et(o.agent),{repoPath:t.repoPath,prompt:p,timeoutSeconds:o.timeoutSeconds,bin:Be(t.cfg,o.agent),configDir:t.claudeConfigDir,mode:o.allowWeb?"read_only_web":"read_only",model:o.model||void 0,sessionId:c,onLog:(_,I)=>e(_,I),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 _=f.error??"Claude Code produced no output";e("error",`Run failed: ${_}`),await Ps(t,_),n(f.timedOut?"timed_out":"failed",{error:_,...f.cancelled?{errorKind:"guard"}:{},...w});return}let v=Ti(f.resultText);if(v){await vi({kind:"plan",allowWeb:o.allowWeb,runId:t.runId,issueKey:t.issueKey,repoPath:t.repoPath,sessionId:c,doneLabel:i.doneLabel,failedLabel:i.failedLabel,timeoutSeconds:o.timeoutSeconds,jira:t.jira,nextLogSeq:s(),rounds:1,claudeConfigDir:t.claudeConfigDir,agent:o.agent,model:o.model},v,e,n,w);return}await Zp({runId:t.runId,issueKey:t.issueKey,doneLabel:i.doneLabel,jira:t.jira,resultText:f.resultText,costFields:w,emit:e,setStatus:n})}catch(d){let p=d instanceof Error?d.message:String(d);e("error",`Run failed: ${p}`),await Ps(t,p),n("failed",{error:p})}finally{In(t.repoPath)}}async function Ic(t,e,n,r){let{emit:s,setStatus:i,sendUsage:o,nextSeq:l}=zr(t.runId,r.transport,t.nextLogSeq);try{i("running"),s("info",`Reply received on ${t.issueKey} - continuing run \`${t.runId}\``);let c=sf(e)+await ds(r.jiraFor(t.repoName??""),n,t.repoPath,s),d=await Ns(t.runId,et(t.agent),{repoPath:t.repoPath,prompt:c,timeoutSeconds:t.timeoutSeconds,bin:Be(r.cfg,t.agent??""),configDir:t.claudeConfigDir,mode:t.allowWeb?"read_only_web":"read_only",model:t.model||void 0,sessionId:t.sessionId,resume:!0,onLog:(w,v)=>s(w,v),onUsage:o},s),p={costUsd:d.costUsd,inputTokens:d.inputTokens,outputTokens:d.outputTokens,billingMode:d.billingMode,model:d.model};if(!d.ok||!d.resultText.trim()){let w=d.error??"Claude Code produced no output";s("error",`Run failed: ${w}`),await Bt(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,w),Ft(t.runId),i(d.timedOut?"timed_out":"failed",{error:w,...d.cancelled?{errorKind:"guard"}:{},...p});return}let f=Ti(d.resultText);if(f){if(t.rounds>=Hp){await of(r.jiraFor(t.repoName??""),t,s,i,p);return}await vi({kind:"plan",allowWeb:t.allowWeb,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 Zp({runId:t.runId,issueKey:t.issueKey,doneLabel:t.doneLabel,jira:r.jiraFor(t.repoName??""),resultText:d.resultText,costFields:p,emit:s,setStatus:i}),Ft(t.runId)}catch(c){let d=c instanceof Error?c.message:String(c);s("error",`Run failed: ${d}`),await Bt(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,d),Ft(t.runId),i("failed",{error:d})}finally{In(t.repoPath)}}async function Zp(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 d=`
697
698
 
698
699
  ---
699
- _Allwright plan-only run \`${e}\` \xB7 cost $${o.costUsd.toFixed(4)} \xB7 no code was written._`;await s.addComment(n,i+d),await s.editLabels(n,{add:[r],remove:[Ie.NEEDS_INPUT_LABEL]}),l("info",`Labeled ${n} with "${r}"`),c("succeeded",{...o,resultSummary:zr(i)}),l("info",`Run succeeded \xB7 $${o.costUsd.toFixed(4)}`)}async function Ik(t){let{emit:e,setStatus:n,sendUsage:r}=jr(t.runId,t.transport),s=t.rule.action;if(s.type!=="respond")return;let i=jn(s.agent,s.type);if(i){e("error",i),await t.jira.addComment(t.issueKey,`**Allwright could not answer this question.**
700
+ _Allwright plan-only run \`${e}\` \xB7 cost $${o.costUsd.toFixed(4)} \xB7 no code was written._`;await s.addComment(n,i+d),await s.editLabels(n,{add:[r],remove:[Ee.NEEDS_INPUT_LABEL]}),l("info",`Labeled ${n} with "${r}"`),c("succeeded",{...o,resultSummary:Lr(i)}),l("info",`Run succeeded \xB7 $${o.costUsd.toFixed(4)}`)}async function t_(t){let{emit:e,setStatus:n,sendUsage:r}=zr(t.runId,t.transport),s=t.rule.action;if(s.type!=="respond")return;let i=Ln(s.agent,s.type);if(i){e("error",i),await t.jira.addComment(t.issueKey,`**Allwright could not answer this question.**
700
701
 
701
- ${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=sn(s.promptTemplate,{issueKey:o.key,summary:o.summary,description:o.description||"(no description)",comments:Mr(o.comments),question:t.question?.body??"(see the latest comment on the ticket)",questionAuthor:t.question?.author??"the commenter"})+await cs(t.jira,o.attachments,t.repoPath,e)+gc(t.repoPath)+qo(t.repoPath)+Mn.FOCUSED_READING_PROMPT;e("info",`Starting Claude Code in ${t.repoPath} - read-only tools, path-jailed, timeout ${s.timeoutSeconds}s`);let c=await $s(t.runId,Je(s.agent),{repoPath:t.repoPath,prompt:l,timeoutSeconds:s.timeoutSeconds,bin:Xe(t.cfg,s.agent),configDir:t.claudeConfigDir,mode:"read_only",model:s.model||void 0,sessionId:(0,Vo.randomUUID)(),onLog:(p,f)=>e(p,f),onUsage:r},e),d={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.**
702
+ ${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=cn(s.promptTemplate,{issueKey:o.key,summary:o.summary,description:o.description||"(no description)",comments:Dr(o.comments),question:t.question?.body??"(see the latest comment on the ticket)",questionAuthor:t.question?.author??"the commenter"})+await ds(t.jira,o.attachments,t.repoPath,e)+xc(t.repoPath)+Ho(t.repoPath)+Un.FOCUSED_READING_PROMPT;e("info",`Starting Claude Code in ${t.repoPath} - read-only tools, path-jailed, timeout ${s.timeoutSeconds}s`);let c=await Ns(t.runId,et(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,Qo.randomUUID)(),onLog:(p,f)=>e(p,f),onUsage:r},e),d={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.**
702
703
 
703
704
  Error: ${p.slice(0,800)}
704
705
 
705
- 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"}:{},...d});return}n("posting",d),e("info",`Posting answer to ${t.issueKey} (${c.resultText.length} chars)`),await t.jira.addComment(t.issueKey,c.resultText),n("succeeded",{...d,resultSummary:zr(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{_n(t.repoPath)}}async function Up(t,e,n,r){let s=`${e}-wip`;try{return _n(t),await Ir(t,`WIP: turn limit exhausted (Allwright run ${n})`),await fl(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 qp(t){return`
706
+ 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"}:{},...d});return}n("posting",d),e("info",`Posting answer to ${t.issueKey} (${c.resultText.length} chars)`),await t.jira.addComment(t.issueKey,c.resultText),n("succeeded",{...d,resultSummary:Lr(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{In(t.repoPath)}}async function Vp(t,e,n,r){let s=`${e}-wip`;try{return In(t),await Er(t,`WIP: turn limit exhausted (Allwright run ${n})`),await Tl(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 Jp(t){return`
706
707
 
707
- 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 Ek(t){let{emit:e,setStatus:n,sendUsage:r,nextSeq:s}=jr(t.runId,t.transport,t.startLogSeq??0),{trigger:i}=t.rule,o=t.rule.action;if(o.type!=="implement")return;let l=jn(o.agent,o.type);if(l){e("error",l),await Cs(t,l),n("failed",{error:l});return}let c=sn(o.branchTemplate,{issueKey:t.issueKey}),d=t.chain?null:_p(t.project.id,t.issueKey,c),p=t.chain?.worktreePath??d?.worktreePath??Zo.default.join(rn(),t.runId),f=t.chain?.sessionId??d?.sessionId??(0,Vo.randomUUID)(),w=!1,v=!1,_=!1;try{if(!Ro(ke()??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(c===o.baseBranch&&!t.continueBranch)throw new Error(`rendered branch "${c}" 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(g){e("warn",`Jira start transition failed: ${g instanceof Error?g.message:g} - continuing anyway`)}let I=await Rr(t.repoPath);if(e("info",`Repo origin: ${I}`),!_t(I))throw new Error(`origin "${I}" is not a GitHub remote - implement mode supports GitHub only`);e("info",`Fetching ${t.issueKey} from Jira`);let E=await t.jira.getIssue(t.issueKey);if(/^epic$/i.test(E.issueType)&&!t.preflightAnswer&&!d&&!t.chain){_=!0;let g="```";await yi({kind:"implement",runId:t.runId,issueKey:t.issueKey,repoPath:t.repoPath,sessionId:f,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:c,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:E.summary,preflight:"epic-confirm",ruleId:t.rule.id},`This ticket is an **Epic** - usually a container whose child tickets hold the actual work. Implementing the container itself burns a full agent run on a description that was rarely written as a spec, and can contradict the children.
708
+ 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 n_(t){let{emit:e,setStatus:n,sendUsage:r,nextSeq:s}=zr(t.runId,t.transport,t.startLogSeq??0),{trigger:i}=t.rule,o=t.rule.action;if(o.type!=="implement")return;let l=Ln(o.agent,o.type);if(l){e("error",l),await Ps(t,l),n("failed",{error:l});return}let c=cn(o.branchTemplate,{issueKey:t.issueKey}),d=t.chain?null:$p(t.project.id,t.issueKey,c),p=t.chain?.worktreePath??d?.worktreePath??Xo.default.join(ln(),t.runId),f=t.chain?.sessionId??d?.sessionId??(0,Qo.randomUUID)(),w=!1,v=!1,_=!1;try{if(!$o(ve()??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(c===o.baseBranch&&!t.continueBranch)throw new Error(`rendered branch "${c}" 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(y){e("warn",`Jira start transition failed: ${y instanceof Error?y.message:y} - continuing anyway`)}let I=await Cr(t.repoPath);if(e("info",`Repo origin: ${I}`),!St(I))throw new Error(`origin "${I}" is not a GitHub remote - implement mode supports GitHub only`);e("info",`Fetching ${t.issueKey} from Jira`);let R=await t.jira.getIssue(t.issueKey);if(/^epic$/i.test(R.issueType)&&!t.preflightAnswer&&!d&&!t.chain){_=!0;let y="```";await vi({kind:"implement",allowWeb:o.allowWeb,runId:t.runId,issueKey:t.issueKey,repoPath:t.repoPath,sessionId:f,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:c,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:R.summary,preflight:"epic-confirm",ruleId:t.rule.id},`This ticket is an **Epic** - usually a container whose child tickets hold the actual work. Implementing the container itself burns a full agent run on a description that was rarely written as a spec, and can contradict the children.
708
709
 
709
710
  Should this run implement the epic ticket itself?
710
711
 
711
- ${g}${Ie.NEEDS_INPUT_ASK_FENCE}
712
- {"options": ["${_k}", "${Sk}"]}
713
- ${g}`,e,n,{costUsd:0,inputTokens:0,outputTokens:0});return}let C=t.continueBranch;C&&!d&&await yl(t.repoPath,c)===!1&&(e("info",`Batch branch "${c}" is not on origin - an earlier ticket in this batch finished without pushing one. Starting it from origin/${o.baseBranch}.`),C=!1);let Y=C?c:o.baseBranch;d?e("info",`Resuming the session that timed out on this ticket (timeout resume ${d.resumes}/${ic}) - same worktree, uncommitted work intact, repo context cached`):(e("info",C?`Continuing branch "${c}" from origin/${c} (autopilot batch)`:`Preparing worktree on branch "${c}" from origin/${o.baseBranch}`),await Cn(t.repoPath,Y),t.chain&&C||await bl(t.repoPath,c),t.chain?(e("info","Chaining onto the previous ticket's workspace - resuming its agent session (repo context cached, not re-explored)"),await Tl(p,c,C?`origin/${c}`:`origin/${o.baseBranch}`)):await wl(t.repoPath,p,c,Y)),w=!0;let X=sn(o.promptTemplate,{issueKey:E.key,summary:E.summary,description:E.description||"(no description)",comments:Mr(E.comments)});!d&&!$k(`${E.summary}
714
- ${E.description??""}`)&&e("info","This ticket names no files or symbols - the agent has to discover them, which costs extra reads. Tickets that name paths run cheaper.");let $=d?null:await gl(p,o.baseBranch,E.key).catch(()=>null),b=[],U=(g,x)=>(x&&b.push({part:g,chars:x.length}),x),j=U("ticket: rule template + summary (rendered)",X)+U("attachments listing",await cs(t.jira,E.attachments,p,e))+U("design guideline pointer",gc(p))+U("knowledge: packs + lessons",vk(t.repoPath))+U("doc index",qo(p))+U("repo brief (machine-generated)",t.chain?"":di(t.project.repoName))+U("revision: previous delivery + what is new",$?Ck($,E.comments,pt):"")+U("appendix: focused reading",Mn.FOCUSED_READING_PROMPT)+U("appendix: protected paths",gk)+U("appendix: needs-input options",Ie.NEEDS_INPUT_OPTIONS_PROMPT)+U("appendix: PR summary",yk)+U("appendix: go-live",t.project.goLiveIssueKey?bk:"")+U("appendix: write tests",o.writeTests?Mn.WRITE_TESTS_PROMPT:"")+U("appendix: update memory",o.updateMemory?Ie.MEMORY_UPDATE_PROMPT:"")+U("epic confirmation answer",t.preflightAnswer?`
712
+ ${y}${Ee.NEEDS_INPUT_ASK_FENCE}
713
+ {"options": ["${Yk}", "${Xk}"]}
714
+ ${y}`,e,n,{costUsd:0,inputTokens:0,outputTokens:0});return}let C=t.continueBranch;C&&!d&&await Rl(t.repoPath,c)===!1&&(e("info",`Batch branch "${c}" is not on origin - an earlier ticket in this batch finished without pushing one. Starting it from origin/${o.baseBranch}.`),C=!1);let V=C?c:o.baseBranch;d?e("info",`Resuming the session that timed out on this ticket (timeout resume ${d.resumes}/${mc}) - same worktree, uncommitted work intact, repo context cached`):(e("info",C?`Continuing branch "${c}" from origin/${c} (autopilot batch)`:`Preparing worktree on branch "${c}" from origin/${o.baseBranch}`),await jn(t.repoPath,V),t.chain&&C||await El(t.repoPath,c),t.chain?(e("info","Chaining onto the previous ticket's workspace - resuming its agent session (repo context cached, not re-explored)"),await jl(p,c,C?`origin/${c}`:`origin/${o.baseBranch}`)):await Al(t.repoPath,p,c,V)),w=!0;let J=cn(o.promptTemplate,{issueKey:R.key,summary:R.summary,description:R.description||"(no description)",comments:Dr(R.comments)});!d&&!o_(`${R.summary}
715
+ ${R.description??""}`)&&e("info","This ticket names no files or symbols - the agent has to discover them, which costs extra reads. Tickets that name paths run cheaper.");let $=d?null:await Il(p,o.baseBranch,R.key).catch(()=>null),b=[],U=(y,x)=>(x&&b.push({part:y,chars:x.length}),x),j=U("ticket: rule template + summary (rendered)",J)+U("attachments listing",await ds(t.jira,R.attachments,p,e))+U("design guideline pointer",xc(p))+U("knowledge: packs + lessons",Vk(t.repoPath))+U("doc index",Ho(p))+U("repo brief (machine-generated)",t.chain?"":fi(t.project.repoName))+U("revision: previous delivery + what is new",$?i_($,R.comments,ft):"")+U("appendix: focused reading",Un.FOCUSED_READING_PROMPT)+U("appendix: protected paths",Kk)+U("appendix: needs-input options",Ee.NEEDS_INPUT_OPTIONS_PROMPT)+U("appendix: PR summary",Gk)+U("appendix: go-live",t.project.goLiveIssueKey?Wk:"")+U("appendix: write tests",o.writeTests?Un.WRITE_TESTS_PROMPT:"")+U("appendix: update memory",o.updateMemory?Ee.MEMORY_UPDATE_PROMPT:"")+U("epic confirmation answer",t.preflightAnswer?`
715
716
 
716
717
  THIS TICKET IS AN EPIC, and a human was asked whether to implement the epic ticket itself. They said to proceed, in these words - treat any guidance in them as part of the ticket:
717
- ${t.preflightAnswer.slice(0,4e3)}`:"");E.description&&b.push({part:"\u21B3 of which ticket description",chars:E.description.length});let H=Mr(E.comments).length;H&&b.push({part:"\u21B3 of which comment history",chars:H}),t.transport.sendRunContext({runId:t.runId,pieces:d?[{part:"continuation prompt (session resumed - original context already cached)",chars:pc.length}]:b,totalChars:d?pc.length:j.length,sessionMode:d?"timeout-resume":t.chain?"chained":t.preflightAnswer?"preflight-resume":"fresh"}),e("info",`Starting Claude Code in the worktree - edit tools enabled, path-jailed, no shell, timeout ${o.timeoutSeconds}s`);let q=await $s(t.runId,Je(o.agent),{repoPath:p,prompt:d?pc:j,timeoutSeconds:o.timeoutSeconds,bin:Xe(t.cfg,o.agent),configDir:t.claudeConfigDir,mode:"edit_no_shell",model:o.model||void 0,maxTurns:o.maxTurns,maxCostUsd:o.maxCostUsd,sessionId:f,resume:!!t.chain||!!d,onLog:(g,x)=>e(g,x),onUsage:r},e,()=>So(p)),u={costUsd:q.costUsd,inputTokens:q.inputTokens,outputTokens:q.outputTokens,billingMode:q.billingMode,model:q.model};if(!q.ok){let g=q.error??"Claude Code failed";e("error",`Run failed: ${g}`);let x=g,P=(q.timedOut||q.costCapped)&&!q.cancelled&&Je(o.agent)?.capabilities.sessionResume&&(d?.resumes??0)<ic;if(q.turnLimitHit&&!P){let O=await Up(p,c,t.runId,e);O&&(x+=qp(O))}P&&(kp(t.project.id,t.issueKey,{sessionId:f,worktreePath:p,branch:c,resumes:(d?.resumes??0)+1}),v=!0,e("info","Worktree and session preserved - the next trigger on this ticket resumes here"),x+=" - the work done so far is preserved: trigger this ticket again and the run RESUMES the same session where it stopped instead of starting over"),ft(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:"implement failed",detail:g.slice(0,500)}),await Cs(t,x),n(q.timedOut?"timed_out":"failed",{error:x,...q.cancelled||q.costCapped?{errorKind:"guard"}:{},...u});return}let m=ki(q.resultText);if(m){_=!0,await yi({kind:"implement",runId:t.runId,issueKey:t.issueKey,repoPath:p,sessionId:f,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:c,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:E.summary},m,e,n,u);return}_n(p),await Fp({runId:t.runId,issueKey:t.issueKey,issueSummary:E.summary,worktreePath:p,agentConfigDir:t.claudeConfigDir,baseRepoPath:t.repoPath,branch:c,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:q.resultText,costFields:u,runTests:o.runTests,fixSession:{sessionId:f,agent:o.agent,model:o.model,timeoutSeconds:o.timeoutSeconds,maxTurns:o.maxTurns},sendUsage:r,mergeOnApprove:o.mergeOnApprove,mergeMethod:o.mergeMethod,autoMerge:o.autoMerge,emit:e,setStatus:n}),t.onChainSession?.({sessionId:f,worktreePath:p})}catch(I){let E=I instanceof Error?I.message:String(I);e("error",`Run failed: ${E}`),ft(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:"implement failed",detail:E.slice(0,500)}),await Cs(t,E),n("failed",{error:E})}finally{w&&!_&&!t.keepWorktree&&!v&&await Ot(t.repoPath,p).catch(()=>{})}}async function bc(t,e,n,r){let{emit:s,setStatus:i,sendUsage:o,nextSeq:l}=jr(t.runId,r.transport,t.nextLogSeq);if(t.preflight==="epic-confirm"){let p=e.trim();if(/stop this run/i.test(p)){s("info","Epic confirmed as a container - stopping before any agent spend"),i("failed",{error:"stopped by choice: this Epic's work lives in its child tickets - queue those instead. No agent ran and nothing was spent.",errorKind:"guard"});return}let f=r.findRule?.(t.ruleId??"")??null;if(!f){i("failed",{error:"the rule this run would use no longer exists on this runner (it was deleted or edited away while the question waited) - trigger the ticket again from a current rule"});return}s("info","Epic confirmed by a human - starting the implement run"),await wi({runId:t.runId,rule:f.rule,project:f.project,issueKey:t.issueKey,repoPath:f.repoPath,cfg:r.cfg,jira:r.jiraFor(f.project.repoName),transport:r.transport,claudeConfigDir:t.claudeConfigDir,actorEmail:t.actorEmail,preflightAnswer:e,startLogSeq:l()});return}let c=t.repoPath,d=!1;try{if(!Ro(ke()??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=Vp(e)+await cs(r.jiraFor(t.repoName??""),n,c,s),f=await $s(t.runId,Je(t.agent),{repoPath:c,prompt:p,timeoutSeconds:t.timeoutSeconds,bin:Xe(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:(_,I)=>s(_,I),onUsage:o},s,()=>So(c)),w={costUsd:f.costUsd,inputTokens:f.inputTokens,outputTokens:f.outputTokens,billingMode:f.billingMode,model:f.model};if(!f.ok){let _=f.error??"Claude Code failed";s("error",`Run failed: ${_}`);let I=_;if(f.turnLimitHit&&t.branch){let E=await Up(c,t.branch,t.runId,s);E&&(I+=qp(E))}await Ut(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,I),Lt(t.runId),i(f.timedOut?"timed_out":"failed",{error:_,...f.cancelled?{errorKind:"guard"}:{},...w});return}let v=ki(f.resultText);if(v){if(t.rounds>=jp){await Yp(r.jiraFor(t.repoName??""),t,s,i,w);return}d=!0,await yi({kind:"implement",runId:t.runId,issueKey:t.issueKey,repoPath:c,sessionId:t.sessionId,doneLabel:t.doneLabel,failedLabel:t.failedLabel,timeoutSeconds:t.timeoutSeconds,jira:r.jiraFor(t.repoName??""),nextLogSeq:l(),rounds:t.rounds+1,createdAt:t.createdAt,claudeConfigDir:t.claudeConfigDir,actorEmail:t.actorEmail,agent:t.agent,model:t.model,baseRepoPath:t.baseRepoPath,repoName:t.repoName,branch:t.branch,baseBranch:t.baseBranch,jiraTransition:t.jiraTransition,jiraTransitionOnMerge:t.jiraTransitionOnMerge,requireApproval:t.requireApproval,mergeOnApprove:t.mergeOnApprove,mergeMethod:t.mergeMethod,autoMerge:t.autoMerge,runTests:t.runTests,maxTurns:t.maxTurns,issueSummary:t.issueSummary},v,s,i,w);return}_n(c),await Fp({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}),Lt(t.runId)}catch(p){let f=p instanceof Error?p.message:String(p);s("error",`Run failed: ${f}`),await Ut(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,f),Lt(t.runId),i("failed",{error:f})}finally{d||await Ot(t.baseRepoPath??c,c).catch(()=>{})}}async function Fp(t){let{runId:e,issueKey:n,issueSummary:r,worktreePath:s,baseRepoPath:i,branch:o,baseBranch:l,jiraTransition:c,jiraTransitionOnMerge:d,requireApproval:p,doneLabel:f,failedLabel:w,repoName:v,jira:_,cfg:I,actorEmail:E,runTests:C,mergeOnApprove:Y,mergeMethod:X,autoMerge:$,resultText:b,costFields:U,emit:j,setStatus:H}=t,q=await ws(s);q.deleted.length&&j("info",`Deleted ${q.deleted.length} file(s) listed in ${nn}: `+q.deleted.slice(0,10).join(", ")+(q.deleted.length>10?", \u2026":""));for(let ae of q.refused)j("warn",`${nn} entry refused: ${ae}`);j("info","Committing changes"),await Ir(s,`${n}: ${r}
718
+ ${t.preflightAnswer.slice(0,4e3)}`:"");R.description&&b.push({part:"\u21B3 of which ticket description",chars:R.description.length});let K=Dr(R.comments).length;K&&b.push({part:"\u21B3 of which comment history",chars:K}),t.transport.sendRunContext({runId:t.runId,pieces:d?[{part:"continuation prompt (session resumed - original context already cached)",chars:Sc.length}]:b,totalChars:d?Sc.length:j.length,sessionMode:d?"timeout-resume":t.chain?"chained":t.preflightAnswer?"preflight-resume":"fresh"}),e("info",`Starting Claude Code in the worktree - edit tools enabled, path-jailed, no shell, timeout ${o.timeoutSeconds}s`);let F=await Ns(t.runId,et(o.agent),{repoPath:p,prompt:d?Sc:j,timeoutSeconds:o.timeoutSeconds,bin:Be(t.cfg,o.agent),configDir:t.claudeConfigDir,mode:o.allowWeb?"edit_no_shell_web":"edit_no_shell",model:o.model||void 0,maxTurns:o.maxTurns,maxCostUsd:o.maxCostUsd,sessionId:f,resume:!!t.chain||!!d,onLog:(y,x)=>e(y,x),onUsage:r},e,()=>Io(p)),u={costUsd:F.costUsd,inputTokens:F.inputTokens,outputTokens:F.outputTokens,billingMode:F.billingMode,model:F.model};if(!F.ok){let y=F.error??"Claude Code failed";e("error",`Run failed: ${y}`);let x=y,M=(F.timedOut||F.costCapped)&&!F.cancelled&&et(o.agent)?.capabilities.sessionResume&&(d?.resumes??0)<mc;if(F.turnLimitHit&&!M){let P=await Vp(p,c,t.runId,e);P&&(x+=Jp(P))}M&&(Cp(t.project.id,t.issueKey,{sessionId:f,worktreePath:p,branch:c,resumes:(d?.resumes??0)+1}),v=!0,e("info","Worktree and session preserved - the next trigger on this ticket resumes here"),x+=" - the work done so far is preserved: trigger this ticket again and the run RESUMES the same session where it stopped instead of starting over"),mt(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:"implement failed",detail:y.slice(0,500)}),await Ps(t,x),n(F.timedOut?"timed_out":"failed",{error:x,...F.cancelled||F.costCapped?{errorKind:"guard"}:{},...u});return}let m=Ti(F.resultText);if(m){_=!0,await vi({kind:"implement",allowWeb:o.allowWeb,runId:t.runId,issueKey:t.issueKey,repoPath:p,sessionId:f,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:c,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:R.summary},m,e,n,u);return}In(p),await Yp({runId:t.runId,issueKey:t.issueKey,issueSummary:R.summary,worktreePath:p,agentConfigDir:t.claudeConfigDir,baseRepoPath:t.repoPath,branch:c,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:F.resultText,costFields:u,runTests:o.runTests,fixSession:{sessionId:f,agent:o.agent,model:o.model,timeoutSeconds:o.timeoutSeconds,maxTurns:o.maxTurns,allowWeb:o.allowWeb},sendUsage:r,mergeOnApprove:o.mergeOnApprove,mergeMethod:o.mergeMethod,autoMerge:o.autoMerge,emit:e,setStatus:n}),t.onChainSession?.({sessionId:f,worktreePath:p})}catch(I){let R=I instanceof Error?I.message:String(I);e("error",`Run failed: ${R}`),mt(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:"implement failed",detail:R.slice(0,500)}),await Ps(t,R),n("failed",{error:R})}finally{w&&!_&&!t.keepWorktree&&!v&&await Dt(t.repoPath,p).catch(()=>{})}}async function Rc(t,e,n,r){let{emit:s,setStatus:i,sendUsage:o,nextSeq:l}=zr(t.runId,r.transport,t.nextLogSeq);if(t.preflight==="epic-confirm"){let p=e.trim();if(/stop this run/i.test(p)){s("info","Epic confirmed as a container - stopping before any agent spend"),i("failed",{error:"stopped by choice: this Epic's work lives in its child tickets - queue those instead. No agent ran and nothing was spent.",errorKind:"guard"});return}let f=r.findRule?.(t.ruleId??"")??null;if(!f){i("failed",{error:"the rule this run would use no longer exists on this runner (it was deleted or edited away while the question waited) - trigger the ticket again from a current rule"});return}s("info","Epic confirmed by a human - starting the implement run"),await _i({runId:t.runId,rule:f.rule,project:f.project,issueKey:t.issueKey,repoPath:f.repoPath,cfg:r.cfg,jira:r.jiraFor(f.project.repoName),transport:r.transport,claudeConfigDir:t.claudeConfigDir,actorEmail:t.actorEmail,preflightAnswer:e,startLogSeq:l()});return}let c=t.repoPath,d=!1;if(!Yo.default.existsSync(c)){i("failed",{error:`the workspace this run was parked in (${c}) no longer exists - it was cleaned up while the question waited (an autopilot batch that moved on, or a runner restart). The answer was still posted to ${t.issueKey}; re-trigger the ticket and the fresh run will read it there.`,errorKind:"guard"});return}try{if(!$o(ve()??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=sf(e)+await ds(r.jiraFor(t.repoName??""),n,c,s),f=await Ns(t.runId,et(t.agent),{repoPath:c,prompt:p,timeoutSeconds:t.timeoutSeconds,bin:Be(r.cfg,t.agent??""),configDir:t.claudeConfigDir,mode:t.allowWeb?"edit_no_shell_web":"edit_no_shell",model:t.model||void 0,maxTurns:t.maxTurns??120,sessionId:t.sessionId,resume:!0,onLog:(_,I)=>s(_,I),onUsage:o},s,()=>Io(c)),w={costUsd:f.costUsd,inputTokens:f.inputTokens,outputTokens:f.outputTokens,billingMode:f.billingMode,model:f.model};if(!f.ok){let _=f.error??"Claude Code failed";s("error",`Run failed: ${_}`);let I=_;if(f.turnLimitHit&&t.branch){let R=await Vp(c,t.branch,t.runId,s);R&&(I+=Jp(R))}await Bt(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,I),Ft(t.runId),i(f.timedOut?"timed_out":"failed",{error:_,...f.cancelled?{errorKind:"guard"}:{},...w});return}let v=Ti(f.resultText);if(v){if(t.rounds>=Hp){await of(r.jiraFor(t.repoName??""),t,s,i,w);return}d=!0,await vi({kind:"implement",allowWeb:t.allowWeb,runId:t.runId,issueKey:t.issueKey,repoPath:c,sessionId:t.sessionId,doneLabel:t.doneLabel,failedLabel:t.failedLabel,timeoutSeconds:t.timeoutSeconds,jira:r.jiraFor(t.repoName??""),nextLogSeq:l(),rounds:t.rounds+1,createdAt:t.createdAt,claudeConfigDir:t.claudeConfigDir,actorEmail:t.actorEmail,agent:t.agent,model:t.model,baseRepoPath:t.baseRepoPath,repoName:t.repoName,branch:t.branch,baseBranch:t.baseBranch,jiraTransition:t.jiraTransition,jiraTransitionOnMerge:t.jiraTransitionOnMerge,requireApproval:t.requireApproval,mergeOnApprove:t.mergeOnApprove,mergeMethod:t.mergeMethod,autoMerge:t.autoMerge,runTests:t.runTests,maxTurns:t.maxTurns,issueSummary:t.issueSummary},v,s,i,w);return}In(c),await Yp({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,allowWeb:t.allowWeb},sendUsage:o,mergeOnApprove:t.mergeOnApprove,mergeMethod:t.mergeMethod,autoMerge:t.autoMerge??!1,emit:s,setStatus:i}),Ft(t.runId)}catch(p){let f=p instanceof Error?p.message:String(p);s("error",`Run failed: ${f}`),await Bt(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,f),Ft(t.runId),i("failed",{error:f})}finally{d||await Dt(t.baseRepoPath??c,c).catch(()=>{})}}async function Yp(t){let{runId:e,issueKey:n,issueSummary:r,worktreePath:s,baseRepoPath:i,branch:o,baseBranch:l,jiraTransition:c,jiraTransitionOnMerge:d,requireApproval:p,doneLabel:f,failedLabel:w,repoName:v,jira:_,cfg:I,actorEmail:R,runTests:C,mergeOnApprove:V,mergeMethod:J,autoMerge:$,resultText:b,costFields:U,emit:j,setStatus:K}=t,F=await ks(s);F.deleted.length&&j("info",`Deleted ${F.deleted.length} file(s) listed in ${an}: `+F.deleted.slice(0,10).join(", ")+(F.deleted.length>10?", \u2026":""));for(let re of F.refused)j("warn",`${an} entry refused: ${re}`);j("info","Committing changes"),await Er(s,`${n}: ${r}
718
719
 
719
- Allwright run ${e}`);let u=await $n(s,l);if(!u.ok){let ae=u.forbidden.length?`refusing to push: changes touch protected paths (${u.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 (${u.files} files, ${u.insertions+u.deletions} lines; limits ${Rn}/${An})`;j("error",ae),await Ut(_,n,e,w,ae),H("failed",{error:ae,errorKind:"guard",...U});return}j("info",`Diff: ${u.files} file(s), +${u.insertions}/-${u.deletions}`);let m={...U},g="",x="",P,O,Z;if(C){let ae=xs(s);if(!ae)j("info","No TEST.md in this repo - skipping the test run (nothing documented to run)");else{let xe=Is(mc.default.readFileSync(ae,"utf8"));if(!xe.length)j("info",`${Zo.default.basename(ae)} lists no commands - nothing to run`);else{j("info",`Running ${xe.length} documented test command(s) - no tokens, plain shell`);let Ne=await Cr(s,xe,{perCommandTimeoutMs:15*6e4}),Be=Ne.filter(fe=>fe.exitCode!==0),Bn=Be.length;for(let fe of Ne)j(fe.exitCode===0?"info":"warn",$p(fe));let st="";if(Be.length&&t.fixSession){let fe=await Ak({runId:e,issueKey:n,worktreePath:s,baseBranch:l,fixSession:t.fixSession,agentConfigDir:t.agentConfigDir,cfg:I,failed:Be,emit:j,sendUsage:t.sendUsage,baseCost:m});if(m.costUsd+=fe.cost.costUsd,m.inputTokens+=fe.cost.inputTokens,m.outputTokens+=fe.cost.outputTokens,fe.outcome==="cancelled"){let J="stopped by a person during the automatic test-fix attempt - nothing was pushed";j("warn",J),Bo({runId:e,issueKey:n,issueSummary:r,mergeOnApprove:Y,mergeMethod:X,autoMerge:$,repoName:v,baseRepoPath:i,branch:o,baseBranch:l,headSha:await Ye(s),requireApproval:p,doneLabel:f,failedLabel:w,jiraTransition:c,jiraTransitionOnMerge:d,actorEmail:E,resultSummary:Op(b),prSummary:fc(b)??"",costUsd:m.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),await Ut(_,n,e,w,`${J}. The commit survived on the runner - "Retry push" on the run's dashboard page ships it without a new agent run.`),H("failed",{error:J,errorKind:"guard",retryAvailable:!0,...m});return}if(fe.outcome==="committed"){x=fe.resultText,j("info",`Re-running ${xe.length} documented test command(s) after the fix`),Ne=await Cr(s,xe,{perCommandTimeoutMs:15*6e4}),Be=Ne.filter(J=>J.exitCode!==0);for(let J of Ne)j(J.exitCode===0?"info":"warn",$p(J));st=Be.length?`One automatic same-session fix attempt ran; the results above are AFTER it. First pass: ${Bn} failure(s). ${fe.note}`:`The first pass had ${Bn} failure(s); one automatic same-session fix attempt resolved them. ${fe.note}`}else st=fe.note}P=Be.slice(0,20).map(fe=>({command:fe.command.slice(0,500),exitCode:fe.exitCode,tail:fe.tail.slice(-4e3)})),O=Ne.length-Be.length,Z=Ne.length,g=`
720
+ Allwright run ${e}`);let u=await On(s,l);if(!u.ok){let re=u.forbidden.length?`refusing to push: changes touch protected paths (${u.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 (${u.files} files, ${u.insertions+u.deletions} lines; limits ${Pn}/${Nn})`;j("error",re),await Bt(_,n,e,w,re),K("failed",{error:re,errorKind:"guard",...U});return}j("info",`Diff: ${u.files} file(s), +${u.insertions}/-${u.deletions}`);let m={...U},y="",x="",M,P,Y;if(C){let re=Rs(s);if(!re)j("info","No TEST.md in this repo - skipping the test run (nothing documented to run)");else{let xe=Es(Yo.default.readFileSync(re,"utf8"));if(!xe.length)j("info",`${Xo.default.basename(re)} lists no commands - nothing to run`);else{j("info",`Running ${xe.length} documented test command(s) - no tokens, plain shell`);let Pe=await Pr(s,xe,{perCommandTimeoutMs:15*6e4}),Ke=Pe.filter(fe=>fe.exitCode!==0),Ys=Ke.length;for(let fe of Pe)j(fe.exitCode===0?"info":"warn",Up(fe));let wn="";if(Ke.length&&t.fixSession){let fe=await s_({runId:e,issueKey:n,worktreePath:s,baseBranch:l,fixSession:t.fixSession,agentConfigDir:t.agentConfigDir,cfg:I,failed:Ke,emit:j,sendUsage:t.sendUsage,baseCost:m});if(m.costUsd+=fe.cost.costUsd,m.inputTokens+=fe.cost.inputTokens,m.outputTokens+=fe.cost.outputTokens,fe.outcome==="cancelled"){let Ze="stopped by a person during the automatic test-fix attempt - nothing was pushed";j("warn",Ze),Go({runId:e,issueKey:n,issueSummary:r,mergeOnApprove:V,mergeMethod:J,autoMerge:$,repoName:v,baseRepoPath:i,branch:o,baseBranch:l,headSha:await Qe(s),requireApproval:p,doneLabel:f,failedLabel:w,jiraTransition:c,jiraTransitionOnMerge:d,actorEmail:R,resultSummary:Bp(b),prSummary:Tc(b)??"",costUsd:m.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),await Bt(_,n,e,w,`${Ze}. The commit survived on the runner - "Retry push" on the run's dashboard page ships it without a new agent run.`),K("failed",{error:Ze,errorKind:"guard",retryAvailable:!0,...m});return}if(fe.outcome==="committed"){x=fe.resultText,j("info",`Re-running ${xe.length} documented test command(s) after the fix`),Pe=await Pr(s,xe,{perCommandTimeoutMs:15*6e4}),Ke=Pe.filter(Ze=>Ze.exitCode!==0);for(let Ze of Pe)j(Ze.exitCode===0?"info":"warn",Up(Ze));wn=Ke.length?`One automatic same-session fix attempt ran; the results above are AFTER it. First pass: ${Ys} failure(s). ${fe.note}`:`The first pass had ${Ys} failure(s); one automatic same-session fix attempt resolved them. ${fe.note}`}else wn=fe.note}M=Ke.slice(0,20).map(fe=>({command:fe.command.slice(0,500),exitCode:fe.exitCode,tail:fe.tail.slice(-4e3)})),P=Pe.length-Ke.length,Y=Pe.length,y=`
720
721
 
721
722
  ### Tests
722
- `+Ne.map(fe=>`- ${fe.exitCode===0?"PASS":"FAIL"} \`${fe.command}\``).join(`
723
- `)+(Be.length?`
723
+ `+Pe.map(fe=>`- ${fe.exitCode===0?"PASS":"FAIL"} \`${fe.command}\``).join(`
724
+ `)+(Ke.length?`
724
725
 
725
- **${Be.length} of ${Ne.length} failed.** Output is in the run log.`:`
726
+ **${Ke.length} of ${Pe.length} failed.** Output is in the run log.`:`
726
727
 
727
- All ${Ne.length} passed.`)+(st?`
728
+ All ${Pe.length} passed.`)+(wn?`
728
729
 
729
- ${st}`:""),Be.length&&j("warn",`${Be.length} test command(s) failed - the PR will say so; review before merging`),Bn>0&&ft(i,{issueKey:n,runId:e,title:Be.length?`TEST.md commands failing at PR (${Be.length} of ${Ne.length})`:"TEST.md failures fixed by same-session retry",detail:Ne.map(fe=>`${fe.exitCode===0?"PASS":"FAIL"} ${fe.command}`).join(`
730
- `)+(st?`
731
- ${st}`:"")})}}}let W=await Rr(s),B=_t(W);if(!B){let ae=`origin "${W}" is not a GitHub remote - implement mode supports GitHub only`;j("error",ae),await Ut(_,n,e,w,ae),H("failed",{error:ae,...U});return}let D=await Ye(s),ue=Op(b),V=(x?fc(x):null)??fc(b);try{await Bp({gitDir:s,ownerRepo:B,runId:e,issueKey:n,issueSummary:r,agentConfigDir:t.agentConfigDir,branch:o,baseBranch:l,jiraTransition:c,jiraTransitionOnMerge:d,requireApproval:p,doneLabel:f,failedLabel:w,repoName:v,jira:_,cfg:I,actorEmail:E,mergeOnApprove:Y,mergeMethod:X,autoMerge:$,summary:ue,prSummary:V??void 0,cost:m,testReport:g,failedTests:P,testsPassed:O,testsTotal:Z,goLiveDraft:(x?Cp(x):null)??Cp(b)??void 0,emit:j,setStatus:H})}catch(ae){let xe=ae instanceof Error?ae.message:String(ae);Bo({runId:e,issueKey:n,issueSummary:r,mergeOnApprove:Y,mergeMethod:X,autoMerge:$,repoName:v,baseRepoPath:i,branch:o,baseBranch:l,headSha:D,requireApproval:p,doneLabel:f,failedLabel:w,jiraTransition:c,jiraTransitionOnMerge:d,actorEmail:E,resultSummary:ue,prSummary:V??"",costUsd:m.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),j("error",`Run failed: ${xe}`),j("info",`The commit itself survived on the runner (branch ${o}) - fix the cause, then use "Retry push" on this run's dashboard page.`),await Ut(_,n,e,w,`${xe}
730
+ ${wn}`:""),Ke.length&&j("warn",`${Ke.length} test command(s) failed - the PR will say so; review before merging`),Ys>0&&mt(i,{issueKey:n,runId:e,title:Ke.length?`TEST.md commands failing at PR (${Ke.length} of ${Pe.length})`:"TEST.md failures fixed by same-session retry",detail:Pe.map(fe=>`${fe.exitCode===0?"PASS":"FAIL"} ${fe.command}`).join(`
731
+ `)+(wn?`
732
+ ${wn}`:"")})}}}let B=await Cr(s),q=St(B);if(!q){let re=`origin "${B}" is not a GitHub remote - implement mode supports GitHub only`;j("error",re),await Bt(_,n,e,w,re),K("failed",{error:re,...U});return}let D=await Qe(s),ce=Bp(b),Z=(x?Tc(x):null)??Tc(b);try{await Xp({gitDir:s,ownerRepo:q,runId:e,issueKey:n,issueSummary:r,agentConfigDir:t.agentConfigDir,branch:o,baseBranch:l,jiraTransition:c,jiraTransitionOnMerge:d,requireApproval:p,doneLabel:f,failedLabel:w,repoName:v,jira:_,cfg:I,actorEmail:R,mergeOnApprove:V,mergeMethod:J,autoMerge:$,summary:ce,prSummary:Z??void 0,cost:m,testReport:y,failedTests:M,testsPassed:P,testsTotal:Y,goLiveDraft:(x?Lp(x):null)??Lp(b)??void 0,emit:j,setStatus:K})}catch(re){let xe=re instanceof Error?re.message:String(re);Go({runId:e,issueKey:n,issueSummary:r,mergeOnApprove:V,mergeMethod:J,autoMerge:$,repoName:v,baseRepoPath:i,branch:o,baseBranch:l,headSha:D,requireApproval:p,doneLabel:f,failedLabel:w,jiraTransition:c,jiraTransitionOnMerge:d,actorEmail:R,resultSummary:ce,prSummary:Z??"",costUsd:m.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),j("error",`Run failed: ${xe}`),j("info",`The commit itself survived on the runner (branch ${o}) - fix the cause, then use "Retry push" on this run's dashboard page.`),await Bt(_,n,e,w,`${xe}
732
733
 
733
- The agent's commit survived on the runner - "Retry push" on the dashboard's run page re-pushes it without a new agent run.`),H("failed",{error:xe,retryAvailable:!0,...m})}}async function Ak(t){let{runId:e,issueKey:n,worktreePath:r,baseBranch:s,fixSession:i,cfg:o,failed:l,emit:c,sendUsage:d,baseCost:p}=t,f=Je(i.agent);if(!f?.capabilities.sessionResume){let C=`No automatic fix attempt: the ${i.agent||"configured"} adapter cannot resume sessions.`;return c("info",C),{outcome:"skipped",note:C,cost:Rk}}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 Ye(r),v=await $s(e,f,{repoPath:r,prompt:wk(l),timeoutSeconds:i.timeoutSeconds,bin:Xe(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:(C,Y)=>c(C,Y),onUsage:d?C=>d({...C,inputTokens:p.inputTokens+C.inputTokens,outputTokens:p.outputTokens+C.outputTokens,costUsd:C.costUsd===void 0?void 0:p.costUsd+C.costUsd}):void 0},c),_={costUsd:v.costUsd,inputTokens:v.inputTokens,outputTokens:v.outputTokens};if(v.cancelled)return{outcome:"cancelled",cost:_};if(!v.ok){let C=`One automatic fix attempt did not complete (${v.error??"agent error"}) - the results above are from the original work.`;return c("warn",C),{outcome:"agent_failed",note:C,cost:_}}if(ki(v.resultText)){let C="One automatic fix attempt asked for human input instead of fixing - the original commit ships unchanged; answer on the PR instead.";return c("warn",C),{outcome:"agent_failed",note:C,cost:_}}let I=await ws(r);for(let C of I.refused)c("warn",`${nn} entry refused: ${C}`);try{await Ir(r,`${n}: fix failing TEST.md commands
734
+ The agent's commit survived on the runner - "Retry push" on the dashboard's run page re-pushes it without a new agent run.`),K("failed",{error:xe,retryAvailable:!0,...m})}}async function s_(t){let{runId:e,issueKey:n,worktreePath:r,baseBranch:s,fixSession:i,cfg:o,failed:l,emit:c,sendUsage:d,baseCost:p}=t,f=et(i.agent);if(!f?.capabilities.sessionResume){let C=`No automatic fix attempt: the ${i.agent||"configured"} adapter cannot resume sessions.`;return c("info",C),{outcome:"skipped",note:C,cost:r_}}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 Qe(r),v=await Ns(e,f,{repoPath:r,prompt:Zk(l),timeoutSeconds:i.timeoutSeconds,bin:Be(o,i.agent),configDir:t.agentConfigDir,mode:i.allowWeb?"edit_no_shell_web":"edit_no_shell",model:i.model||void 0,maxTurns:Math.min(i.maxTurns??120,60),sessionId:i.sessionId,resume:!0,onLog:(C,V)=>c(C,V),onUsage:d?C=>d({...C,inputTokens:p.inputTokens+C.inputTokens,outputTokens:p.outputTokens+C.outputTokens,costUsd:C.costUsd===void 0?void 0:p.costUsd+C.costUsd}):void 0},c),_={costUsd:v.costUsd,inputTokens:v.inputTokens,outputTokens:v.outputTokens};if(v.cancelled)return{outcome:"cancelled",cost:_};if(!v.ok){let C=`One automatic fix attempt did not complete (${v.error??"agent error"}) - the results above are from the original work.`;return c("warn",C),{outcome:"agent_failed",note:C,cost:_}}if(Ti(v.resultText)){let C="One automatic fix attempt asked for human input instead of fixing - the original commit ships unchanged; answer on the PR instead.";return c("warn",C),{outcome:"agent_failed",note:C,cost:_}}let I=await ks(r);for(let C of I.refused)c("warn",`${an} entry refused: ${C}`);try{await Er(r,`${n}: fix failing TEST.md commands
734
735
 
735
- Allwright run ${e} (automatic test-fix attempt)`)}catch{let C=`An automatic fix attempt concluded no code change was warranted: ${zr(v.resultText)}`;return c("info",C),{outcome:"no_changes",note:C,cost:_}}let E=await $n(r,s);if(!E.ok){await vs(r,w);let C=E.forbidden.length?`An automatic fix attempt touched protected paths (${E.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",C),{outcome:"reverted",note:C,cost:_}}return{outcome:"committed",note:`Fix attempt: ${zr(v.resultText)}`,resultText:v.resultText,cost:_}}async function Bp(t){let{gitDir:e,ownerRepo:n,runId:r,issueKey:s,issueSummary:i,mergeOnApprove:o,mergeMethod:l,autoMerge:c,branch:d,baseBranch:p,jiraTransition:f,jiraTransitionOnMerge:w,requireApproval:v,doneLabel:_,failedLabel:I,repoName:E,jira:C,cfg:Y,actorEmail:X,summary:$,prSummary:b,cost:U,testReport:j,emit:H,setStatus:q}=t;H("info",`Pushing ${d} to origin`),await Er(e,d);let u=await To(e,d),g=`${b?.trim()?`${b.trim()}
736
+ Allwright run ${e} (automatic test-fix attempt)`)}catch{let C=`An automatic fix attempt concluded no code change was warranted: ${Lr(v.resultText)}`;return c("info",C),{outcome:"no_changes",note:C,cost:_}}let R=await On(r,s);if(!R.ok){await _s(r,w);let C=R.forbidden.length?`An automatic fix attempt touched protected paths (${R.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",C),{outcome:"reverted",note:C,cost:_}}return{outcome:"committed",note:`Fix attempt: ${Lr(v.resultText)}`,resultText:v.resultText,cost:_}}async function Xp(t){let{gitDir:e,ownerRepo:n,runId:r,issueKey:s,issueSummary:i,mergeOnApprove:o,mergeMethod:l,autoMerge:c,branch:d,baseBranch:p,jiraTransition:f,jiraTransitionOnMerge:w,requireApproval:v,doneLabel:_,failedLabel:I,repoName:R,jira:C,cfg:V,actorEmail:J,summary:$,prSummary:b,cost:U,testReport:j,emit:K,setStatus:F}=t;K("info",`Pushing ${d} to origin`),await Ar(e,d);let u=await Ro(e,d),y=`${b?.trim()?`${b.trim()}
736
737
 
737
738
  <details>
738
739
  <summary>Technical details</summary>
@@ -742,14 +743,14 @@ ${$}
742
743
  </details>`:$}${j??""}
743
744
 
744
745
  ---
745
- Jira: ${new URL(`/browse/${s}`,Y.jira?.baseUrl??"").toString()}
746
- _Allwright implement run \`${r}\` \xB7 cost $${U.costUsd.toFixed(4)}. `+(j?"Tests were run by the runner, not the agent._":"The agent has no shell and no tests were run here - review accordingly._");H("info","Opening pull request");let x=Ro(ke()??Y,E,X);x.source==="user"&&H("info",`PR will be authored with ${X}'s own GitHub token`);let O=await new Fe(x.token).createPullRequest(n.owner,n.repo,{title:`${s}: ${i}`.slice(0,250),head:d,base:p,body:g});H("info",`PR ready: ${O.url}`),xp({runId:r,issueKey:s,repoName:E,owner:n.owner,repo:n.repo,prNumber:O.number,prUrl:O.url,jiraTransitionOnMerge:w??"",createdAt:new Date().toISOString()}),q("posting",U);let Z={nextDecisionSeq:1e5,runId:r,issueKey:s,repoName:E,owner:n.owner,repo:n.repo,prNumber:O.number,prUrl:O.url,branch:d,headSha:u,doneLabel:_,failedLabel:I,jiraTransition:f,mergeOnApprove:o,mergeMethod:l,autoMerge:c,agentConfigDir:t.agentConfigDir};if(v)xt(Z),await C.addComment(s,`**Allwright opened a pull request for review.**
746
+ Jira: ${new URL(`/browse/${s}`,V.jira?.baseUrl??"").toString()}
747
+ _Allwright implement run \`${r}\` \xB7 cost $${U.costUsd.toFixed(4)}. `+(j?"Tests were run by the runner, not the agent._":"The agent has no shell and no tests were run here - review accordingly._");K("info","Opening pull request");let x=$o(ve()??V,R,J);x.source==="user"&&K("info",`PR will be authored with ${J}'s own GitHub token`);let P=await new He(x.token).createPullRequest(n.owner,n.repo,{title:`${s}: ${i}`.slice(0,250),head:d,base:p,body:y});K("info",`PR ready: ${P.url}`),jp({runId:r,issueKey:s,repoName:R,owner:n.owner,repo:n.repo,prNumber:P.number,prUrl:P.url,jiraTransitionOnMerge:w??"",createdAt:new Date().toISOString()}),F("posting",U);let Y={nextDecisionSeq:1e5,runId:r,issueKey:s,repoName:R,owner:n.owner,repo:n.repo,prNumber:P.number,prUrl:P.url,branch:d,headSha:u,doneLabel:_,failedLabel:I,jiraTransition:f,mergeOnApprove:o,mergeMethod:l,autoMerge:c,agentConfigDir:t.agentConfigDir};if(v)Rt(Y),await C.addComment(s,`**Allwright opened a pull request for review.**
747
748
 
748
- PR: ${O.url}
749
+ PR: ${P.url}
749
750
 
750
- 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}\`)`),q("awaiting_approval",{...U,prUrl:O.url,headSha:u,resultSummary:zr(b?.trim()||$),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}:{}}),H("info",`Awaiting approval on the dashboard \xB7 $${U.costUsd.toFixed(4)}`);else{if(c){H("info",`Auto-merging PR #${O.number} (${l})`);let B=Ue(Y,E),D=B?await new Fe(B).mergePullRequest(n.owner,n.repo,O.number,l,{sha:u,title:`${s} (#${O.number})`}):{merged:!1,reason:"no GitHub token applies to this repo"};D.merged?H("info",`PR #${O.number} merged`):(H("warn",`Auto-merge did not go through - ${D.reason}. The PR stays open.`),await C.addComment(s,`**Allwright:** the work is done and the PR is open, but auto-merge did not go through - ${D.reason}
751
+ 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}\`)`),F("awaiting_approval",{...U,prUrl:P.url,headSha:u,resultSummary:Lr(b?.trim()||$),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}:{}}),K("info",`Awaiting approval on the dashboard \xB7 $${U.costUsd.toFixed(4)}`);else{if(c){K("info",`Auto-merging PR #${P.number} (${l})`);let q=qe(V,R),D=q?await new He(q).mergePullRequest(n.owner,n.repo,P.number,l,{sha:u,title:`${s} (#${P.number})`}):{merged:!1,reason:"no GitHub token applies to this repo"};D.merged?K("info",`PR #${P.number} merged`):(K("warn",`Auto-merge did not go through - ${D.reason}. The PR stays open.`),await C.addComment(s,`**Allwright:** the work is done and the PR is open, but auto-merge did not go through - ${D.reason}
751
752
 
752
- PR: ${O.url}`))}let W=(ke()??Y).repos[E]?.path;W&&li(W,s)&&ft(W,{issueKey:s,runId:r,title:"shipped after earlier failure",detail:`PR ${O.url} merged/opened straight-through.`}),await Hp({jira:C,issueKey:s},Z,H),q("succeeded",{...U,prUrl:O.url,headSha:u,resultSummary:zr(b?.trim()||$),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}:{}}),H("info",`Run succeeded \xB7 ${O.url} \xB7 $${U.costUsd.toFixed(4)}`)}}async function Hp(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.**
753
+ PR: ${P.url}`))}let B=(ve()??V).repos[R]?.path;B&&di(B,s)&&mt(B,{issueKey:s,runId:r,title:"shipped after earlier failure",detail:`PR ${P.url} merged/opened straight-through.`}),await Qp({jira:C,issueKey:s},Y,K),F("succeeded",{...U,prUrl:P.url,headSha:u,resultSummary:Lr(b?.trim()||$),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}:{}}),K("info",`Run succeeded \xB7 ${P.url} \xB7 $${U.costUsd.toFixed(4)}`)}}async function Qp(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.**
753
754
 
754
755
  PR: ${e.prUrl}`:`**Allwright: the change is approved, but NOT merged yet.**
755
756
 
@@ -759,77 +760,77 @@ This rule is set to "my team merges on GitHub", so Allwright deliberately did no
759
760
 
760
761
  Note: ${r}`:"")+`
761
762
 
762
- (run \`${e.runId}\`)`),await t.jira.editLabels(e.issueKey,{add:[e.doneLabel],remove:[Ie.NEEDS_INPUT_LABEL]}),r}async function vi(t,e,n){let r=As(e);if(!r){y.warn(`run.approved for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:s,setStatus:i}=Wp(t,e);try{let o=Ue(ke()??t.cfg,r.repoName);if(!o)throw new Error("GitHub token missing on this runner");let l=new Fe(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 d=n??r.headSha;if(c.state==="open"&&c.headSha!==d){let p=`PR #${r.prNumber} changed since review started (${d.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:d,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}
763
+ (run \`${e.runId}\`)`),await t.jira.editLabels(e.issueKey,{add:[e.doneLabel],remove:[Ee.NEEDS_INPUT_LABEL]}),r}async function Si(t,e,n){let r=$s(e);if(!r){g.warn(`run.approved for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:s,setStatus:i}=nf(t,e);try{let o=qe(ve()??t.cfg,r.repoName);if(!o)throw new Error("GitHub token missing on this runner");let l=new He(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 d=n??r.headSha;if(c.state==="open"&&c.headSha!==d){let p=`PR #${r.prNumber} changed since review started (${d.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:d,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}
763
764
 
764
- PR: ${r.prUrl}`),i("awaiting_approval",{prUrl:r.prUrl,headSha:c.headSha,resultSummary:f});return}s("info",`PR #${r.prNumber} merged`)}{let p=(ke()??t.cfg).repos[r.repoName??""]?.path;p&&li(p,r.issueKey)&&ft(p,{issueKey:r.issueKey,runId:e,title:"shipped after earlier failure",detail:`PR ${r.prUrl} approved and completed.`})}await Hp({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.'),Nr(e)}catch(o){let l=o instanceof Error?o.message:String(o);s("error",`Approval handling failed: ${l}`),await Zp(t,r,l),i("failed",{error:l}),Nr(e)}}async function Kp(t,e){let n=As(e);if(!n){y.warn(`run.rejected for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:r,setStatus:s}=Wp(t,e);try{let i=Ue(ke()??t.cfg,n.repoName);if(!i)throw new Error("GitHub token missing on this runner");let o=new Fe(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.**
765
+ PR: ${r.prUrl}`),i("awaiting_approval",{prUrl:r.prUrl,headSha:c.headSha,resultSummary:f});return}s("info",`PR #${r.prNumber} merged`)}{let p=(ve()??t.cfg).repos[r.repoName??""]?.path;p&&di(p,r.issueKey)&&mt(p,{issueKey:r.issueKey,runId:e,title:"shipped after earlier failure",detail:`PR ${r.prUrl} approved and completed.`})}await Qp({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.'),Or(e)}catch(o){let l=o instanceof Error?o.message:String(o);s("error",`Approval handling failed: ${l}`),await rf(t,r,l),i("failed",{error:l}),Or(e)}}async function ef(t,e){let n=$s(e);if(!n){g.warn(`run.rejected for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:r,setStatus:s}=nf(t,e);try{let i=qe(ve()??t.cfg,n.repoName);if(!i)throw new Error("GitHub token missing on this runner");let o=new He(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.**
765
766
 
766
- 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"),Nr(e)}catch(i){let o=i instanceof Error?i.message:String(i);r("error",`Rejection handling failed: ${o}`),await Zp(t,n,o),s("failed",{error:o}),Nr(e)}}async function Gp(t,e){let n=Ho(e);if(!n){y.warn(`run.retryPush for ${e}: no retry record (already pushed, or invalidated?)`);let{emit:l,setStatus:c,sendUsage:d}=jr(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}=jr(e,t.transport,n.nextLogSeq);try{let l=await To(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.`),dc(e),s("failed",{retryAvailable:!1});return}let c=await Rr(n.baseRepoPath),d=_t(c);if(!d)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 Bp({gitDir:n.baseRepoPath,ownerRepo:d,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:ke()??t.cfg,actorEmail:n.actorEmail,summary:n.resultSummary,prSummary:n.prSummary||void 0,cost:{costUsd:n.costUsd},emit:r,setStatus:s}),dc(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}`),Bo({...n,nextLogSeq:o()}),s("failed",{error:c,retryAvailable:!0})}}function Wp(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 Zp(t,e,n){try{await t.jiraFor(e.repoName??"").addComment(e.issueKey,`**Allwright could not complete the approval decision.**
767
+ 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"),Or(e)}catch(i){let o=i instanceof Error?i.message:String(i);r("error",`Rejection handling failed: ${o}`),await rf(t,n,o),s("failed",{error:o}),Or(e)}}async function tf(t,e){let n=Wo(e);if(!n){g.warn(`run.retryPush for ${e}: no retry record (already pushed, or invalidated?)`);let{emit:l,setStatus:c,sendUsage:d}=zr(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}=zr(e,t.transport,n.nextLogSeq);try{let l=await Ro(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.`),kc(e),s("failed",{retryAvailable:!1});return}let c=await Cr(n.baseRepoPath),d=St(c);if(!d)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 Xp({gitDir:n.baseRepoPath,ownerRepo:d,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:ve()??t.cfg,actorEmail:n.actorEmail,summary:n.resultSummary,prSummary:n.prSummary||void 0,cost:{costUsd:n.costUsd},emit:r,setStatus:s}),kc(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}`),Go({...n,nextLogSeq:o()}),s("failed",{error:c,retryAvailable:!0})}}function nf(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 rf(t,e,n){try{await t.jiraFor(e.repoName??"").addComment(e.issueKey,`**Allwright could not complete the approval decision.**
767
768
 
768
769
  Error: ${n.slice(0,800)}
769
770
 
770
771
  PR: ${e.prUrl}
771
- (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 Ck(t,e,n){let r=0;for(let l of e)n(l.body)&&(r=Math.max(r,new Date(l.created).getTime()));let s=e.filter(l=>!n(l.body)&&new Date(l.created).getTime()>r),i=s.length?Mr(s):"(nothing new was said - re-read the newest comments above and do only what they ask)",o=t.files.length?t.files.map(l=>`- ${l}`).join(`
772
+ (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 i_(t,e,n){let r=0;for(let l of e)n(l.body)&&(r=Math.max(r,new Date(l.created).getTime()));let s=e.filter(l=>!n(l.body)&&new Date(l.created).getTime()>r),i=s.length?Dr(s):"(nothing new was said - re-read the newest comments above and do only what they ask)",o=t.files.length?t.files.map(l=>`- ${l}`).join(`
772
773
  `)+(t.more?`
773
- - (\u2026 ${t.more} more file(s))`:""):"(the commit touched no files this checkout can list)";return Mn.REVISION_PROMPT+`
774
+ - (\u2026 ${t.more} more file(s))`:""):"(the commit touched no files this checkout can list)";return Un.REVISION_PROMPT+`
774
775
 
775
776
  ALREADY SHIPPED: commit ${t.sha.slice(0,10)} - ${t.subject}
776
777
  Files it touched, your reading list:
777
778
  ${o}
778
779
 
779
780
  ASKED SINCE THAT DELIVERY - this is the work:
780
- ${i}`}function Mr(t){if(!t.length)return"(no comments)";let e=6e4,n=t.map(i=>`${i.author} (${i.created}):
781
+ ${i}`}function Dr(t){if(!t.length)return"(no comments)";let e=6e4,n=t.map(i=>`${i.author} (${i.created}):
781
782
  ${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(`
782
783
  ---
783
- `)}function Vp(t){return`The ticket author replied:
784
+ `)}function sf(t){return`The ticket author replied:
784
785
 
785
786
  ${t}
786
787
 
787
- 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 ${Ie.NEEDS_INPUT_MARKER} marker).`}function $k(t){if(!t)return!1;for(let n of t.matchAll(/`([^`\n]+)`/g)){let r=n[1].trim();if(r.length>=2&&!/\s/.test(r)&&/[A-Za-z]/.test(r))return!0}let e=t.replace(/\b[a-z][a-z0-9+.-]*:\/\/\S+/gi," ");return/[\w.-]+\/[\w./-]*[\w-]+\.[A-Za-z][A-Za-z0-9]{0,4}\b/.test(e)}function Pk(t){let e=t.trim().replace(/^[#*_>\s]+/,"").replace(/[*_:.\s]+$/,"");if(!/^[A-Za-z][A-Za-z \-]*$/.test(e))return!1;let n=r=>r.replace(/[^a-z]/gi,"").toUpperCase();return n(e)===n(Ie.NEEDS_INPUT_MARKER)}function ki(t){let e=t.trim().split(`
788
- `);for(let n=0;n<e.length;n++){if(!Pk(e[n]))continue;let r=e.slice(n+1).join(`
789
- `).trim();if(r)return r}return null}function Nk(t){let n=[...t.matchAll(new RegExp(`\`\`\`${Ie.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(`\`\`\`${Ie.NEEDS_INPUT_ASK_FENCE}\\s*\\n[\\s\\S]*?\`\`\``,"g"),"").trim()||t.trim(),options:r}}async function yi(t,e,n,r,s){let{questions:i,options:o}=Nk(e);n("info",`Claude needs more information - posting questions to ${t.issueKey}`),await t.jira.addComment(t.issueKey,`**${Ie.NEEDS_INPUT_COMMENT_MARKER} before it can continue.**
788
+ 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 ${Ee.NEEDS_INPUT_MARKER} marker).`}function o_(t){if(!t)return!1;for(let n of t.matchAll(/`([^`\n]+)`/g)){let r=n[1].trim();if(r.length>=2&&!/\s/.test(r)&&/[A-Za-z]/.test(r))return!0}let e=t.replace(/\b[a-z][a-z0-9+.-]*:\/\/\S+/gi," ");return/[\w.-]+\/[\w./-]*[\w-]+\.[A-Za-z][A-Za-z0-9]{0,4}\b/.test(e)}function a_(t){let e=t.trim().replace(/^[#*_>\s]+/,"").replace(/[*_:.\s]+$/,"");if(!/^[A-Za-z][A-Za-z \-]*$/.test(e))return!1;let n=r=>r.replace(/[^a-z]/gi,"").toUpperCase();return n(e)===n(Ee.NEEDS_INPUT_MARKER)}function Ti(t){let e=t.trim().split(`
789
+ `);for(let n=0;n<e.length;n++){if(!a_(e[n]))continue;let r=e.slice(n+1).join(`
790
+ `).trim();if(r)return r}return null}function l_(t){let n=[...t.matchAll(new RegExp(`\`\`\`${Ee.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(`\`\`\`${Ee.NEEDS_INPUT_ASK_FENCE}\\s*\\n[\\s\\S]*?\`\`\``,"g"),"").trim()||t.trim(),options:r}}async function vi(t,e,n,r,s){let{questions:i,options:o}=l_(e);n("info",`Claude needs more information - posting questions to ${t.issueKey}`),await t.jira.addComment(t.issueKey,`**${Ee.NEEDS_INPUT_COMMENT_MARKER} before it can continue.**
790
791
 
791
792
  ${i}
792
793
 
793
- 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:[Ie.NEEDS_INPUT_LABEL]}),Rp({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,preflight:t.preflight,ruleId:t.ruleId}),r("needs_input",{...s,resultSummary:zr(i),inputQuestions:i.slice(0,4e3),inputOptions:o}),n("info",`Waiting for an answer on ${t.issueKey} (label "${Ie.NEEDS_INPUT_LABEL}") or on this run page`+(o.length?` - ${o.length} suggested answer(s) offered`:""))}async function Yp(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 Ut(t,e.issueKey,e.runId,e.failedLabel,i),Lt(e.runId),r("failed",{error:i,...s})}async function Cs(t,e){await Ut(t.jira,t.issueKey,t.runId,t.rule.trigger.failedLabel,e)}async function Ut(t,e,n,r,s){try{await t.addComment(e,`**Allwright run failed.**
794
+ 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:[Ee.NEEDS_INPUT_LABEL]}),zp({runId:t.runId,issueKey:t.issueKey,kind:t.kind,allowWeb:t.allowWeb??!1,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,preflight:t.preflight,ruleId:t.ruleId}),r("needs_input",{...s,resultSummary:Lr(i),inputQuestions:i.slice(0,4e3),inputOptions:o}),n("info",`Waiting for an answer on ${t.issueKey} (label "${Ee.NEEDS_INPUT_LABEL}") or on this run page`+(o.length?` - ${o.length} suggested answer(s) offered`:""))}async function of(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 Bt(t,e.issueKey,e.runId,e.failedLabel,i),Ft(e.runId),r("failed",{error:i,...s})}async function Ps(t,e){await Bt(t.jira,t.issueKey,t.runId,t.rule.trigger.failedLabel,e)}async function Bt(t,e,n,r,s){try{await t.addComment(e,`**Allwright run failed.**
794
795
 
795
796
  Error: ${s.slice(0,800)}
796
797
 
797
- 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:[Ie.NEEDS_INPUT_LABEL]})}catch(i){y.error(`could not post failure comment to ${e}: ${i}`)}}function Op(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 fc(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 zr(t){for(let e of t.split(`
798
- `)){let n=e.replace(/^#+\s*/,"").trim();if(n.length>10)return n.slice(0,200)}return t.slice(0,200)}var mc,Zo,Vo,Ie,Mn,gk,yk,bk,jp,Pp,kk,Np,pc,_k,Sk,Tk,gi,Rk,Dr=ne(()=>{"use strict";mc=R(require("node:fs"),1),Zo=R(require("node:path"),1),Vo=require("node:crypto"),Ie=R(Re(),1);rl();Ee();oi();Dt();ec();jo();Oo();ci();Mn=R(Re(),1);dp();sc();Sp();Tt();Ar();jt();mi();zt();gk=`
798
+ 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:[Ee.NEEDS_INPUT_LABEL]})}catch(i){g.error(`could not post failure comment to ${e}: ${i}`)}}function Bp(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 Tc(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 Lr(t){for(let e of t.split(`
799
+ `)){let n=e.replace(/^#+\s*/,"").trim();if(n.length>10)return n.slice(0,200)}return t.slice(0,200)}var Yo,Xo,Qo,Ee,Un,Kk,Gk,Wk,Hp,qp,Jk,Fp,Sc,Yk,Xk,Qk,wi,r_,Ur=te(()=>{"use strict";Yo=E(require("node:fs"),1),Xo=E(require("node:path"),1),Qo=require("node:crypto"),Ee=E(Re(),1);pl();Ae();ci();xt();uc();Do();zo();hi();Un=E(Re(),1);vp();fc();Pp();It();$r();Lt();bi();qt();Kk=`
799
800
 
800
- 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.`,yk=`
801
+ 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.`,Gk=`
801
802
 
802
- 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.`,bk=`
803
+ 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.`,Wk=`
803
804
 
804
- 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.`;jp=5,Pp=2,kk=8,Np=2,pc="Your previous run on this ticket hit its wall-clock time limit - nothing failed. You are back in the SAME worktree with your uncommitted work intact and your own memory of the ticket. Check git status and your last steps, then continue exactly where you stopped - do not re-read files you already know or redo completed work. Finish the remaining work and end with the final summary the original instructions asked for.",_k="Proceed - this epic's own description is the spec for this run",Sk="Stop this run - the work lives in the child tickets",Tk="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.";gi=new Map;Rk={costUsd:0,inputTokens:0,outputTokens:0}});function Ok(){try{return wc.default.userInfo().username}catch{return"the user the runner service runs as"}}function jk(t,e){let n=Ur.default.join(t,"apps","api","prisma","manual"),r=Ur.default.join(t,"prisma","manual");for(let s of[n,r]){let i;try{i=Lr.default.readdirSync(s).filter(o=>o.endsWith(".sql")).sort()}catch{continue}for(let o of i.reverse())try{let l=Lr.default.readFileSync(Ur.default.join(s,o),"utf8");if(new RegExp(`"${e}"`,"i").test(l))return o}catch{}}return null}function vc(t,e){let n=t.slice(-4e3),r=Ok(),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 d=(i[1]??"").split(".").pop()??"",p=e?.cwd?jk(e.cwd,d):null;return{cause:`The code expects "${d}" 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 "${d}"`,"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 d="";try{let p=Ur.default.join(wc.default.homedir(),".nvm","versions","node"),f=Lr.default.readdirSync(p).sort();f.length&&(d=Ur.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'
805
+ 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.`;Hp=5,qp=2,Jk=8,Fp=2,Sc="Your previous run on this ticket hit its wall-clock time limit - nothing failed. You are back in the SAME worktree with your uncommitted work intact and your own memory of the ticket. Check git status and your last steps, then continue exactly where you stopped - do not re-read files you already know or redo completed work. Finish the remaining work and end with the final summary the original instructions asked for.",Yk="Proceed - this epic's own description is the spec for this run",Xk="Stop this run - the work lives in the child tickets",Qk="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.";wi=new Map;r_={costUsd:0,inputTokens:0,outputTokens:0}});function c_(){try{return Ec.default.userInfo().username}catch{return"the user the runner service runs as"}}function u_(t,e){let n=Fr.default.join(t,"apps","api","prisma","manual"),r=Fr.default.join(t,"prisma","manual");for(let s of[n,r]){let i;try{i=qr.default.readdirSync(s).filter(o=>o.endsWith(".sql")).sort()}catch{continue}for(let o of i.reverse())try{let l=qr.default.readFileSync(Fr.default.join(s,o),"utf8");if(new RegExp(`"${e}"`,"i").test(l))return o}catch{}}return null}function Ac(t,e){let n=t.slice(-4e3),r=c_(),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 d=(i[1]??"").split(".").pop()??"",p=e?.cwd?u_(e.cwd,d):null;return{cause:`The code expects "${d}" 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 "${d}"`,"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 d="";try{let p=Fr.default.join(Ec.default.homedir(),".nvm","versions","node"),f=qr.default.readdirSync(p).sort();f.length&&(d=Fr.default.join(p,f[f.length-1],"bin"))}catch{}return{cause:`"${o[1]}" was not on the PATH of the process that ran this. npm's own first line is "#!/usr/bin/env node", so pointing at npm by absolute path does not help - npm still has to find node, and a systemd unit starts with a bare PATH that has never heard of nvm. It exits 127 immediately, and with Restart=always it does that forever while the start timestamp keeps moving, which is why a restart can look like it worked.`,commands:["sudo mkdir -p /etc/systemd/system/<your-unit>.service.d",`sudo tee /etc/systemd/system/<your-unit>.service.d/path.conf >/dev/null <<'EOF'
805
806
  [Service]
806
807
  Environment=PATH=${d||"<the bin directory holding node>"}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
807
- 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 d=l[2]??l[4]??"",f=(Lr.default.existsSync("/etc/systemd/system")?Lr.default.readdirSync("/etc/systemd/system").filter(w=>w.endsWith(".service")).filter(w=>{try{let v=Lr.default.readFileSync(Ur.default.join("/etc/systemd/system",w),"utf8");return e?.cwd?v.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"}${d?`:${d}`:""}. `+(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 Jp(t){return t?`
808
+ 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 d=l[2]??l[4]??"",f=(qr.default.existsSync("/etc/systemd/system")?qr.default.readdirSync("/etc/systemd/system").filter(w=>w.endsWith(".service")).filter(w=>{try{let v=qr.default.readFileSync(Fr.default.join("/etc/systemd/system",w),"utf8");return e?.cwd?v.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"}${d?`:${d}`:""}. `+(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 af(t){return t?`
808
809
 
809
810
  What this means: ${t.cause}
810
811
  Run these ON THE DEPLOY MACHINE:
811
812
  `+t.commands.map(e=>` ${e}`).join(`
812
813
  `)+`
813
- ${t.note}`:""}var Lr,wc,Ur,Xp=ne(()=>{"use strict";Lr=R(require("node:fs"),1),wc=R(require("node:os"),1),Ur=R(require("node:path"),1)});function tf(t,e=512e3){try{let n=tt.default.statSync(t);return!n.isFile()||n.size>e?null:tt.default.readFileSync(t,"utf8")}catch{return null}}function nf(t,e=60){try{return tt.default.readdirSync(t).slice(0,e).map(n=>_i.default.join(t,n)).filter(n=>{try{return tt.default.statSync(n).isFile()}catch{return!1}})}catch{return[]}}function Yo(t,e=Mk){let n=t.replace(/\/+$/,"");if(!n)return[];let r=[];for(let s of e)for(let i of nf(s)){if(!i.endsWith(".service"))continue;let o=tf(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(`${_i.default.basename(i,".service")} (User=${c})`+(l?` runs: ${l}`:""))}return r}function rf(t,e=Qp,n=ef){let r=t.map(o=>o.trim().toLowerCase()).filter(Boolean);if(!r.length)return[];let s=[...e,...n.flatMap(o=>nf(o))],i=[];for(let o of s){let l=tf(o);if(!l)continue;let c=l.toLowerCase(),d=r.find(f=>c.includes(f));if(!d)continue;let p=l.split(`
814
- `).filter(f=>/reverse_proxy|proxy_pass|root\s+\*?\s*\//i.test(f)).map(f=>f.trim()).slice(0,8);i.push({file:o,host:d,lines:p})}return i}function sf(t){return`${t.file} mentions ${t.host}`+(t.lines.length?` - routing lines: ${t.lines.join(" | ")}`:" - no routing line found")}function zk(t,e=Qp,n=ef){return rf(t,e,n).map(sf)}function of(t){return t.trim().replace(/\/+$/,"")}function Dk(t){let e=t.trim().replace(/;\s*$/,"").replace(/\{\s*$/,"").trim(),n=/^root\s+(?:\*\s+)?(\S+)$/i.exec(e);return n?.[1]?of(n[1].replace(/^["']|["']$/g,"")):null}function Lk(t,e){let n=of(e);if(!n)return!1;let r=!1;for(let s of t){if(/(?:^|\s)(?:reverse_proxy|proxy_pass)(?:\s|$|;)/i.test(s))return!1;let i=Dk(s);i&&(i===n||i.startsWith(`${n}/`))&&(r=!0)}return r}function Uk(t){return t.replace(/(\b[a-z][a-z0-9+.-]*:\/\/)[^/\s@]+@/gi,"$1***@").replace(/\b(ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{10,}/g,"$1_***").replace(/\bgithub_pat_[A-Za-z0-9_]{10,}/g,"github_pat_***")}function qk(t){try{let e=tt.default.statSync(t).uid;return(0,qt.execFileSync)("id",["-nu",String(e)],{encoding:"utf8",timeout:5e3}).trim()||null}catch{return null}}function Jo(t){let e=(0,qt.spawnSync)("git",["-C",t,"ls-remote","--heads","origin"],{encoding:"utf8",timeout:25e3,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"true",GIT_SSH_COMMAND:"ssh -oBatchMode=yes"}});return e.status===0?{ok:!0,branches:(e.stdout??"").split(`
815
- `).map(n=>n.split(/\s+/)[1]??"").map(n=>n.replace(/^refs\/heads\//,"")).filter(Boolean)}:Fk(`${e.stderr??""}`,t,qk(t),e.error?.message)}function Fk(t,e,n,r){let s=Uk(t.trim()),i=s.split(`
816
- `).find(c=>c.trim())??r??"git failed with no output",o=n?`sudo -u ${n} `:"",l=`Verify it non-interactively (a plain ls-remote would just prompt you and pass): GIT_TERMINAL_PROMPT=0 GIT_ASKPASS=true git -C ${e} ls-remote --heads origin`;return/not a git repository/i.test(s)?{ok:!1,reason:"not-a-checkout",detail:`${e} is not a git checkout`,fix:`Clone the repository into ${e} first.`}:/No such remote|does not appear to be a git repository|'origin' does not appear/i.test(s)&&!/authenticat/i.test(s)?{ok:!1,reason:"no-remote",detail:`this checkout has no usable "origin" remote - ${i}`,fix:`Add it: ${o}git -C ${e} remote add origin <url>`}:/could not read (Username|Password)|terminal prompts disabled|Authentication failed|Invalid username or password|Permission denied \(publickey\)|Support for password authentication was removed|Repository not found|access rights|Host key verification failed/i.test(s)?{ok:!1,reason:"auth",detail:`cannot read origin: git has no usable credential${n?` for ${n}`:""} on this machine - ${i}. The branch may well exist; this machine simply cannot ask.`,fix:`Give ${n??"the user the deploy runs as"} a saved credential: ${o}git config --global credential.helper store, then ${o}git -C ${e} fetch origin once and paste a GitHub PAT as the password (an account password is refused). ${l}`}:/Could not resolve host|Connection (timed out|refused)|Network is unreachable|unable to access|Operation timed out/i.test(s)||r?{ok:!1,reason:"network",detail:`origin could not be reached from this machine - ${i}. This is DNS or a firewall, not a missing branch.`,fix:`Check outbound network from this machine, then re-run. ${l}`}:{ok:!1,reason:"unknown",detail:`origin could not be read - ${i}`,fix:`Run it by hand on this machine to see the whole error: ${o}git -C ${e} ls-remote --heads origin`}}function Si(t){let e=l=>{try{return(0,qt.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=Jo(t),r=e(["branch","--format=%(refname:short)"]),s=e(["branch","-r","--format=%(refname:short)"]),i=n.ok?n.branches:null,o=[`
814
+ ${t.note}`:""}var qr,Ec,Fr,lf=te(()=>{"use strict";qr=E(require("node:fs"),1),Ec=E(require("node:os"),1),Fr=E(require("node:path"),1)});function df(t,e=512e3){try{let n=rt.default.statSync(t);return!n.isFile()||n.size>e?null:rt.default.readFileSync(t,"utf8")}catch{return null}}function hf(t,e=60){try{return rt.default.readdirSync(t).slice(0,e).map(n=>xi.default.join(t,n)).filter(n=>{try{return rt.default.statSync(n).isFile()}catch{return!1}})}catch{return[]}}function ea(t,e=d_){let n=t.replace(/\/+$/,"");if(!n)return[];let r=[];for(let s of e)for(let i of hf(s)){if(!i.endsWith(".service"))continue;let o=df(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(`${xi.default.basename(i,".service")} (User=${c})`+(l?` runs: ${l}`:""))}return r}function pf(t,e=cf,n=uf){let r=t.map(o=>o.trim().toLowerCase()).filter(Boolean);if(!r.length)return[];let s=[...e,...n.flatMap(o=>hf(o))],i=[];for(let o of s){let l=df(o);if(!l)continue;let c=l.toLowerCase(),d=r.find(f=>c.includes(f));if(!d)continue;let p=l.split(`
815
+ `).filter(f=>/reverse_proxy|proxy_pass|root\s+\*?\s*\//i.test(f)).map(f=>f.trim()).slice(0,8);i.push({file:o,host:d,lines:p})}return i}function ff(t){return`${t.file} mentions ${t.host}`+(t.lines.length?` - routing lines: ${t.lines.join(" | ")}`:" - no routing line found")}function h_(t,e=cf,n=uf){return pf(t,e,n).map(ff)}function mf(t){return t.trim().replace(/\/+$/,"")}function p_(t){let e=t.trim().replace(/;\s*$/,"").replace(/\{\s*$/,"").trim(),n=/^root\s+(?:\*\s+)?(\S+)$/i.exec(e);return n?.[1]?mf(n[1].replace(/^["']|["']$/g,"")):null}function f_(t,e){let n=mf(e);if(!n)return!1;let r=!1;for(let s of t){if(/(?:^|\s)(?:reverse_proxy|proxy_pass)(?:\s|$|;)/i.test(s))return!1;let i=p_(s);i&&(i===n||i.startsWith(`${n}/`))&&(r=!0)}return r}function m_(t){return t.replace(/(\b[a-z][a-z0-9+.-]*:\/\/)[^/\s@]+@/gi,"$1***@").replace(/\b(ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{10,}/g,"$1_***").replace(/\bgithub_pat_[A-Za-z0-9_]{10,}/g,"github_pat_***")}function g_(t){try{let e=rt.default.statSync(t).uid;return(0,Ht.execFileSync)("id",["-nu",String(e)],{encoding:"utf8",timeout:5e3}).trim()||null}catch{return null}}function ta(t){let e=(0,Ht.spawnSync)("git",["-C",t,"ls-remote","--heads","origin"],{encoding:"utf8",timeout:25e3,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"true",GIT_SSH_COMMAND:"ssh -oBatchMode=yes"}});return e.status===0?{ok:!0,branches:(e.stdout??"").split(`
816
+ `).map(n=>n.split(/\s+/)[1]??"").map(n=>n.replace(/^refs\/heads\//,"")).filter(Boolean)}:y_(`${e.stderr??""}`,t,g_(t),e.error?.message)}function y_(t,e,n,r){let s=m_(t.trim()),i=s.split(`
817
+ `).find(c=>c.trim())??r??"git failed with no output",o=n?`sudo -u ${n} `:"",l=`Verify it non-interactively (a plain ls-remote would just prompt you and pass): GIT_TERMINAL_PROMPT=0 GIT_ASKPASS=true git -C ${e} ls-remote --heads origin`;return/not a git repository/i.test(s)?{ok:!1,reason:"not-a-checkout",detail:`${e} is not a git checkout`,fix:`Clone the repository into ${e} first.`}:/No such remote|does not appear to be a git repository|'origin' does not appear/i.test(s)&&!/authenticat/i.test(s)?{ok:!1,reason:"no-remote",detail:`this checkout has no usable "origin" remote - ${i}`,fix:`Add it: ${o}git -C ${e} remote add origin <url>`}:/could not read (Username|Password)|terminal prompts disabled|Authentication failed|Invalid username or password|Permission denied \(publickey\)|Support for password authentication was removed|Repository not found|access rights|Host key verification failed/i.test(s)?{ok:!1,reason:"auth",detail:`cannot read origin: git has no usable credential${n?` for ${n}`:""} on this machine - ${i}. The branch may well exist; this machine simply cannot ask.`,fix:`Give ${n??"the user the deploy runs as"} a saved credential: ${o}git config --global credential.helper store, then ${o}git -C ${e} fetch origin once and paste a GitHub PAT as the password (an account password is refused). ${l}`}:/Could not resolve host|Connection (timed out|refused)|Network is unreachable|unable to access|Operation timed out/i.test(s)||r?{ok:!1,reason:"network",detail:`origin could not be reached from this machine - ${i}. This is DNS or a firewall, not a missing branch.`,fix:`Check outbound network from this machine, then re-run. ${l}`}:{ok:!1,reason:"unknown",detail:`origin could not be read - ${i}`,fix:`Run it by hand on this machine to see the whole error: ${o}git -C ${e} ls-remote --heads origin`}}function Ii(t){let e=l=>{try{return(0,Ht.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=ta(t),r=e(["branch","--format=%(refname:short)"]),s=e(["branch","-r","--format=%(refname:short)"]),i=n.ok?n.branches:null,o=[`
817
818
 
818
819
  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(n.ok?`- on origin: ${n.branches.join(", ")||"(none)"}`:`- origin could NOT be read (${n.reason}): ${n.detail} Report this as "the branch could not be verified from this machine", never as "the branch does not exist", and give this as the fix: ${n.fix}`),r&&o.push(`- local branches in this checkout: ${r.split(`
819
820
  `).join(", ")}`),s&&o.push(`- remote-tracking refs already fetched here: ${s.split(`
820
821
  `).join(", ")}`),i&&s){let l=new Set(s.split(`
821
822
  `).map(d=>d.replace(/^origin\//,""))),c=i.filter(d=>!l.has(d));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(`
822
- `)}function Bk(t){try{let e=tt.default.realpathSync(t),n=tt.default.openSync(e,"r"),r=Buffer.alloc(128),s=tt.default.readSync(n,r,0,128,0);tt.default.closeSync(n);let i=r.subarray(0,s).toString("utf8").split(`
823
- `)[0]??"";if(!i.startsWith("#!"))return null;let o=i.trim(),l=/^#!\s*\/usr\/bin\/env\s+(?:-S\s+)?(\S+)/.exec(o);return{target:e,shebang:o,viaEnv:l?.[1]??null}}catch{return null}}function kc(){let t=s=>{try{return(0,qt.execFileSync)(s,["--version"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}},e=(s,i)=>{try{return(0,qt.execFileSync)("which",[s],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"],...i?{env:{...process.env,PATH:i}}:{}}).trim()}catch{return""}},n=[],r=!1;for(let s of["node","npm","python3","pip3","yarn","pnpm"]){let i=e(s);if(!i)continue;let o=[i,`/usr/bin/${s}`,`/usr/local/bin/${s}`].filter((l,c,d)=>d.indexOf(l)===c&&tt.default.existsSync(l));for(let l of o){let c=t(l);if(!c)continue;let d=l===i?`${s} in the RUNNER's PATH (${l}) - deploy steps run with THIS`:`${s} at ${l}`;n.push(`- ${d}: ${c}`);let p=Bk(l);if(p)if(p.viaEnv){let f=p.viaEnv,w=e(f),v=w?t(w):null;if(n.push(` ${l}${p.target===l?"":` -> ${p.target}`} is a SCRIPT, not a binary. Its shebang is "${p.shebang}", so it runs under the FIRST ${f} in PATH`+(w?` - right now ${w}${v?` (${v})`:""}`:"")+`. Writing the absolute path to ${_i.default.basename(l)} therefore pins NOTHING.`),w&&tt.default.existsSync(`/usr/bin/${f}`)){let _=t(`/usr/bin/${f}`),I=v;_&&I&&_!==I&&(r=!0)}}else n.push(` ${l} runs under ${p.shebang.slice(2).trim()} (fixed by its shebang).`)}}return n.length?`
823
+ `)}function b_(t){try{let e=rt.default.realpathSync(t),n=rt.default.openSync(e,"r"),r=Buffer.alloc(128),s=rt.default.readSync(n,r,0,128,0);rt.default.closeSync(n);let i=r.subarray(0,s).toString("utf8").split(`
824
+ `)[0]??"";if(!i.startsWith("#!"))return null;let o=i.trim(),l=/^#!\s*\/usr\/bin\/env\s+(?:-S\s+)?(\S+)/.exec(o);return{target:e,shebang:o,viaEnv:l?.[1]??null}}catch{return null}}function Cc(){let t=s=>{try{return(0,Ht.execFileSync)(s,["--version"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}},e=(s,i)=>{try{return(0,Ht.execFileSync)("which",[s],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"],...i?{env:{...process.env,PATH:i}}:{}}).trim()}catch{return""}},n=[],r=!1;for(let s of["node","npm","python3","pip3","yarn","pnpm"]){let i=e(s);if(!i)continue;let o=[i,`/usr/bin/${s}`,`/usr/local/bin/${s}`].filter((l,c,d)=>d.indexOf(l)===c&&rt.default.existsSync(l));for(let l of o){let c=t(l);if(!c)continue;let d=l===i?`${s} in the RUNNER's PATH (${l}) - deploy steps run with THIS`:`${s} at ${l}`;n.push(`- ${d}: ${c}`);let p=b_(l);if(p)if(p.viaEnv){let f=p.viaEnv,w=e(f),v=w?t(w):null;if(n.push(` ${l}${p.target===l?"":` -> ${p.target}`} is a SCRIPT, not a binary. Its shebang is "${p.shebang}", so it runs under the FIRST ${f} in PATH`+(w?` - right now ${w}${v?` (${v})`:""}`:"")+`. Writing the absolute path to ${xi.default.basename(l)} therefore pins NOTHING.`),w&&rt.default.existsSync(`/usr/bin/${f}`)){let _=t(`/usr/bin/${f}`),I=v;_&&I&&_!==I&&(r=!0)}}else n.push(` ${l} runs under ${p.shebang.slice(2).trim()} (fixed by its shebang).`)}}return n.length?`
824
825
  - runtime versions (a MISMATCH between the runner's PATH and the system install is a common root cause):
825
826
  ${n.map(s=>` ${s}`).join(`
826
- `)}`+(r?"\n- PINNING A RUNTIME - this machine needs it, and it is the step most contracts get wrong: a wrapper script above resolves its interpreter through PATH, and the PATH the deploy steps inherit selects a DIFFERENT version from the system one. An absolute path to the wrapper does not fix that. Pin PATH itself in any step that builds, installs or compiles, e.g. `env PATH=/usr/bin:/bin /usr/bin/npm ci`, and say in the document WHY the bare form is wrong. This matters most for native modules: they are compiled against whichever interpreter ran the install, and the service then fails to load them at runtime.":""):""}function Hk(){let t=o=>{try{return(0,qt.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,qt.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`
827
+ `)}`+(r?"\n- PINNING A RUNTIME - this machine needs it, and it is the step most contracts get wrong: a wrapper script above resolves its interpreter through PATH, and the PATH the deploy steps inherit selects a DIFFERENT version from the system one. An absolute path to the wrapper does not fix that. Pin PATH itself in any step that builds, installs or compiles, e.g. `env PATH=/usr/bin:/bin /usr/bin/npm ci`, and say in the document WHY the bare form is wrong. This matters most for native modules: they are compiled against whichever interpreter ran the install, and the service then fails to load them at runtime.":""):""}function w_(){let t=o=>{try{return(0,Ht.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,Ht.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`
827
828
 
828
829
  WHAT THIS MACHINE ALREADY RUNS - build the answer on these, never on a tool that is not here:
829
830
  - installed: ${r.join(", ")||"(none of the usual ones)"}
830
831
  - NOT installed: ${s.join(", ")||"(none missing)"}
831
832
  - reverse proxy currently running: ${i.join(", ")||"(none)"}
832
- 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 Kk(t){try{return new URL(t).hostname}catch{return""}}function _c(t){let e=t.urls.map(Kk).filter(Boolean),n=Yo(t.repoPath),r=zk(e),s=[`
833
+ 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 v_(t){try{return new URL(t).hostname}catch{return""}}function $c(t){let e=t.urls.map(v_).filter(Boolean),n=ea(t.repoPath),r=h_(e),s=[`
833
834
 
834
835
  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}):
835
836
  `+n.map(i=>` - ${i}`).join(`
@@ -838,7 +839,7 @@ ABOUT THE MACHINE THIS RUNS ON - gathered by the runner just now, read-only. Tru
838
839
  `+r.map(i=>` - ${i}`).join(`
839
840
  `)+`
840
841
  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(`
841
- `)+Hk()+kc()}function af(t){let e=[],n=o=>o.workdir.trim()||t.repoPath,r=Jo(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=Yo(l),d="";try{d=o.publicUrl?new URL(o.publicUrl).hostname:""}catch{d=""}let p=d?rf([d]):[],f=c.length?void 0:p.find(w=>Lk(w.lines,l));if(e.push({environment:o.name,question:`Something supervises the app in ${l}`,ok:c.length>0||!!f,blocking:!f,detail:c.length?c.join(" \xB7 "):f?`static site - ${f.file} serves files from ${l} directly, so there is no process to supervise`:`no systemd unit on this machine references ${l}. This goes green with either a unit whose WorkingDirectory or ExecStart names ${l}, or a reverse-proxy root serving this environment's hostname from it.`}),o.servePath?.trim()){let w=o.servePath.trim(),v=(C,Y)=>{try{return(0,qt.execFileSync)("git",Y,{cwd:C,encoding:"utf8",timeout:1e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"true"},stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}},_=v(w,["rev-parse","HEAD"]),I=o.branch.trim()?v(t.repoPath,["rev-parse",`origin/${o.branch.trim()}`]):null,E=_&&I&&_!==I?v(t.repoPath,["rev-list","--count",`${_}..${I}`]):null;e.push({environment:o.name,question:`The live checkout at ${w} serves the latest ${o.branch.trim()||"commit"}`,ok:_!==null&&(I===null||_===I),blocking:!1,detail:_?I===null?`serving ${_.slice(0,10)}${o.branch.trim()?` (could not resolve origin/${o.branch.trim()} to compare)`:""}`:_===I?`serving ${_.slice(0,10)} = origin/${o.branch.trim()}`:`serving ${_.slice(0,10)}, but origin/${o.branch.trim()} is at ${I.slice(0,10)}`+(E?` - ${E} commit(s) behind`:"")+". The last deploy did not take effect, or none has run since those commits landed.":`cannot read a git HEAD at ${w} - wrong path, or not a git checkout`})}if(o.publicUrl){let w=d,v=p.map(sf);e.push({environment:o.name,question:`A reverse proxy here serves ${w||o.publicUrl}`,ok:v.length>0,blocking:!1,detail:v.length?v.join(" \xB7 "):`no proxy configuration on this machine mentions ${w||o.publicUrl}`})}if(o.publicUrl){let w=d;if(w){let v="";for(let _ of["DEPLOY.md",".ticketpilot/deploy.md","docs/DEPLOY.md"])try{v=tt.default.readFileSync(_i.default.join(l,_),"utf8");break}catch{}if(v){let _=v.includes(w);e.push({environment:o.name,question:`DEPLOY.md mentions ${w}`,ok:_,blocking:!1,detail:_?"":"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)if(!r.ok)e.push({environment:o.name,question:`Branch "${o.branch}" could be checked on origin`,ok:!1,blocking:!0,detail:`${r.detail} Fix: ${r.fix}`});else{let w=r.branches.includes(o.branch);e.push({environment:o.name,question:`Branch "${o.branch}" exists on origin`,ok:w,blocking:!0,detail:w?"":`origin was reached and does not have "${o.branch}" - it has: ${r.branches.join(", ")||"(no branches at all)"}`})}}return e}var qt,tt,_i,Mk,Qp,ef,Xo=ne(()=>{"use strict";qt=require("node:child_process"),tt=R(require("node:fs"),1),_i=R(require("node:path"),1),Mk=["/etc/systemd/system","/lib/systemd/system","/usr/lib/systemd/system"],Qp=["/etc/caddy/Caddyfile","/usr/local/etc/caddy/Caddyfile","/etc/nginx/nginx.conf"],ef=["/etc/nginx/sites-enabled","/etc/nginx/conf.d","/etc/caddy/conf.d","/etc/caddy/sites-enabled"]});function cf(t){lf=(t??"").trim()}function uf(){return lf}var lf,Sc=ne(()=>{"use strict";lf=""});function xc(t){return t.replace(/([A-Za-z_][A-Za-z0-9_]*)=(\S+)/g,(e,n,r)=>Gk.test(n)?`${n}=<redacted>`:e)}function an(t,e){try{let r=(0,hf.execFileSync)(t,e,{encoding:"utf8",timeout:1e4,maxBuffer:2e6,stdio:["ignore","pipe","pipe"]}).trim();return r?r.slice(0,df):null}catch(n){let r=n,s=`${r?.stdout??""}${r?.stderr??""}`.trim();return s?s.slice(0,df):null}}function Wk(t){let e=["/etc/systemd/system","/lib/systemd/system"],n=[];for(let r of e){let s;try{s=Tc.default.readdirSync(r)}catch{continue}for(let i of s)if(i.endsWith(".service"))try{let o=Tc.default.readFileSync(pf.default.join(r,i),"utf8");t&&o.includes(t)&&n.push(i.replace(/\.service$/,""))}catch{}}return[...new Set(n)].slice(0,3)}function ff(t){let e=t.errorText.slice(-6e3),n=[],r=(o,l)=>{l&&n.push({command:o,output:xc(l)})},s=Wk(t.repoPath);for(let o of s)r(`systemctl status ${o}`,an("systemctl",["status",o,"--no-pager","-l"])),r(`journalctl -u ${o} -n 40`,an("journalctl",["-u",o,"-n","40","--no-pager"])),r(`systemctl show ${o} -p ExecStart -p Environment -p WorkingDirectory -p User`,an("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",an("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)`,an("bash",["-lc",`command -v ${JSON.stringify(o)} || echo "not on this PATH"`])),r("ls of the usual system locations",an("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",an("bash",["-lc","df -h | head -10"])),/EACCES|Permission denied|Operation not permitted/i.test(e)&&(r("id",an("id",[])),r(`ls -ld ${t.repoPath}`,an("bash",["-lc",`ls -ld ${JSON.stringify(t.repoPath)} 2>&1`]))),n}function mf(t){return t.length?`
842
+ `)+w_()+Cc()}function gf(t){let e=[],n=o=>o.workdir.trim()||t.repoPath,r=ta(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=ea(l),d="";try{d=o.publicUrl?new URL(o.publicUrl).hostname:""}catch{d=""}let p=d?pf([d]):[],f=c.length?void 0:p.find(w=>f_(w.lines,l));if(e.push({environment:o.name,question:`Something supervises the app in ${l}`,ok:c.length>0||!!f,blocking:!f,detail:c.length?c.join(" \xB7 "):f?`static site - ${f.file} serves files from ${l} directly, so there is no process to supervise`:`no systemd unit on this machine references ${l}. This goes green with either a unit whose WorkingDirectory or ExecStart names ${l}, or a reverse-proxy root serving this environment's hostname from it.`}),o.servePath?.trim()){let w=o.servePath.trim(),v=(C,V)=>{try{return(0,Ht.execFileSync)("git",V,{cwd:C,encoding:"utf8",timeout:1e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"true"},stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}},_=v(w,["rev-parse","HEAD"]),I=o.branch.trim()?v(t.repoPath,["rev-parse",`origin/${o.branch.trim()}`]):null,R=_&&I&&_!==I?v(t.repoPath,["rev-list","--count",`${_}..${I}`]):null;e.push({environment:o.name,question:`The live checkout at ${w} serves the latest ${o.branch.trim()||"commit"}`,ok:_!==null&&(I===null||_===I),blocking:!1,detail:_?I===null?`serving ${_.slice(0,10)}${o.branch.trim()?` (could not resolve origin/${o.branch.trim()} to compare)`:""}`:_===I?`serving ${_.slice(0,10)} = origin/${o.branch.trim()}`:`serving ${_.slice(0,10)}, but origin/${o.branch.trim()} is at ${I.slice(0,10)}`+(R?` - ${R} commit(s) behind`:"")+". The last deploy did not take effect, or none has run since those commits landed.":`cannot read a git HEAD at ${w} - wrong path, or not a git checkout`})}if(o.publicUrl){let w=d,v=p.map(ff);e.push({environment:o.name,question:`A reverse proxy here serves ${w||o.publicUrl}`,ok:v.length>0,blocking:!1,detail:v.length?v.join(" \xB7 "):`no proxy configuration on this machine mentions ${w||o.publicUrl}`})}if(o.publicUrl){let w=d;if(w){let v="";for(let _ of["DEPLOY.md",".ticketpilot/deploy.md","docs/DEPLOY.md"])try{v=rt.default.readFileSync(xi.default.join(l,_),"utf8");break}catch{}if(v){let _=v.includes(w);e.push({environment:o.name,question:`DEPLOY.md mentions ${w}`,ok:_,blocking:!1,detail:_?"":"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)if(!r.ok)e.push({environment:o.name,question:`Branch "${o.branch}" could be checked on origin`,ok:!1,blocking:!0,detail:`${r.detail} Fix: ${r.fix}`});else{let w=r.branches.includes(o.branch);e.push({environment:o.name,question:`Branch "${o.branch}" exists on origin`,ok:w,blocking:!0,detail:w?"":`origin was reached and does not have "${o.branch}" - it has: ${r.branches.join(", ")||"(no branches at all)"}`})}}return e}var Ht,rt,xi,d_,cf,uf,na=te(()=>{"use strict";Ht=require("node:child_process"),rt=E(require("node:fs"),1),xi=E(require("node:path"),1),d_=["/etc/systemd/system","/lib/systemd/system","/usr/lib/systemd/system"],cf=["/etc/caddy/Caddyfile","/usr/local/etc/caddy/Caddyfile","/etc/nginx/nginx.conf"],uf=["/etc/nginx/sites-enabled","/etc/nginx/conf.d","/etc/caddy/conf.d","/etc/caddy/sites-enabled"]});function bf(t){yf=(t??"").trim()}function wf(){return yf}var yf,Pc=te(()=>{"use strict";yf=""});function jc(t){return t.replace(/([A-Za-z_][A-Za-z0-9_]*)=(\S+)/g,(e,n,r)=>k_.test(n)?`${n}=<redacted>`:e)}function dn(t,e){try{let r=(0,kf.execFileSync)(t,e,{encoding:"utf8",timeout:1e4,maxBuffer:2e6,stdio:["ignore","pipe","pipe"]}).trim();return r?r.slice(0,vf):null}catch(n){let r=n,s=`${r?.stdout??""}${r?.stderr??""}`.trim();return s?s.slice(0,vf):null}}function __(t){let e=["/etc/systemd/system","/lib/systemd/system"],n=[];for(let r of e){let s;try{s=Nc.default.readdirSync(r)}catch{continue}for(let i of s)if(i.endsWith(".service"))try{let o=Nc.default.readFileSync(_f.default.join(r,i),"utf8");t&&o.includes(t)&&n.push(i.replace(/\.service$/,""))}catch{}}return[...new Set(n)].slice(0,3)}function Sf(t){let e=t.errorText.slice(-6e3),n=[],r=(o,l)=>{l&&n.push({command:o,output:jc(l)})},s=__(t.repoPath);for(let o of s)r(`systemctl status ${o}`,dn("systemctl",["status",o,"--no-pager","-l"])),r(`journalctl -u ${o} -n 40`,dn("journalctl",["-u",o,"-n","40","--no-pager"])),r(`systemctl show ${o} -p ExecStart -p Environment -p WorkingDirectory -p User`,dn("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",dn("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)`,dn("bash",["-lc",`command -v ${JSON.stringify(o)} || echo "not on this PATH"`])),r("ls of the usual system locations",dn("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",dn("bash",["-lc","df -h | head -10"])),/EACCES|Permission denied|Operation not permitted/i.test(e)&&(r("id",dn("id",[])),r(`ls -ld ${t.repoPath}`,dn("bash",["-lc",`ls -ld ${JSON.stringify(t.repoPath)} 2>&1`]))),n}function Tf(t){return t.length?`
842
843
 
843
844
  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.
844
845
 
@@ -847,66 +848,66 @@ ${e.output}`).join(`
847
848
 
848
849
  `)+`
849
850
 
850
- 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 hf,Tc,pf,df,Gk,Ic=ne(()=>{"use strict";hf=require("node:child_process"),Tc=R(require("node:fs"),1),pf=R(require("node:path"),1),df=4e3,Gk=/(TOKEN|KEY|SECRET|PASSWORD|PASSWD|CREDENTIAL|AUTH|COOKIE|SESSION)/i});var If={};Kt(If,{executeDeploy:()=>Ti,findDeployDoc:()=>Ii,handleDeployApproved:()=>Pc,handleDeployRejected:()=>Nc,isPendingDeploy:()=>ta,makeRedactor:()=>xi,parseFixTicketBlock:()=>xf,parseSuggestion:()=>zc,preflightEnvironmentSteps:()=>Oc,resolveWorkdir:()=>$c,runSavedStep:()=>e_,suggestDeployFix:()=>jc,suggestDeploySteps:()=>Mc});function yf(t,e){t("warn",`${e.length} step(s) still need YOU - Allwright deliberately did not run these:
851
+ 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 kf,Nc,_f,vf,k_,Oc=te(()=>{"use strict";kf=require("node:child_process"),Nc=E(require("node:fs"),1),_f=E(require("node:path"),1),vf=4e3,k_=/(TOKEN|KEY|SECRET|PASSWORD|PASSWD|CREDENTIAL|AUTH|COOKIE|SESSION)/i});var Of={};$t(Of,{executeDeploy:()=>Ri,findDeployDoc:()=>Ai,handleDeployApproved:()=>qc,handleDeployRejected:()=>Fc,isPendingDeploy:()=>ia,makeRedactor:()=>Ei,parseFixTicketBlock:()=>jf,parseSuggestion:()=>Gc,preflightEnvironmentSteps:()=>Bc,resolveWorkdir:()=>Uc,runSavedStep:()=>A_,suggestDeployFix:()=>Hc,suggestDeploySteps:()=>Kc});function If(t,e){t("warn",`${e.length} step(s) still need YOU - Allwright deliberately did not run these:
851
852
  `+e.map(n=>` ${n.command}${n.why?` # ${n.why}`:""}`).join(`
852
- `))}function Cc(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,Zk)}),s!=="agent"&&y.info(`[deploy ${t.runId}] ${i}`)},setStatus:(s,i={})=>{t.transport.send({type:"run.status",runId:t.runId,status:s,...i})}}}function Yk(t){let e=Vk.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 Ti(t){let{emit:e,setStatus:n}=Cc(t),r=t.environment;try{let s=Jk(t);if(s){e("error",s),await mt(t,`**Allwright could not deploy to \`${r.name}\`.**
853
+ `))}function Lc(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,S_)}),s!=="agent"&&g.info(`[deploy ${t.runId}] ${i}`)},setStatus:(s,i={})=>{t.transport.send({type:"run.status",runId:t.runId,status:s,...i})}}}function x_(t){let e=T_.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 Ri(t){let{emit:e,setStatus:n}=Lc(t),r=t.environment;try{let s=I_(t);if(s){e("error",s),await gt(t,`**Allwright could not deploy to \`${r.name}\`.**
853
854
 
854
- ${s}`),n("failed",{error:s});return}if(r.requireApproval){Ep({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 mt(t,`**Allwright: deploy to \`${r.name}\` needs approval.**
855
+ ${s}`),n("failed",{error:s});return}if(r.requireApproval){Mp({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 gt(t,`**Allwright: deploy to \`${r.name}\` needs approval.**
855
856
 
856
- ${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 kf(t,e,n)}catch(s){let i=s instanceof Error?s.message:String(s);e("error",`Deploy failed: ${i}`),await mt(t,`**Allwright deploy to \`${r.name}\` failed.**
857
+ ${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 Cf(t,e,n)}catch(s){let i=s instanceof Error?s.message:String(s);e("error",`Deploy failed: ${i}`),await gt(t,`**Allwright deploy to \`${r.name}\` failed.**
857
858
 
858
859
  ${i.slice(0,800)}
859
860
 
860
- (run \`${t.runId}\`)`),n("failed",{error:i})}}function Jk(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=$t(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 kf(t,e,n){let r=t.environment,s=$t(t.cfg,t.project.repoName,r.name),i=xi(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 $=Ce(t.cfg,t.project,"assist"),b="error"in $?{ok:!1,error:$.error}:await Es({projectId:t.project.id,repoPath:t.repoPath,role:r.auditBeforeDeploy,scope:{kind:"repo",ref:""},model:"",agent:$,jira:t.jira});if(!b.ok)e("warn",`Pre-deploy audit could not run: ${b.error} - deploying anyway (advisory)`);else if(!b.audit.findings.length)e("info","Pre-deploy audit: no findings \u2713");else{let U={};for(let j of b.audit.findings)U[j.severity]=(U[j.severity]??0)+1;e("warn",`Pre-deploy audit: ${b.audit.findings.length} finding(s) (`+Object.entries(U).map(([j,H])=>`${H} ${j}`).join(", ")+") - full report on the Audits page. Deploying anyway (advisory).");for(let j of b.audit.findings.slice(0,5))e("warn",` [${j.severity}] ${j.title} - ${j.evidence[0]?.file??""}`)}}catch($){e("warn",`Pre-deploy audit crashed: ${$ instanceof Error?$.message:String($)} - deploying anyway`)}}if(r.requireSyncCheck){if(!r.previousEnvBranch||!r.branch){let b=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",b),await mt(t,`**Allwright refused to deploy to \`${r.name}\`.**
861
+ (run \`${t.runId}\`)`),n("failed",{error:i})}}function I_(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=Ot(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 Cf(t,e,n){let r=t.environment,s=Ot(t.cfg,t.project.repoName,r.name),i=Ei(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 $=Ce(t.cfg,t.project,"assist"),b="error"in $?{ok:!1,error:$.error}:await As({projectId:t.project.id,repoPath:t.repoPath,role:r.auditBeforeDeploy,scope:{kind:"repo",ref:""},model:"",agent:$,jira:t.jira});if(!b.ok)e("warn",`Pre-deploy audit could not run: ${b.error} - deploying anyway (advisory)`);else if(!b.audit.findings.length)e("info","Pre-deploy audit: no findings \u2713");else{let U={};for(let j of b.audit.findings)U[j.severity]=(U[j.severity]??0)+1;e("warn",`Pre-deploy audit: ${b.audit.findings.length} finding(s) (`+Object.entries(U).map(([j,K])=>`${K} ${j}`).join(", ")+") - full report on the Audits page. Deploying anyway (advisory).");for(let j of b.audit.findings.slice(0,5))e("warn",` [${j.severity}] ${j.title} - ${j.evidence[0]?.file??""}`)}}catch($){e("warn",`Pre-deploy audit crashed: ${$ instanceof Error?$.message:String($)} - deploying anyway`)}}if(r.requireSyncCheck){if(!r.previousEnvBranch||!r.branch){let b=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",b),await gt(t,`**Allwright refused to deploy to \`${r.name}\`.**
861
862
 
862
863
  ${b}
863
864
 
864
- (run \`${t.runId}\`)`),n("failed",{error:b,errorKind:"guard"});return}let $=await Qk(t,e);if($){await mt(t,$.comment),n("failed",{error:$.error,...$.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 xl({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 $=sn(r.ticketBranchTemplate,{issueKey:t.issueKey});e("info",`Merging "${$}" into "${r.branch}"`);let b=await Il(c,$,`Deploy ${t.issueKey} to ${r.name}
865
+ (run \`${t.runId}\`)`),n("failed",{error:b,errorKind:"guard"});return}let $=await E_(t,e);if($){await gt(t,$.comment),n("failed",{error:$.error,...$.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 Ol({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 $=cn(r.ticketBranchTemplate,{issueKey:t.issueKey});e("info",`Merging "${$}" into "${r.branch}"`);let b=await Ml(c,$,`Deploy ${t.issueKey} to ${r.name}
865
866
 
866
- Allwright run ${t.runId}`);if(!b.ok){e("error",b.reason??"merge failed"),await mt(t,`**Allwright deploy to \`${r.name}\` failed before running anything.**
867
+ Allwright run ${t.runId}`);if(!b.ok){e("error",b.reason??"merge failed"),await gt(t,`**Allwright deploy to \`${r.name}\` failed before running anything.**
867
868
 
868
- ${b.reason}`),n("failed",{error:b.reason});return}b.alreadyMerged?e("info",`"${$}" is already in "${r.branch}" - nothing to merge`):(e("info",`Pushing "${r.branch}" to origin`),await Cl(c,r.branch))}let p=await Ye(c).catch(()=>"");p&&e("info",`Deploying commit ${p.slice(0,10)}`);let f=$c(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},v=0,_=r.timeoutSeconds*1e3,I=zp(t.runId),E=()=>I.signal.aborted;try{for(let[$,b]of r.steps.entries()){if(E()){let H=`stopped from the dashboard during step ${$+1} - nothing further ran`;e("error",H),n("failed",{error:H,errorKind:"guard",deployedRef:p});return}let U=_-(Date.now()-o);if(U<=0){let H=`deploy exceeded its ${r.timeoutSeconds}s budget before step ${$+1}`;e("error",H),await mt(t,`**Allwright deploy to \`${r.name}\` timed out.**
869
+ ${b.reason}`),n("failed",{error:b.reason});return}b.alreadyMerged?e("info",`"${$}" is already in "${r.branch}" - nothing to merge`):(e("info",`Pushing "${r.branch}" to origin`),await Ul(c,r.branch))}let p=await Qe(c).catch(()=>"");p&&e("info",`Deploying commit ${p.slice(0,10)}`);let f=Uc(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},v=0,_=r.timeoutSeconds*1e3,I=Gp(t.runId),R=()=>I.signal.aborted;try{for(let[$,b]of r.steps.entries()){if(R()){let K=`stopped from the dashboard during step ${$+1} - nothing further ran`;e("error",K),n("failed",{error:K,errorKind:"guard",deployedRef:p});return}let U=_-(Date.now()-o);if(U<=0){let K=`deploy exceeded its ${r.timeoutSeconds}s budget before step ${$+1}`;e("error",K),await gt(t,`**Allwright deploy to \`${r.name}\` timed out.**
869
870
 
870
- ${H}`),n("timed_out",{error:H,deployedRef:p});return}e("info",`\u25B6 step ${$+1}/${r.steps.length}: ${b.name}`);let j=await _f({command:b.run,cwd:f,env:w,timeoutMs:U,signal:I.signal,onLine:(H,q)=>{v++;let u=Yk(q);u&&l.length<20&&l.push(u),v===gf&&e("warn","(output truncated - deploy log limit reached)"),!(v>=gf)&&e(H,i(q))}});if(j.timedOut){let H=`step "${b.name}" hit the ${r.timeoutSeconds}s deploy budget and was killed`;e("error",H),await mt(t,`**Allwright deploy to \`${r.name}\` timed out.**
871
+ ${K}`),n("timed_out",{error:K,deployedRef:p});return}e("info",`\u25B6 step ${$+1}/${r.steps.length}: ${b.name}`);let j=await $f({command:b.run,cwd:f,env:w,timeoutMs:U,signal:I.signal,onLine:(K,F)=>{v++;let u=x_(F);u&&l.length<20&&l.push(u),v===xf&&e("warn","(output truncated - deploy log limit reached)"),!(v>=xf)&&e(K,i(F))}});if(j.timedOut){let K=`step "${b.name}" hit the ${r.timeoutSeconds}s deploy budget and was killed`;e("error",K),await gt(t,`**Allwright deploy to \`${r.name}\` timed out.**
871
872
 
872
- ${H}`),n("timed_out",{error:H,deployedRef:p});return}if(j.code!==0){if(b.continueOnError){e("warn",`step "${b.name}" exited ${j.code} - continuing (marked continue-on-error)`);continue}let H="";try{H=i(await ml(c))}catch{}let q=j.failures?i(j.failures):"",u=j.tail?i(j.tail):"",m=Jp(vc(`${q}
873
- ${u}`.trim(),{cwd:c})),g=`step ${$+1} "${b.name}" failed with exit code ${j.code}`+(q?`:
874
- ${q}`:"")+(u?`${q?`
873
+ ${K}`),n("timed_out",{error:K,deployedRef:p});return}if(j.code!==0){if(b.continueOnError){e("warn",`step "${b.name}" exited ${j.code} - continuing (marked continue-on-error)`);continue}let K="";try{K=i(await xl(c))}catch{}let F=j.failures?i(j.failures):"",u=j.tail?i(j.tail):"",m=af(Ac(`${F}
874
+ ${u}`.trim(),{cwd:c})),y=`step ${$+1} "${b.name}" failed with exit code ${j.code}`+(F?`:
875
+ ${F}`:"")+(u?`${F?`
875
876
 
876
877
  how the output ended:
877
- `:": "}${u}`:"")+m+(H?`
878
+ `:": "}${u}`:"")+m+(K?`
878
879
 
879
880
  Checkout at failure:
880
- ${H}`:"");e("error",g),await mt(t,`**Allwright deploy to \`${r.name}\` failed.**
881
+ ${K}`:"");e("error",y),await gt(t,`**Allwright deploy to \`${r.name}\` failed.**
881
882
 
882
883
  Step ${$+1} \`${b.name}\` exited ${j.code}.
883
884
 
884
- `+(q?`\`\`\`
885
- ${q}
885
+ `+(F?`\`\`\`
886
+ ${F}
886
887
  \`\`\`
887
888
 
888
- `:"")+(u?`${q?`How the output ended:
889
+ `:"")+(u?`${F?`How the output ended:
889
890
  `:""}\`\`\`
890
891
  ${u.slice(0,1200)}
891
892
  \`\`\`
892
893
 
893
894
  `:"")+(m?`${m.trim()}
894
895
 
895
- `:"")+(H?`Checkout at failure:
896
+ `:"")+(K?`Checkout at failure:
896
897
  \`\`\`
897
- ${H.slice(0,800)}
898
+ ${K.slice(0,800)}
898
899
  \`\`\`
899
900
 
900
901
  `:"")+(l.length?`**Before retrying, these still need a person:**
901
902
  `+l.map(x=>`- \`${x.command}\`${x.why?` - ${x.why}`:""}`).join(`
902
903
  `)+`
903
904
 
904
- `:"")+`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 ${$+1} "${b.name}" exit ${j.code}`+(q||u?`
905
- ${(q||u).slice(0,500)}`:"")}),l.length&&yf(e,l),n("failed",{error:g.slice(0,4e3),deployedRef:p,...l.length?{manualSteps:l}:{}});return}e("info",`\u2713 step ${$+1}/${r.steps.length}: ${b.name}`)}}finally{Dp(t.runId)}if(p=await Ye(c).catch(()=>"")||p,r.servePath?.trim()){let $=r.servePath.trim(),b=r.branch.trim(),U=await Ye($).catch(()=>"");if(!U)e("warn",`serving check: cannot read a git HEAD at ${$} - the deploy is done, but whether that checkout serves THIS build could not be verified`);else{p=U;let j=b?await vl($,b):"";if(!j)e("warn",`serving check: ${$} is at ${U.slice(0,10)}, but `+(b?`origin/${b} could not be resolved there`:"this environment tracks no branch")+` - whether that is the latest ${b||"commit"} could not be verified`);else if(U!==j){let H=await kl($,U,j),q=`The steps all succeeded, but the live checkout at ${$} is at ${U.slice(0,10)} while origin/${b} is at ${j.slice(0,10)}`+(H?` - ${H} commit(s) behind`:"")+`. Users are NOT getting the latest ${b}. Usually one of: a step pulls a different directory than the one that serves, the pull failed quietly, or the serve path in this environment's settings points at the wrong checkout.`;e("error",`serving check: ${q}`),await mt(t,`**Allwright deployed to \`${r.name}\`, but it did not take.**
905
+ `:"")+`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 ${$+1} "${b.name}" exit ${j.code}`+(F||u?`
906
+ ${(F||u).slice(0,500)}`:"")}),l.length&&If(e,l),n("failed",{error:y.slice(0,4e3),deployedRef:p,...l.length?{manualSteps:l}:{}});return}e("info",`\u2713 step ${$+1}/${r.steps.length}: ${b.name}`)}}finally{Wp(t.runId)}if(p=await Qe(c).catch(()=>"")||p,r.servePath?.trim()){let $=r.servePath.trim(),b=r.branch.trim(),U=await Qe($).catch(()=>"");if(!U)e("warn",`serving check: cannot read a git HEAD at ${$} - the deploy is done, but whether that checkout serves THIS build could not be verified`);else{p=U;let j=b?await Cl($,b):"";if(!j)e("warn",`serving check: ${$} is at ${U.slice(0,10)}, but `+(b?`origin/${b} could not be resolved there`:"this environment tracks no branch")+` - whether that is the latest ${b||"commit"} could not be verified`);else if(U!==j){let K=await $l($,U,j),F=`The steps all succeeded, but the live checkout at ${$} is at ${U.slice(0,10)} while origin/${b} is at ${j.slice(0,10)}`+(K?` - ${K} commit(s) behind`:"")+`. Users are NOT getting the latest ${b}. Usually one of: a step pulls a different directory than the one that serves, the pull failed quietly, or the serve path in this environment's settings points at the wrong checkout.`;e("error",`serving check: ${F}`),await gt(t,`**Allwright deployed to \`${r.name}\`, but it did not take.**
906
907
 
907
- ${q}`),ft(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.name} did not take effect`,detail:`serving ${U.slice(0,10)}, origin/${b} at ${j.slice(0,10)} (${$})`}),n("failed",{error:q,deployedRef:p});return}else e("info",`serving check: ${$} is at ${U.slice(0,10)} = origin/${b} - users get this build`)}}n("posting");let C=Math.round((Date.now()-o)/1e3),Y=null;r.publicUrl?.trim()&&(Y=await r_(r.publicUrl.trim()),e(Y?"warn":"info",Y??`${r.publicUrl.trim()} points at this machine - the deploy is live there`)),t.issueKey!==Fr.BRANCH_DEPLOY_ISSUE_KEY&&await mt(t,`**Allwright deployed \`${t.issueKey}\` to \`${r.name}\`.**
908
+ ${F}`),mt(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.name} did not take effect`,detail:`serving ${U.slice(0,10)}, origin/${b} at ${j.slice(0,10)} (${$})`}),n("failed",{error:F,deployedRef:p});return}else e("info",`serving check: ${$} is at ${U.slice(0,10)} = origin/${b} - users get this build`)}}n("posting");let C=Math.round((Date.now()-o)/1e3),V=null;r.publicUrl?.trim()&&(V=await P_(r.publicUrl.trim()),e(V?"warn":"info",V??`${r.publicUrl.trim()} points at this machine - the deploy is live there`)),t.issueKey!==Hr.BRANCH_DEPLOY_ISSUE_KEY&&await gt(t,`**Allwright deployed \`${t.issueKey}\` to \`${r.name}\`.**
908
909
 
909
- `+(Y?`> **Live where?** ${Y}
910
+ `+(V?`> **Live where?** ${V}
910
911
 
911
912
  `:"")+(l.length?`**${l.length} step(s) still need a person - Allwright did not run these:**
912
913
  `+l.map($=>`- \`${$.command}\`${$.why?` - ${$.why}`:""}`).join(`
@@ -915,51 +916,51 @@ ${q}`),ft(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.nam
915
916
  `:"")+(p?`Commit: \`${p.slice(0,10)}\`${r.branch?` on \`${r.branch}\``:""}
916
917
  `:"")+`${r.steps.length} step(s) in ${C}s.`+(t.requestedBy?` Requested by ${t.requestedBy}.`:"")+`
917
918
 
918
- (run \`${t.runId}\`)`);let X=await Xk(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`),li(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&&yf(e,l),n("succeeded",{resultSummary:`Deployed to ${r.name}${p?` at ${p.slice(0,10)}`:""} in ${C}s`+(X!==null?` \xB7 ${X} ticket(s) moved to "${r.deployToColumn}"`:"")+(l.length?` \xB7 ${l.length} manual step(s) left for you`:"")+(Y?` \xB7 NOT reachable at ${r.publicUrl} yet`:""),deployedRef:p,...l.length?{manualSteps:l}:{}}),e("info",`Deploy to "${r.name}" succeeded in ${C}s`)}async function Xk(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}.**
919
+ (run \`${t.runId}\`)`);let J=await R_(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`),di(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&&If(e,l),n("succeeded",{resultSummary:`Deployed to ${r.name}${p?` at ${p.slice(0,10)}`:""} in ${C}s`+(J!==null?` \xB7 ${J} ticket(s) moved to "${r.deployToColumn}"`:"")+(l.length?` \xB7 ${l.length} manual step(s) left for you`:"")+(V?` \xB7 NOT reachable at ${r.publicUrl} yet`:""),deployedRef:p,...l.length?{manualSteps:l}:{}}),e("info",`Deploy to "${r.name}" succeeded in ${C}s`)}async function R_(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}.**
919
920
 
920
921
  `+(n?`Commit: \`${n.slice(0,10)}\`${r.branch?` on \`${r.branch}\``:""}
921
- `:"")+(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 Qk(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}\`.**
922
+ `:"")+(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 E_(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}\`.**
922
923
 
923
924
  ${l}
924
925
 
925
- (run \`${t.runId}\`)`});e("info",`Checking "${n.branch}" is in sync with "${r}" before deploying`);try{await Cn(t.repoPath,r),await Cn(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 $l(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=Ue(ke()??t.cfg,t.project.repoName);if(!o)return s(`"${n.branch}" and "${r}" have diverged, and no GitHub token applies to this repo to open a PR. Run \`allwright github set-token\`, or merge them manually, then retry the deploy.`,!0);try{let l=await Rr(t.repoPath),c=_t(l);if(!c)throw new Error(`could not parse a GitHub owner/repo from origin "${l}"`);let p=await new Fe(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.
926
+ (run \`${t.runId}\`)`});e("info",`Checking "${n.branch}" is in sync with "${r}" before deploying`);try{await jn(t.repoPath,r),await jn(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 ql(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=qe(ve()??t.cfg,t.project.repoName);if(!o)return s(`"${n.branch}" and "${r}" have diverged, and no GitHub token applies to this repo to open a PR. Run \`allwright github set-token\`, or merge them manually, then retry the deploy.`,!0);try{let l=await Cr(t.repoPath),c=St(l);if(!c)throw new Error(`could not parse a GitHub owner/repo from origin "${l}"`);let p=await new He(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.
926
927
 
927
- (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)}`)}}async function e_(t){let e=$t(t.cfg,t.repoName,t.environmentName),n=xi(Object.values(e)),r=$c(t.repoPath,t.workdir),s=await _f({command:t.step.run,cwd:r,env:{...process.env,...e,ALLWRIGHT_ENVIRONMENT:t.environmentName,ALLWRIGHT_BRANCH:t.branch,TICKETPILOT_ENVIRONMENT:t.environmentName,TICKETPILOT_BRANCH:t.branch},timeoutMs:t.timeoutMs,signal:t.signal,onLine:()=>{}}),i=[s.failures.trim()?`FAILING LINES:
928
+ (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)}`)}}async function A_(t){let e=Ot(t.cfg,t.repoName,t.environmentName),n=Ei(Object.values(e)),r=Uc(t.repoPath,t.workdir),s=await $f({command:t.step.run,cwd:r,env:{...process.env,...e,ALLWRIGHT_ENVIRONMENT:t.environmentName,ALLWRIGHT_BRANCH:t.branch,TICKETPILOT_ENVIRONMENT:t.environmentName,TICKETPILOT_BRANCH:t.branch},timeoutMs:t.timeoutMs,signal:t.signal,onLine:()=>{}}),i=[s.failures.trim()?`FAILING LINES:
928
929
  ${s.failures.trim()}`:"",s.tail.trim()?`LAST LINES:
929
930
  ${s.tail.trim()}`:""].filter(Boolean);return{commandLine:t.step.run,exitCode:s.code,timedOut:s.timedOut,output:n(i.join(`
930
931
 
931
- `)||"(the step produced no output)").slice(0,8e3)}}function $c(t,e){if(!e.trim())return t;let n=qr.default.resolve(t,e),r=qr.default.relative(t,n);if(r.startsWith("..")||qr.default.isAbsolute(r))throw new Error(`working directory "${e}" is outside the repository checkout`);return n}function _f(t){return new Promise(e=>{let n=(0,ea.spawn)("bash",["-lc",t.command],{cwd:t.cwd,env:t.env,detached:!0,stdio:["ignore","pipe","pipe"]}),r=[],s=(0,Ns.failureCollector)(),i=f=>{r.push(f),r.length>20&&r.shift(),s.push(f)},o=!1,l=!1,c=f=>{o||(o=!0,clearTimeout(d),t.signal?.removeEventListener("abort",p),e({code:f,timedOut:l,tail:r.join(`
932
- `),failures:s.text()}))},d=setTimeout(()=>{l=!0,Qo(n.pid,"SIGTERM"),setTimeout(()=>Qo(n.pid,"SIGKILL"),1e4).unref()},t.timeoutMs),p=()=>{t.onLine("warn","stop requested - killing this step"),Qo(n.pid,"SIGTERM"),setTimeout(()=>Qo(n.pid,"SIGKILL"),5e3).unref()};t.signal&&(t.signal.aborted?p():t.signal.addEventListener("abort",p,{once:!0})),Rc.default.createInterface({input:n.stdout}).on("line",f=>{i(f),t.onLine("info",f)}),Rc.default.createInterface({input:n.stderr}).on("line",f=>{i(f),t.onLine("warn",f)}),n.on("error",f=>{i(`failed to start: ${f.message}`),c(127)}),n.on("close",f=>c(f??1))})}function Qo(t,e){if(t)try{process.kill(-t,e)}catch{try{process.kill(t,e)}catch{}}}function xi(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 mt(t,e){if(t.issueKey!==Fr.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 ta(t){return Go(t)!==null}async function Pc(t,e){let n=Go(e);if(!n)return;let{emit:r,setStatus:s}=Cc({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}),Wo(e);return}Wo(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 kf(o,r,s)}catch(l){let c=l instanceof Error?l.message:String(l);r("error",`Deploy failed: ${c}`),await mt(o,`**Allwright deploy failed.**
932
+ `)||"(the step produced no output)").slice(0,8e3)}}function Uc(t,e){if(!e.trim())return t;let n=Br.default.resolve(t,e),r=Br.default.relative(t,n);if(r.startsWith("..")||Br.default.isAbsolute(r))throw new Error(`working directory "${e}" is outside the repository checkout`);return n}function $f(t){return new Promise(e=>{let n=(0,sa.spawn)("bash",["-lc",t.command],{cwd:t.cwd,env:t.env,detached:!0,stdio:["ignore","pipe","pipe"]}),r=[],s=(0,Os.failureCollector)(),i=f=>{r.push(f),r.length>20&&r.shift(),s.push(f)},o=!1,l=!1,c=f=>{o||(o=!0,clearTimeout(d),t.signal?.removeEventListener("abort",p),e({code:f,timedOut:l,tail:r.join(`
933
+ `),failures:s.text()}))},d=setTimeout(()=>{l=!0,ra(n.pid,"SIGTERM"),setTimeout(()=>ra(n.pid,"SIGKILL"),1e4).unref()},t.timeoutMs),p=()=>{t.onLine("warn","stop requested - killing this step"),ra(n.pid,"SIGTERM"),setTimeout(()=>ra(n.pid,"SIGKILL"),5e3).unref()};t.signal&&(t.signal.aborted?p():t.signal.addEventListener("abort",p,{once:!0})),zc.default.createInterface({input:n.stdout}).on("line",f=>{i(f),t.onLine("info",f)}),zc.default.createInterface({input:n.stderr}).on("line",f=>{i(f),t.onLine("warn",f)}),n.on("error",f=>{i(`failed to start: ${f.message}`),c(127)}),n.on("close",f=>c(f??1))})}function ra(t,e){if(t)try{process.kill(-t,e)}catch{try{process.kill(t,e)}catch{}}}function Ei(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 gt(t,e){if(t.issueKey!==Hr.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 ia(t){return Vo(t)!==null}async function qc(t,e){let n=Vo(e);if(!n)return;let{emit:r,setStatus:s}=Lc({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}),Jo(e);return}Jo(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 Cf(o,r,s)}catch(l){let c=l instanceof Error?l.message:String(l);r("error",`Deploy failed: ${c}`),await gt(o,`**Allwright deploy failed.**
933
934
 
934
- ${c.slice(0,800)}`),s("failed",{error:c})}}async function Nc(t,e){let n=Go(e);if(!n)return;let{emit:r,setStatus:s}=Cc({runId:e,transport:t.transport});Wo(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.**
935
+ ${c.slice(0,800)}`),s("failed",{error:c})}}async function Fc(t,e){let n=Vo(e);if(!n)return;let{emit:r,setStatus:s}=Lc({runId:e,transport:t.transport});Jo(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.**
935
936
 
936
- 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"})}function Ii(t){for(let e of Ns.DEPLOY_DOC_CANDIDATES){let n=qr.default.join(t,e);try{if(!Ps.default.existsSync(n))continue;let r=Ps.default.readFileSync(n,"utf8");if(!r.trim())continue;return{path:e,content:r.length>bf?r.slice(0,bf)+`
937
+ 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"})}function Ai(t){for(let e of Os.DEPLOY_DOC_CANDIDATES){let n=Br.default.join(t,e);try{if(!js.default.existsSync(n))continue;let r=js.default.readFileSync(n,"utf8");if(!r.trim())continue;return{path:e,content:r.length>Rf?r.slice(0,Rf)+`
937
938
 
938
- [\u2026document truncated\u2026]`:r}}catch{continue}}return null}function Sf(t){return n_("bash",["-lc",`command -v ${JSON.stringify(t)}`]).trim().length>0}function n_(t,e){try{let n=(0,ea.spawnSync)(t,e,{encoding:"utf8",timeout:5e3});return n.status===0?n.stdout??"":""}catch{return""}}async function r_(t){let e;try{e=new URL(t)}catch{return null}let n=[];try{let{resolve4:o,resolve6:l}=await import("node:dns/promises"),[c,d]=await Promise.all([o(e.hostname).catch(()=>[]),l(e.hostname).catch(()=>[])]);n=[...c,...d]}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(o=>o??[]).filter(o=>!o.internal).map(o=>o.address)),i=uf();return i&&s.add(i),n.some(o=>s.has(o))?null:`${e.hostname} resolves to ${n.slice(0,3).join(", ")}, which is not an address of this machine`+(i?` (this machine is ${i})`:" as far as it can tell - its own public address is not known here, so treat this as a prompt to check rather than a verdict")+". 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 s_(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 i_(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?`
939
+ [\u2026document truncated\u2026]`:r}}catch{continue}}return null}function Pf(t){return $_("bash",["-lc",`command -v ${JSON.stringify(t)}`]).trim().length>0}function $_(t,e){try{let n=(0,sa.spawnSync)(t,e,{encoding:"utf8",timeout:5e3});return n.status===0?n.stdout??"":""}catch{return""}}async function P_(t){let e;try{e=new URL(t)}catch{return null}let n=[];try{let{resolve4:o,resolve6:l}=await import("node:dns/promises"),[c,d]=await Promise.all([o(e.hostname).catch(()=>[]),l(e.hostname).catch(()=>[])]);n=[...c,...d]}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(o=>o??[]).filter(o=>!o.internal).map(o=>o.address)),i=wf();return i&&s.add(i),n.some(o=>s.has(o))?null:`${e.hostname} resolves to ${n.slice(0,3).join(", ")}, which is not an address of this machine`+(i?` (this machine is ${i})`:" as far as it can tell - its own public address is not known here, so treat this as a prompt to check rather than a verdict")+". 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 N_(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 j_(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?`
939
940
  - absolute paths the document mentions, checked on THIS machine:
940
- ${n.map(s=>` - ${s}: ${Ps.default.existsSync(s)?"EXISTS on this machine":"not found on this machine"}`).join(`
941
- `)}`:""}function Tf(t,e,n,r="",s="."){let i=wf.filter(c=>Sf(c)),o=wf.filter(c=>!i.includes(c)),l=Object.keys($t(t,e,n));return`About the machine these steps will run on (gathered by the runner, trust it):
941
+ ${n.map(s=>` - ${s}: ${js.default.existsSync(s)?"EXISTS on this machine":"not found on this machine"}`).join(`
942
+ `)}`:""}function Nf(t,e,n,r="",s="."){let i=Ef.filter(c=>Pf(c)),o=Ef.filter(c=>!i.includes(c)),l=Object.keys(Ot(t,e,n));return`About the machine these steps will run on (gathered by the runner, trust it):
942
943
  - available tools: ${i.join(", ")||"(none of the common ones)"}
943
944
  - NOT installed: ${o.join(", ")||"(none missing)"}
944
- - secrets already stored for this environment (names only): ${l.join(", ")||"(none yet)"}`+kc()+i_(r)+Si(s)}async function Oc(t){let e=[];if(t.publicUrl?.trim()&&await s_(t.publicUrl.trim(),e),e.push(Ps.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=qr.default.isAbsolute(t.workdir)?t.workdir:qr.default.join(t.repoPath,t.workdir);e.push(Ps.default.existsSync(l)?{name:"workdir",ok:!0,detail:l}:{name:"workdir",ok:!1,detail:`does not exist: ${l}`})}if(t.branch){let l=Jo(t.repoPath);l.ok?e.push(l.branches.includes(t.branch)?{name:"branch",ok:!0,detail:`origin/${t.branch} exists`}:{name:"branch",ok:!1,detail:`origin has no branch "${t.branch}" - it really was asked, and answered with: ${l.branches.join(", ")||"(no branches at all)"}`}):e.push({name:"branch",ok:!1,detail:`${l.detail} Fix: ${l.fix}`})}let n=$t(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 d=c.trim().split(/\s+/),p=d.shift();for(;p&&(/^[A-Za-z_][A-Za-z0-9_]*=/.test(p)||p==="sudo"||p==="env"||p==="nohup");)p=d.shift();!p||p.startsWith("$")||p.startsWith("#")||p.startsWith("(")||i.add(p)}let o=[...i].filter(l=>!Sf(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}}function xf(t){let e=/```ticket\s*\n([\s\S]*?)```/i.exec(t);if(!e)return null;try{let n=JSON.parse(e[1]),r=typeof n.summary=="string"?n.summary.trim().slice(0,250):"";return r?{summary:r,description:typeof n.description=="string"?n.description.trim().slice(0,2e4):""}:null}catch{return null}}async function jc(t){let e=Tf(t.cfg,t.repoName,t.environmentName,"",t.repoPath),n=sn(Ns.DEPLOY_FIX_PROMPT_TEMPLATE,{envName:t.environmentName,steps:t.steps.map((f,w)=>`${w+1}. [${f.name}]${f.continueOnError?" (continues on error)":""}
945
+ - secrets already stored for this environment (names only): ${l.join(", ")||"(none yet)"}`+Cc()+j_(r)+Ii(s)}async function Bc(t){let e=[];if(t.publicUrl?.trim()&&await N_(t.publicUrl.trim(),e),e.push(js.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=Br.default.isAbsolute(t.workdir)?t.workdir:Br.default.join(t.repoPath,t.workdir);e.push(js.default.existsSync(l)?{name:"workdir",ok:!0,detail:l}:{name:"workdir",ok:!1,detail:`does not exist: ${l}`})}if(t.branch){let l=ta(t.repoPath);l.ok?e.push(l.branches.includes(t.branch)?{name:"branch",ok:!0,detail:`origin/${t.branch} exists`}:{name:"branch",ok:!1,detail:`origin has no branch "${t.branch}" - it really was asked, and answered with: ${l.branches.join(", ")||"(no branches at all)"}`}):e.push({name:"branch",ok:!1,detail:`${l.detail} Fix: ${l.fix}`})}let n=Ot(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 d=c.trim().split(/\s+/),p=d.shift();for(;p&&(/^[A-Za-z_][A-Za-z0-9_]*=/.test(p)||p==="sudo"||p==="env"||p==="nohup");)p=d.shift();!p||p.startsWith("$")||p.startsWith("#")||p.startsWith("(")||i.add(p)}let o=[...i].filter(l=>!Pf(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}}function jf(t){let e=/```ticket\s*\n([\s\S]*?)```/i.exec(t);if(!e)return null;try{let n=JSON.parse(e[1]),r=typeof n.summary=="string"?n.summary.trim().slice(0,250):"";return r?{summary:r,description:typeof n.description=="string"?n.description.trim().slice(0,2e4):""}:null}catch{return null}}async function Hc(t){let e=Nf(t.cfg,t.repoName,t.environmentName,"",t.repoPath),n=cn(Os.DEPLOY_FIX_PROMPT_TEMPLATE,{envName:t.environmentName,steps:t.steps.map((f,w)=>`${w+1}. [${f.name}]${f.continueOnError?" (continues on error)":""}
945
946
  ${f.run}`).join(`
946
- `),failedStep:t.failedStep||"(unknown)",errorText:t.errorText||"(no error text recorded)",knownCause:(()=>{let f=vc(t.errorText,{cwd:t.repoPath});return f?`
947
+ `),failedStep:t.failedStep||"(unknown)",errorText:t.errorText||"(no error text recorded)",knownCause:(()=>{let f=Ac(t.errorText,{cwd:t.repoPath});return f?`
947
948
 
948
949
  THE RUNNER ALREADY RECOGNISES THIS FAILURE, and told the operator so:
949
950
  - what it means: ${f.cause}
950
951
  - what closes it: ${f.commands.join(" ; ")}
951
952
  - ${f.note}
952
- 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:mf(ff({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,Ac.randomUUID)(),onLog:()=>{}});if(!r.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:r.error??"the agent produced no output"};let s=zc(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=xf(r.resultText),d=l?Ii(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 p=/^\s*CAUSE TYPE:\s*(CODE|MACHINE)\b/im.exec(r.resultText)?.[1]?.toUpperCase();return p?{ok:!1,steps:[],requiredSecrets:[],notes:i,error:p==="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."+(c?" A fix ticket is drafted below - creating it starts the ordinary implement flow.":""),...p==="CODE"&&c?{fixTicketSummary:c.summary,fixTicketDescription:c.description}:{}}:{ok:!0,...s,notes:i||s.notes,docPath:d?.path??(l?"DEPLOY.md":""),docContent:l}}async function Mc(t){let e=Ii(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=Tf(t.cfg,t.repoName,t.environmentName,e.content,t.repoPath),r=sn(Fr.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,Ac.randomUUID)(),onLog:()=>{}});if(!s.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:s.error??"Claude Code produced no output"};let i=zc(s.resultText);return i?{ok:!0,...i}:(y.warn(`deploy step suggestion could not be parsed. Claude's raw answer follows:
953
- `+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 zc(t){for(let e of o_(t)){let n;try{n=JSON.parse(e)}catch{continue}let r=t_.safeParse(a_(n));if(r.success&&r.data.steps.length||r.success&&r.data.notes.trim())return r.data}return null}function o_(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 a_(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:vf(o,l),run:o.trim()}:null;if(!o||typeof o!="object")return null;let c=o,d=Ec(c.run,c.command,c.cmd,c.script,c.shell);return d?{name:(Ec(c.name,c.title,c.description)??vf(d,l)).slice(0,120),run:d,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:Ec(e.notes,e.note,e.explanation)??""}}function Ec(...t){for(let e of t)if(typeof e=="string"&&e.trim())return e.trim()}function vf(t,e){return(t.split(`
954
- `)[0].trim()||`Step ${e+1}`).slice(0,120)}var Ps,qr,ea,Rc,Ac,Fr,Ns,gf,Zk,Vk,t_,bf,wf,Os=ne(()=>{"use strict";Ps=R(require("node:fs"),1);ci();Xp();qr=R(require("node:path"),1),ea=require("node:child_process"),Rc=R(require("node:readline"),1),Ac=require("node:crypto"),Fr=R(Re(),1);vn();Ee();Dt();Ns=R(Re(),1);ec();jt();Tt();Ar();Mo();mi();Xo();Sc();Ic();Dr();zt();gf=4e3,Zk=4e3;Vk=/^\s*(?:ALLWRIGHT|TICKETPILOT)[-\s]MANUAL:\s*(.+)$/i;t_=k.object({steps:k.array(Fr.DeployStep).max(50).default([]),requiredSecrets:k.array(k.string()).max(50).default([]),notes:k.string().default("")}),bf=24e3;wf=["docker","docker-compose","pm2","systemctl","node","pnpm","npm","yarn","make","python3","pip","rsync","ssh","caddy","nginx"]});var Ef={};Kt(Ef,{MAX_CHAIN_DEPTH:()=>Lc,breakChain:()=>Bc,breakSingleModeChain:()=>Wc,chainOf:()=>qc,chainSessionFor:()=>ia,loadBatchPlan:()=>Uc,nextMemberWillChain:()=>Zc,parsePlanAnswer:()=>Vc,recordChainSession:()=>Fc,recordSingleModeSession:()=>Kc,saveBatchPlan:()=>l_,singleModeChainIntact:()=>Gc,singleModeSessionFor:()=>Hc});function l_(t){js.default.mkdirSync(Dc(),{recursive:!0,mode:448}),js.default.writeFileSync(sa.default.join(Dc(),`${t.batchId}.json`),JSON.stringify(t,null,2),{mode:384})}function Uc(t){if(!t)return null;try{return JSON.parse(js.default.readFileSync(sa.default.join(Dc(),`${t}.json`),"utf8"))}catch{return null}}function qc(t,e){return t?t.chains.find(n=>n.includes(e)&&n.length>1)??null:null}function ia(t,e,n){let r=e.indexOf(n);if(r<=0)return null;let s=ln.get(ra(t,e));return!s||s.lastIssue!==e[r-1]||s.depth>=Lc||!js.default.existsSync(s.worktreePath)?null:s}function Fc(t,e,n,r){let s=ln.get(ra(t,e));ln.set(ra(t,e),{sessionId:r.sessionId,worktreePath:r.worktreePath,depth:(s?.depth??0)+1,lastIssue:n})}function Bc(t,e){ln.delete(ra(t,e))}function Hc(t){let e=ln.get(Ei(t));return!e||e.depth>=Lc||!js.default.existsSync(e.worktreePath)?null:e}function Kc(t,e,n,r){let s=ln.get(Ei(t));ln.set(Ei(t),{sessionId:n.sessionId,worktreePath:n.worktreePath,depth:r?(s?.depth??0)+1:1,lastIssue:e})}function Gc(t,e){return ln.get(Ei(t))?.lastIssue===e}function Wc(t){ln.delete(Ei(t))}function Zc(t,e){if(!t)return!1;let n=t.indexOf(e);return n!==-1&&n<t.length-1}function Vc(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]),d=typeof s.reasoning=="string"?s.reasoning.slice(0,1e3):"";return{order:o,chains:l,dependencies:c,reasoning:d}}var js,sa,Lc,Dc,ln,ra,Ei,oa=ne(()=>{"use strict";js=R(require("node:fs"),1),sa=R(require("node:path"),1);Ee();Lc=3,Dc=()=>sa.default.join(se(),"autopilot-plans");ln=new Map,ra=(t,e)=>`${t}:${e[0]}`;Ei=t=>`${t}:__single__`});var cn=de((vE,cm)=>{"use strict";var am=["nodebuffer","arraybuffer","fragments"],lm=typeof Blob<"u";lm&&am.push("blob");cm.exports={BINARY_TYPES:am,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:lm,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Ci=de((kE,ha)=>{"use strict";var{EMPTY_BUFFER:j_}=cn(),su=Buffer[Symbol.species];function M_(t,e){if(t.length===0)return j_;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 su(n.buffer,n.byteOffset,r):n}function um(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function dm(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function z_(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function iu(t){if(iu.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new su(t):ArrayBuffer.isView(t)?e=new su(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),iu.readOnly=!1),e}ha.exports={concat:M_,mask:um,toArrayBuffer:z_,toBuffer:iu,unmask:dm};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");ha.exports.mask=function(e,n,r,s,i){i<48?um(e,n,r,s,i):t.mask(e,n,r,s,i)},ha.exports.unmask=function(e,n){e.length<32?dm(e,n):t.unmask(e,n)}}catch{}});var fm=de((_E,pm)=>{"use strict";var hm=Symbol("kDone"),ou=Symbol("kRun"),au=class{constructor(e){this[hm]=()=>{this.pending--,this[ou]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[ou]()}[ou](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[hm])}}};pm.exports=au});var Ls=de((SE,bm)=>{"use strict";var $i=require("zlib"),mm=Ci(),D_=fm(),{kStatusCode:gm}=cn(),L_=Buffer[Symbol.species],U_=Buffer.from([0,0,255,255]),fa=Symbol("permessage-deflate"),un=Symbol("total-length"),zs=Symbol("callback"),Dn=Symbol("buffers"),Ds=Symbol("error"),pa,lu=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,!pa){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;pa=new D_(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[zs];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){pa.add(s=>{this._decompress(e,n,(i,o)=>{s(),r(i,o)})})}compress(e,n,r){pa.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"?$i.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=$i.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[fa]=this,this._inflate[un]=0,this._inflate[Dn]=[],this._inflate.on("error",F_),this._inflate.on("data",ym)}this._inflate[zs]=r,this._inflate.write(e),n&&this._inflate.write(U_),this._inflate.flush(()=>{let i=this._inflate[Ds];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=mm.concat(this._inflate[Dn],this._inflate[un]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[un]=0,this._inflate[Dn]=[],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"?$i.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=$i.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[un]=0,this._deflate[Dn]=[],this._deflate.on("data",q_)}this._deflate[zs]=r,this._deflate.write(e),this._deflate.flush($i.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=mm.concat(this._deflate[Dn],this._deflate[un]);n&&(i=new L_(i.buffer,i.byteOffset,i.length-4)),this._deflate[zs]=null,this._deflate[un]=0,this._deflate[Dn]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};bm.exports=lu;function q_(t){this[Dn].push(t),this[un]+=t.length}function ym(t){if(this[un]+=t.length,this[fa]._maxPayload<1||this[un]<=this[fa]._maxPayload){this[Dn].push(t);return}this[Ds]=new RangeError("Max payload size exceeded"),this[Ds].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Ds][gm]=1009,this.removeListener("data",ym),this.reset()}function F_(t){if(this[fa]._inflate=null,this[Ds]){this[zs](this[Ds]);return}t[gm]=1007,this[zs](t)}});var Us=de((TE,ma)=>{"use strict";var{isUtf8:wm}=require("buffer"),{hasBlob:B_}=cn(),H_=[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 K_(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function cu(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 G_(t){return B_&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}ma.exports={isBlob:G_,isValidStatusCode:K_,isValidUTF8:cu,tokenChars:H_};if(wm)ma.exports.isValidUTF8=function(t){return t.length<24?cu(t):wm(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");ma.exports.isValidUTF8=function(e){return e.length<32?cu(e):t(e)}}catch{}});var fu=de((xE,Im)=>{"use strict";var{Writable:W_}=require("stream"),vm=Ls(),{BINARY_TYPES:Z_,EMPTY_BUFFER:km,kStatusCode:V_,kWebSocket:Y_}=cn(),{concat:uu,toArrayBuffer:J_,unmask:X_}=Ci(),{isValidStatusCode:Q_,isValidUTF8:_m}=Us(),ga=Buffer[Symbol.species],yt=0,Sm=1,Tm=2,xm=3,du=4,hu=5,ya=6,pu=class extends W_{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Z_[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[Y_]=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=yt}_write(e,n,r){if(this._opcode===8&&this._state==yt)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 ga(r.buffer,r.byteOffset+e,r.length-e),new ga(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 ga(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 yt:this.getInfo(e);break;case Sm:this.getPayloadLength16(e);break;case Tm:this.getPayloadLength64(e);break;case xm:this.getMask();break;case du:this.getData(e);break;case hu:case ya: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[vm.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=Sm:this._payloadLength===127?this._state=Tm: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=xm:this._state=du}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=du}getData(e){let n=km;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&&X_(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=hu,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[vm.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===yt&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=yt;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=uu(r,n):this._binaryType==="arraybuffer"?s=J_(uu(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=yt):(this._state=ya,setImmediate(()=>{this.emit("message",s,!0),this._state=yt,this.startLoop(e)}))}else{let s=uu(r,n);if(!this._skipUTF8Validation&&!_m(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===hu||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=yt):(this._state=ya,setImmediate(()=>{this.emit("message",s,!1),this._state=yt,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,km),this.end();else{let r=e.readUInt16BE(0);if(!Q_(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new ga(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!_m(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=yt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=yt):(this._state=ya,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=yt,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[V_]=s,o}};Im.exports=pu});var yu=de((EE,Am)=>{"use strict";var{Duplex:IE}=require("stream"),{randomFillSync:eS}=require("crypto"),{types:{isUint8Array:tS}}=require("util"),Em=Ls(),{EMPTY_BUFFER:nS,kWebSocket:rS,NOOP:sS}=cn(),{isBlob:qs,isValidStatusCode:iS}=Us(),{mask:Rm,toBuffer:Wr}=Ci(),bt=Symbol("kByteLength"),oS=Buffer.alloc(4),ba=8*1024,Zr,Fs=ba,It=0,aS=1,lS=2,mu=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=It,this.onerror=sS,this[rS]=void 0}static frame(e,n){let r,s=!1,i=2,o=!1;n.mask&&(r=n.maskBuffer||oS,n.generateMask?n.generateMask(r):(Fs===ba&&(Zr===void 0&&(Zr=Buffer.alloc(ba)),eS(Zr,0,ba),Fs=0),r[0]=Zr[Fs++],r[1]=Zr[Fs++],r[2]=Zr[Fs++],r[3]=Zr[Fs++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let l;typeof e=="string"?(!n.mask||o)&&n[bt]!==void 0?l=n[bt]:(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 d=Buffer.allocUnsafe(s?l+i:i);return d[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(d[0]|=64),d[1]=c,c===126?d.writeUInt16BE(l,2):c===127&&(d[2]=d[3]=0,d.writeUIntBE(l,4,6)),n.mask?(d[1]|=128,d[i-4]=r[0],d[i-3]=r[1],d[i-2]=r[2],d[i-1]=r[3],o?[d,e]:s?(Rm(e,r,d,i,l),[d]):(Rm(e,r,e,0,l),[d,e])):[d,e]}close(e,n,r,s){let i;if(e===void 0)i=nS;else{if(typeof e!="number"||!iS(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(tS(n))i.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[bt]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==It?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(t.frame(i,o),s)}ping(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):qs(e)?(s=e.size,i=!1):(e=Wr(e),s=e.length,i=Wr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[bt]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};qs(e)?this._state!==It?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==It?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}pong(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):qs(e)?(s=e.size,i=!1):(e=Wr(e),s=e.length,i=Wr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[bt]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};qs(e)?this._state!==It?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==It?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let s=this._extensions[Em.extensionName],i=n.binary?2:1,o=n.compress,l,c;typeof e=="string"?(l=Buffer.byteLength(e),c=!1):qs(e)?(l=e.size,c=!1):(e=Wr(e),l=e.length,c=Wr.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 d={[bt]:l,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};qs(e)?this._state!==It?this.enqueue([this.getBlobData,e,this._compress,d,r]):this.getBlobData(e,this._compress,d,r):this._state!==It?this.enqueue([this.dispatch,e,this._compress,d,r]):this.dispatch(e,this._compress,d,r)}getBlobData(e,n,r,s){this._bufferedBytes+=r[bt],this._state=lS,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let l=new Error("The socket was closed while the blob was being read");process.nextTick(gu,this,l,s);return}this._bufferedBytes-=r[bt];let o=Wr(i);n?this.dispatch(o,n,r,s):(this._state=It,this.sendFrame(t.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(cS,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[Em.extensionName];this._bufferedBytes+=r[bt],this._state=aS,i.compress(e,r.fin,(o,l)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");gu(this,c,s);return}this._bufferedBytes-=r[bt],this._state=It,r.readOnly=!1,this.sendFrame(t.frame(l,r),s),this.dequeue()})}dequeue(){for(;this._state===It&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][bt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][bt],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)}};Am.exports=mu;function gu(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 cS(t,e,n){gu(t,e,n),t.onerror(e)}});var Dm=de((RE,zm)=>{"use strict";var{kForOnEventAttribute:Pi,kListener:bu}=cn(),Cm=Symbol("kCode"),$m=Symbol("kData"),Pm=Symbol("kError"),Nm=Symbol("kMessage"),Om=Symbol("kReason"),Bs=Symbol("kTarget"),jm=Symbol("kType"),Mm=Symbol("kWasClean"),dn=class{constructor(e){this[Bs]=null,this[jm]=e}get target(){return this[Bs]}get type(){return this[jm]}};Object.defineProperty(dn.prototype,"target",{enumerable:!0});Object.defineProperty(dn.prototype,"type",{enumerable:!0});var Vr=class extends dn{constructor(e,n={}){super(e),this[Cm]=n.code===void 0?0:n.code,this[Om]=n.reason===void 0?"":n.reason,this[Mm]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Cm]}get reason(){return this[Om]}get wasClean(){return this[Mm]}};Object.defineProperty(Vr.prototype,"code",{enumerable:!0});Object.defineProperty(Vr.prototype,"reason",{enumerable:!0});Object.defineProperty(Vr.prototype,"wasClean",{enumerable:!0});var Hs=class extends dn{constructor(e,n={}){super(e),this[Pm]=n.error===void 0?null:n.error,this[Nm]=n.message===void 0?"":n.message}get error(){return this[Pm]}get message(){return this[Nm]}};Object.defineProperty(Hs.prototype,"error",{enumerable:!0});Object.defineProperty(Hs.prototype,"message",{enumerable:!0});var Ni=class extends dn{constructor(e,n={}){super(e),this[$m]=n.data===void 0?null:n.data}get data(){return this[$m]}};Object.defineProperty(Ni.prototype,"data",{enumerable:!0});var uS={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[Pi]&&s[bu]===e&&!s[Pi])return;let r;if(t==="message")r=function(i,o){let l=new Ni("message",{data:o?i:i.toString()});l[Bs]=this,wa(e,this,l)};else if(t==="close")r=function(i,o){let l=new Vr("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});l[Bs]=this,wa(e,this,l)};else if(t==="error")r=function(i){let o=new Hs("error",{error:i,message:i.message});o[Bs]=this,wa(e,this,o)};else if(t==="open")r=function(){let i=new dn("open");i[Bs]=this,wa(e,this,i)};else return;r[Pi]=!!n[Pi],r[bu]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[bu]===e&&!n[Pi]){this.removeListener(t,n);break}}};zm.exports={CloseEvent:Vr,ErrorEvent:Hs,Event:dn,EventTarget:uS,MessageEvent:Ni};function wa(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var va=de((AE,Lm)=>{"use strict";var{tokenChars:Oi}=Us();function Ft(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function dS(t){let e=Object.create(null),n=Object.create(null),r=!1,s=!1,i=!1,o,l,c=-1,d=-1,p=-1,f=0;for(;f<t.length;f++)if(d=t.charCodeAt(f),o===void 0)if(p===-1&&Oi[d]===1)c===-1&&(c=f);else if(f!==0&&(d===32||d===9))p===-1&&c!==-1&&(p=f);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f);let v=t.slice(c,p);d===44?(Ft(e,v,n),n=Object.create(null)):o=v,c=p=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);else if(l===void 0)if(p===-1&&Oi[d]===1)c===-1&&(c=f);else if(d===32||d===9)p===-1&&c!==-1&&(p=f);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f),Ft(n,t.slice(c,p),!0),d===44&&(Ft(e,o,n),n=Object.create(null),o=void 0),c=p=-1}else if(d===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[d]!==1)throw new SyntaxError(`Unexpected character at index ${f}`);c===-1?c=f:r||(r=!0),s=!1}else if(i)if(Oi[d]===1)c===-1&&(c=f);else if(d===34&&c!==-1)i=!1,p=f;else if(d===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(d===34&&t.charCodeAt(f-1)===61)i=!0;else if(p===-1&&Oi[d]===1)c===-1&&(c=f);else if(c!==-1&&(d===32||d===9))p===-1&&(p=f);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f);let v=t.slice(c,p);r&&(v=v.replace(/\\/g,""),r=!1),Ft(n,l,v),d===44&&(Ft(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||d===32||d===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=f);let w=t.slice(c,p);return o===void 0?Ft(e,w,n):(l===void 0?Ft(n,w,!0):r?Ft(n,l,w.replace(/\\/g,"")):Ft(n,l,w),Ft(e,o,n)),e}function hS(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(", ")}Lm.exports={format:hS,parse:dS}});var Ta=de((PE,Jm)=>{"use strict";var pS=require("events"),fS=require("https"),mS=require("http"),Fm=require("net"),gS=require("tls"),{randomBytes:yS,createHash:bS}=require("crypto"),{Duplex:CE,Readable:$E}=require("stream"),{URL:wu}=require("url"),Ln=Ls(),wS=fu(),vS=yu(),{isBlob:kS}=Us(),{BINARY_TYPES:Um,CLOSE_TIMEOUT:_S,EMPTY_BUFFER:ka,GUID:SS,kForOnEventAttribute:vu,kListener:TS,kStatusCode:xS,kWebSocket:$e,NOOP:Bm}=cn(),{EventTarget:{addEventListener:IS,removeEventListener:ES}}=Dm(),{format:RS,parse:AS}=va(),{toBuffer:CS}=Ci(),Hm=Symbol("kAborted"),ku=[8,13],hn=["CONNECTING","OPEN","CLOSING","CLOSED"],$S=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ye=class t extends pS{constructor(e,n,r){super(),this._binaryType=Um[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=ka,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]),Km(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Um.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 wS({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 vS(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[$e]=this,i[$e]=this,e[$e]=this,s.on("conclude",OS),s.on("drain",jS),s.on("error",MS),s.on("message",zS),s.on("ping",DS),s.on("pong",LS),i.onerror=US,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Zm),e.on("data",Sa),e.on("end",Vm),e.on("error",Ym),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[Ln.extensionName]&&this._extensions[Ln.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){nt(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())}),Wm(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){_u(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||ka,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){_u(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||ka,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){_u(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Ln.extensionName]||(s.compress=!1),this._sender.send(e||ka,s,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){nt(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(ye,"CONNECTING",{enumerable:!0,value:hn.indexOf("CONNECTING")});Object.defineProperty(ye.prototype,"CONNECTING",{enumerable:!0,value:hn.indexOf("CONNECTING")});Object.defineProperty(ye,"OPEN",{enumerable:!0,value:hn.indexOf("OPEN")});Object.defineProperty(ye.prototype,"OPEN",{enumerable:!0,value:hn.indexOf("OPEN")});Object.defineProperty(ye,"CLOSING",{enumerable:!0,value:hn.indexOf("CLOSING")});Object.defineProperty(ye.prototype,"CLOSING",{enumerable:!0,value:hn.indexOf("CLOSING")});Object.defineProperty(ye,"CLOSED",{enumerable:!0,value:hn.indexOf("CLOSED")});Object.defineProperty(ye.prototype,"CLOSED",{enumerable:!0,value:hn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(ye.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(ye.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[vu])return e[TS];return null},set(e){for(let n of this.listeners(t))if(n[vu]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[vu]:!0})}})});ye.prototype.addEventListener=IS;ye.prototype.removeEventListener=ES;Jm.exports=ye;function Km(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:_S,protocolVersion:ku[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,!ku.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${ku.join(", ")})`);let i;if(e instanceof wu)i=e;else try{i=new wu(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 I=new SyntaxError(c);if(t._redirects===0)throw I;_a(t,I);return}let d=o?443:80,p=yS(16).toString("base64"),f=o?fS.request:mS.request,w=new Set,v;if(s.createConnection=s.createConnection||(o?NS:PS),s.defaultPort=s.defaultPort||d,s.port=i.port||d,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(v=new Ln({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=RS({[Ln.extensionName]:v.offer()})),n.length){for(let I of n){if(typeof I!="string"||!$S.test(I)||w.has(I))throw new SyntaxError("An invalid or duplicated subprotocol was specified");w.add(I)}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 I=s.path.split(":");s.socketPath=I[0],s.path=I[1]}let _;if(s.followRedirects){if(t._redirects===0){t._originalIpc=l,t._originalSecure=o,t._originalHostOrSocketPath=l?s.socketPath:i.host;let I=r&&r.headers;if(r={...r,headers:{}},I)for(let[E,C]of Object.entries(I))r.headers[E.toLowerCase()]=C}else if(t.listenerCount("redirect")===0){let I=l?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!I||t._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,I||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),_=t._req=f(s),t._redirects&&t.emit("redirect",t.url,_)}else _=t._req=f(s);s.timeout&&_.on("timeout",()=>{nt(t,_,"Opening handshake has timed out")}),_.on("error",I=>{_===null||_[Hm]||(_=t._req=null,_a(t,I))}),_.on("response",I=>{let E=I.headers.location,C=I.statusCode;if(E&&s.followRedirects&&C>=300&&C<400){if(++t._redirects>s.maxRedirects){nt(t,_,"Maximum redirects exceeded");return}_.abort();let Y;try{Y=new wu(E,e)}catch{let $=new SyntaxError(`Invalid URL: ${E}`);_a(t,$);return}Km(t,Y,n,r)}else t.emit("unexpected-response",_,I)||nt(t,_,`Unexpected server response: ${I.statusCode}`)}),_.on("upgrade",(I,E,C)=>{if(t.emit("upgrade",I),t.readyState!==ye.CONNECTING)return;_=t._req=null;let Y=I.headers.upgrade;if(Y===void 0||Y.toLowerCase()!=="websocket"){nt(t,E,"Invalid Upgrade header");return}let X=bS("sha1").update(p+SS).digest("base64");if(I.headers["sec-websocket-accept"]!==X){nt(t,E,"Invalid Sec-WebSocket-Accept header");return}let $=I.headers["sec-websocket-protocol"],b;if($!==void 0?w.size?w.has($)||(b="Server sent an invalid subprotocol"):b="Server sent a subprotocol but none was requested":w.size&&(b="Server sent no subprotocol"),b){nt(t,E,b);return}$&&(t._protocol=$);let U=I.headers["sec-websocket-extensions"];if(U!==void 0){if(!v){nt(t,E,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let j;try{j=AS(U)}catch{nt(t,E,"Invalid Sec-WebSocket-Extensions header");return}let H=Object.keys(j);if(H.length!==1||H[0]!==Ln.extensionName){nt(t,E,"Server indicated an extension that was not requested");return}try{v.accept(j[Ln.extensionName])}catch{nt(t,E,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Ln.extensionName]=v}t.setSocket(E,C,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(_,t):_.end()}function _a(t,e){t._readyState=ye.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function PS(t){return t.path=t.socketPath,Fm.connect(t)}function NS(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Fm.isIP(t.host)?"":t.host),gS.connect(t)}function nt(t,e,n){t._readyState=ye.CLOSING;let r=new Error(n);Error.captureStackTrace(r,nt),e.setHeader?(e[Hm]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(_a,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function _u(t,e,n){if(e){let r=kS(e)?e.size:CS(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${hn[t.readyState]})`);process.nextTick(n,r)}}function OS(t,e){let n=this[$e];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[$e]!==void 0&&(n._socket.removeListener("data",Sa),process.nextTick(Gm,n._socket),t===1005?n.close():n.close(t,e))}function jS(){let t=this[$e];t.isPaused||t._socket.resume()}function MS(t){let e=this[$e];e._socket[$e]!==void 0&&(e._socket.removeListener("data",Sa),process.nextTick(Gm,e._socket),e.close(t[xS])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function qm(){this[$e].emitClose()}function zS(t,e){this[$e].emit("message",t,e)}function DS(t){let e=this[$e];e._autoPong&&e.pong(t,!this._isServer,Bm),e.emit("ping",t)}function LS(t){this[$e].emit("pong",t)}function Gm(t){t.resume()}function US(t){let e=this[$e];e.readyState!==ye.CLOSED&&(e.readyState===ye.OPEN&&(e._readyState=ye.CLOSING,Wm(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Wm(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Zm(){let t=this[$e];if(this.removeListener("close",Zm),this.removeListener("data",Sa),this.removeListener("end",Vm),t._readyState=ye.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[$e]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",qm),t._receiver.on("finish",qm))}function Sa(t){this[$e]._receiver.write(t)||this.pause()}function Vm(){let t=this[$e];t._readyState=ye.CLOSING,t._receiver.end(),this.end()}function Ym(){let t=this[$e];this.removeListener("error",Ym),this.on("error",Bm),t&&(t._readyState=ye.CLOSING,this.destroy())}});var tg=de((OE,eg)=>{"use strict";var NE=Ta(),{Duplex:qS}=require("stream");function Xm(t){t.emit("close")}function FS(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Qm(t){this.removeListener("error",Qm),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function BS(t,e){let n=!0,r=new qS({...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(Xm,r);return}let o=!1;t.once("error",function(c){o=!0,i(c)}),t.once("close",function(){o||i(s),process.nextTick(Xm,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",FS),r.on("error",Qm),r}eg.exports=BS});var Su=de((jE,ng)=>{"use strict";var{tokenChars:HS}=Us();function KS(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&&HS[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}ng.exports={parse:KS}});var cg=de((zE,lg)=>{"use strict";var GS=require("events"),xa=require("http"),{Duplex:ME}=require("stream"),{createHash:WS}=require("crypto"),rg=va(),Yr=Ls(),ZS=Su(),VS=Ta(),{CLOSE_TIMEOUT:YS,GUID:JS,kWebSocket:XS}=cn(),QS=/^[+/0-9A-Za-z]{22}==$/,sg=0,ig=1,ag=2,Tu=class extends GS{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:YS,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:VS,...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=xa.createServer((r,s)=>{let i=xa.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=e0(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=sg}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===ag){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(ji,this);return}if(e&&this.once("close",e),this._state!==ig)if(this._state=ig,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(ji,this):process.nextTick(ji,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{ji(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",og);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,l=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Jr(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Jr(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!QS.test(i)){Jr(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(l!==13&&l!==8){Jr(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Mi(n,400);return}let c=e.headers["sec-websocket-protocol"],d=new Set;if(c!==void 0)try{d=ZS.parse(c)}catch{Jr(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 Yr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let v=rg.parse(p);v[Yr.extensionName]&&(w.accept(v[Yr.extensionName]),f[Yr.extensionName]=w)}catch{Jr(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,(v,_,I,E)=>{if(!v)return Mi(n,_||401,I,E);this.completeUpgrade(f,i,d,e,n,r,s)});return}if(!this.options.verifyClient(w))return Mi(n,401)}this.completeUpgrade(f,i,d,e,n,r,s)}completeUpgrade(e,n,r,s,i,o,l){if(!i.readable||!i.writable)return i.destroy();if(i[XS])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>sg)return Mi(i,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${WS("sha1").update(n+JS).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&&(d.push(`Sec-WebSocket-Protocol: ${f}`),p._protocol=f)}if(e[Yr.extensionName]){let f=e[Yr.extensionName].params,w=rg.format({[Yr.extensionName]:[f]});d.push(`Sec-WebSocket-Extensions: ${w}`),p._extensions=e}this.emit("headers",d,s),i.write(d.concat(`\r
953
+ 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:Tf(Sf({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,Dc.randomUUID)(),onLog:()=>{}});if(!r.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:r.error??"the agent produced no output"};let s=Gc(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=jf(r.resultText),d=l?Ai(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 p=/^\s*CAUSE TYPE:\s*(CODE|MACHINE)\b/im.exec(r.resultText)?.[1]?.toUpperCase();return p?{ok:!1,steps:[],requiredSecrets:[],notes:i,error:p==="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."+(c?" A fix ticket is drafted below - creating it starts the ordinary implement flow.":""),...p==="CODE"&&c?{fixTicketSummary:c.summary,fixTicketDescription:c.description}:{}}:{ok:!0,...s,notes:i||s.notes,docPath:d?.path??(l?"DEPLOY.md":""),docContent:l}}async function Kc(t){let e=Ai(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=Nf(t.cfg,t.repoName,t.environmentName,e.content,t.repoPath),r=cn(Hr.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,Dc.randomUUID)(),onLog:()=>{}});if(!s.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:s.error??"Claude Code produced no output"};let i=Gc(s.resultText);return i?{ok:!0,...i}:(g.warn(`deploy step suggestion could not be parsed. Claude's raw answer follows:
954
+ `+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 Gc(t){for(let e of O_(t)){let n;try{n=JSON.parse(e)}catch{continue}let r=C_.safeParse(M_(n));if(r.success&&r.data.steps.length||r.success&&r.data.notes.trim())return r.data}return null}function O_(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 M_(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:Af(o,l),run:o.trim()}:null;if(!o||typeof o!="object")return null;let c=o,d=Mc(c.run,c.command,c.cmd,c.script,c.shell);return d?{name:(Mc(c.name,c.title,c.description)??Af(d,l)).slice(0,120),run:d,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:Mc(e.notes,e.note,e.explanation)??""}}function Mc(...t){for(let e of t)if(typeof e=="string"&&e.trim())return e.trim()}function Af(t,e){return(t.split(`
955
+ `)[0].trim()||`Step ${e+1}`).slice(0,120)}var js,Br,sa,zc,Dc,Hr,Os,xf,S_,T_,C_,Rf,Ef,Ms=te(()=>{"use strict";js=E(require("node:fs"),1);hi();lf();Br=E(require("node:path"),1),sa=require("node:child_process"),zc=E(require("node:readline"),1),Dc=require("node:crypto"),Hr=E(Re(),1);Tn();Ae();xt();Os=E(Re(),1);uc();Lt();It();$r();Lo();bi();na();Pc();Oc();Ur();qt();xf=4e3,S_=4e3;T_=/^\s*(?:ALLWRIGHT|TICKETPILOT)[-\s]MANUAL:\s*(.+)$/i;C_=k.object({steps:k.array(Hr.DeployStep).max(50).default([]),requiredSecrets:k.array(k.string()).max(50).default([]),notes:k.string().default("")}),Rf=24e3;Ef=["docker","docker-compose","pm2","systemctl","node","pnpm","npm","yarn","make","python3","pip","rsync","ssh","caddy","nginx"]});var Mf={};$t(Mf,{MAX_CHAIN_DEPTH:()=>Zc,breakChain:()=>Xc,breakSingleModeChain:()=>nu,chainOf:()=>Jc,chainSessionFor:()=>ca,loadBatchPlan:()=>Vc,nextMemberWillChain:()=>ru,parsePlanAnswer:()=>su,recordChainSession:()=>Yc,recordSingleModeSession:()=>eu,saveBatchPlan:()=>z_,singleModeChainIntact:()=>tu,singleModeSessionFor:()=>Qc});function z_(t){zs.default.mkdirSync(Wc(),{recursive:!0,mode:448}),zs.default.writeFileSync(la.default.join(Wc(),`${t.batchId}.json`),JSON.stringify(t,null,2),{mode:384})}function Vc(t){if(!t)return null;try{return JSON.parse(zs.default.readFileSync(la.default.join(Wc(),`${t}.json`),"utf8"))}catch{return null}}function Jc(t,e){return t?t.chains.find(n=>n.includes(e)&&n.length>1)??null:null}function ca(t,e,n){let r=e.indexOf(n);if(r<=0)return null;let s=hn.get(aa(t,e));return!s||s.lastIssue!==e[r-1]||s.depth>=Zc||!zs.default.existsSync(s.worktreePath)?null:s}function Yc(t,e,n,r){let s=hn.get(aa(t,e));hn.set(aa(t,e),{sessionId:r.sessionId,worktreePath:r.worktreePath,depth:(s?.depth??0)+1,lastIssue:n})}function Xc(t,e){hn.delete(aa(t,e))}function Qc(t){let e=hn.get(Ci(t));return!e||e.depth>=Zc||!zs.default.existsSync(e.worktreePath)?null:e}function eu(t,e,n,r){let s=hn.get(Ci(t));hn.set(Ci(t),{sessionId:n.sessionId,worktreePath:n.worktreePath,depth:r?(s?.depth??0)+1:1,lastIssue:e})}function tu(t,e){return hn.get(Ci(t))?.lastIssue===e}function nu(t){hn.delete(Ci(t))}function ru(t,e){if(!t)return!1;let n=t.indexOf(e);return n!==-1&&n<t.length-1}function su(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]),d=typeof s.reasoning=="string"?s.reasoning.slice(0,1e3):"";return{order:o,chains:l,dependencies:c,reasoning:d}}var zs,la,Zc,Wc,hn,aa,Ci,ua=te(()=>{"use strict";zs=E(require("node:fs"),1),la=E(require("node:path"),1);Ae();Zc=3,Wc=()=>la.default.join(ie(),"autopilot-plans");hn=new Map,aa=(t,e)=>`${t}:${e[0]}`;Ci=t=>`${t}:__single__`});var pn=he((uE,km)=>{"use strict";var wm=["nodebuffer","arraybuffer","fragments"],vm=typeof Blob<"u";vm&&wm.push("blob");km.exports={BINARY_TYPES:wm,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:vm,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Ni=he((dE,ga)=>{"use strict";var{EMPTY_BUFFER:uS}=pn(),pu=Buffer[Symbol.species];function dS(t,e){if(t.length===0)return uS;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 pu(n.buffer,n.byteOffset,r):n}function _m(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function Sm(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function hS(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function fu(t){if(fu.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new pu(t):ArrayBuffer.isView(t)?e=new pu(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),fu.readOnly=!1),e}ga.exports={concat:dS,mask:_m,toArrayBuffer:hS,toBuffer:fu,unmask:Sm};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");ga.exports.mask=function(e,n,r,s,i){i<48?_m(e,n,r,s,i):t.mask(e,n,r,s,i)},ga.exports.unmask=function(e,n){e.length<32?Sm(e,n):t.unmask(e,n)}}catch{}});var Im=he((hE,xm)=>{"use strict";var Tm=Symbol("kDone"),mu=Symbol("kRun"),gu=class{constructor(e){this[Tm]=()=>{this.pending--,this[mu]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[mu]()}[mu](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Tm])}}};xm.exports=gu});var Us=he((pE,Cm)=>{"use strict";var ji=require("zlib"),Rm=Ni(),pS=Im(),{kStatusCode:Em}=pn(),fS=Buffer[Symbol.species],mS=Buffer.from([0,0,255,255]),ba=Symbol("permessage-deflate"),fn=Symbol("total-length"),Ds=Symbol("callback"),Fn=Symbol("buffers"),Ls=Symbol("error"),ya,yu=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,!ya){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;ya=new pS(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[Ds];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){ya.add(s=>{this._decompress(e,n,(i,o)=>{s(),r(i,o)})})}compress(e,n,r){ya.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"?ji.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=ji.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[ba]=this,this._inflate[fn]=0,this._inflate[Fn]=[],this._inflate.on("error",yS),this._inflate.on("data",Am)}this._inflate[Ds]=r,this._inflate.write(e),n&&this._inflate.write(mS),this._inflate.flush(()=>{let i=this._inflate[Ls];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=Rm.concat(this._inflate[Fn],this._inflate[fn]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[fn]=0,this._inflate[Fn]=[],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"?ji.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=ji.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[fn]=0,this._deflate[Fn]=[],this._deflate.on("data",gS)}this._deflate[Ds]=r,this._deflate.write(e),this._deflate.flush(ji.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Rm.concat(this._deflate[Fn],this._deflate[fn]);n&&(i=new fS(i.buffer,i.byteOffset,i.length-4)),this._deflate[Ds]=null,this._deflate[fn]=0,this._deflate[Fn]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};Cm.exports=yu;function gS(t){this[Fn].push(t),this[fn]+=t.length}function Am(t){if(this[fn]+=t.length,this[ba]._maxPayload<1||this[fn]<=this[ba]._maxPayload){this[Fn].push(t);return}this[Ls]=new RangeError("Max payload size exceeded"),this[Ls].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Ls][Em]=1009,this.removeListener("data",Am),this.reset()}function yS(t){if(this[ba]._inflate=null,this[Ls]){this[Ds](this[Ls]);return}t[Em]=1007,this[Ds](t)}});var qs=he((fE,wa)=>{"use strict";var{isUtf8:$m}=require("buffer"),{hasBlob:bS}=pn(),wS=[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 vS(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function bu(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 kS(t){return bS&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}wa.exports={isBlob:kS,isValidStatusCode:vS,isValidUTF8:bu,tokenChars:wS};if($m)wa.exports.isValidUTF8=function(t){return t.length<24?bu(t):$m(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");wa.exports.isValidUTF8=function(e){return e.length<32?bu(e):t(e)}}catch{}});var Su=he((mE,Dm)=>{"use strict";var{Writable:_S}=require("stream"),Pm=Us(),{BINARY_TYPES:SS,EMPTY_BUFFER:Nm,kStatusCode:TS,kWebSocket:xS}=pn(),{concat:wu,toArrayBuffer:IS,unmask:RS}=Ni(),{isValidStatusCode:ES,isValidUTF8:jm}=qs(),va=Buffer[Symbol.species],bt=0,Om=1,Mm=2,zm=3,vu=4,ku=5,ka=6,_u=class extends _S{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||SS[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[xS]=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=bt}_write(e,n,r){if(this._opcode===8&&this._state==bt)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 va(r.buffer,r.byteOffset+e,r.length-e),new va(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 va(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 bt:this.getInfo(e);break;case Om:this.getPayloadLength16(e);break;case Mm:this.getPayloadLength64(e);break;case zm:this.getMask();break;case vu:this.getData(e);break;case ku:case ka: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[Pm.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=Om:this._payloadLength===127?this._state=Mm: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=zm:this._state=vu}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=vu}getData(e){let n=Nm;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&&RS(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=ku,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Pm.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===bt&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=bt;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=wu(r,n):this._binaryType==="arraybuffer"?s=IS(wu(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=bt):(this._state=ka,setImmediate(()=>{this.emit("message",s,!0),this._state=bt,this.startLoop(e)}))}else{let s=wu(r,n);if(!this._skipUTF8Validation&&!jm(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===ku||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=bt):(this._state=ka,setImmediate(()=>{this.emit("message",s,!1),this._state=bt,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Nm),this.end();else{let r=e.readUInt16BE(0);if(!ES(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new va(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!jm(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=bt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=bt):(this._state=ka,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=bt,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[TS]=s,o}};Dm.exports=_u});var Iu=he((yE,qm)=>{"use strict";var{Duplex:gE}=require("stream"),{randomFillSync:AS}=require("crypto"),{types:{isUint8Array:CS}}=require("util"),Lm=Us(),{EMPTY_BUFFER:$S,kWebSocket:PS,NOOP:NS}=pn(),{isBlob:Fs,isValidStatusCode:jS}=qs(),{mask:Um,toBuffer:Jr}=Ni(),wt=Symbol("kByteLength"),OS=Buffer.alloc(4),_a=8*1024,Yr,Bs=_a,Et=0,MS=1,zS=2,Tu=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=Et,this.onerror=NS,this[PS]=void 0}static frame(e,n){let r,s=!1,i=2,o=!1;n.mask&&(r=n.maskBuffer||OS,n.generateMask?n.generateMask(r):(Bs===_a&&(Yr===void 0&&(Yr=Buffer.alloc(_a)),AS(Yr,0,_a),Bs=0),r[0]=Yr[Bs++],r[1]=Yr[Bs++],r[2]=Yr[Bs++],r[3]=Yr[Bs++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let l;typeof e=="string"?(!n.mask||o)&&n[wt]!==void 0?l=n[wt]:(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 d=Buffer.allocUnsafe(s?l+i:i);return d[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(d[0]|=64),d[1]=c,c===126?d.writeUInt16BE(l,2):c===127&&(d[2]=d[3]=0,d.writeUIntBE(l,4,6)),n.mask?(d[1]|=128,d[i-4]=r[0],d[i-3]=r[1],d[i-2]=r[2],d[i-1]=r[3],o?[d,e]:s?(Um(e,r,d,i,l),[d]):(Um(e,r,e,0,l),[d,e])):[d,e]}close(e,n,r,s){let i;if(e===void 0)i=$S;else{if(typeof e!="number"||!jS(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(CS(n))i.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[wt]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Et?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):Fs(e)?(s=e.size,i=!1):(e=Jr(e),s=e.length,i=Jr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[wt]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Fs(e)?this._state!==Et?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==Et?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):Fs(e)?(s=e.size,i=!1):(e=Jr(e),s=e.length,i=Jr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[wt]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Fs(e)?this._state!==Et?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==Et?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let s=this._extensions[Lm.extensionName],i=n.binary?2:1,o=n.compress,l,c;typeof e=="string"?(l=Buffer.byteLength(e),c=!1):Fs(e)?(l=e.size,c=!1):(e=Jr(e),l=e.length,c=Jr.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 d={[wt]:l,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};Fs(e)?this._state!==Et?this.enqueue([this.getBlobData,e,this._compress,d,r]):this.getBlobData(e,this._compress,d,r):this._state!==Et?this.enqueue([this.dispatch,e,this._compress,d,r]):this.dispatch(e,this._compress,d,r)}getBlobData(e,n,r,s){this._bufferedBytes+=r[wt],this._state=zS,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let l=new Error("The socket was closed while the blob was being read");process.nextTick(xu,this,l,s);return}this._bufferedBytes-=r[wt];let o=Jr(i);n?this.dispatch(o,n,r,s):(this._state=Et,this.sendFrame(t.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(DS,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[Lm.extensionName];this._bufferedBytes+=r[wt],this._state=MS,i.compress(e,r.fin,(o,l)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");xu(this,c,s);return}this._bufferedBytes-=r[wt],this._state=Et,r.readOnly=!1,this.sendFrame(t.frame(l,r),s),this.dequeue()})}dequeue(){for(;this._state===Et&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][wt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][wt],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)}};qm.exports=Tu;function xu(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 DS(t,e,n){xu(t,e,n),t.onerror(e)}});var Jm=he((bE,Vm)=>{"use strict";var{kForOnEventAttribute:Oi,kListener:Ru}=pn(),Fm=Symbol("kCode"),Bm=Symbol("kData"),Hm=Symbol("kError"),Km=Symbol("kMessage"),Gm=Symbol("kReason"),Hs=Symbol("kTarget"),Wm=Symbol("kType"),Zm=Symbol("kWasClean"),mn=class{constructor(e){this[Hs]=null,this[Wm]=e}get target(){return this[Hs]}get type(){return this[Wm]}};Object.defineProperty(mn.prototype,"target",{enumerable:!0});Object.defineProperty(mn.prototype,"type",{enumerable:!0});var Xr=class extends mn{constructor(e,n={}){super(e),this[Fm]=n.code===void 0?0:n.code,this[Gm]=n.reason===void 0?"":n.reason,this[Zm]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Fm]}get reason(){return this[Gm]}get wasClean(){return this[Zm]}};Object.defineProperty(Xr.prototype,"code",{enumerable:!0});Object.defineProperty(Xr.prototype,"reason",{enumerable:!0});Object.defineProperty(Xr.prototype,"wasClean",{enumerable:!0});var Ks=class extends mn{constructor(e,n={}){super(e),this[Hm]=n.error===void 0?null:n.error,this[Km]=n.message===void 0?"":n.message}get error(){return this[Hm]}get message(){return this[Km]}};Object.defineProperty(Ks.prototype,"error",{enumerable:!0});Object.defineProperty(Ks.prototype,"message",{enumerable:!0});var Mi=class extends mn{constructor(e,n={}){super(e),this[Bm]=n.data===void 0?null:n.data}get data(){return this[Bm]}};Object.defineProperty(Mi.prototype,"data",{enumerable:!0});var LS={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[Oi]&&s[Ru]===e&&!s[Oi])return;let r;if(t==="message")r=function(i,o){let l=new Mi("message",{data:o?i:i.toString()});l[Hs]=this,Sa(e,this,l)};else if(t==="close")r=function(i,o){let l=new Xr("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});l[Hs]=this,Sa(e,this,l)};else if(t==="error")r=function(i){let o=new Ks("error",{error:i,message:i.message});o[Hs]=this,Sa(e,this,o)};else if(t==="open")r=function(){let i=new mn("open");i[Hs]=this,Sa(e,this,i)};else return;r[Oi]=!!n[Oi],r[Ru]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Ru]===e&&!n[Oi]){this.removeListener(t,n);break}}};Vm.exports={CloseEvent:Xr,ErrorEvent:Ks,Event:mn,EventTarget:LS,MessageEvent:Mi};function Sa(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Ta=he((wE,Ym)=>{"use strict";var{tokenChars:zi}=qs();function Kt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function US(t){let e=Object.create(null),n=Object.create(null),r=!1,s=!1,i=!1,o,l,c=-1,d=-1,p=-1,f=0;for(;f<t.length;f++)if(d=t.charCodeAt(f),o===void 0)if(p===-1&&zi[d]===1)c===-1&&(c=f);else if(f!==0&&(d===32||d===9))p===-1&&c!==-1&&(p=f);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f);let v=t.slice(c,p);d===44?(Kt(e,v,n),n=Object.create(null)):o=v,c=p=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);else if(l===void 0)if(p===-1&&zi[d]===1)c===-1&&(c=f);else if(d===32||d===9)p===-1&&c!==-1&&(p=f);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f),Kt(n,t.slice(c,p),!0),d===44&&(Kt(e,o,n),n=Object.create(null),o=void 0),c=p=-1}else if(d===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(zi[d]!==1)throw new SyntaxError(`Unexpected character at index ${f}`);c===-1?c=f:r||(r=!0),s=!1}else if(i)if(zi[d]===1)c===-1&&(c=f);else if(d===34&&c!==-1)i=!1,p=f;else if(d===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(d===34&&t.charCodeAt(f-1)===61)i=!0;else if(p===-1&&zi[d]===1)c===-1&&(c=f);else if(c!==-1&&(d===32||d===9))p===-1&&(p=f);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f);let v=t.slice(c,p);r&&(v=v.replace(/\\/g,""),r=!1),Kt(n,l,v),d===44&&(Kt(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||d===32||d===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=f);let w=t.slice(c,p);return o===void 0?Kt(e,w,n):(l===void 0?Kt(n,w,!0):r?Kt(n,l,w.replace(/\\/g,"")):Kt(n,l,w),Kt(e,o,n)),e}function qS(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(", ")}Ym.exports={format:qS,parse:US}});var Ea=he((_E,cg)=>{"use strict";var FS=require("events"),BS=require("https"),HS=require("http"),eg=require("net"),KS=require("tls"),{randomBytes:GS,createHash:WS}=require("crypto"),{Duplex:vE,Readable:kE}=require("stream"),{URL:Eu}=require("url"),Bn=Us(),ZS=Su(),VS=Iu(),{isBlob:JS}=qs(),{BINARY_TYPES:Xm,CLOSE_TIMEOUT:YS,EMPTY_BUFFER:xa,GUID:XS,kForOnEventAttribute:Au,kListener:QS,kStatusCode:e0,kWebSocket:je,NOOP:tg}=pn(),{EventTarget:{addEventListener:t0,removeEventListener:n0}}=Jm(),{format:r0,parse:s0}=Ta(),{toBuffer:i0}=Ni(),ng=Symbol("kAborted"),Cu=[8,13],gn=["CONNECTING","OPEN","CLOSING","CLOSED"],o0=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,be=class t extends FS{constructor(e,n,r){super(),this._binaryType=Xm[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=xa,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]),rg(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Xm.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 ZS({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 VS(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[je]=this,i[je]=this,e[je]=this,s.on("conclude",c0),s.on("drain",u0),s.on("error",d0),s.on("message",h0),s.on("ping",p0),s.on("pong",f0),i.onerror=m0,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",og),e.on("data",Ra),e.on("end",ag),e.on("error",lg),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[Bn.extensionName]&&this._extensions[Bn.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){st(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())}),ig(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){$u(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||xa,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){$u(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||xa,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){$u(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Bn.extensionName]||(s.compress=!1),this._sender.send(e||xa,s,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){st(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(be,"CONNECTING",{enumerable:!0,value:gn.indexOf("CONNECTING")});Object.defineProperty(be.prototype,"CONNECTING",{enumerable:!0,value:gn.indexOf("CONNECTING")});Object.defineProperty(be,"OPEN",{enumerable:!0,value:gn.indexOf("OPEN")});Object.defineProperty(be.prototype,"OPEN",{enumerable:!0,value:gn.indexOf("OPEN")});Object.defineProperty(be,"CLOSING",{enumerable:!0,value:gn.indexOf("CLOSING")});Object.defineProperty(be.prototype,"CLOSING",{enumerable:!0,value:gn.indexOf("CLOSING")});Object.defineProperty(be,"CLOSED",{enumerable:!0,value:gn.indexOf("CLOSED")});Object.defineProperty(be.prototype,"CLOSED",{enumerable:!0,value:gn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(be.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(be.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Au])return e[QS];return null},set(e){for(let n of this.listeners(t))if(n[Au]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Au]:!0})}})});be.prototype.addEventListener=t0;be.prototype.removeEventListener=n0;cg.exports=be;function rg(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:YS,protocolVersion:Cu[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,!Cu.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Cu.join(", ")})`);let i;if(e instanceof Eu)i=e;else try{i=new Eu(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 I=new SyntaxError(c);if(t._redirects===0)throw I;Ia(t,I);return}let d=o?443:80,p=GS(16).toString("base64"),f=o?BS.request:HS.request,w=new Set,v;if(s.createConnection=s.createConnection||(o?l0:a0),s.defaultPort=s.defaultPort||d,s.port=i.port||d,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(v=new Bn({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=r0({[Bn.extensionName]:v.offer()})),n.length){for(let I of n){if(typeof I!="string"||!o0.test(I)||w.has(I))throw new SyntaxError("An invalid or duplicated subprotocol was specified");w.add(I)}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 I=s.path.split(":");s.socketPath=I[0],s.path=I[1]}let _;if(s.followRedirects){if(t._redirects===0){t._originalIpc=l,t._originalSecure=o,t._originalHostOrSocketPath=l?s.socketPath:i.host;let I=r&&r.headers;if(r={...r,headers:{}},I)for(let[R,C]of Object.entries(I))r.headers[R.toLowerCase()]=C}else if(t.listenerCount("redirect")===0){let I=l?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!I||t._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,I||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),_=t._req=f(s),t._redirects&&t.emit("redirect",t.url,_)}else _=t._req=f(s);s.timeout&&_.on("timeout",()=>{st(t,_,"Opening handshake has timed out")}),_.on("error",I=>{_===null||_[ng]||(_=t._req=null,Ia(t,I))}),_.on("response",I=>{let R=I.headers.location,C=I.statusCode;if(R&&s.followRedirects&&C>=300&&C<400){if(++t._redirects>s.maxRedirects){st(t,_,"Maximum redirects exceeded");return}_.abort();let V;try{V=new Eu(R,e)}catch{let $=new SyntaxError(`Invalid URL: ${R}`);Ia(t,$);return}rg(t,V,n,r)}else t.emit("unexpected-response",_,I)||st(t,_,`Unexpected server response: ${I.statusCode}`)}),_.on("upgrade",(I,R,C)=>{if(t.emit("upgrade",I),t.readyState!==be.CONNECTING)return;_=t._req=null;let V=I.headers.upgrade;if(V===void 0||V.toLowerCase()!=="websocket"){st(t,R,"Invalid Upgrade header");return}let J=WS("sha1").update(p+XS).digest("base64");if(I.headers["sec-websocket-accept"]!==J){st(t,R,"Invalid Sec-WebSocket-Accept header");return}let $=I.headers["sec-websocket-protocol"],b;if($!==void 0?w.size?w.has($)||(b="Server sent an invalid subprotocol"):b="Server sent a subprotocol but none was requested":w.size&&(b="Server sent no subprotocol"),b){st(t,R,b);return}$&&(t._protocol=$);let U=I.headers["sec-websocket-extensions"];if(U!==void 0){if(!v){st(t,R,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let j;try{j=s0(U)}catch{st(t,R,"Invalid Sec-WebSocket-Extensions header");return}let K=Object.keys(j);if(K.length!==1||K[0]!==Bn.extensionName){st(t,R,"Server indicated an extension that was not requested");return}try{v.accept(j[Bn.extensionName])}catch{st(t,R,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Bn.extensionName]=v}t.setSocket(R,C,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(_,t):_.end()}function Ia(t,e){t._readyState=be.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function a0(t){return t.path=t.socketPath,eg.connect(t)}function l0(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=eg.isIP(t.host)?"":t.host),KS.connect(t)}function st(t,e,n){t._readyState=be.CLOSING;let r=new Error(n);Error.captureStackTrace(r,st),e.setHeader?(e[ng]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Ia,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function $u(t,e,n){if(e){let r=JS(e)?e.size:i0(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${gn[t.readyState]})`);process.nextTick(n,r)}}function c0(t,e){let n=this[je];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[je]!==void 0&&(n._socket.removeListener("data",Ra),process.nextTick(sg,n._socket),t===1005?n.close():n.close(t,e))}function u0(){let t=this[je];t.isPaused||t._socket.resume()}function d0(t){let e=this[je];e._socket[je]!==void 0&&(e._socket.removeListener("data",Ra),process.nextTick(sg,e._socket),e.close(t[e0])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Qm(){this[je].emitClose()}function h0(t,e){this[je].emit("message",t,e)}function p0(t){let e=this[je];e._autoPong&&e.pong(t,!this._isServer,tg),e.emit("ping",t)}function f0(t){this[je].emit("pong",t)}function sg(t){t.resume()}function m0(t){let e=this[je];e.readyState!==be.CLOSED&&(e.readyState===be.OPEN&&(e._readyState=be.CLOSING,ig(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function ig(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function og(){let t=this[je];if(this.removeListener("close",og),this.removeListener("data",Ra),this.removeListener("end",ag),t._readyState=be.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[je]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Qm),t._receiver.on("finish",Qm))}function Ra(t){this[je]._receiver.write(t)||this.pause()}function ag(){let t=this[je];t._readyState=be.CLOSING,t._receiver.end(),this.end()}function lg(){let t=this[je];this.removeListener("error",lg),this.on("error",tg),t&&(t._readyState=be.CLOSING,this.destroy())}});var pg=he((TE,hg)=>{"use strict";var SE=Ea(),{Duplex:g0}=require("stream");function ug(t){t.emit("close")}function y0(){!this.destroyed&&this._writableState.finished&&this.destroy()}function dg(t){this.removeListener("error",dg),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function b0(t,e){let n=!0,r=new g0({...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(ug,r);return}let o=!1;t.once("error",function(c){o=!0,i(c)}),t.once("close",function(){o||i(s),process.nextTick(ug,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",y0),r.on("error",dg),r}hg.exports=b0});var Pu=he((xE,fg)=>{"use strict";var{tokenChars:w0}=qs();function v0(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&&w0[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}fg.exports={parse:v0}});var kg=he((RE,vg)=>{"use strict";var k0=require("events"),Aa=require("http"),{Duplex:IE}=require("stream"),{createHash:_0}=require("crypto"),mg=Ta(),Qr=Us(),S0=Pu(),T0=Ea(),{CLOSE_TIMEOUT:x0,GUID:I0,kWebSocket:R0}=pn(),E0=/^[+/0-9A-Za-z]{22}==$/,gg=0,yg=1,wg=2,Nu=class extends k0{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:x0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:T0,...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=Aa.createServer((r,s)=>{let i=Aa.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=A0(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=gg}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===wg){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Di,this);return}if(e&&this.once("close",e),this._state!==yg)if(this._state=yg,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(Di,this):process.nextTick(Di,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Di(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",bg);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,l=+e.headers["sec-websocket-version"];if(e.method!=="GET"){es(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){es(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!E0.test(i)){es(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(l!==13&&l!==8){es(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"],d=new Set;if(c!==void 0)try{d=S0.parse(c)}catch{es(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 Qr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let v=mg.parse(p);v[Qr.extensionName]&&(w.accept(v[Qr.extensionName]),f[Qr.extensionName]=w)}catch{es(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,(v,_,I,R)=>{if(!v)return Li(n,_||401,I,R);this.completeUpgrade(f,i,d,e,n,r,s)});return}if(!this.options.verifyClient(w))return Li(n,401)}this.completeUpgrade(f,i,d,e,n,r,s)}completeUpgrade(e,n,r,s,i,o,l){if(!i.readable||!i.writable)return i.destroy();if(i[R0])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>gg)return Li(i,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${_0("sha1").update(n+I0).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&&(d.push(`Sec-WebSocket-Protocol: ${f}`),p._protocol=f)}if(e[Qr.extensionName]){let f=e[Qr.extensionName].params,w=mg.format({[Qr.extensionName]:[f]});d.push(`Sec-WebSocket-Extensions: ${w}`),p._extensions=e}this.emit("headers",d,s),i.write(d.concat(`\r
955
956
  `).join(`\r
956
- `)),i.removeListener("error",og),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(ji,this)})),l(p,s)}};lg.exports=Tu;function e0(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 ji(t){t._state=ag,t.emit("close")}function og(){this.destroy()}function Mi(t,e,n,r){n=n||xa.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} ${xa.STATUS_CODES[e]}\r
957
+ `)),i.removeListener("error",bg),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(Di,this)})),l(p,s)}};vg.exports=Nu;function A0(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 Di(t){t._state=wg,t.emit("close")}function bg(){this.destroy()}function Li(t,e,n,r){n=n||Aa.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} ${Aa.STATUS_CODES[e]}\r
957
958
  `+Object.keys(r).map(s=>`${s}: ${r[s]}`).join(`\r
958
959
  `)+`\r
959
960
  \r
960
- `+n)}function Jr(t,e,n,r,s,i){if(t.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,Jr),t.emit("wsClientError",o,n,e)}else Mi(n,r,s,i)}});var bg={};Kt(bg,{CATALOGUE:()=>Pu,catalogueForPrompt:()=>Nu,describeDiagnostic:()=>v0,runDiagnostic:()=>k0});function Nu(){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(`
961
- `)}function v0(t){let e=Pu[t.command];return e?e.describe(t.args??{}):null}async function k0(t){let e=Pu[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,yg.execFile)(n[0],n.slice(1),{timeout:b0,maxBuffer:2e6},(i,o,l)=>{let c=`${o??""}${l?`
962
- ${l}`:""}`.trim(),d=xc(c).slice(0,w0)||(i?String(i.message):"(no output)");s({ok:!0,commandLine:r,output:d})})})}var yg,$u,b0,w0,mg,gg,Cu,wt,Ca,Pu,Ou=ne(()=>{"use strict";yg=require("node:child_process"),$u=R(require("node:fs"),1);Ic();b0=1e4,w0=8e3,mg=/(\/\.(config|claude)\/|\/\.env($|[^a-z])|credentials|\.ssh\/|\.npmrc|runner\.json)/i,gg=/^[a-zA-Z0-9@._-]{1,80}$/,Cu=/^\/[^\0\n]{1,300}$/,wt=t=>typeof t=="string"?t.trim():"",Ca=(t,e,n)=>{let r=typeof t=="number"?Math.floor(t):n;return r>0&&r<=e?r:n},Pu={service_status:{describe:t=>`systemctl status ${wt(t.unit)}`,build:t=>{let e=wt(t.unit);return gg.test(e)?["systemctl","status",e,"--no-pager","-l"]:"refused: that is not a plausible unit name"}},service_logs:{describe:t=>`journalctl -u ${wt(t.unit)} -n ${Ca(t.lines,200,50)}`,build:t=>{let e=wt(t.unit);return gg.test(e)?["journalctl","-u",e,"-n",String(Ca(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 ${wt(t.path)}`,build:t=>{let e=wt(t.path);return Cu.test(e)?mg.test(e)?"refused: that path can hold credentials":["ls","-la",e]:"refused: absolute path required"}},read_file:{describe:t=>`head -n ${Ca(t.lines,200,100)} ${wt(t.path)}`,build:t=>{let e=wt(t.path);if(!Cu.test(e))return"refused: absolute path required";if(mg.test(e))return"refused: that path can hold credentials";try{if($u.default.statSync(e).size>2e6)return"refused: file too large for a chat"}catch{}return["head","-n",String(Ca(t.lines,200,100)),e]}},http_check:{describe:t=>`curl -sS -o /dev/null -w '%{http_code}' ${wt(t.url)}`,build:t=>{let e=wt(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 ${wt(t.path)} status + last 3 commits`,build:t=>{let e=wt(t.path);return Cu.test(e)?$u.default.existsSync(`${e}/.git`)?["git","-C",e,"log","--oneline","-3","--decorate"]:"refused: not a git checkout":"refused: absolute path required"}}}});var Cg={};Kt(Cg,{MANAGED_MARKER:()=>Fi,caddyBlock:()=>Gs,checkoutOwner:()=>Ag,detectApp:()=>kg,envPrepare:()=>T0,nginxBlock:()=>Li,nodeBinDir:()=>vg,ownsProxyFile:()=>Eg,pickPort:()=>Sg,portsClaimedByUnits:()=>_g,resolveProxyChoice:()=>Rg,spliceCaddyBlock:()=>Ig,spliceManagedBlock:()=>Mu,sudoersText:()=>xg,unitSlug:()=>wg,unitText:()=>Tg});function wg(t,e){let n=r=>r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return`${n(t)}-${n(e)}`.slice(0,60)}function vg(t){let e=n=>{try{let r=(0,Ht.execFileSync)(n[0],n.slice(1),{encoding:"utf8",timeout:1e4}).trim();return r?Et.default.dirname(r):null}catch{return null}};return t&&t!==qi.default.userInfo().username?e(["sudo","-u",t,"bash","-lc","command -v node"]):e(["bash","-lc","command -v node"])}function kg(t){let e=Et.default.join(t,"package.json");if(!be.default.existsSync(e))return{kind:"unknown",reason:"no package.json - only Node apps are supported so far"};let n;try{n=JSON.parse(be.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 _g(){let t=new Set;try{for(let e of be.default.readdirSync("/etc/systemd/system"))if(e.endsWith(".service"))try{let n=be.default.readFileSync(Et.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 Sg(t){let e=_g(),n=r=>new Promise(s=>{let i=ju.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 Tg(t){return`${Fi}
961
+ `+n)}function es(t,e,n,r,s,i){if(t.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,es),t.emit("wsClientError",o,n,e)}else Li(n,r,s,i)}});var Cg={};$t(Cg,{CATALOGUE:()=>qu,catalogueForPrompt:()=>Fu,describeDiagnostic:()=>V0,runDiagnostic:()=>J0});function Fu(){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(`
962
+ `)}function V0(t){let e=qu[t.command];return e?e.describe(t.args??{}):null}async function J0(t){let e=qu[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,Ag.execFile)(n[0],n.slice(1),{timeout:W0,maxBuffer:2e6},(i,o,l)=>{let c=`${o??""}${l?`
963
+ ${l}`:""}`.trim(),d=jc(c).slice(0,Z0)||(i?String(i.message):"(no output)");s({ok:!0,commandLine:r,output:d})})})}var Ag,Uu,W0,Z0,Rg,Eg,Lu,vt,ja,qu,Bu=te(()=>{"use strict";Ag=require("node:child_process"),Uu=E(require("node:fs"),1);Oc();W0=1e4,Z0=8e3,Rg=/(\/\.(config|claude)\/|\/\.env($|[^a-z])|credentials|\.ssh\/|\.npmrc|runner\.json)/i,Eg=/^[a-zA-Z0-9@._-]{1,80}$/,Lu=/^\/[^\0\n]{1,300}$/,vt=t=>typeof t=="string"?t.trim():"",ja=(t,e,n)=>{let r=typeof t=="number"?Math.floor(t):n;return r>0&&r<=e?r:n},qu={service_status:{describe:t=>`systemctl status ${vt(t.unit)}`,build:t=>{let e=vt(t.unit);return Eg.test(e)?["systemctl","status",e,"--no-pager","-l"]:"refused: that is not a plausible unit name"}},service_logs:{describe:t=>`journalctl -u ${vt(t.unit)} -n ${ja(t.lines,200,50)}`,build:t=>{let e=vt(t.unit);return Eg.test(e)?["journalctl","-u",e,"-n",String(ja(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 ${vt(t.path)}`,build:t=>{let e=vt(t.path);return Lu.test(e)?Rg.test(e)?"refused: that path can hold credentials":["ls","-la",e]:"refused: absolute path required"}},read_file:{describe:t=>`head -n ${ja(t.lines,200,100)} ${vt(t.path)}`,build:t=>{let e=vt(t.path);if(!Lu.test(e))return"refused: absolute path required";if(Rg.test(e))return"refused: that path can hold credentials";try{if(Uu.default.statSync(e).size>2e6)return"refused: file too large for a chat"}catch{}return["head","-n",String(ja(t.lines,200,100)),e]}},http_check:{describe:t=>`curl -sS -o /dev/null -w '%{http_code}' ${vt(t.url)}`,build:t=>{let e=vt(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 ${vt(t.path)} status + last 3 commits`,build:t=>{let e=vt(t.path);return Lu.test(e)?Uu.default.existsSync(`${e}/.git`)?["git","-C",e,"log","--oneline","-3","--decorate"]:"refused: not a git checkout":"refused: absolute path required"}}}});var Fg={};$t(Fg,{MANAGED_MARKER:()=>Ki,caddyBlock:()=>Ws,checkoutOwner:()=>qg,detectApp:()=>Ng,envPrepare:()=>Q0,nginxBlock:()=>Fi,nodeBinDir:()=>Pg,ownsProxyFile:()=>Lg,pickPort:()=>Og,portsClaimedByUnits:()=>jg,resolveProxyChoice:()=>Ug,spliceCaddyBlock:()=>Dg,spliceManagedBlock:()=>Ku,sudoersText:()=>zg,unitSlug:()=>$g,unitText:()=>Mg});function $g(t,e){let n=r=>r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return`${n(t)}-${n(e)}`.slice(0,60)}function Pg(t){let e=n=>{try{let r=(0,Wt.execFileSync)(n[0],n.slice(1),{encoding:"utf8",timeout:1e4}).trim();return r?At.default.dirname(r):null}catch{return null}};return t&&t!==Hi.default.userInfo().username?e(["sudo","-u",t,"bash","-lc","command -v node"]):e(["bash","-lc","command -v node"])}function Ng(t){let e=At.default.join(t,"package.json");if(!we.default.existsSync(e))return{kind:"unknown",reason:"no package.json - only Node apps are supported so far"};let n;try{n=JSON.parse(we.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 jg(){let t=new Set;try{for(let e of we.default.readdirSync("/etc/systemd/system"))if(e.endsWith(".service"))try{let n=we.default.readFileSync(At.default.join("/etc/systemd/system",e),"utf8");for(let r of n.matchAll(/^Environment=PORT=(\d+)$/gm))t.add(Number(r[1]))}catch{}}catch{}return t}async function Og(t){let e=jg(),n=r=>new Promise(s=>{let i=Hu.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 Mg(t){return`${Ki}
963
964
  [Unit]
964
965
  Description=${t.repoName} ${t.envName} (Allwright-prepared)
965
966
  After=network-online.target
@@ -989,14 +990,14 @@ RestartSec=3
989
990
 
990
991
  [Install]
991
992
  WantedBy=multi-user.target
992
- `}function xg(t){return`${Fi}
993
+ `}function zg(t){return`${Ki}
993
994
  # Exactly two commands, exactly one unit - what a deploy needs and nothing else.
994
995
  ${t.user} ALL=(root) NOPASSWD: /usr/bin/systemctl restart ${t.slug}, /usr/bin/systemctl is-active ${t.slug}
995
- `}function Gs(t){return`# BEGIN allwright ${t.slug}
996
+ `}function Ws(t){return`# BEGIN allwright ${t.slug}
996
997
  ${t.hostname} {
997
998
  reverse_proxy 127.0.0.1:${t.port}
998
999
  }
999
- # END allwright ${t.slug}`}function Li(t){return`# BEGIN allwright ${t.slug}
1000
+ # END allwright ${t.slug}`}function Fi(t){return`# BEGIN allwright ${t.slug}
1000
1001
  server {
1001
1002
  listen 80;
1002
1003
  server_name ${t.hostname};
@@ -1007,10 +1008,10 @@ server {
1007
1008
  proxy_set_header X-Forwarded-Proto $scheme;
1008
1009
  }
1009
1010
  }
1010
- # END allwright ${t.slug}`}function Mu(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*$/,"")+`
1011
+ # END allwright ${t.slug}`}function Ku(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*$/,"")+`
1011
1012
 
1012
1013
  `+n+`
1013
- `}function Ig(t,e,n){return Mu(t,e,n)}function Eg(t){return t.trim()===""||t.includes("# BEGIN allwright ")||t.includes(Fi)}function Rg(t){let{flag:e,caddyActive:n,nginxActive:r}=t;return e!==void 0&&e!=="caddy"&&e!=="nginx"&&e!=="none"?{error:`--proxy must be caddy, nginx or none (got "${e}")`}:e==="none"?{mode:"none"}:e==="caddy"&&r&&!n?{error:"nginx is the proxy already running on this machine, and two proxies cannot share :80/:443 - the running one wins. Re-run with --proxy nginx (or stop nginx first); this command never sets up a second proxy alongside a live one."}:e==="nginx"&&n&&!r?{error:"caddy is the proxy already running on this machine, and two proxies cannot share :80/:443 - the running one wins. Re-run with --proxy caddy (or stop caddy first); this command never sets up a second proxy alongside a live one."}:e==="caddy"||e==="nginx"?{mode:e}:n?{mode:"caddy"}:r?{mode:"nginx"}:{mode:"print-both"}}function Ag(t){let e=be.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,Ht.execFileSync)("id",["-nu",String(e)],{encoding:"utf8",timeout:5e3}).trim()}catch{return qi.default.userInfo().username}}function _e(t,e){(0,Ht.execFileSync)("sudo",t,{encoding:"utf8",timeout:6e4,...e!==void 0?{input:e}:{},stdio:[e!==void 0?"pipe":"inherit","inherit","inherit"]})}function _0(t){if(t.sudoers){let e=Et.default.join(qi.default.tmpdir(),`allwright-sudoers-${process.pid}`);be.default.writeFileSync(e,t.content,{mode:384});try{(0,Ht.execFileSync)("sudo",["visudo","-cf",e],{encoding:"utf8",timeout:3e4}),_e(["install","-m",t.mode,"-o","root","-g","root",e,t.path])}finally{be.default.rmSync(e,{force:!0})}return}_e(["mkdir","-p",Et.default.dirname(t.path)]),_e(["tee",t.path],t.content),_e(["chmod",t.mode,t.path])}function S0(t){try{return be.default.readFileSync(t,"utf8").includes(Fi)}catch{return!0}}async function T0(t){if(!be.default.existsSync(t.dir))throw new Error(`${t.dir} does not exist - clone the repo there first`);if(!be.default.existsSync(Et.default.join(t.dir,".git")))throw new Error(`${t.dir} is not a git checkout`);let e=kg(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=Rg({flag:t.proxy,caddyActive:Ui("caddy"),nginxActive:Ui("nginx")});if("error"in n)throw new Error(n.error);let r=n.mode,s=wg(t.repoName,t.envName),i=t.publicUrl?x0(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==="none")return;if(!i){y.info("Pass --url to wire the proxy, or configure it in your web server by hand.");return}let E=`
1014
+ `}function Dg(t,e,n){return Ku(t,e,n)}function Lg(t){return t.trim()===""||t.includes("# BEGIN allwright ")||t.includes(Ki)}function Ug(t){let{flag:e,caddyActive:n,nginxActive:r}=t;return e!==void 0&&e!=="caddy"&&e!=="nginx"&&e!=="none"?{error:`--proxy must be caddy, nginx or none (got "${e}")`}:e==="none"?{mode:"none"}:e==="caddy"&&r&&!n?{error:"nginx is the proxy already running on this machine, and two proxies cannot share :80/:443 - the running one wins. Re-run with --proxy nginx (or stop nginx first); this command never sets up a second proxy alongside a live one."}:e==="nginx"&&n&&!r?{error:"caddy is the proxy already running on this machine, and two proxies cannot share :80/:443 - the running one wins. Re-run with --proxy caddy (or stop caddy first); this command never sets up a second proxy alongside a live one."}:e==="caddy"||e==="nginx"?{mode:e}:n?{mode:"caddy"}:r?{mode:"nginx"}:{mode:"print-both"}}function qg(t){let e=we.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,Wt.execFileSync)("id",["-nu",String(e)],{encoding:"utf8",timeout:5e3}).trim()}catch{return Hi.default.userInfo().username}}function Se(t,e){(0,Wt.execFileSync)("sudo",t,{encoding:"utf8",timeout:6e4,...e!==void 0?{input:e}:{},stdio:[e!==void 0?"pipe":"inherit","inherit","inherit"]})}function Y0(t){if(t.sudoers){let e=At.default.join(Hi.default.tmpdir(),`allwright-sudoers-${process.pid}`);we.default.writeFileSync(e,t.content,{mode:384});try{(0,Wt.execFileSync)("sudo",["visudo","-cf",e],{encoding:"utf8",timeout:3e4}),Se(["install","-m",t.mode,"-o","root","-g","root",e,t.path])}finally{we.default.rmSync(e,{force:!0})}return}Se(["mkdir","-p",At.default.dirname(t.path)]),Se(["tee",t.path],t.content),Se(["chmod",t.mode,t.path])}function X0(t){try{return we.default.readFileSync(t,"utf8").includes(Ki)}catch{return!0}}async function Q0(t){if(!we.default.existsSync(t.dir))throw new Error(`${t.dir} does not exist - clone the repo there first`);if(!we.default.existsSync(At.default.join(t.dir,".git")))throw new Error(`${t.dir} is not a git checkout`);let e=Ng(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=Ug({flag:t.proxy,caddyActive:Bi("caddy"),nginxActive:Bi("nginx")});if("error"in n)throw new Error(n.error);let r=n.mode,s=$g(t.repoName,t.envName),i=t.publicUrl?eT(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==="none")return;if(!i){g.info("Pass --url to wire the proxy, or configure it in your web server by hand.");return}let R=`
1014
1015
  ${i} {
1015
1016
  root * ${t.dir}/<your build output>
1016
1017
  file_server
@@ -1024,26 +1025,30 @@ server {
1024
1025
  try_files $uri $uri/ =404;
1025
1026
  }
1026
1027
  }
1027
- `;r==="caddy"?(y.info("Add a site block for it to /etc/caddy/Caddyfile yourself, for example:"),y.info(E)):r==="nginx"?(y.info("Add a server block for it under /etc/nginx yourself, for example:"),y.info(C),y.info("TLS stays yours: nginx does not fetch certificates (Caddy does) - certbot when you are ready.")):(y.info("No proxy is running on this machine. Pick ONE - never run two proxies on the same :80/:443 - and re-run with --proxy caddy or --proxy nginx. The blocks would be:"),y.info(E),y.info(C));return}let o=Yo(t.dir).filter(E=>!E.startsWith(s)),l=`/etc/systemd/system/${s}.service`;if(o.length&&!be.default.existsSync(l)){y.info(`this checkout is already supervised: ${o.join(" \xB7 ")}. Leaving it alone - remove that unit first if you want Allwright to manage this environment.`);return}if(!S0(l))throw new Error(`${l} exists and was not written by this command - refusing to overwrite a hand-written unit. Delete it yourself if you want it replaced.`);let c=Ag(t.dir),d=vg(c);if(!d)throw new Error(`node is not on ${c}'s PATH - the service will run as ${c} (the checkout's owner), so Node must be installed for THAT user (or system-wide). Install it, then re-run.`);let p=await Sg(t.port),f=[{path:l,content:Tg({slug:s,repoName:t.repoName,envName:t.envName,dir:t.dir,user:c,port:p,nodeBin:d}),mode:"644"},{path:`/etc/sudoers.d/allwright-${s}`,content:xg({slug:s,user:c}),mode:"440",sudoers:!0}];if(t.dryRun){y.info(`DRY RUN - nothing will be written. Planned (port ${p}, user ${c}):`);for(let E of f)y.info(`
1028
- --- ${E.path} (mode ${E.mode}) ---
1029
- ${E.content}`);i&&r==="caddy"&&y.info(`--- appended to /etc/caddy/Caddyfile ---
1030
- ${Gs({slug:s,hostname:i,port:p})}`),i&&r==="nginx"&&y.info(`--- written to /etc/nginx/{sites-available,conf.d}/allwright-${s}.conf ---
1031
- `+Li({slug:s,hostname:i,port:p})),i&&r==="print-both"&&y.info(`--- no proxy is running; one of these, whichever you pick with --proxy ---
1032
- ${Gs({slug:s,hostname:i,port:p})}
1033
-
1034
- ${Li({slug:s,hostname:i,port:p})}`);return}for(let E of f)_0(E);let w=`/etc/allwright/env.d/${s}.env`;be.default.existsSync(w)||(_e(["install","-d","-m","755","/etc/allwright"]),_e(["install","-d","-m","750","/etc/allwright/env.d"]),_e(["install","-m","600","-o","root","-g","root","/dev/null",w]),y.info(`created empty ${w} - add secrets with: sudoedit ${w}`));let v=be.default.existsSync(Et.default.join(t.dir,".next"))||be.default.existsSync(Et.default.join(t.dir,"dist"));v||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 ${s}`),_e(["systemctl","daemon-reload"]),_e(["systemctl","reset-failed",s]),_e(["systemctl","enable","--now",s]),i&&r!=="none"&&(r==="caddy"?E0({slug:s,hostname:i,port:p}):r==="nginx"?R0({slug:s,hostname:i,port:p}):(y.info("No proxy is running on this machine. Pick ONE - never run two proxies on the same :80/:443 - and re-run with --proxy caddy or --proxy nginx. The block would be:"),y.info(`
1035
- ${Gs({slug:s,hostname:i,port:p})}
1036
- `),y.info(`
1037
- ${Li({slug:s,hostname:i,port:p})}
1038
- `)));let _=v?await I0(p,3e4):!1,I=Ui(s);y.info(""),y.info(`${I?"\u2713":"\u2717"} service ${s}: ${I?"active":"NOT active - journalctl -u "+s+" -n 40"}`),v&&y.info(`${_?"\u2713":"\u2717"} listening on 127.0.0.1:${p}${_?"":" - 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 ${s}`),i&&y.info(`Health checks should target: http://127.0.0.1:${p}/ (and later https://${i}/)`),y.info(`DNS stays yours: point ${i||"your hostname"} at this machine when you are ready.`)}function x0(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 Ui(t){try{return(0,Ht.execFileSync)("systemctl",["is-active",t],{encoding:"utf8",timeout:1e4}).trim()==="active"}catch{return!1}}async function I0(t,e){let n=Date.now()+e;for(;Date.now()<n;){if(await new Promise(s=>{let i=ju.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 E0(t){let e="/etc/caddy/Caddyfile";if(!be.default.existsSync(e)||!Ui("caddy")){y.warn(`caddy is not running here (or ${e} does not exist) - add this to your web server yourself:
1039
- ${Gs(t)}`);return}let n;try{n=be.default.readFileSync(e,"utf8")}catch{n=(0,Ht.execFileSync)("sudo",["cat",e],{encoding:"utf8",timeout:1e4})}let r=Ig(n,t.slug,Gs(t));if(r===n){y.info(`caddy already routes ${t.hostname} - unchanged`);return}let s=Et.default.join(qi.default.tmpdir(),`Caddyfile-allwright-${process.pid}`);be.default.writeFileSync(s,r,{mode:420});try{(0,Ht.execFileSync)("sudo",["caddy","validate","--config",s,"--adapter","caddyfile"],{encoding:"utf8",timeout:3e4}),_e(["cp",e,`${e}.bak.${Math.floor(Date.now()/1e3)}`]),_e(["cp",s,e]),_e(["systemctl","reload","caddy"]),y.info(`\u2713 caddy: ${t.hostname} \u2192 127.0.0.1:${t.port} (validated, reloaded, backup kept)`)}finally{be.default.rmSync(s,{force:!0})}}function R0(t){let e=Li(t),n=`TLS stays yours: nginx does not fetch certificates (Caddy does) - run certbot for ${t.hostname} when DNS points here.`;if(!be.default.existsSync("/etc/nginx")||!Ui("nginx")){y.warn(`nginx is not running here (or /etc/nginx does not exist) - add this server block yourself:
1040
- ${e}`),y.info(n);return}let r=be.default.existsSync("/etc/nginx/sites-enabled"),s=r?`/etc/nginx/sites-available/allwright-${t.slug}.conf`:`/etc/nginx/conf.d/allwright-${t.slug}.conf`,i=r?`/etc/nginx/sites-enabled/allwright-${t.slug}.conf`:null,o=null;if(be.default.existsSync(s)){try{o=be.default.readFileSync(s,"utf8")}catch{o=(0,Ht.execFileSync)("sudo",["cat",s],{encoding:"utf8",timeout:1e4})}if(!Eg(o))throw new Error(`${s} exists and was not written by this command - refusing to overwrite a hand-written site. Delete it yourself if you want it replaced.`)}let l=Mu(o??"",t.slug,e).replace(/^\n+/,"");if(o!==null&&l===o){y.info(`nginx already routes ${t.hostname} - unchanged`);return}let c=i?be.default.existsSync(i):!1;_e(["mkdir","-p",Et.default.dirname(s)]),_e(["tee",s],l),_e(["chmod","644",s]),i&&!c&&_e(["ln","-s",s,i]);try{(0,Ht.execFileSync)("sudo",["nginx","-t"],{encoding:"utf8",timeout:3e4})}catch(d){o!==null?(_e(["tee",s],o),_e(["chmod","644",s])):(i&&!c&&_e(["rm","-f",i]),_e(["rm","-f",s]));let p=d&&typeof d=="object"&&"stderr"in d&&typeof d.stderr=="string"?d.stderr.trim():String(d);throw new Error(`nginx -t rejected the new config - ${s} was ${o!==null?"restored":"removed"} and nginx was NOT reloaded. nginx said:
1041
- ${p}`)}_e(["systemctl","reload","nginx"]),y.info(`\u2713 nginx: ${t.hostname} \u2192 127.0.0.1:${t.port} (${s}, validated, reloaded)`),y.info(n)}var Ht,be,ju,qi,Et,Fi,$g=ne(()=>{"use strict";Ht=require("node:child_process"),be=R(require("node:fs"),1),ju=R(require("node:net"),1),qi=R(require("node:os"),1),Et=R(require("node:path"),1);zt();Xo();Fi="# managed by allwright env prepare"});var zg={};Kt(zg,{buildSetupReport:()=>C0,claudeLoggedIn:()=>Mg,repoCurrentBranch:()=>Og,repoDefaultBranch:()=>jg});function Og(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 jg(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 Mg(t=Pg.default.homedir()){if(Un.default.existsSync(Qr.default.join(t,".claude",".credentials.json")))return!0;try{return!!JSON.parse(Un.default.readFileSync(Qr.default.join(t,".claude.json"),"utf8")).oauthAccount}catch{return!1}}async function C0(t,e,n){let r=!1,s="";if(Bi&&Date.now()-Bi.at<6e4)r=Bi.installed,s=Bi.version;else{try{let{stdout:l}=await A0(t.claudeBin,["--version"],{timeout:1e4});r=!0,s=l.trim().slice(0,60)}catch{r=!1}Bi={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 d=Un.default.existsSync(c.path);return{repoName:l,path:c.path,mapped:!0,liveMapped:n?!!n.repos?.[l]:!0,pathExists:d,isGit:d&&Un.default.existsSync(Qr.default.join(c.path,".git")),currentBranch:d?Og(c.path):"",claudeMd:d&&Un.default.existsSync(Qr.default.join(c.path,"CLAUDE.md")),deployMd:d&&Un.default.existsSync(Qr.default.join(c.path,"DEPLOY.md")),testMd:d&&Un.default.existsSync(Qr.default.join(c.path,"TEST.md")),githubToken:!!Ue(t,l),githubTokenOwn:!!c.github?.token,defaultBranch:d?jg(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:Mg()},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,Un,Pg,Qr,Ng,A0,Bi,Dg=ne(()=>{"use strict";Hi=require("node:child_process"),Un=R(require("node:fs"),1),Pg=R(require("node:os"),1),Qr=R(require("node:path"),1),Ng=require("node:util");Ar();A0=(0,Ng.promisify)(Hi.execFile);Bi=null});var rt=R(require("node:fs"),1),Ki=R(require("node:os"),1),pn=R(require("node:path"),1),mn=require("node:child_process"),qn=require("node:crypto"),Fn=R(require("node:readline/promises"),1);var ed=R(Qu(),1),{program:Z0,createCommand:V0,createArgument:Y0,createOption:J0,CommanderError:X0,InvalidArgumentError:Q0,InvalidOptionArgumentError:eT,Command:td,Argument:tT,Option:nT,Help:rT}=ed.default;Ee();var oo=require("node:child_process"),Qe=R(require("node:fs"),1),ao=R(require("node:path"),1);Ee();var _b=new Set(["runner.log","runner.pid"]);function Sb(t){return Qe.default.readdirSync(t).filter(e=>!_b.has(e)&&!/\.bak-\d+$/.test(e)).sort()}function yd(t){let e=se();if(!Qe.default.existsSync(e))throw new Error(`nothing to export - ${e} does not exist`);let n=Sb(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=ao.default.resolve(t||`ticketpilot-backup-${r}.tgz`);return Qe.default.writeFileSync(s,"",{mode:384}),(0,oo.execFileSync)("tar",["-czf",s,"-C",e,...n]),Qe.default.chmodSync(s,384),{file:s,entries:n}}function bd(t){let e=ao.default.resolve(t);if(!Qe.default.existsSync(e))throw new Error(`backup file not found: ${e}`);let n=(0,oo.execFileSync)("tar",["-tzf",e],{encoding:"utf8"}).split(`
1042
- `).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=se(),s;Qe.default.existsSync(r)&&Qe.default.readdirSync(r).length&&(s=`${r}.bak-${Date.now()}`,Qe.default.renameSync(r,s)),Qe.default.mkdirSync(r,{recursive:!0,mode:448}),(0,oo.execFileSync)("tar",["-xzf",e,"-C",r]);for(let i of Qe.default.readdirSync(r)){let o=ao.default.join(r,i);Qe.default.statSync(o).isFile()&&Qe.default.chmodSync(o,384)}return{restored:n.map(i=>i.replace(/\/$/,"")).sort(),previousDir:s}}rl();var ze=R(require("node:fs"),1),uo=R(require("node:path"),1);Ee();function us(){return uo.default.join(se(),"runner.pid")}function co(){return uo.default.join(se(),"runner.log")}function _d(){ze.default.mkdirSync(se(),{recursive:!0,mode:448});let t=ze.default.openSync(co(),"a",384);try{ze.default.chmodSync(co(),384)}catch{}return t}function ar(){let t=us();if(!ze.default.existsSync(t))return null;let e=Number(ze.default.readFileSync(t,"utf8").trim());return Number.isFinite(e)&&e>0?e:null}function Ab(t){try{return process.kill(t,0),!0}catch{return!1}}function Sd(){try{return ze.default.readFileSync("/proc/sys/kernel/random/boot_id","utf8").trim()||null}catch{return null}}function Cb(t){let e;try{e=ze.default.readFileSync(`/proc/${t}/cmdline`,"utf8")}catch{return null}return e?/allwright|ticketpilot|cli\.(js|ts|cjs|mjs)/i.test(e):null}function lr(t){return Ab(t)?Cb(t)!==!1:!1}function Td(t){ze.default.mkdirSync(se(),{recursive:!0,mode:448}),ze.default.writeFileSync(us(),String(t),{mode:384})}function xd(t){ar()===t&&ze.default.rmSync(us(),{force:!0})}function sl(){return uo.default.join(se(),"runner.lock")}function Id(){let t;try{t=ze.default.readFileSync(sl(),"utf8").trim()}catch{return null}let e,n=null;if(t.startsWith("{"))try{let r=JSON.parse(t);e=Number(r.pid),n=typeof r.boot=="string"?r.boot:null}catch{return null}else e=Number(t);return Number.isFinite(e)&&e>0?{pid:e,boot:n}:null}function ds(){let t=Id();if(!t||t.pid===process.pid)return null;let e=Sd();return t.boot&&e&&t.boot!==e?null:lr(t.pid)?t.pid:null}function Ed(){let t=ds();return t?{ok:!1,pid:t}:(ze.default.mkdirSync(se(),{recursive:!0,mode:448}),ze.default.writeFileSync(sl(),JSON.stringify({pid:process.pid,boot:Sd()}),{mode:384}),{ok:!0})}function il(){try{Id()?.pid===process.pid&&ze.default.rmSync(sl(),{force:!0})}catch{}}function Rd(t){try{let e=ze.default.readFileSync(`/proc/${t}/cgroup`,"utf8"),n=/\/([A-Za-z0-9._@-]+)\.service/.exec(e);return n?n[1]:null}catch{return null}}var wo=R(require("node:fs"),1),si=R(require("node:path"),1),eh=R(Re(),1);Ee();async function th(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:vo})});if(!n.ok){let i=await n.text().catch(()=>"");throw new Error(`enrollment failed (${n.status}): ${i.slice(0,300)}`)}let r=eh.EnrollResponse.parse(await n.json()),s={...t,runnerId:r.runnerId,runnerToken:r.runnerToken};return we(s),s}function hv(){try{let t=process.argv[1]?wo.default.realpathSync(process.argv[1]):"";for(let e of[si.default.dirname(t),si.default.dirname(si.default.dirname(t))]){let n=si.default.join(e,"package.json");if(!wo.default.existsSync(n))continue;let r=JSON.parse(wo.default.readFileSync(n,"utf8")).version;if(typeof r=="string"&&r)return r}}catch{}return"0.0.0"}var vo=hv();jt();oi();function hh(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:
1028
+ `;r==="caddy"?(g.info("Add a site block for it to /etc/caddy/Caddyfile yourself, for example:"),g.info(R)):r==="nginx"?(g.info("Add a server block for it under /etc/nginx yourself, for example:"),g.info(C),g.info("TLS stays yours: nginx does not fetch certificates (Caddy does) - certbot when you are ready.")):(g.info("No proxy is running on this machine. Pick ONE - never run two proxies on the same :80/:443 - and re-run with --proxy caddy or --proxy nginx. The blocks would be:"),g.info(R),g.info(C));return}let o=ea(t.dir).filter(R=>!R.startsWith(s)),l=`/etc/systemd/system/${s}.service`;if(o.length&&!we.default.existsSync(l)){g.info(`this checkout is already supervised: ${o.join(" \xB7 ")}. Leaving it alone - remove that unit first if you want Allwright to manage this environment.`);return}if(!X0(l))throw new Error(`${l} exists and was not written by this command - refusing to overwrite a hand-written unit. Delete it yourself if you want it replaced.`);let c=qg(t.dir),d=Pg(c);if(!d)throw new Error(`node is not on ${c}'s PATH - the service will run as ${c} (the checkout's owner), so Node must be installed for THAT user (or system-wide). Install it, then re-run.`);let p=await Og(t.port),f=[{path:l,content:Mg({slug:s,repoName:t.repoName,envName:t.envName,dir:t.dir,user:c,port:p,nodeBin:d}),mode:"644"},{path:`/etc/sudoers.d/allwright-${s}`,content:zg({slug:s,user:c}),mode:"440",sudoers:!0}];if(t.dryRun){g.info(`DRY RUN - nothing will be written. Planned (port ${p}, user ${c}):`);for(let R of f)g.info(`
1029
+ --- ${R.path} (mode ${R.mode}) ---
1030
+ ${R.content}`);i&&r==="caddy"&&g.info(`--- appended to /etc/caddy/Caddyfile ---
1031
+ ${Ws({slug:s,hostname:i,port:p})}`),i&&r==="nginx"&&g.info(`--- written to /etc/nginx/{sites-available,conf.d}/allwright-${s}.conf ---
1032
+ `+Fi({slug:s,hostname:i,port:p})),i&&r==="print-both"&&g.info(`--- no proxy is running; one of these, whichever you pick with --proxy ---
1033
+ ${Ws({slug:s,hostname:i,port:p})}
1034
+
1035
+ ${Fi({slug:s,hostname:i,port:p})}`);return}for(let R of f)Y0(R);let w=`/etc/allwright/env.d/${s}.env`;we.default.existsSync(w)||(Se(["install","-d","-m","755","/etc/allwright"]),Se(["install","-d","-m","750","/etc/allwright/env.d"]),Se(["install","-m","600","-o","root","-g","root","/dev/null",w]),g.info(`created empty ${w} - add secrets with: sudoedit ${w}`));let v=we.default.existsSync(At.default.join(t.dir,".next"))||we.default.existsSync(At.default.join(t.dir,"dist"));v||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 ${s}`),Se(["systemctl","daemon-reload"]),Se(["systemctl","reset-failed",s]),Se(["systemctl","enable","--now",s]),i&&r!=="none"&&(r==="caddy"?nT({slug:s,hostname:i,port:p}):r==="nginx"?rT({slug:s,hostname:i,port:p}):(g.info("No proxy is running on this machine. Pick ONE - never run two proxies on the same :80/:443 - and re-run with --proxy caddy or --proxy nginx. The block would be:"),g.info(`
1036
+ ${Ws({slug:s,hostname:i,port:p})}
1037
+ `),g.info(`
1038
+ ${Fi({slug:s,hostname:i,port:p})}
1039
+ `)));let _=v?await tT(p,3e4):!1,I=Bi(s);g.info(""),g.info(`${I?"\u2713":"\u2717"} service ${s}: ${I?"active":"NOT active - journalctl -u "+s+" -n 40"}`),v&&g.info(`${_?"\u2713":"\u2717"} listening on 127.0.0.1:${p}${_?"":" - 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 ${s}`),i&&g.info(`Health checks should target: http://127.0.0.1:${p}/ (and later https://${i}/)`),g.info(`DNS stays yours: point ${i||"your hostname"} at this machine when you are ready.`)}function eT(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 Bi(t){try{return(0,Wt.execFileSync)("systemctl",["is-active",t],{encoding:"utf8",timeout:1e4}).trim()==="active"}catch{return!1}}async function tT(t,e){let n=Date.now()+e;for(;Date.now()<n;){if(await new Promise(s=>{let i=Hu.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 nT(t){let e="/etc/caddy/Caddyfile";if(!we.default.existsSync(e)||!Bi("caddy")){g.warn(`caddy is not running here (or ${e} does not exist) - add this to your web server yourself:
1040
+ ${Ws(t)}`);return}let n;try{n=we.default.readFileSync(e,"utf8")}catch{n=(0,Wt.execFileSync)("sudo",["cat",e],{encoding:"utf8",timeout:1e4})}let r=Dg(n,t.slug,Ws(t));if(r===n){g.info(`caddy already routes ${t.hostname} - unchanged`);return}let s=At.default.join(Hi.default.tmpdir(),`Caddyfile-allwright-${process.pid}`);we.default.writeFileSync(s,r,{mode:420});try{(0,Wt.execFileSync)("sudo",["caddy","validate","--config",s,"--adapter","caddyfile"],{encoding:"utf8",timeout:3e4}),Se(["cp",e,`${e}.bak.${Math.floor(Date.now()/1e3)}`]),Se(["cp",s,e]),Se(["systemctl","reload","caddy"]),g.info(`\u2713 caddy: ${t.hostname} \u2192 127.0.0.1:${t.port} (validated, reloaded, backup kept)`)}finally{we.default.rmSync(s,{force:!0})}}function rT(t){let e=Fi(t),n=`TLS stays yours: nginx does not fetch certificates (Caddy does) - run certbot for ${t.hostname} when DNS points here.`;if(!we.default.existsSync("/etc/nginx")||!Bi("nginx")){g.warn(`nginx is not running here (or /etc/nginx does not exist) - add this server block yourself:
1041
+ ${e}`),g.info(n);return}let r=we.default.existsSync("/etc/nginx/sites-enabled"),s=r?`/etc/nginx/sites-available/allwright-${t.slug}.conf`:`/etc/nginx/conf.d/allwright-${t.slug}.conf`,i=r?`/etc/nginx/sites-enabled/allwright-${t.slug}.conf`:null,o=null;if(we.default.existsSync(s)){try{o=we.default.readFileSync(s,"utf8")}catch{o=(0,Wt.execFileSync)("sudo",["cat",s],{encoding:"utf8",timeout:1e4})}if(!Lg(o))throw new Error(`${s} exists and was not written by this command - refusing to overwrite a hand-written site. Delete it yourself if you want it replaced.`)}let l=Ku(o??"",t.slug,e).replace(/^\n+/,"");if(o!==null&&l===o){g.info(`nginx already routes ${t.hostname} - unchanged`);return}let c=i?we.default.existsSync(i):!1;Se(["mkdir","-p",At.default.dirname(s)]),Se(["tee",s],l),Se(["chmod","644",s]),i&&!c&&Se(["ln","-s",s,i]);try{(0,Wt.execFileSync)("sudo",["nginx","-t"],{encoding:"utf8",timeout:3e4})}catch(d){o!==null?(Se(["tee",s],o),Se(["chmod","644",s])):(i&&!c&&Se(["rm","-f",i]),Se(["rm","-f",s]));let p=d&&typeof d=="object"&&"stderr"in d&&typeof d.stderr=="string"?d.stderr.trim():String(d);throw new Error(`nginx -t rejected the new config - ${s} was ${o!==null?"restored":"removed"} and nginx was NOT reloaded. nginx said:
1042
+ ${p}`)}Se(["systemctl","reload","nginx"]),g.info(`\u2713 nginx: ${t.hostname} \u2192 127.0.0.1:${t.port} (${s}, validated, reloaded)`),g.info(n)}var Wt,we,Hu,Hi,At,Ki,Bg=te(()=>{"use strict";Wt=require("node:child_process"),we=E(require("node:fs"),1),Hu=E(require("node:net"),1),Hi=E(require("node:os"),1),At=E(require("node:path"),1);qt();na();Ki="# managed by allwright env prepare"});var Xg={};$t(Xg,{collectServerInventory:()=>hT,parseContainers:()=>Vg,parseListeningPorts:()=>Jg,parseProcesses:()=>Yg,parseServices:()=>Zg});async function Zs(t,e){try{let{stdout:n}=await sT(t,e,{timeout:iT,maxBuffer:4e6});return n}catch{return""}}function Zg(t){return t.split(`
1043
+ `).map(e=>e.trim()).filter(Boolean).map(e=>{let n=/^(\S+)\.service\s+\S+\s+(\S+)\s+running\s+(.*)$/.exec(e);return n?{name:n[1],description:n[3].slice(0,120),active:n[2]}:null}).filter(e=>e!==null).slice(0,150)}function Vg(t){return t.split(`
1044
+ `).filter(Boolean).map(e=>{let[n,r="",s="",i=""]=e.split(" ");return{name:n,image:r.slice(0,120),status:s.slice(0,80),ports:i.slice(0,200)}}).filter(e=>e.name).slice(0,60)}function Jg(t){let e=new Map;for(let n of t.split(`
1045
+ `)){if(!n.trim())continue;let s=n.trim().split(/\s+/)[3]??"",i=Number(s.slice(s.lastIndexOf(":")+1));if(!Number.isFinite(i)||i<=0)continue;let o=/users:\(\("([^"]+)",pid=(\d+)/.exec(n);e.has(i)||e.set(i,{port:i,process:o?.[1]??"",pid:o?Number(o[2]):0})}return[...e.values()].sort((n,r)=>n.port-r.port).slice(0,150)}function Yg(t){return t.split(`
1046
+ `).slice(1).map(e=>{let n=/^\s*(\d+)\s+(\S+)\s+([\d.]+)\s+([\d.]+)\s+(.*)$/.exec(e);return n?{pid:Number(n[1]),user:n[2].slice(0,30),cpuPct:Number(n[3]),memPct:Number(n[4]),command:n[5].slice(0,160)}:null}).filter(e=>e!==null).slice(0,40)}function uT(){let t=[],e=oT.map(r=>({dir:r,depth:0})),n=0;for(;e.length&&t.length<Wg&&n<lT;){let{dir:r,depth:s}=e.shift();n++;let i;try{i=Hg.default.readdirSync(r,{withFileTypes:!0})}catch{continue}if(i.some(o=>o.name===".git"&&o.isDirectory())){t.push(r);continue}if(!(s>=aT))for(let o of i)o.isDirectory()&&!o.isSymbolicLink()&&!cT.has(o.name)&&!o.name.startsWith(".")&&e.push({dir:Oa.default.join(r,o.name),depth:s+1})}return t}async function dT(t){let e=new Map;for(let[s,i]of Object.entries(t.repos))e.set(Oa.default.resolve(i.path),s);let n=[...new Set([...e.keys(),...uT().map(s=>Oa.default.resolve(s))])];return(await Promise.all(n.slice(0,Wg).map(async s=>({path:s,repoName:e.get(s)??"",remoteUrl:(await Zs("git",["-C",s,"config","--get","remote.origin.url"])).trim().replace(/\/\/[^@/]+@/,"//").slice(0,200),branch:(await Zs("git",["-C",s,"rev-parse","--abbrev-ref","HEAD"])).trim().slice(0,80)})))).sort((s,i)=>(s.repoName?0:1)-(i.repoName?0:1)||s.path.localeCompare(i.path))}async function hT(t){let[e,n,r,s,i]=await Promise.all([dT(t),Zs("systemctl",["list-units","--type=service","--state=running","--no-legend","--plain","--no-pager"]).then(Zg),Zs("docker",["ps","--format","{{.Names}} {{.Image}} {{.Status}} {{.Ports}}"]).then(Vg),Zs("ss",["-tlnpH"]).then(Jg),Zs("ps",["axo","pid,user,pcpu,pmem,args","--sort=-pmem"]).then(Yg)]);return{checkouts:e,services:n,containers:r,ports:s,processes:i}}var Hg,Oa,Kg,Gg,sT,iT,oT,aT,lT,Wg,cT,Qg=te(()=>{"use strict";Hg=E(require("node:fs"),1),Oa=E(require("node:path"),1),Kg=require("node:child_process"),Gg=require("node:util"),sT=(0,Gg.promisify)(Kg.execFile),iT=8e3,oT=["/opt","/var/www","/srv","/home","/root"],aT=3,lT=800,Wg=60,cT=new Set(["node_modules",".git","dist","build",".next","vendor",".cache","snap"])});function ey(t,...e){try{return JSON.parse(za.default.readFileSync(Da.default.join(t,...e),"utf8"))}catch{return null}}function Ma(t,...e){try{return za.default.readFileSync(Da.default.join(t,...e),"utf8")}catch{return""}}function gT(t){for(let e of["prisma/schema.prisma","schema.prisma","apps/api/prisma/schema.prisma"]){let n=/provider\s*=\s*"(postgresql|mysql|sqlite|mongodb|sqlserver|cockroachdb)"/.exec(Ma(t,e));if(n)return`${{postgresql:"PostgreSQL",mysql:"MySQL",sqlite:"SQLite",mongodb:"MongoDB",sqlserver:"SQL Server",cockroachdb:"CockroachDB"}[n[1]]} (Prisma)`}return""}function ty(t){let e={languages:[],frameworks:[],databases:[],docker:Te(t,"Dockerfile"),dockerCompose:Te(t,"docker-compose.yml")||Te(t,"docker-compose.yaml")||Te(t,"compose.yml")||Te(t,"compose.yaml"),packageManager:"",monorepo:""},n=(i,o)=>{o&&!i.includes(o)&&i.push(o)},r=ey(t,"package.json");if(r){n(e.languages,Te(t,"tsconfig.json")?"TypeScript":"JavaScript");let i={...r.dependencies,...r.devDependencies};for(let[o,l]of pT)i[o]&&n(e.frameworks,l);n(e.databases,i.prisma||i["@prisma/client"]?gT(t):"");for(let[o,l]of fT)i[o]&&n(e.databases,l);e.packageManager=Te(t,"pnpm-lock.yaml")?"pnpm":Te(t,"yarn.lock")?"yarn":Te(t,"package-lock.json")?"npm":"",e.monorepo=Te(t,"pnpm-workspace.yaml")?"pnpm workspaces":Te(t,"turbo.json")?"turborepo":r.workspaces?"npm/yarn workspaces":""}let s=(Ma(t,"requirements.txt")+Ma(t,"pyproject.toml")).toLowerCase();if(s||Te(t,"manage.py")){n(e.languages,"Python");for(let[i,o]of mT)(s.includes(i)||i==="django"&&Te(t,"manage.py"))&&n(e.frameworks,o);s.includes("psycopg")&&n(e.databases,"PostgreSQL"),s.includes("pymongo")&&n(e.databases,"MongoDB"),(s.includes("mysqlclient")||s.includes("pymysql"))&&n(e.databases,"MySQL"),e.packageManager||(e.packageManager=Te(t,"poetry.lock")?"poetry":Te(t,"requirements.txt")?"pip":"")}return Te(t,"go.mod")&&n(e.languages,"Go"),Te(t,"Cargo.toml")&&n(e.languages,"Rust"),Te(t,"composer.json")&&(n(e.languages,"PHP"),(ey(t,"composer.json")?.require??{})["laravel/framework"]&&n(e.frameworks,"Laravel")),Te(t,"Gemfile")&&(n(e.languages,"Ruby"),Ma(t,"Gemfile").includes("rails")&&n(e.frameworks,"Rails")),(Te(t,"pom.xml")||Te(t,"build.gradle")||Te(t,"build.gradle.kts"))&&n(e.languages,"Java/Kotlin"),e.languages=e.languages.slice(0,4),e.frameworks=e.frameworks.slice(0,6),e.databases=e.databases.slice(0,4),e}var za,Da,Te,pT,fT,mT,ny=te(()=>{"use strict";za=E(require("node:fs"),1),Da=E(require("node:path"),1),Te=(t,...e)=>za.default.existsSync(Da.default.join(t,...e));pT=[["next","Next.js"],["@nestjs/core","NestJS"],["nuxt","Nuxt"],["@angular/core","Angular"],["vue","Vue"],["svelte","Svelte"],["react","React"],["express","Express"],["fastify","Fastify"],["@remix-run/react","Remix"],["astro","Astro"],["electron","Electron"],["react-native","React Native"],["tailwindcss","Tailwind"]],fT=[["mongoose","MongoDB"],["mongodb","MongoDB"],["pg","PostgreSQL"],["postgres","PostgreSQL"],["mysql2","MySQL"],["mysql","MySQL"],["better-sqlite3","SQLite"],["sqlite3","SQLite"],["redis","Redis"],["ioredis","Redis"]],mT=[["django","Django"],["flask","Flask"],["fastapi","FastAPI"]]});var hy={};$t(hy,{buildAgentReport:()=>dy,buildSetupReport:()=>vT,claudeLoggedIn:()=>ly,codexLoggedIn:()=>cy,kimiLoggedIn:()=>uy,repoCurrentBranch:()=>oy,repoDefaultBranch:()=>ay});function oy(t){try{let e=(0,Gi.execFileSync)("git",["-C",t,"rev-parse","--abbrev-ref","HEAD"],{encoding:"utf8",timeout:1e4}).trim();return e==="HEAD"?"":e}catch{return""}}function ay(t){let e=(...s)=>{try{return(0,Gi.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 ly(t=Wi.default.homedir()){if(Ct.default.existsSync(Zt.default.join(t,".claude",".credentials.json")))return!0;try{return!!JSON.parse(Ct.default.readFileSync(Zt.default.join(t,".claude.json"),"utf8")).oauthAccount}catch{return!1}}function bT(t){try{return Ct.default.readdirSync(t).length>0}catch{return!1}}function cy(t=Wi.default.homedir()){return Ct.default.existsSync(Zt.default.join(t,".codex","auth.json"))}function uy(t=Wi.default.homedir()){return bT(Zt.default.join(t,".kimi","credentials"))||Ct.default.existsSync(Zt.default.join(t,".kimi","credentials.json"))}async function wT(t){let e=sy.get(t);if(e&&Date.now()-e.at<6e4)return{installed:e.installed,version:e.version};let n=!1,r="";try{let{stdout:s}=await yT(t,["--version"],{timeout:1e4});n=!0,r=s.trim().slice(0,60)}catch{n=!1}return sy.set(t,{at:Date.now(),installed:n,version:r}),{installed:n,version:r}}async function dy(t){let e=La.REGISTERED_AGENTS.filter(r=>ry[r.id]),n=await Promise.all(e.map(async r=>{let{installed:s,version:i}=await wT(Be(t,r.id)),o=ry[r.id](Wi.default.homedir());return[r.id,{installed:s,version:i,loggedIn:o}]}));return Object.fromEntries(n)}async function vT(t,e,n){let r=await dy(t),s=e.map(o=>{let l=t.repos[o];if(!l)return{repoName:o,path:"",mapped:!1,liveMapped:!!n?.repos?.[o],pathExists:!1,isGit:!1,currentBranch:"",claudeMd:!1,deployMd:!1,testMd:!1,githubToken:!1,githubTokenOwn:!1,defaultBranch:""};let c=Ct.default.existsSync(l.path);return{repoName:o,path:l.path,mapped:!0,liveMapped:n?!!n.repos?.[o]:!0,pathExists:c,isGit:c&&Ct.default.existsSync(Zt.default.join(l.path,".git")),currentBranch:c?oy(l.path):"",claudeMd:c&&Ct.default.existsSync(Zt.default.join(l.path,"CLAUDE.md")),deployMd:c&&Ct.default.existsSync(Zt.default.join(l.path,"DEPLOY.md")),testMd:c&&Ct.default.existsSync(Zt.default.join(l.path,"TEST.md")),githubToken:!!qe(t,o),githubTokenOwn:!!l.github?.token,defaultBranch:c?ay(l.path):"",architecture:c?ty(l.path):void 0}}),i=Object.values(t.repos).find(o=>o.github?.token);return{jiraConfigured:!!t.jira,jiraEmail:t.jira?.email??"",agents:r,claude:r[La.DEFAULT_AGENT_ID]??{installed:!1,version:"",loggedIn:!1},githubTokenSet:!!(t.github?.token||i),githubLogin:t.github?.login??i?.github?.login??"",deploysEnabled:t.deploy.enabled,jiraUserCount:Object.keys(t.jiraUsers).length,repos:s}}var Gi,Ct,Wi,Zt,iy,La,yT,ry,sy,py=te(()=>{"use strict";Gi=require("node:child_process"),Ct=E(require("node:fs"),1),Wi=E(require("node:os"),1),Zt=E(require("node:path"),1),iy=require("node:util"),La=E(Re(),1);xt();$r();ny();yT=(0,iy.promisify)(Gi.execFile);ry={"claude-code":ly,codex:cy,kimi:uy},sy=new Map});var it=E(require("node:fs"),1),Zi=E(require("node:os"),1),yn=E(require("node:path"),1),bn=require("node:child_process"),Hn=require("node:crypto"),Kn=E(require("node:readline/promises"),1);var cd=E(ld(),1),{program:DT,createCommand:LT,createArgument:UT,createOption:qT,CommanderError:FT,InvalidArgumentError:BT,InvalidOptionArgumentError:HT,Command:ud,Argument:KT,Option:GT,Help:WT}=cd.default;Ae();var co=require("node:child_process"),tt=E(require("node:fs"),1),uo=E(require("node:path"),1);Ae();var Yb=new Set(["runner.log","runner.pid"]);function Xb(t){return tt.default.readdirSync(t).filter(e=>!Yb.has(e)&&!/\.bak-\d+$/.test(e)).sort()}function Id(t){let e=ie();if(!tt.default.existsSync(e))throw new Error(`nothing to export - ${e} does not exist`);let n=Xb(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=uo.default.resolve(t||`ticketpilot-backup-${r}.tgz`);return tt.default.writeFileSync(s,"",{mode:384}),(0,co.execFileSync)("tar",["-czf",s,"-C",e,...n]),tt.default.chmodSync(s,384),{file:s,entries:n}}function Rd(t){let e=uo.default.resolve(t);if(!tt.default.existsSync(e))throw new Error(`backup file not found: ${e}`);let n=(0,co.execFileSync)("tar",["-tzf",e],{encoding:"utf8"}).split(`
1047
+ `).filter(Boolean);for(let i of n)if(i.startsWith("/")||i.split("/").includes(".."))throw new Error(`refusing to import - unsafe path in archive: ${i}`);let r=ie(),s;tt.default.existsSync(r)&&tt.default.readdirSync(r).length&&(s=`${r}.bak-${Date.now()}`,tt.default.renameSync(r,s)),tt.default.mkdirSync(r,{recursive:!0,mode:448}),(0,co.execFileSync)("tar",["-xzf",e,"-C",r]);for(let i of tt.default.readdirSync(r)){let o=uo.default.join(r,i);tt.default.statSync(o).isFile()&&tt.default.chmodSync(o,384)}return{restored:n.map(i=>i.replace(/\/$/,"")).sort(),previousDir:s}}pl();var De=E(require("node:fs"),1),fo=E(require("node:path"),1);Ae();function hs(){return fo.default.join(ie(),"runner.pid")}function po(){return fo.default.join(ie(),"runner.log")}function $d(){De.default.mkdirSync(ie(),{recursive:!0,mode:448});let t=De.default.openSync(po(),"a",384);try{De.default.chmodSync(po(),384)}catch{}return t}function cr(){let t=hs();if(!De.default.existsSync(t))return null;let e=Number(De.default.readFileSync(t,"utf8").trim());return Number.isFinite(e)&&e>0?e:null}function sw(t){try{return process.kill(t,0),!0}catch{return!1}}function Pd(){try{return De.default.readFileSync("/proc/sys/kernel/random/boot_id","utf8").trim()||null}catch{return null}}function iw(t){let e;try{e=De.default.readFileSync(`/proc/${t}/cmdline`,"utf8")}catch{return null}return e?/allwright|ticketpilot|cli\.(js|ts|cjs|mjs)/i.test(e):null}function ur(t){return sw(t)?iw(t)!==!1:!1}function Nd(t){De.default.mkdirSync(ie(),{recursive:!0,mode:448}),De.default.writeFileSync(hs(),String(t),{mode:384})}function jd(t){cr()===t&&De.default.rmSync(hs(),{force:!0})}function fl(){return fo.default.join(ie(),"runner.lock")}function Od(){let t;try{t=De.default.readFileSync(fl(),"utf8").trim()}catch{return null}let e,n=null;if(t.startsWith("{"))try{let r=JSON.parse(t);e=Number(r.pid),n=typeof r.boot=="string"?r.boot:null}catch{return null}else e=Number(t);return Number.isFinite(e)&&e>0?{pid:e,boot:n}:null}function ps(){let t=Od();if(!t||t.pid===process.pid)return null;let e=Pd();return t.boot&&e&&t.boot!==e?null:ur(t.pid)?t.pid:null}function Md(){let t=ps();return t?{ok:!1,pid:t}:(De.default.mkdirSync(ie(),{recursive:!0,mode:448}),De.default.writeFileSync(fl(),JSON.stringify({pid:process.pid,boot:Pd()}),{mode:384}),{ok:!0})}function ml(){try{Od()?.pid===process.pid&&De.default.rmSync(fl(),{force:!0})}catch{}}function zd(t){try{let e=De.default.readFileSync(`/proc/${t}/cgroup`,"utf8"),n=/\/([A-Za-z0-9._@-]+)\.service/.exec(e);return n?n[1]:null}catch{return null}}var _o=E(require("node:fs"),1),ai=E(require("node:path"),1),ch=E(Re(),1);Ae();async function uh(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:So})});if(!n.ok){let i=await n.text().catch(()=>"");throw new Error(`enrollment failed (${n.status}): ${i.slice(0,300)}`)}let r=ch.EnrollResponse.parse(await n.json()),s={...t,runnerId:r.runnerId,runnerToken:r.runnerToken};return ye(s),s}function qv(){try{let t=process.argv[1]?_o.default.realpathSync(process.argv[1]):"";for(let e of[ai.default.dirname(t),ai.default.dirname(ai.default.dirname(t))]){let n=ai.default.join(e,"package.json");if(!_o.default.existsSync(n))continue;let r=JSON.parse(_o.default.readFileSync(n,"utf8")).version;if(typeof r=="string"&&r)return r}}catch{}return"0.0.0"}var So=qv();Lt();ci();function kh(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:
1043
1048
 
1044
1049
  allwright jira user-add ${s}
1045
1050
 
1046
- 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 ph(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 fh(t){return["s","skip","n","no","later"].includes(t.trim().toLowerCase())}Ar();var gv=/\btickets?[ \t-]?#?(\d{1,2})\b/gi;function gh(t,e){let n=!1;return{text:t.replace(gv,(s,i)=>{let o=Number(i);return o<1||o>e.length?s:(n=!0,e[o-1])}),changed:n}}var Nn=require("node:child_process"),On=R(require("node:fs"),1),Ao=R(require("node:os"),1),_s=R(require("node:path"),1),bh=R(Re(),1);var ks="allwright",yh=`/etc/systemd/system/${ks}.service`,Co="ticketpilot-runner";function jl(){let t=process.env.SUDO_USER&&process.env.SUDO_USER!=="root"?process.env.SUDO_USER:"",e=t||Ao.default.userInfo().username,n=t?_s.default.join("/home",t):Ao.default.homedir();return{nodePath:process.execPath,scriptPath:On.default.realpathSync(process.argv[1]),user:e,home:n}}function Ml(t){let e=_s.default.dirname(t.nodePath);return`[Unit]
1051
+ 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 _h(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 Sh(t){return["s","skip","n","no","later"].includes(t.trim().toLowerCase())}$r();var Kv=/\btickets?[ \t-]?#?(\d{1,2})\b/gi;function xh(t,e){let n=!1;return{text:t.replace(Kv,(s,i)=>{let o=Number(i);return o<1||o>e.length?s:(n=!0,e[o-1])}),changed:n}}var zn=require("node:child_process"),Dn=E(require("node:fs"),1),Po=E(require("node:os"),1),Ts=E(require("node:path"),1),Rh=E(Re(),1);var Ss="allwright",Ih=`/etc/systemd/system/${Ss}.service`,No="ticketpilot-runner";function Kl(){let t=process.env.SUDO_USER&&process.env.SUDO_USER!=="root"?process.env.SUDO_USER:"",e=t||Po.default.userInfo().username,n=t?Ts.default.join("/home",t):Po.default.homedir();return{nodePath:process.execPath,scriptPath:Dn.default.realpathSync(process.argv[1]),user:e,home:n}}function Gl(t){let e=Ts.default.dirname(t.nodePath);return`[Unit]
1047
1052
  Description=Allwright runner
1048
1053
  After=network-online.target
1049
1054
 
@@ -1061,8 +1066,8 @@ TimeoutStopSec=2h
1061
1066
 
1062
1067
  [Install]
1063
1068
  WantedBy=multi-user.target
1064
- `}function zl(){return process.platform==="linux"&&On.default.existsSync("/run/systemd/system")}function wh(t){if(!zl())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=jl(),n=Ml(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 ${yh}:`),t.info(`
1065
- `+n);return}try{(0,Nn.execFileSync)("systemctl",["disable","--now",Co]),t.info(`stopped the old ${Co} service - this one replaces it`)}catch{}let r=ds();if(r)try{process.kill(r,"SIGTERM"),t.info(`stopped the running runner (pid ${r}) - the service takes over`)}catch{}On.default.writeFileSync(yh,n),(0,Nn.execFileSync)("systemctl",["daemon-reload"]),(0,Nn.execFileSync)("systemctl",["enable","--now",ks]),(0,Nn.execFileSync)("systemctl",["restart",ks]),t.info(`Installed and started (runs as ${e.user}, survives reboots).`),t.info(`Watch it: journalctl -u ${ks} -f`),t.info("Status: allwright service status")}function yv(t){if(t.override)return[_s.default.join(t.override,"runner.json")];let e=[];for(let n of t.homes)for(let r of["allwright","ticketpilot"]){let s=_s.default.join(n,".config",r,"runner.json");e.includes(s)||e.push(s)}return e}function bv(){let t=process.env.SUDO_USER&&process.env.SUDO_USER!=="root"?process.env.SUDO_USER:"",e=[Ao.default.homedir()];return t&&e.push(_s.default.join("/home",t)),yv({override:process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR,homes:e})}function wv(){let t={removed:!1,paths:[],problems:[]};for(let e of bv())if(On.default.existsSync(e))try{On.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 Dl(){return typeof process.getuid!="function"||process.getuid()===0}function Ol(t){if(Dl()){(0,Nn.execFileSync)("systemctl",t,{stdio:"ignore"});return}(0,Nn.execFileSync)("sudo",["-n","systemctl",...t],{stdio:"ignore"})}function vv(t){if(Dl()){On.default.rmSync(t);return}(0,Nn.execFileSync)("sudo",["-n","rm","-f",t],{stdio:"ignore"})}function kv(){if(!zl())return{removed:!1,absent:!0,error:""};let t=[ks,Co].map(e=>({name:e,file:`/etc/systemd/system/${e}.service`})).filter(e=>On.default.existsSync(e.file));if(t.length===0)return{removed:!1,absent:!0,error:""};try{for(let e of t){try{Ol(["disable",e.name])}catch{}vv(e.file)}return Ol(["daemon-reload"]),{removed:!0,absent:!1,error:""}}catch(e){let n=e instanceof Error?e.message:String(e);return{removed:!1,absent:!1,error:Dl()?`could not remove the systemd unit: ${n}`:"removing the systemd unit needs root, and this runner does not have passwordless sudo"}}}function Ll(){if(zl())for(let t of[ks,Co])try{Ol(["stop",t])}catch{}}function Ul(){let t=kv(),e={serviceRemoved:t.removed,serviceAbsent:t.absent,configRemoved:!1,removedPaths:[],problems:[]};if(t.error)return e.problems.push(`${t.error} - finish with: ${bh.RUNNER_UNINSTALL_COMMAND}`),e;let n=wv();return e.configRemoved=n.removed,e.removedPaths=n.paths,e.problems=n.problems,e}function vh(t){let e=Ul();e.serviceRemoved?(Ll(),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 kh=R(Re(),1);function _h(t){return t.filter(e=>e.statusCategory!=="done"&&!e.labels.includes("agent-implemented")&&!e.labels.includes(kh.NEEDS_INPUT_LABEL))}function Sh(t,e,n){let r=n.map(s=>{let i=(s.description??"").trim().slice(0,600);return`- ${s.key} [${s.status}] ${s.summary}${i?`
1069
+ `}function Wl(){return process.platform==="linux"&&Dn.default.existsSync("/run/systemd/system")}function Eh(t){if(!Wl())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=Kl(),n=Gl(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 ${Ih}:`),t.info(`
1070
+ `+n);return}try{(0,zn.execFileSync)("systemctl",["disable","--now",No]),t.info(`stopped the old ${No} service - this one replaces it`)}catch{}let r=ps();if(r)try{process.kill(r,"SIGTERM"),t.info(`stopped the running runner (pid ${r}) - the service takes over`)}catch{}Dn.default.writeFileSync(Ih,n),(0,zn.execFileSync)("systemctl",["daemon-reload"]),(0,zn.execFileSync)("systemctl",["enable","--now",Ss]),(0,zn.execFileSync)("systemctl",["restart",Ss]),t.info(`Installed and started (runs as ${e.user}, survives reboots).`),t.info(`Watch it: journalctl -u ${Ss} -f`),t.info("Status: allwright service status")}function Gv(t){if(t.override)return[Ts.default.join(t.override,"runner.json")];let e=[];for(let n of t.homes)for(let r of["allwright","ticketpilot"]){let s=Ts.default.join(n,".config",r,"runner.json");e.includes(s)||e.push(s)}return e}function Wv(){let t=process.env.SUDO_USER&&process.env.SUDO_USER!=="root"?process.env.SUDO_USER:"",e=[Po.default.homedir()];return t&&e.push(Ts.default.join("/home",t)),Gv({override:process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR,homes:e})}function Zv(){let t={removed:!1,paths:[],problems:[]};for(let e of Wv())if(Dn.default.existsSync(e))try{Dn.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 Zl(){return typeof process.getuid!="function"||process.getuid()===0}function Hl(t){if(Zl()){(0,zn.execFileSync)("systemctl",t,{stdio:"ignore"});return}(0,zn.execFileSync)("sudo",["-n","systemctl",...t],{stdio:"ignore"})}function Vv(t){if(Zl()){Dn.default.rmSync(t);return}(0,zn.execFileSync)("sudo",["-n","rm","-f",t],{stdio:"ignore"})}function Jv(){if(!Wl())return{removed:!1,absent:!0,error:""};let t=[Ss,No].map(e=>({name:e,file:`/etc/systemd/system/${e}.service`})).filter(e=>Dn.default.existsSync(e.file));if(t.length===0)return{removed:!1,absent:!0,error:""};try{for(let e of t){try{Hl(["disable",e.name])}catch{}Vv(e.file)}return Hl(["daemon-reload"]),{removed:!0,absent:!1,error:""}}catch(e){let n=e instanceof Error?e.message:String(e);return{removed:!1,absent:!1,error:Zl()?`could not remove the systemd unit: ${n}`:"removing the systemd unit needs root, and this runner does not have passwordless sudo"}}}function Vl(){if(Wl())for(let t of[Ss,No])try{Hl(["stop",t])}catch{}}function Jl(){let t=Jv(),e={serviceRemoved:t.removed,serviceAbsent:t.absent,configRemoved:!1,removedPaths:[],problems:[]};if(t.error)return e.problems.push(`${t.error} - finish with: ${Rh.RUNNER_UNINSTALL_COMMAND}`),e;let n=Zv();return e.configRemoved=n.removed,e.removedPaths=n.paths,e.problems=n.problems,e}function Ah(t){let e=Jl();e.serviceRemoved?(Vl(),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 Ch=E(Re(),1);function $h(t){return t.filter(e=>e.statusCategory!=="done"&&!e.labels.includes("agent-implemented")&&!e.labels.includes(Ch.NEEDS_INPUT_LABEL))}function Ph(t,e,n){let r=n.map(s=>{let i=(s.description??"").trim().slice(0,600);return`- ${s.key} [${s.status}] ${s.summary}${i?`
1066
1071
  ${i.replace(/\n+/g," ")}`:""}`}).join(`
1067
1072
  `);return`You are looking at this repository to help sequence work on the Jira epic ${t} ("${e}"). These child tickets are still pending:
1068
1073
 
@@ -1073,19 +1078,19 @@ Pick the ONE ticket that should be implemented FIRST. Weigh, in this order: (1)
1073
1078
  Answer with ONLY a fenced json block, nothing after it:
1074
1079
  \`\`\`json
1075
1080
  {"issueKey": "<one of the keys above>", "reason": "<2-3 sentences: why this one first, and what it unblocks>"}
1076
- \`\`\``}function Th(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"}}}Mo();Oo();No();var zn=R(Re(),1);Ee();oi();Dr();Os();jt();mi();Dr();Tt();Ar();Mo();Dt();function na(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}}}No();zt();oa();var Rf=24*3600*1e3,aa=14,c_=aa*24*3600*1e3,u_=new Set(["to","on","this","the","a","an","env","environment","please","now","it"]),la=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;externalBusy=()=>0;setExternalBusy(e){this.externalBusy=e}get busyCount(){return Math.max(this.inFlight.size,this.activeWork)+this.externalBusy()}activeWork=0;get idle(){return!this.ticking&&this.inFlight.size===0&&this.activeWork===0&&this.externalBusy()===0}repoQueues=new Map;envQueues=new Map;timer=null;ticking=!1;paused=!1;jiraOf(e){return this.jiraFor(e.repoName)}hasJira(e){return!!so(this.cfg,e)}get jiraless(){return io(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=Mh(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=Ce(this.cfg,n,"assist");if("error"in s){y.warn(`Scheduled audit skipped: ${s.error}`);continue}let i=await Es({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 b=Date.parse(e.pausedUntil);Number.isFinite(b)&&(this.autopilotPausedUntil=b);return}let n=e.item;if(!n)return;let r=this.rules.find(b=>b.id===n.ruleId&&b.enabled),s=this.projects.find(b=>b.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=na(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 d=this.jiraOf(o),p="";try{p=(await d.getIssue(n.issueKey))?.summary??""}catch(b){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:`could not read ${n.issueKey} from Jira: ${b instanceof Error?b.message:String(b)}`});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 v=this.resolveClaudeProfile(f.runId,f.claudeProfile),_=!!(n.batchId&&n.branchOverride),I=n.batchId?Uc(n.batchId):null,E=!n.continueBranch&&!_?qc(I,n.issueKey):null,C=E?ia(n.batchId,E,n.issueKey):null,Y=_&&n.continueBranch?Hc(n.batchId):null,X=C??Y,$=Zc(E,n.issueKey)||_&&n.remainingInBatch>0;this.enqueueForRepo(l.path,async()=>{try{await wi({runId:f.runId,rule:c,project:o,issueKey:n.issueKey,repoPath:l.path,cfg:this.cfg,jira:d,transport:this.transport,claudeConfigDir:v,actorEmail:f.actorEmail,continueBranch:n.continueBranch,...X?{chain:{sessionId:X.sessionId,worktreePath:X.worktreePath}}:{},keepWorktree:$,onChainSession:E?b=>Fc(n.batchId,E,n.issueKey,b):_&&$?b=>Kc(n.batchId,n.issueKey,b,!!Y):void 0}),E&&!ia(n.batchId,E,E[E.indexOf(n.issueKey)+1]??"")&&E.indexOf(n.issueKey)<E.length-1&&Bc(n.batchId,E),_&&!Gc(n.batchId,n.issueKey)&&Wc(n.batchId)}finally{this.inFlight.delete(w)}})}async sweepGitHubApprovals(){let e=Object.values(fi());if(!e.length)return;let n=ke()??this.cfg,r=new Map,s=i=>{let o=Ue(n,i);if(!o)return null;let l=r.get(o);return l||r.set(o,l=new Fe(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,d;try{[c,d]=await Promise.all([o.getReviews(i.owner,i.repo,i.prNumber),o.getPullRequest(i.owner,i.repo,i.prNumber)])}catch(v){y.warn(`review check failed for ${i.owner}/${i.repo}#${i.prNumber}: ${v instanceof Error?v.message:v}`);continue}if(!d)continue;let p={cfg:this.cfg,jiraFor:this.jiraFor,transport:this.transport};if(d.merged){y.info(`PR #${i.prNumber} for ${i.issueKey} was merged on GitHub - completing the run`),this.inFlight.add(l);try{await vi(p,i.runId,d.headSha)}finally{this.inFlight.delete(l)}continue}if(d.state==="closed"){y.info(`PR #${i.prNumber} for ${i.issueKey} was closed unmerged on GitHub - failing the run`);let v=this.jiraFor(i.repoName),_=`PR #${i.prNumber} was closed on GitHub without merging`;await v.addComment(i.issueKey,`**Allwright: the pull request for this ticket was closed on GitHub without merging.**
1081
+ \`\`\``}function Nh(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"}}}Lo();zo();Mo();var qn=E(Re(),1);Ae();ci();Ur();Ms();Lt();bi();Ur();It();$r();Lo();xt();function oa(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}}}Mo();qt();ua();var zf=24*3600*1e3,da=14,D_=da*24*3600*1e3,L_=new Set(["to","on","this","the","a","an","env","environment","please","now","it"]),ha=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;externalBusy=()=>0;setExternalBusy(e){this.externalBusy=e}get busyCount(){return Math.max(this.inFlight.size,this.activeWork)+this.externalBusy()}activeWork=0;get idle(){return!this.ticking&&this.inFlight.size===0&&this.activeWork===0&&this.externalBusy()===0}repoQueues=new Map;envQueues=new Map;timer=null;ticking=!1;paused=!1;jiraOf(e){return this.jiraFor(e.repoName)}hasJira(e){return!!ao(this.cfg,e)}get jiraless(){return lo(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=Kh(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=Ce(this.cfg,n,"assist");if("error"in s){g.warn(`Scheduled audit skipped: ${s.error}`);continue}let i=await As({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 b=Date.parse(e.pausedUntil);Number.isFinite(b)&&(this.autopilotPausedUntil=b);return}let n=e.item;if(!n)return;let r=this.rules.find(b=>b.id===n.ruleId&&b.enabled),s=this.projects.find(b=>b.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=oa(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 d=this.jiraOf(o),p="";try{p=(await d.getIssue(n.issueKey))?.summary??""}catch(b){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:`could not read ${n.issueKey} from Jira: ${b instanceof Error?b.message:String(b)}`});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 v=this.resolveClaudeProfile(f.runId,f.claudeProfile),_=!!(n.batchId&&n.branchOverride),I=n.batchId?Vc(n.batchId):null,R=!n.continueBranch&&!_?Jc(I,n.issueKey):null,C=R?ca(n.batchId,R,n.issueKey):null,V=_&&n.continueBranch?Qc(n.batchId):null,J=C??V,$=ru(R,n.issueKey)||_&&n.remainingInBatch>0;this.enqueueForRepo(l.path,async()=>{try{await _i({runId:f.runId,rule:c,project:o,issueKey:n.issueKey,repoPath:l.path,cfg:this.cfg,jira:d,transport:this.transport,claudeConfigDir:v,actorEmail:f.actorEmail,continueBranch:n.continueBranch,...J?{chain:{sessionId:J.sessionId,worktreePath:J.worktreePath}}:{},keepWorktree:$,onChainSession:R?b=>Yc(n.batchId,R,n.issueKey,b):_&&$?b=>eu(n.batchId,n.issueKey,b,!!V):void 0}),R&&!ca(n.batchId,R,R[R.indexOf(n.issueKey)+1]??"")&&R.indexOf(n.issueKey)<R.length-1&&Xc(n.batchId,R),_&&!tu(n.batchId,n.issueKey)&&nu(n.batchId)}finally{this.inFlight.delete(w)}})}async sweepGitHubApprovals(){let e=Object.values(yi());if(!e.length)return;let n=ve()??this.cfg,r=new Map,s=i=>{let o=qe(n,i);if(!o)return null;let l=r.get(o);return l||r.set(o,l=new He(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,d;try{[c,d]=await Promise.all([o.getReviews(i.owner,i.repo,i.prNumber),o.getPullRequest(i.owner,i.repo,i.prNumber)])}catch(v){g.warn(`review check failed for ${i.owner}/${i.repo}#${i.prNumber}: ${v instanceof Error?v.message:v}`);continue}if(!d)continue;let p={cfg:this.cfg,jiraFor:this.jiraFor,transport:this.transport};if(d.merged){g.info(`PR #${i.prNumber} for ${i.issueKey} was merged on GitHub - completing the run`),this.inFlight.add(l);try{await Si(p,i.runId,d.headSha)}finally{this.inFlight.delete(l)}continue}if(d.state==="closed"){g.info(`PR #${i.prNumber} for ${i.issueKey} was closed unmerged on GitHub - failing the run`);let v=this.jiraFor(i.repoName),_=`PR #${i.prNumber} was closed on GitHub without merging`;await v.addComment(i.issueKey,`**Allwright: the pull request for this ticket was closed on GitHub without merging.**
1077
1082
 
1078
1083
  PR: ${i.prUrl}
1079
1084
 
1080
- The run is marked failed. Remove the \`${i.failedLabel}\` label (or hit Retry on the Allwright board) to implement again. (run \`${i.runId}\`)`).catch(()=>{}),await v.editLabels(i.issueKey,{add:[i.failedLabel]}).catch(()=>{}),this.transport.send({type:"run.status",runId:i.runId,status:"failed",error:_}),Nr(i.runId);continue}d.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.
1085
+ The run is marked failed. Remove the \`${i.failedLabel}\` label (or hit Retry on the Allwright board) to implement again. (run \`${i.runId}\`)`).catch(()=>{}),await v.editLabels(i.issueKey,{add:[i.failedLabel]}).catch(()=>{}),this.transport.send({type:"run.status",runId:i.runId,status:"failed",error:_}),Or(i.runId);continue}d.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.
1081
1086
 
1082
1087
  PR: ${i.prUrl}
1083
1088
 
1084
- 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,xt(i),y.info(`merge conflicts on PR #${i.prNumber} for ${i.issueKey} - ticket notified`))):d.mergeableState!==null&&d.mergeableState!=="unknown"&&(this.transport.send({type:"run.pr.conflict",runId:i.runId,conflicted:!1}),i.conflictNotified&&(i.conflictNotified=!1,xt(i)));let f=c.filter(v=>v.state==="APPROVED"||v.state==="CHANGES_REQUESTED").sort((v,_)=>v.submittedAt.localeCompare(_.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}).
1089
+ To fix: Reject this run on the Allwright dashboard (that closes the conflicted PR), then post the implement trigger comment again - a fresh run rebuilds the change on the current base. Or resolve the conflicts manually on branch \`${i.branch}\`; approval works normally once the PR is conflict-free. (run \`${i.runId}\`)`).catch(()=>{}),i.conflictNotified=!0,Rt(i),g.info(`merge conflicts on PR #${i.prNumber} for ${i.issueKey} - ticket notified`))):d.mergeableState!==null&&d.mergeableState!=="unknown"&&(this.transport.send({type:"run.pr.conflict",runId:i.runId,conflicted:!1}),i.conflictNotified&&(i.conflictNotified=!1,Rt(i)));let f=c.filter(v=>v.state==="APPROVED"||v.state==="CHANGES_REQUESTED").sort((v,_)=>v.submittedAt.localeCompare(_.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}).
1085
1090
 
1086
1091
  PR: ${i.prUrl}
1087
1092
 
1088
- Reply to the review on GitHub, or reject the run on the Allwright dashboard and re-trigger with new instructions. (run \`${i.runId}\`)`).catch(()=>{}),xt({...i,changesRequestedNotified:!0}),y.info(`changes requested on PR #${i.prNumber} for ${i.issueKey} - ticket notified`));continue}if(w.commitId===d.headSha){y.info(`PR #${i.prNumber} for ${i.issueKey} approved on GitHub by ${w.user} - completing the run`),this.inFlight.add(l);try{await vi(p,i.runId,w.commitId)}catch(v){y.warn(`github-approval completion failed for ${i.runId}: ${v instanceof Error?v.message:v}`)}finally{this.inFlight.delete(l)}}}}}async sweepMergedPRs(){let e=Object.values(Ko());if(!e.length)return;let n=ke()??this.cfg,r=new Map,s=l=>{let c=Ue(n,l);if(!c)return null;let d=r.get(c);return d||r.set(c,d=new Fe(c)),d},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`),pi(l.runId);continue}let d;try{d=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(!d){pi(l.runId);continue}if(d.state==="open")continue;if(!d.merged){pi(l.runId);continue}let p=this.jiraFor(l.repoName),f="";if(l.jiraTransitionOnMerge)try{f=await p.transitionByName(l.issueKey,l.jiraTransitionOnMerge)?`
1093
+ Reply to the review on GitHub, or reject the run on the Allwright dashboard and re-trigger with new instructions. (run \`${i.runId}\`)`).catch(()=>{}),Rt({...i,changesRequestedNotified:!0}),g.info(`changes requested on PR #${i.prNumber} for ${i.issueKey} - ticket notified`));continue}if(w.commitId===d.headSha){g.info(`PR #${i.prNumber} for ${i.issueKey} approved on GitHub by ${w.user} - completing the run`),this.inFlight.add(l);try{await Si(p,i.runId,w.commitId)}catch(v){g.warn(`github-approval completion failed for ${i.runId}: ${v instanceof Error?v.message:v}`)}finally{this.inFlight.delete(l)}}}}}async sweepMergedPRs(){let e=Object.values(Zo());if(!e.length)return;let n=ve()??this.cfg,r=new Map,s=l=>{let c=qe(n,l);if(!c)return null;let d=r.get(c);return d||r.set(c,d=new He(c)),d},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`),gi(l.runId);continue}let d;try{d=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(!d){gi(l.runId);continue}if(d.state==="open")continue;if(!d.merged){gi(l.runId);continue}let p=this.jiraFor(l.repoName),f="";if(l.jiraTransitionOnMerge)try{f=await p.transitionByName(l.issueKey,l.jiraTransitionOnMerge)?`
1089
1094
 
1090
1095
  Ticket moved to **${l.jiraTransitionOnMerge}**.`:`
1091
1096
 
@@ -1095,19 +1100,19 @@ Note: the "${l.jiraTransitionOnMerge}" transition failed: ${w instanceof Error?w
1095
1100
 
1096
1101
  PR: ${l.prUrl} (merged at \`${d.headSha.slice(0,10)}\`)${f}
1097
1102
 
1098
- (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`),pi(l.runId)}}async sweepNeedsInput(e){let n;try{n=await this.jiraOf(e).search(`project = "${e.jiraProjectKey}" AND labels = "${zn.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=Or();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:[zn.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()>c_){this.inFlight.add(c),this.abandonStaleInput(l,e).finally(()=>this.inFlight.delete(c));continue}try{o=o??await this.jiraOf(e).getIssue(s.key)}catch(_){y.warn(`needs-input check failed for ${s.key}: ${_ instanceof Error?_.message:_}`);continue}let d=new Date(l.questionsPostedAt).getTime(),p=o.comments.filter(_=>!pt(_.body)&&new Date(_.created).getTime()>d);if(!p.length)continue;let f=Mr(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:[zn.NEEDS_INPUT_LABEL]}).catch(_=>{y.warn(`could not remove needs-input label on ${s.key}: ${_}`)});let v={jiraFor:this.jiraFor,transport:this.transport,cfg:this.cfg,findRule:_=>this.findRuleForResume(_)};l.kind==="implement"?this.enqueueForRepo(l.baseRepoPath??l.repoPath,async()=>{try{await bc(l,f,w,v)}finally{this.inFlight.delete(c)}}):this.enqueueForRepo(l.repoPath,async()=>{try{await yc(l,f,w,v)}finally{this.inFlight.delete(c)}})}}}findRuleForResume(e){let n=this.rules.find(i=>i.id===e),r=n&&this.projects.find(i=>i.id===n.projectId),s=r&&this.cfg.repos[r.repoName]?.path;return n&&r&&s?{rule:n,project:r,repoPath:s}:null}async answerPendingInput(e,n,r){let s=Ap(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}`:""}.**
1103
+ (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`),gi(l.runId)}}async sweepNeedsInput(e){let n;try{n=await this.jiraOf(e).search(`project = "${e.jiraProjectKey}" AND labels = "${qn.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=Mr();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:[qn.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()>D_){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(_){g.warn(`needs-input check failed for ${s.key}: ${_ instanceof Error?_.message:_}`);continue}let d=new Date(l.questionsPostedAt).getTime(),p=o.comments.filter(_=>!ft(_.body)&&new Date(_.created).getTime()>d);if(!p.length)continue;let f=Dr(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:[qn.NEEDS_INPUT_LABEL]}).catch(_=>{g.warn(`could not remove needs-input label on ${s.key}: ${_}`)});let v={jiraFor:this.jiraFor,transport:this.transport,cfg:this.cfg,findRule:_=>this.findRuleForResume(_)};l.kind==="implement"?this.enqueueForRepo(l.baseRepoPath??l.repoPath,async()=>{try{await Rc(l,f,w,v)}finally{this.inFlight.delete(c)}}):this.enqueueForRepo(l.repoPath,async()=>{try{await Ic(l,f,w,v)}finally{this.inFlight.delete(c)}})}}}findRuleForResume(e){let n=this.rules.find(i=>i.id===e),r=n&&this.projects.find(i=>i.id===n.projectId),s=r&&this.cfg.repos[r.repoName]?.path;return n&&r&&s?{rule:n,project:r,repoPath:s}:null}async answerPendingInput(e,n,r){let s=Dp(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}`:""}.**
1099
1104
 
1100
1105
  ${n}
1101
1106
 
1102
- This run is continuing from where it left off. (run \`${e}\`)`),await o.editLabels(s.issueKey,{remove:[zn.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,d={jiraFor:this.jiraFor,transport:this.transport,cfg:this.cfg,findRule:f=>this.findRuleForResume(f)},p=s.kind==="implement"?s.baseRepoPath??s.repoPath:s.repoPath;return this.enqueueForRepo(p,async()=>{try{s.kind==="implement"?await bc(s,c,l,d):await yc(s,c,l,d)}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 ${aa}d - abandoning run ${e.runId}`);try{await this.jiraOf(n).addComment(e.issueKey,`**Allwright gave up waiting for an answer.**
1107
+ This run is continuing from where it left off. (run \`${e}\`)`),await o.editLabels(s.issueKey,{remove:[qn.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,d={jiraFor:this.jiraFor,transport:this.transport,cfg:this.cfg,findRule:f=>this.findRuleForResume(f)},p=s.kind==="implement"?s.baseRepoPath??s.repoPath:s.repoPath;return this.enqueueForRepo(p,async()=>{try{s.kind==="implement"?await Rc(s,c,l,d):await Ic(s,c,l,d)}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 ${da}d - abandoning run ${e.runId}`);try{await this.jiraOf(n).addComment(e.issueKey,`**Allwright gave up waiting for an answer.**
1103
1108
 
1104
- No reply arrived within ${aa} 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:[zn.NEEDS_INPUT_LABEL]})}catch(r){y.warn(`could not post staleness notice for ${e.issueKey}: ${r}`)}e.kind==="implement"&&await Ot(e.baseRepoPath??e.repoPath,e.repoPath).catch(()=>{}),Lt(e.runId),this.transport.send({type:"run.status",runId:e.runId,status:"failed",error:`no reply within ${aa} 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=na(n,i.components??[]);if("error"in l){this.warnRoutingOnce(`${e.id}:${i.issueKey}`,`${i.issueKey}: ${l.error}`);continue}let c=l.project,d=c.repoName===n.repoName?r:this.cfg.repos[c.repoName]?.path;if(!d){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(d,async()=>{try{await wi({runId:p.runId,rule:e,project:c,issueKey:i.issueKey,repoPath:d,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()-Rf;for(let c of i){let d=await this.jiraOf(n).getIssue(c.key);for(let p of d.comments){if(!p.body.toLowerCase().includes(o)||pt(p.body)||new Date(p.created).getTime()<l||!p.id)continue;let f=`respond:${p.id}`;if(this.inFlight.has(f))continue;let w=na(n,c.components??[]);if("error"in w){this.warnRoutingOnce(`${e.id}:${c.key}`,`${c.key}: ${w.error}`);continue}let v=w.project,_=v.repoName===n.repoName?r:this.cfg.repos[v.repoName]?.path;if(!_){this.warnRoutingOnce(`${e.id}:${c.key}:path`,`${c.key}: routed to repo "${v.repoName}" but it has no local checkout - run: allwright repo add "${v.repoName}" /path/to/checkout`);continue}let I=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(!I.accepted||!I.runId){I.reason!=="duplicate"&&y.warn(`respond claim rejected for ${c.key}: ${I.reason??"unknown"}`);continue}this.inFlight.add(f),y.info(`claimed respond run ${I.runId}: ${c.key} (comment ${p.id})`+(v.repoName!==n.repoName?` (routed \u2192 ${v.repoName})`:"")+(I.claudeProfile?` (claude profile "${I.claudeProfile}")`:""));let E={author:p.author,body:p.body},C=this.resolveClaudeProfile(I.runId,I.claudeProfile);this.enqueueForRepo(_,async()=>{try{await wi({runId:I.runId,rule:e,project:v,issueKey:c.key,repoPath:_,cfg:this.cfg,jira:this.jiraOf(v),transport:this.transport,question:E,claudeConfigDir:C,actorEmail:I.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)pt(p.body)&&(c=Math.max(c??0,new Date(p.created).getTime()));if(c===null||!l.comments.some(p=>!pt(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.**
1109
+ No reply arrived within ${da} 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:[qn.NEEDS_INPUT_LABEL]})}catch(r){g.warn(`could not post staleness notice for ${e.issueKey}: ${r}`)}e.kind==="implement"&&await Dt(e.baseRepoPath??e.repoPath,e.repoPath).catch(()=>{}),Ft(e.runId),this.transport.send({type:"run.status",runId:e.runId,status:"failed",error:`no reply within ${da} 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=oa(n,i.components??[]);if("error"in l){this.warnRoutingOnce(`${e.id}:${i.issueKey}`,`${i.issueKey}: ${l.error}`);continue}let c=l.project,d=c.repoName===n.repoName?r:this.cfg.repos[c.repoName]?.path;if(!d){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(d,async()=>{try{await _i({runId:p.runId,rule:e,project:c,issueKey:i.issueKey,repoPath:d,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()-zf;for(let c of i){let d=await this.jiraOf(n).getIssue(c.key);for(let p of d.comments){if(!p.body.toLowerCase().includes(o)||ft(p.body)||new Date(p.created).getTime()<l||!p.id)continue;let f=`respond:${p.id}`;if(this.inFlight.has(f))continue;let w=oa(n,c.components??[]);if("error"in w){this.warnRoutingOnce(`${e.id}:${c.key}`,`${c.key}: ${w.error}`);continue}let v=w.project,_=v.repoName===n.repoName?r:this.cfg.repos[v.repoName]?.path;if(!_){this.warnRoutingOnce(`${e.id}:${c.key}:path`,`${c.key}: routed to repo "${v.repoName}" but it has no local checkout - run: allwright repo add "${v.repoName}" /path/to/checkout`);continue}let I=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(!I.accepted||!I.runId){I.reason!=="duplicate"&&g.warn(`respond claim rejected for ${c.key}: ${I.reason??"unknown"}`);continue}this.inFlight.add(f),g.info(`claimed respond run ${I.runId}: ${c.key} (comment ${p.id})`+(v.repoName!==n.repoName?` (routed \u2192 ${v.repoName})`:"")+(I.claudeProfile?` (claude profile "${I.claudeProfile}")`:""));let R={author:p.author,body:p.body},C=this.resolveClaudeProfile(I.runId,I.claudeProfile);this.enqueueForRepo(_,async()=>{try{await _i({runId:I.runId,rule:e,project:v,issueKey:c.key,repoPath:_,cfg:this.cfg,jira:this.jiraOf(v),transport:this.transport,question:R,claudeConfigDir:C,actorEmail:I.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)ft(p.body)&&(c=Math.max(c??0,new Date(p.created).getTime()));if(c===null||!l.comments.some(p=>!ft(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.**
1105
1110
 
1106
1111
  ${l.reason}`+(i.requestedByAccountId?`
1107
1112
 
1108
1113
  Jira account id: \`${i.requestedByAccountId}\``:"")+`
1109
1114
 
1110
- (run \`${l.runId}\`)`).catch(d=>y.warn(`could not post refusal to ${i.issueKey}: ${d}`)),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 Ti({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()-Rf,c=this.environments.filter(f=>f.projectId===n.id).map(f=>f.name),d=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 v of w.comments){if(!v.body.toLowerCase().includes(o)||pt(v.body)||new Date(v.created).getTime()<l||!v.id)continue;let _=s.envSelection==="fixed"?d:d_(v.body,r.keyword,c);p.push({issueKey:f.key,summary:f.summary,environmentName:_,requestedByAccountId:v.authorAccountId??void 0,requestedByDisplayName:v.author,dedupKey:`deploy:comment:${v.id}`,fingerprint:`comment "${r.keyword}" by ${v.author} at ${v.created}`+(_?` \u2192 ${_}`:"")})}}return p}async matchStatusDeploys(e,n){let r=e.trigger,s=e.action;if(r.type!=="status_changed"||s.type!=="deploy")return[];let i=await this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND status = "${r.status}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=this.fixedEnvironmentName(s.environmentId),l=[];for(let c of i){let d=await this.jiraOf(n).lastEnteredStatus(c.key,r.status);d&&l.push({issueKey:c.key,summary:c.summary,environmentName:o,requestedByAccountId:d.authorAccountId??void 0,requestedByDisplayName:d.author,dedupKey:`deploy:status:${e.id}:${c.key}:${d.at}`,fingerprint:`moved to "${r.status}" by ${d.author} at ${d.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}", "${zn.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}", "${zn.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)&&!pt(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),d=c.filter(p=>p.environmentName);return{matchedCount:d.length,excludedCount:c.length-d.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,d]=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:d.length,excludedSample:d.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 d_(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(!u_.has(o.toLowerCase()))return o;return""}Sc();Dt();var Af=R(require("node:fs"),1),Cf=R(require("node:path"),1),Yc=require("node:crypto");jt();Dt();Dr();var h_=`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.
1115
+ (run \`${l.runId}\`)`).catch(d=>g.warn(`could not post refusal to ${i.issueKey}: ${d}`)),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 Ri({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()-zf,c=this.environments.filter(f=>f.projectId===n.id).map(f=>f.name),d=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 v of w.comments){if(!v.body.toLowerCase().includes(o)||ft(v.body)||new Date(v.created).getTime()<l||!v.id)continue;let _=s.envSelection==="fixed"?d:U_(v.body,r.keyword,c);p.push({issueKey:f.key,summary:f.summary,environmentName:_,requestedByAccountId:v.authorAccountId??void 0,requestedByDisplayName:v.author,dedupKey:`deploy:comment:${v.id}`,fingerprint:`comment "${r.keyword}" by ${v.author} at ${v.created}`+(_?` \u2192 ${_}`:"")})}}return p}async matchStatusDeploys(e,n){let r=e.trigger,s=e.action;if(r.type!=="status_changed"||s.type!=="deploy")return[];let i=await this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND status = "${r.status}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=this.fixedEnvironmentName(s.environmentId),l=[];for(let c of i){let d=await this.jiraOf(n).lastEnteredStatus(c.key,r.status);d&&l.push({issueKey:c.key,summary:c.summary,environmentName:o,requestedByAccountId:d.authorAccountId??void 0,requestedByDisplayName:d.author,dedupKey:`deploy:status:${e.id}:${c.key}:${d.at}`,fingerprint:`moved to "${r.status}" by ${d.author} at ${d.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}", "${qn.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}", "${qn.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)&&!ft(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),d=c.filter(p=>p.environmentName);return{matchedCount:d.length,excludedCount:c.length-d.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,d]=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:d.length,excludedSample:d.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 U_(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(!L_.has(o.toLowerCase()))return o;return""}Pc();xt();var Df=E(require("node:fs"),1),Lf=E(require("node:path"),1),iu=require("node:crypto");Lt();xt();Ur();var q_=`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.
1111
1116
 
1112
1117
  Rules:
1113
1118
  - Edit ONLY the conflicted files listed below. Do not touch anything else, do not refactor, do not "improve" surrounding code.
@@ -1116,10 +1121,10 @@ Rules:
1116
1121
  - When you are done, every listed file must contain no conflict markers and must be syntactically valid.
1117
1122
 
1118
1123
  Conflicted files:
1119
- `;async function $f(t){let{cfg:e,repoPath:n,branch:r,baseBranch:s,issueKey:i,onLog:o}=t,l=Cf.default.join(rn(),`conflict-${(0,Yc.randomUUID)().slice(0,8)}`),c=!1;try{o("info",`Preparing a worktree for ${r} to merge ${s} into it`),await ii(n,l,r),c=!0;let d=await El(l,s);if(d.ok&&d.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(!d.ok&&d.conflicts===null)return{ok:!1,note:`The merge could not even be started: ${d.reason}`};let p={},f=!1;if(!d.ok){let _=d.conflicts;o("info",`git merged everything except ${_.length} file(s): ${_.slice(0,20).join(", ")}`+(_.length>20?", \u2026":""));let I=Je(t.agentId);if(!I)return await Pn(l),{ok:!1,note:`no adapter for agent "${t.agentId}" on this runner`};let E=jn(t.agentId,"edit_no_shell");if(E)return await Pn(l),{ok:!1,note:`${E} Resolve the conflicts yourself on branch ${r}, or use Rebuild on current base.`};o("info",`Asking ${I.displayName} to resolve only those files`);let C=-1,Y=setInterval(()=>{Al(l,_).then(b=>{let U=_.filter(j=>!b.includes(j));U.length!==C&&(C=U.length,o("info",`Conflict progress: ${U.length}/${_.length} resolved`+(U.length?` \xB7 clean: ${U.join(", ")}`:"")+(b.length?` \xB7 still conflicted: ${b.join(", ")}`:"")))}).catch(()=>{})},12e3),X=await bi(I,{repoPath:l,prompt:h_+_.map(b=>`- ${b}`).join(`
1120
- `),timeoutSeconds:t.timeoutSeconds,bin:Xe(e,t.agentId),configDir:t.configDir,mode:"edit_no_shell",sessionId:(0,Yc.randomUUID)(),onLog:(b,U)=>o(b,U)},(b,U)=>o(b==="warn"?"warn":b,U));if(clearInterval(Y),p={costUsd:X.costUsd,inputTokens:X.inputTokens,outputTokens:X.outputTokens},!X.ok)return await Pn(l),{ok:!1,...p,note:`The agent could not do the resolution: ${X.error??"it produced no output"}. Nothing was changed - the merge was rolled back. Fix that first, then Resolve again.`};f=!0;let $=await Io(l);if($.length)return await Pn(l),{ok:!1,...p,note:`The agent left conflict markers in ${$.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 Rl(l,`${i}: merge ${s}, conflicts resolved by the agent
1124
+ `;async function Uf(t){let{cfg:e,repoPath:n,branch:r,baseBranch:s,issueKey:i,onLog:o}=t,l=Lf.default.join(ln(),`conflict-${(0,iu.randomUUID)().slice(0,8)}`),c=!1;try{o("info",`Preparing a worktree for ${r} to merge ${s} into it`),await li(n,l,r),c=!0;let d=await zl(l,s);if(d.ok&&d.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(!d.ok&&d.conflicts===null)return{ok:!1,note:`The merge could not even be started: ${d.reason}`};let p={},f=!1;if(!d.ok){let _=d.conflicts;o("info",`git merged everything except ${_.length} file(s): ${_.slice(0,20).join(", ")}`+(_.length>20?", \u2026":""));let I=et(t.agentId);if(!I)return await Mn(l),{ok:!1,note:`no adapter for agent "${t.agentId}" on this runner`};let R=Ln(t.agentId,"edit_no_shell");if(R)return await Mn(l),{ok:!1,note:`${R} Resolve the conflicts yourself on branch ${r}, or use Rebuild on current base.`};o("info",`Asking ${I.displayName} to resolve only those files`);let C=-1,V=setInterval(()=>{Ll(l,_).then(b=>{let U=_.filter(j=>!b.includes(j));U.length!==C&&(C=U.length,o("info",`Conflict progress: ${U.length}/${_.length} resolved`+(U.length?` \xB7 clean: ${U.join(", ")}`:"")+(b.length?` \xB7 still conflicted: ${b.join(", ")}`:"")))}).catch(()=>{})},12e3),J=await ki(I,{repoPath:l,prompt:q_+_.map(b=>`- ${b}`).join(`
1125
+ `),timeoutSeconds:t.timeoutSeconds,bin:Be(e,t.agentId),configDir:t.configDir,mode:"edit_no_shell",sessionId:(0,iu.randomUUID)(),onLog:(b,U)=>o(b,U)},(b,U)=>o(b==="warn"?"warn":b,U));if(clearInterval(V),p={costUsd:J.costUsd,inputTokens:J.inputTokens,outputTokens:J.outputTokens},!J.ok)return await Mn(l),{ok:!1,...p,note:`The agent could not do the resolution: ${J.error??"it produced no output"}. Nothing was changed - the merge was rolled back. Fix that first, then Resolve again.`};f=!0;let $=await Ao(l);if($.length)return await Mn(l),{ok:!1,...p,note:`The agent left conflict markers in ${$.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 Dl(l,`${i}: merge ${s}, conflicts resolved by the agent
1121
1126
 
1122
- Resolved via Allwright`)}let w=await $n(l,s);if(!w.ok){let _=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 ${Rn}/${An})`;return await Pn(l),{ok:!1,...p,note:`Nothing was pushed: ${_}. The merge was rolled back.`}}await Er(l,r);let v=await Ye(l);return o("info",`Pushed the merge to ${r} (${v.slice(0,7)})`),{ok:!0,...p,freeOfCharge:!f,headSha:v,note:f?`Merged ${s} into ${r}; the agent resolved the overlapping files. The PR is the same one - review the merge commit, then approve.`:`Merged ${s} into ${r} cleanly - no agent was needed, so this cost nothing. The PR is the same one; review and approve.`}}catch(d){return await Pn(l).catch(()=>{}),{ok:!1,note:`Could not resolve the conflict: ${d instanceof Error?d.message.slice(0,300):String(d)}`}}finally{c&&(await Ot(n,l).catch(()=>{}),Af.default.rmSync(l,{recursive:!0,force:!0}))}}var Jc=R(require("node:fs"),1),Pf=R(require("node:path"),1),Xc=require("node:crypto");jt();Dt();Dr();jo();function p_(t,e){let n=e.map(r=>`$ ${r.command} (exit ${r.exitCode})
1127
+ Resolved via Allwright`)}let w=await On(l,s);if(!w.ok){let _=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 ${Pn}/${Nn})`;return await Mn(l),{ok:!1,...p,note:`Nothing was pushed: ${_}. The merge was rolled back.`}}await Ar(l,r);let v=await Qe(l);return o("info",`Pushed the merge to ${r} (${v.slice(0,7)})`),{ok:!0,...p,freeOfCharge:!f,headSha:v,note:f?`Merged ${s} into ${r}; the agent resolved the overlapping files. The PR is the same one - review the merge commit, then approve.`:`Merged ${s} into ${r} cleanly - no agent was needed, so this cost nothing. The PR is the same one; review and approve.`}}catch(d){return await Mn(l).catch(()=>{}),{ok:!1,note:`Could not resolve the conflict: ${d instanceof Error?d.message.slice(0,300):String(d)}`}}finally{c&&(await Dt(n,l).catch(()=>{}),Df.default.rmSync(l,{recursive:!0,force:!0}))}}var ou=E(require("node:fs"),1),qf=E(require("node:path"),1),au=require("node:crypto");Lt();xt();Ur();Do();function F_(t,e){let n=e.map(r=>`$ ${r.command} (exit ${r.exitCode})
1123
1128
  ${r.tail.slice(-2e3)}`).join(`
1124
1129
 
1125
1130
  `);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:
@@ -1132,17 +1137,22 @@ Your ONLY job is to make these commands pass, with the smallest change possible.
1132
1137
  - 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.
1133
1138
  - Do not ask questions; if you cannot fix something safely, say what you found and stop.
1134
1139
  - You have no shell; the runner re-runs every documented command after you finish.
1135
- End with one short paragraph stating exactly what you changed, or why you changed nothing.`}async function Nf(t){let{cfg:e,repoPath:n,branch:r,baseBranch:s,issueKey:i,failedTests:o,onLog:l}=t,c=Pf.default.join(rn(),`testfix-${(0,Xc.randomUUID)().slice(0,8)}`),d=!1;try{let p=Je(t.agentId);if(!p)return{ok:!1,note:`no adapter for agent "${t.agentId}" on this runner`};let f=jn(t.agentId,"edit_no_shell");if(f)return{ok:!1,note:f};l("info",`Preparing a worktree on ${r} for the test fix`),await Cn(n,r),await ii(n,c,r),d=!0,await vs(c,`origin/${r}`);let w=await Ye(c);l("info",`Asking ${p.displayName} to fix ${o.length} failing test command(s) - narrow prompt, failure output included, no re-exploration`);let v=await bi(p,{repoPath:c,prompt:p_(i,o),timeoutSeconds:t.timeoutSeconds,bin:Xe(e,t.agentId),configDir:t.configDir,mode:"edit_no_shell",maxTurns:60,sessionId:(0,Xc.randomUUID)(),onLog:(j,H)=>l(j,H)},(j,H)=>l(j==="warn"?"warn":j,H)),_={costUsd:v.costUsd,inputTokens:v.inputTokens,outputTokens:v.outputTokens};if(!v.ok)return{ok:!1,..._,note:`The fix agent could not run: ${v.error??"it produced no output"}. Nothing was changed or pushed.`};let I=await ws(c);for(let j of I.refused)l("warn",`${nn} entry refused: ${j}`);let E=!0;try{await Ir(c,`${i}: fix failing TEST.md commands
1140
+ End with one short paragraph stating exactly what you changed, or why you changed nothing.`}async function Ff(t){let{cfg:e,repoPath:n,branch:r,baseBranch:s,issueKey:i,failedTests:o,onLog:l}=t,c=qf.default.join(ln(),`testfix-${(0,au.randomUUID)().slice(0,8)}`),d=!1;try{let p=et(t.agentId);if(!p)return{ok:!1,note:`no adapter for agent "${t.agentId}" on this runner`};let f=Ln(t.agentId,"edit_no_shell");if(f)return{ok:!1,note:f};l("info",`Preparing a worktree on ${r} for the test fix`),await jn(n,r),await li(n,c,r),d=!0,await _s(c,`origin/${r}`);let w=await Qe(c);l("info",`Asking ${p.displayName} to fix ${o.length} failing test command(s) - narrow prompt, failure output included, no re-exploration`);let v=await ki(p,{repoPath:c,prompt:F_(i,o),timeoutSeconds:t.timeoutSeconds,bin:Be(e,t.agentId),configDir:t.configDir,mode:"edit_no_shell",maxTurns:60,sessionId:(0,au.randomUUID)(),onLog:(j,K)=>l(j,K)},(j,K)=>l(j==="warn"?"warn":j,K)),_={costUsd:v.costUsd,inputTokens:v.inputTokens,outputTokens:v.outputTokens};if(!v.ok)return{ok:!1,..._,note:`The fix agent could not run: ${v.error??"it produced no output"}. Nothing was changed or pushed.`};let I=await ks(c);for(let j of I.refused)l("warn",`${an} entry refused: ${j}`);let R=!0;try{await Er(c,`${i}: fix failing TEST.md commands
1136
1141
 
1137
- Allwright test-fix run`)}catch{E=!1}if(!E){let j=`The agent changed nothing - its own conclusion: ${v.resultText.trim().slice(0,400)||"(no explanation given)"}`;return l("info",j),{ok:!0,..._,remaining:o,note:j}}let C=await $n(c,s);if(!C.ok){await vs(c,w);let j=C.forbidden.length?`the fixed result touches protected paths (${C.forbidden.slice(0,5).join(", ")})`:`the fixed result is too large (${C.files} files, ${C.insertions+C.deletions} lines; limits ${Rn}/${An})`;return{ok:!1,..._,note:`Nothing was pushed: ${j}. The fix commit was discarded; the PR is unchanged.`}}let Y=o,X,$,b=xs(c);if(b){let j=Is(Jc.default.readFileSync(b,"utf8"));if(j.length){l("info",`Re-running ${j.length} documented test command(s)`);let H=await Cr(c,j,{perCommandTimeoutMs:15*6e4});for(let q of H)l(q.exitCode===0?"info":"warn",`${q.exitCode===0?"PASS":"FAIL"} ${q.command} (exit ${q.exitCode})`+(q.exitCode===0?"":`
1138
- ${q.tail.slice(-1500)}`));Y=H.filter(q=>q.exitCode!==0).slice(0,20).map(q=>({command:q.command.slice(0,500),exitCode:q.exitCode,tail:q.tail.slice(-4e3)})),$=H.length,X=H.length-Y.length}}await Er(c,r);let U=await Ye(c);return l("info",`Pushed the fix to ${r} (${U.slice(0,7)})`),{ok:!0,..._,headSha:U,remaining:Y,testsPassed:X,testsTotal:$,note:Y.length?`The fix was pushed, but ${Y.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{d&&(await Ot(n,c).catch(()=>{}),Jc.default.rmSync(c,{recursive:!0,force:!0}))}}ci();Tt();var Br=R(require("node:fs"),1),Of=R(require("node:path"),1);vn();Ee();var f_=k.object({role:k.enum(["user","agent"]),text:k.string(),steps:k.array(k.string()).default([]),files:k.array(k.string()).default([]),at:k.string().default(""),ms:k.number().int().nonnegative().default(0),tokens:k.number().int().nonnegative().default(0)}),m_=k.object({sessionId:k.string(),projectId:k.string(),title:k.string().default(""),updatedAt:k.string(),ownerUserId:k.string().default(""),messages:k.array(f_).default([])}),g_=k.record(m_),y_=10,b_=200,Qc=2e4,w_=30,v_=2e3,jf=8,Mf=255;function zf(){return Of.default.join(se(),"chat-sessions.json")}function Ri(){let t=zf();if(!Br.default.existsSync(t))return{};try{return g_.parse(JSON.parse(Br.default.readFileSync(t,"utf8")))}catch{return{}}}function Df(t){Br.default.mkdirSync(se(),{recursive:!0,mode:448});let e=zf(),n=e+".tmp";Br.default.writeFileSync(n,JSON.stringify(t,null,2)+`
1139
- `,{mode:384}),Br.default.renameSync(n,e),Br.default.chmodSync(e,384)}function eu(t){t.messages[t.messages.length-1]?.role==="user"&&t.messages.pop()}function Lf(t,e){e.messages=e.messages.slice(-b_),e.updatedAt=new Date().toISOString(),t[e.sessionId]=e;let n=Object.values(t).filter(r=>r.projectId===e.projectId).sort((r,s)=>s.updatedAt.localeCompare(r.updatedAt));for(let r of n.slice(y_))delete t[r.sessionId];Df(t)}function Uf(t,e,n,r=[],s=new Date().toISOString(),i=""){let o=Ri(),l=o[e]??{sessionId:e,projectId:t,title:n.slice(0,80),updatedAt:s,ownerUserId:i,messages:[]};!l.ownerUserId&&i&&(l.ownerUserId=i),eu(l),l.messages.push({role:"user",text:n.slice(0,Qc),steps:[],files:r.slice(0,jf).map(c=>c.slice(0,Mf)),at:s,ms:0,tokens:0}),Lf(o,l)}function ca(t){let e=Ri(),n=e[t];if(!n)return;let r=n.messages.length;eu(n),n.messages.length!==r&&(n.messages.length===0?delete e[t]:e[t]=n,Df(e))}function qf(t,e,n,r,s=[],i=[],o={},l=""){let c=Ri(),p=c[e]??{sessionId:e,projectId:t,title:n.slice(0,80),updatedAt:new Date().toISOString(),ownerUserId:l,messages:[]};!p.ownerUserId&&l&&(p.ownerUserId=l),eu(p),p.messages.push({role:"user",text:n.slice(0,Qc),steps:[],files:i.slice(0,jf).map(f=>f.slice(0,Mf)),at:o.askedAt||new Date().toISOString(),ms:0,tokens:0},{role:"agent",text:r.slice(0,Qc),steps:s.slice(0,w_).map(f=>f.slice(0,v_)),files:[],at:new Date().toISOString(),ms:Math.max(0,Math.round(o.ms??0)),tokens:Math.max(0,Math.round(o.tokens??0))}),Lf(c,p)}function Ff(t){return Object.values(Ri()).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,ownerUserId:e.ownerUserId??""}))}function Ms(t){return Ri()[t]??null}Dt();zt();var Bf=36,Hf=60;function Kf(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 k_=`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:
1142
+ Allwright test-fix run`)}catch{R=!1}if(!R){let j=`The agent changed nothing - its own conclusion: ${v.resultText.trim().slice(0,400)||"(no explanation given)"}`;return l("info",j),{ok:!0,..._,remaining:o,note:j}}let C=await On(c,s);if(!C.ok){await _s(c,w);let j=C.forbidden.length?`the fixed result touches protected paths (${C.forbidden.slice(0,5).join(", ")})`:`the fixed result is too large (${C.files} files, ${C.insertions+C.deletions} lines; limits ${Pn}/${Nn})`;return{ok:!1,..._,note:`Nothing was pushed: ${j}. The fix commit was discarded; the PR is unchanged.`}}let V=o,J,$,b=Rs(c);if(b){let j=Es(ou.default.readFileSync(b,"utf8"));if(j.length){l("info",`Re-running ${j.length} documented test command(s)`);let K=await Pr(c,j,{perCommandTimeoutMs:15*6e4});for(let F of K)l(F.exitCode===0?"info":"warn",`${F.exitCode===0?"PASS":"FAIL"} ${F.command} (exit ${F.exitCode})`+(F.exitCode===0?"":`
1143
+ ${F.tail.slice(-1500)}`));V=K.filter(F=>F.exitCode!==0).slice(0,20).map(F=>({command:F.command.slice(0,500),exitCode:F.exitCode,tail:F.tail.slice(-4e3)})),$=K.length,J=K.length-V.length}}await Ar(c,r);let U=await Qe(c);return l("info",`Pushed the fix to ${r} (${U.slice(0,7)})`),{ok:!0,..._,headSha:U,remaining:V,testsPassed:J,testsTotal:$,note:V.length?`The fix was pushed, but ${V.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{d&&(await Dt(n,c).catch(()=>{}),ou.default.rmSync(c,{recursive:!0,force:!0}))}}hi();It();var Kr=E(require("node:fs"),1),Bf=E(require("node:path"),1);Tn();Ae();var B_=k.object({role:k.enum(["user","agent"]),text:k.string(),steps:k.array(k.string()).default([]),files:k.array(k.string()).default([]),at:k.string().default(""),ms:k.number().int().nonnegative().default(0),tokens:k.number().int().nonnegative().default(0)}),H_=k.object({sessionId:k.string(),projectId:k.string(),title:k.string().default(""),updatedAt:k.string(),ownerUserId:k.string().default(""),agentId:k.string().default(""),messages:k.array(B_).default([])}),K_=k.record(H_),G_=10,W_=200,lu=2e4,Z_=30,V_=2e3,Hf=8,Kf=255;function Gf(){return Bf.default.join(ie(),"chat-sessions.json")}function $i(){let t=Gf();if(!Kr.default.existsSync(t))return{};try{return K_.parse(JSON.parse(Kr.default.readFileSync(t,"utf8")))}catch{return{}}}function Wf(t){Kr.default.mkdirSync(ie(),{recursive:!0,mode:448});let e=Gf(),n=e+".tmp";Kr.default.writeFileSync(n,JSON.stringify(t,null,2)+`
1144
+ `,{mode:384}),Kr.default.renameSync(n,e),Kr.default.chmodSync(e,384)}function cu(t){t.messages[t.messages.length-1]?.role==="user"&&t.messages.pop()}function Zf(t,e){e.messages=e.messages.slice(-W_),e.updatedAt=new Date().toISOString(),t[e.sessionId]=e;let n=Object.values(t).filter(r=>r.projectId===e.projectId).sort((r,s)=>s.updatedAt.localeCompare(r.updatedAt));for(let r of n.slice(G_))delete t[r.sessionId];Wf(t)}function Vf(t,e,n,r=[],s=new Date().toISOString(),i="",o=""){let l=$i(),c=l[e]??{sessionId:e,projectId:t,title:n.slice(0,80),updatedAt:s,ownerUserId:i,agentId:o,messages:[]};!c.ownerUserId&&i&&(c.ownerUserId=i),!c.agentId&&o&&(c.agentId=o),cu(c),c.messages.push({role:"user",text:n.slice(0,lu),steps:[],files:r.slice(0,Hf).map(d=>d.slice(0,Kf)),at:s,ms:0,tokens:0}),Zf(l,c)}function pa(t){let e=$i(),n=e[t];if(!n)return;let r=n.messages.length;cu(n),n.messages.length!==r&&(n.messages.length===0?delete e[t]:e[t]=n,Wf(e))}function Jf(t,e,n,r,s=[],i=[],o={},l="",c=""){let d=$i(),f=d[e]??{sessionId:e,projectId:t,title:n.slice(0,80),updatedAt:new Date().toISOString(),ownerUserId:l,agentId:c,messages:[]};!f.ownerUserId&&l&&(f.ownerUserId=l),!f.agentId&&c&&(f.agentId=c),cu(f),f.messages.push({role:"user",text:n.slice(0,lu),steps:[],files:i.slice(0,Hf).map(w=>w.slice(0,Kf)),at:o.askedAt||new Date().toISOString(),ms:0,tokens:0},{role:"agent",text:r.slice(0,lu),steps:s.slice(0,Z_).map(w=>w.slice(0,V_)),files:[],at:new Date().toISOString(),ms:Math.max(0,Math.round(o.ms??0)),tokens:Math.max(0,Math.round(o.tokens??0))}),Zf(d,f)}function Yf(t){return Object.values($i()).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,ownerUserId:e.ownerUserId??"",agentId:e.agentId??""}))}function Gr(t){return $i()[t]??null}xt();qt();var Xf=36,Qf=60;function em(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 J_=`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:
1140
1145
  Goal: what the user is trying to achieve.
1141
1146
  Decided: choices already made, including ones you talked them out of - each as one line.
1142
1147
  Constraints: rules, preferences and corrections the user gave you.
1143
1148
  Repo facts: what you learned about this codebase that is worth not re-reading.
1144
1149
  Open: what is still unresolved right now.
1145
- Write plain statements, no preamble, no closing offer of help. Do NOT emit a ticket block.`;async function Gf(t,e,n){if(!Ms(e))return null;let s=Ce(n,t.project,"chat");if("error"in s)return null;try{let i=await s.adapter.run({repoPath:t.repoPath,prompt:k_,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 Wf=`
1150
+ Write plain statements, no preamble, no closing offer of help. Do NOT emit a ticket block.`;async function tm(t,e,n){let r=Gr(e);if(!r)return null;let s=Ce(n,t.project,"chat",r.agentId);if("error"in s)return null;try{let i=await s.adapter.run({repoPath:t.repoPath,prompt:J_,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 Y_=`A Jira ticket is being created from this conversation, and the agent that IMPLEMENTS it will see only the ticket - never this chat. Write the context it should inherit, under 300 words, plain statements under these headings (skip a heading with nothing under it):
1151
+ Decisions: what was decided, including approaches considered and REJECTED (and why).
1152
+ Relevant code: files, symbols and places examined here that the work will touch or must not miss - exact paths.
1153
+ Constraints: rules, preferences and corrections the user stated.
1154
+ Watch out: anything discovered here that would waste the implementer's time to rediscover.
1155
+ Do NOT restate the ticket's own story or acceptance criteria - the ticket already says that. No preamble, no closing, no ticket block.`;async function nm(t,e,n){let r=Gr(e);if(!r)return null;let s=Ce(n,t.project,"chat",r.agentId);if("error"in s)return null;try{let i=await s.adapter.run({repoPath:t.repoPath,prompt:Y_,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,2500):null}catch(i){return g.warn(`ticket context capsule failed: ${i instanceof Error?i.message:i}`),null}}var rm=`
1146
1156
 
1147
1157
  TWO OPTIONAL BLOCKS, for the dashboard's benefit. Never mention them in your prose.
1148
1158
  1. When you ASK the user something and the sensible answers are countable, end with:
@@ -1155,12 +1165,12 @@ TWO OPTIONAL BLOCKS, for the dashboard's benefit. Never mention them in your pro
1155
1165
  ["\u2026", "\u2026"]
1156
1166
  \`\`\`
1157
1167
  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.
1158
- Never emit both blocks in one reply, and never let either replace the actual answer.`;sc();var Ai=R(require("node:fs"),1),Zf=R(require("node:path"),1);vn();Ee();var __=k.object({at:k.string(),projectId:k.string(),sessionId:k.string(),userId:k.string(),userName:k.string(),ask:k.string(),commands:k.array(k.string())}),S_=500,T_=200,ua=500;function Vf(){return Zf.default.join(se(),"operator-log.json")}function x_(){try{return k.array(__).parse(JSON.parse(Ai.default.readFileSync(Vf(),"utf8")))}catch{return[]}}function Yf(t){let e=x_();e.push({at:new Date().toISOString(),projectId:t.projectId,sessionId:t.sessionId,userId:t.userId.slice(0,ua),userName:t.userName.slice(0,ua),ask:t.ask.split(`
1159
- `)[0].slice(0,ua),commands:t.commands.slice(0,T_).map(r=>r.slice(0,ua))}),Ai.default.mkdirSync(se(),{recursive:!0,mode:448});let n=Vf();Ai.default.writeFileSync(n+".tmp",JSON.stringify(e.slice(-S_),null,2)+`
1160
- `,{mode:384}),Ai.default.renameSync(n+".tmp",n)}var Hr=R(require("node:fs"),1),gt=R(require("node:path"),1),tu=300,I_=4,Jf=512*1024,E_=new Set([".git","node_modules","dist","build","out",".next","vendor","coverage",".venv","venv","__pycache__",".turbo",".cache"]),Xf=/\.mdx?$/i;function Qf(t){let e=gt.default.resolve(t),n=[],r=(s,i)=>{if(i>I_||n.length>=tu)return;let o;try{o=Hr.default.readdirSync(s,{withFileTypes:!0})}catch{return}for(let l of o){if(n.length>=tu)return;if(!l.isFile()||!Xf.test(l.name))continue;let c=gt.default.join(s,l.name);try{let d=Hr.default.statSync(c);n.push({path:gt.default.relative(e,c).split(gt.default.sep).join("/"),sizeBytes:d.size,updatedAt:d.mtime.toISOString()})}catch{}}for(let l of o){if(n.length>=tu)return;!l.isDirectory()||l.isSymbolicLink()||E_.has(l.name)||l.name.startsWith(".")||r(gt.default.join(s,l.name),i+1)}};return r(e,0),n}function em(t,e){let n=gt.default.resolve(t);if(!Xf.test(e))return{ok:!1,error:"only markdown files can be opened here"};let r=gt.default.resolve(n,e);if(r!==n&&!r.startsWith(n+gt.default.sep))return{ok:!1,error:"that path is outside the project checkout"};let s;try{s=Hr.default.realpathSync(r)}catch{return{ok:!1,error:"file not found in this checkout"}}let i=(()=>{try{return Hr.default.realpathSync(n)}catch{return n}})();if(s!==i&&!s.startsWith(i+gt.default.sep))return{ok:!1,error:"that path links outside the project checkout"};let o;try{o=Hr.default.statSync(s)}catch{return{ok:!1,error:"file not found in this checkout"}}if(!o.isFile())return{ok:!1,error:"that path is not a file"};try{let l=Hr.default.readFileSync(s,"utf8"),c=Buffer.byteLength(l,"utf8")>Jf;return{ok:!0,path:gt.default.relative(i,s).split(gt.default.sep).join("/"),content:c?l.slice(0,Jf):l,truncated:c}}catch(l){return{ok:!1,error:l instanceof Error?l.message:"could not read the file"}}}var Se=R(Re(),1);var da=R(require("node:fs"),1),tm=R(require("node:path"),1);vn();Ee();var R_=k.object({id:k.string(),name:k.string().default(""),jiraProjectKey:k.string().default(""),repoName:k.string().default(""),jiraSiteUrl:k.string().default("")}),A_=k.array(R_);function nm(){return tm.default.join(se(),"synced-projects.json")}function rm(t){try{let e=t.map(n=>({id:n.id,name:n.name,jiraProjectKey:n.jiraProjectKey,repoName:n.repoName,jiraSiteUrl:n.jiraSiteUrl??""}));da.default.mkdirSync(se(),{recursive:!0}),da.default.writeFileSync(nm(),JSON.stringify(e,null,2),{mode:384})}catch{}}function C_(){try{let t=A_.safeParse(JSON.parse(da.default.readFileSync(nm(),"utf8")));return t.success?t.data:[]}catch{return[]}}function sm(t){return C_().find(e=>e.repoName===t)??null}Dr();mi();Os();var ru=R(require("node:fs"),1),Kr=R(require("node:path"),1),im=require("node:child_process"),Gr=R(Re(),1);Ee();Os();var $_=15e4,nu=(t,e,n,r="")=>({ok:!1,file:t,checks:[e],output:r,error:n});function P_(t){let e=Kr.default.join(t,"node_modules",".bin","prisma");return ru.default.existsSync(e)?{bin:e,prefix:[]}:{bin:"npx",prefix:["--yes","prisma"]}}function N_(t,e){if(!(0,Gr.isSelfMigrationFilename)(e))return null;let n=Kr.default.join(t,Gr.SELF_MIGRATION_DIR),r=Kr.default.resolve(n,e),s=Kr.default.relative(n,r);return s!==e||s.startsWith("..")||Kr.default.isAbsolute(s)?null:r}async function om(t){let{file:e}=t,n=N_(t.repoPath,e);if(!n)return nu(e,{name:"file",ok:!1,detail:`"${e}" is not a migration filename`,fix:[]},`"${e}" is not a migration filename`);if(!ru.default.existsSync(n))return nu(e,{name:"file",ok:!1,detail:`${Gr.SELF_MIGRATION_DIR}/${e} does not exist in this checkout`,fix:[`cd ${t.repoPath} && git pull`]},`${Gr.SELF_MIGRATION_DIR}/${e} is not in this checkout - it may be newer than the code here`);let s=$t(t.cfg,t.repoName,t.environmentName)[t.urlSecret]?.trim();if(!s)return nu(e,{name:"database url",ok:!1,detail:`no ${t.urlSecret} in this runner's secret store for "${t.repoName}:${t.environmentName}" - the value stays on this machine`,fix:[`allwright env set ${t.repoName} ${t.environmentName} "${t.urlSecret}=postgresql://\u2026"`]},`this runner has no ${t.urlSecret} for "${t.environmentName}"`);let i=Kr.default.join(t.repoPath,"apps","api"),{bin:o,prefix:l}=P_(i),c=xi([s]),d=await O_(o,[...l,"db","execute","--url",s,"--file",n],i),p=c(d.output).slice(-8e3);return d.code!==0?{ok:!1,file:e,checks:[{name:"apply",ok:!1,detail:`prisma db execute exited ${d.code}`,fix:[`cd apps/api && npx prisma db execute --url "$DATABASE_URL" --file prisma/manual/${e}`]}],output:p,error:`applying ${e} failed (exit ${d.code})`}:{ok:!0,file:e,checks:[{name:"apply",ok:!0,detail:`${Gr.SELF_MIGRATION_DIR}/${e} applied`,fix:[]}],output:p,error:""}}function O_(t,e,n){return new Promise(r=>{(0,im.execFile)(t,e,{cwd:n,timeout:$_,maxBuffer:4*1024*1024,encoding:"utf8"},(s,i,o)=>{let l=[i,o].filter(Boolean).join(`
1161
- `).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 t0=R(tg(),1),n0=R(va(),1),r0=R(Ls(),1),s0=R(fu(),1),i0=R(yu(),1),o0=R(Su(),1),ug=R(Ta(),1),a0=R(cg(),1);var xu=ug.default;var zi=R(require("node:crypto"),1),Bt=R(Re(),1);zt();function l0(t){let e=t&&typeof t=="object"&&"name"in t?String(t.name):null;return e?`"${e}"`:"(unnamed)"}function Iu(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 c0(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=Bt.ProjectConfig.safeParse(l);c.success?r.push(c.data):Iu(n,"project","",c.error.issues[0]?.message??"invalid shape")}let s=[];for(let l of Array.isArray(e.rules)?e.rules:[]){let c=Bt.RuleConfig.safeParse(l);c.success?s.push(c.data):Iu(n,"rule",l0(l),c.error.issues[0]?.message??"invalid shape")}let i=[];for(let l of Array.isArray(e.environments)?e.environments:[]){let c=Bt.EnvironmentConfig.safeParse(l);c.success?i.push(c.data):Iu(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,publicIp:typeof e.publicIp=="string"?e.publicIp:""},warnings:n}}var u0=2e4,d0=6e4,h0=5e3,Ia=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===xu.OPEN}connect(){if(this.closed)return;y.info(`connecting to control plane at ${this.wsUrl}`);let e=new xu(this.wsUrl,{headers:{authorization:`Bearer ${this.runnerToken}`}});this.ws=e,e.on("open",()=>{this.backoffMs=1e3,this.sendNow({type:"hello",protocolVersion:Bt.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()})},u0)}),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,Bt.parseServerMsg)(r)}catch(i){let o=c0(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,d0)}),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==="chat.step.run")return this.events.onChatStepRun(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.ask")return this.events.onSetupAsk(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>=h0){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=zi.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=zi.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:zi.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=zi.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??"",fixTicketSummary:n.fixTicketSummary??"",fixTicketDescription:n.fixTicketDescription??""})}sendChatTurnResult(e,n){this.send({type:"chat.turn.result",requestId:e,...n,outputTruncated:n.outputTruncated??!1,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,ownerUserId:n.ownerUserId??"",messages:n.messages.map(r=>({...r,steps:r.steps??[],files:r.files??[],at:r.at??"",ms:r.ms??0,tokens:r.tokens??0}))})}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"}))})}sendChatStepRunResult(e,n){this.send({type:"chat.step.run.result",requestId:e,ok:n.ok,stepName:n.stepName??"",commandLine:n.commandLine??"",exitCode:n.exitCode??0,timedOut:n.timedOut??!1,output:n.output??"",error:n.error??""})}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??"",truncated:n.truncated??!1})}sendRunContext(e){this.send({type:"run.context",runId:e.runId,pieces:e.pieces.slice(0,30),totalChars:e.totalChars,sessionMode:e.sessionMode})}sendSetupAskResult(e,n){this.send({type:"setup.ask.result",requestId:e,ok:n.ok,error:n.error,answer:n.answer??""})}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 Ea=R(require("node:fs"),1),Ks=R(require("node:path"),1),Eu=require("node:child_process"),p0=/\.mdx?$/i,dg=6,f0=/^[\w.\- ()]+$/;function m0(t,e){let n=e.trim().replace(/\\/g,"/").replace(/^\.\//,"");if(!n)return{ok:!1,error:"empty path"};if(Ks.default.isAbsolute(n))return{ok:!1,error:"path must be repo-relative"};if(!p0.test(n))return{ok:!1,error:"only markdown files (.md) can be saved"};let r=n.split("/");if(r.length>dg)return{ok:!1,error:`path deeper than ${dg} levels`};for(let o of r)if(o==="."||o===".."||!f0.test(o))return{ok:!1,error:`invalid path segment "${o}"`};if(r[0]===".git")return{ok:!1,error:"cannot write under .git"};let s=Ks.default.resolve(t),i=Ks.default.resolve(s,n);return i!==s&&!i.startsWith(s+Ks.default.sep)?{ok:!1,error:"path escapes the checkout"}:{ok:!0,abs:i,rel:n}}async function Ru(t){let e=m0(t.repoPath,t.relPath);if(!e.ok)return{ok:!1,error:e.error};if(Ea.default.existsSync(e.abs)&&!t.overwrite)return{ok:!1,error:`${e.rel} already exists in this checkout`};Ea.default.mkdirSync(Ks.default.dirname(e.abs),{recursive:!0}),Ea.default.writeFileSync(e.abs,t.content.endsWith(`
1168
+ Never emit both blocks in one reply, and never let either replace the actual answer.`;fc();var Pi=E(require("node:fs"),1),sm=E(require("node:path"),1);Tn();Ae();var X_=k.object({at:k.string(),projectId:k.string(),sessionId:k.string(),userId:k.string(),userName:k.string(),ask:k.string(),commands:k.array(k.string())}),Q_=500,eS=200,fa=500;function im(){return sm.default.join(ie(),"operator-log.json")}function om(){try{return k.array(X_).parse(JSON.parse(Pi.default.readFileSync(im(),"utf8")))}catch{return[]}}function am(t){let e=om();e.push({at:new Date().toISOString(),projectId:t.projectId,sessionId:t.sessionId,userId:t.userId.slice(0,fa),userName:t.userName.slice(0,fa),ask:t.ask.split(`
1169
+ `)[0].slice(0,fa),commands:t.commands.slice(0,eS).map(r=>r.slice(0,fa))}),Pi.default.mkdirSync(ie(),{recursive:!0,mode:448});let n=im();Pi.default.writeFileSync(n+".tmp",JSON.stringify(e.slice(-Q_),null,2)+`
1170
+ `,{mode:384}),Pi.default.renameSync(n+".tmp",n)}function lm(){return om()}var Wr=E(require("node:fs"),1),yt=E(require("node:path"),1),uu=300,tS=4,cm=512*1024,nS=new Set([".git","node_modules","dist","build","out",".next","vendor","coverage",".venv","venv","__pycache__",".turbo",".cache"]),um=/\.mdx?$/i;function dm(t){let e=yt.default.resolve(t),n=[],r=(s,i)=>{if(i>tS||n.length>=uu)return;let o;try{o=Wr.default.readdirSync(s,{withFileTypes:!0})}catch{return}for(let l of o){if(n.length>=uu)return;if(!l.isFile()||!um.test(l.name))continue;let c=yt.default.join(s,l.name);try{let d=Wr.default.statSync(c);n.push({path:yt.default.relative(e,c).split(yt.default.sep).join("/"),sizeBytes:d.size,updatedAt:d.mtime.toISOString()})}catch{}}for(let l of o){if(n.length>=uu)return;!l.isDirectory()||l.isSymbolicLink()||nS.has(l.name)||l.name.startsWith(".")||r(yt.default.join(s,l.name),i+1)}};return r(e,0),n}function hm(t,e){let n=yt.default.resolve(t);if(!um.test(e))return{ok:!1,error:"only markdown files can be opened here"};let r=yt.default.resolve(n,e);if(r!==n&&!r.startsWith(n+yt.default.sep))return{ok:!1,error:"that path is outside the project checkout"};let s;try{s=Wr.default.realpathSync(r)}catch{return{ok:!1,error:"file not found in this checkout"}}let i=(()=>{try{return Wr.default.realpathSync(n)}catch{return n}})();if(s!==i&&!s.startsWith(i+yt.default.sep))return{ok:!1,error:"that path links outside the project checkout"};let o;try{o=Wr.default.statSync(s)}catch{return{ok:!1,error:"file not found in this checkout"}}if(!o.isFile())return{ok:!1,error:"that path is not a file"};try{let l=Wr.default.readFileSync(s,"utf8"),c=Buffer.byteLength(l,"utf8")>cm;return{ok:!0,path:yt.default.relative(i,s).split(yt.default.sep).join("/"),content:c?l.slice(0,cm):l,truncated:c}}catch(l){return{ok:!1,error:l instanceof Error?l.message:"could not read the file"}}}var ke=E(Re(),1);var ma=E(require("node:fs"),1),pm=E(require("node:path"),1);Tn();Ae();var rS=k.object({id:k.string(),name:k.string().default(""),jiraProjectKey:k.string().default(""),repoName:k.string().default(""),jiraSiteUrl:k.string().default("")}),sS=k.array(rS);function fm(){return pm.default.join(ie(),"synced-projects.json")}function mm(t){try{let e=t.map(n=>({id:n.id,name:n.name,jiraProjectKey:n.jiraProjectKey,repoName:n.repoName,jiraSiteUrl:n.jiraSiteUrl??""}));ma.default.mkdirSync(ie(),{recursive:!0}),ma.default.writeFileSync(fm(),JSON.stringify(e,null,2),{mode:384})}catch{}}function iS(){try{let t=sS.safeParse(JSON.parse(ma.default.readFileSync(fm(),"utf8")));return t.success?t.data:[]}catch{return[]}}function gm(t){return iS().find(e=>e.repoName===t)??null}Ur();bi();Ms();var hu=E(require("node:fs"),1),Zr=E(require("node:path"),1),ym=require("node:child_process"),Vr=E(Re(),1);Ae();Ms();var oS=15e4,du=(t,e,n,r="")=>({ok:!1,file:t,checks:[e],output:r,error:n});function aS(t){let e=Zr.default.join(t,"node_modules",".bin","prisma");return hu.default.existsSync(e)?{bin:e,prefix:[]}:{bin:"npx",prefix:["--yes","prisma"]}}function lS(t,e){if(!(0,Vr.isSelfMigrationFilename)(e))return null;let n=Zr.default.join(t,Vr.SELF_MIGRATION_DIR),r=Zr.default.resolve(n,e),s=Zr.default.relative(n,r);return s!==e||s.startsWith("..")||Zr.default.isAbsolute(s)?null:r}async function bm(t){let{file:e}=t,n=lS(t.repoPath,e);if(!n)return du(e,{name:"file",ok:!1,detail:`"${e}" is not a migration filename`,fix:[]},`"${e}" is not a migration filename`);if(!hu.default.existsSync(n))return du(e,{name:"file",ok:!1,detail:`${Vr.SELF_MIGRATION_DIR}/${e} does not exist in this checkout`,fix:[`cd ${t.repoPath} && git pull`]},`${Vr.SELF_MIGRATION_DIR}/${e} is not in this checkout - it may be newer than the code here`);let s=Ot(t.cfg,t.repoName,t.environmentName)[t.urlSecret]?.trim();if(!s)return du(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=Zr.default.join(t.repoPath,"apps","api"),{bin:o,prefix:l}=aS(i),c=Ei([s]),d=await cS(o,[...l,"db","execute","--url",s,"--file",n],i),p=c(d.output).slice(-8e3);return d.code!==0?{ok:!1,file:e,checks:[{name:"apply",ok:!1,detail:`prisma db execute exited ${d.code}`,fix:[`cd apps/api && npx prisma db execute --url "$DATABASE_URL" --file prisma/manual/${e}`]}],output:p,error:`applying ${e} failed (exit ${d.code})`}:{ok:!0,file:e,checks:[{name:"apply",ok:!0,detail:`${Vr.SELF_MIGRATION_DIR}/${e} applied`,fix:[]}],output:p,error:""}}function cS(t,e,n){return new Promise(r=>{(0,ym.execFile)(t,e,{cwd:n,timeout:oS,maxBuffer:4*1024*1024,encoding:"utf8"},(s,i,o)=>{let l=[i,o].filter(Boolean).join(`
1171
+ `).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 C0=E(pg(),1),$0=E(Ta(),1),P0=E(Us(),1),N0=E(Su(),1),j0=E(Iu(),1),O0=E(Pu(),1),_g=E(Ea(),1),M0=E(kg(),1);var ju=_g.default;var Ui=E(require("node:crypto"),1),Gt=E(Re(),1);qt();function z0(t){let e=t&&typeof t=="object"&&"name"in t?String(t.name):null;return e?`"${e}"`:"(unnamed)"}function Ou(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 D0(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=Gt.ProjectConfig.safeParse(l);c.success?r.push(c.data):Ou(n,"project","",c.error.issues[0]?.message??"invalid shape")}let s=[];for(let l of Array.isArray(e.rules)?e.rules:[]){let c=Gt.RuleConfig.safeParse(l);c.success?s.push(c.data):Ou(n,"rule",z0(l),c.error.issues[0]?.message??"invalid shape")}let i=[];for(let l of Array.isArray(e.environments)?e.environments:[]){let c=Gt.EnvironmentConfig.safeParse(l);c.success?i.push(c.data):Ou(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,publicIp:typeof e.publicIp=="string"?e.publicIp:""},warnings:n}}var L0=2e4,U0=6e4,q0=5e3,Ca=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===ju.OPEN}connect(){if(this.closed)return;g.info(`connecting to control plane at ${this.wsUrl}`);let e=new ju(this.wsUrl,{headers:{authorization:`Bearer ${this.runnerToken}`}});this.ws=e,e.on("open",()=>{this.backoffMs=1e3,this.sendNow({type:"hello",protocolVersion:Gt.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()})},L0)}),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,Gt.parseServerMsg)(r)}catch(i){let o=D0(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,U0)}),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==="chat.diagnostic")return this.events.onChatDiagnostic(e);if(e.type==="chat.step.run")return this.events.onChatStepRun(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==="server.inventory")return this.events.onServerInventory(e);if(e.type==="setup.claudemd.generate")return this.events.onSetupClaudeMdGenerate(e);if(e.type==="setup.ask")return this.events.onSetupAsk(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>=q0){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=Ui.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=Ui.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:Ui.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=Ui.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??"",fixTicketSummary:n.fixTicketSummary??"",fixTicketDescription:n.fixTicketDescription??""})}sendChatTurnResult(e,n){this.send({type:"chat.turn.result",requestId:e,...n,outputTruncated:n.outputTruncated??!1,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,ownerUserId:n.ownerUserId??"",agentId:n.agentId??"",messages:n.messages.map(r=>({...r,steps:r.steps??[],files:r.files??[],at:r.at??"",ms:r.ms??0,tokens:r.tokens??0}))})}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"}))})}sendChatStepRunResult(e,n){this.send({type:"chat.step.run.result",requestId:e,ok:n.ok,stepName:n.stepName??"",commandLine:n.commandLine??"",exitCode:n.exitCode??0,timedOut:n.timedOut??!1,output:n.output??"",error:n.error??""})}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??"",truncated:n.truncated??!1})}sendRunContext(e){this.send({type:"run.context",runId:e.runId,pieces:e.pieces.slice(0,30),totalChars:e.totalChars,sessionMode:e.sessionMode})}sendSetupAskResult(e,n){this.send({type:"setup.ask.result",requestId:e,ok:n.ok,error:n.error,answer:n.answer??""})}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??""})}sendServerInventoryResult(e,n){this.send({type:"server.inventory.result",requestId:e,...n})}sendSetupStatusResult(e,n){this.send({type:"setup.status.result",requestId:e,ok:n.ok,error:n.error,jiraConfigured:n.jiraConfigured??!1,jiraEmail:n.jiraEmail??"",agents:n.agents??{},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 $a=E(require("node:fs"),1),Gs=E(require("node:path"),1),Mu=require("node:child_process"),F0=/\.mdx?$/i,Sg=6,B0=/^[\w.\- ()]+$/;function H0(t,e){let n=e.trim().replace(/\\/g,"/").replace(/^\.\//,"");if(!n)return{ok:!1,error:"empty path"};if(Gs.default.isAbsolute(n))return{ok:!1,error:"path must be repo-relative"};if(!F0.test(n))return{ok:!1,error:"only markdown files (.md) can be saved"};let r=n.split("/");if(r.length>Sg)return{ok:!1,error:`path deeper than ${Sg} levels`};for(let o of r)if(o==="."||o===".."||!B0.test(o))return{ok:!1,error:`invalid path segment "${o}"`};if(r[0]===".git")return{ok:!1,error:"cannot write under .git"};let s=Gs.default.resolve(t),i=Gs.default.resolve(s,n);return i!==s&&!i.startsWith(s+Gs.default.sep)?{ok:!1,error:"path escapes the checkout"}:{ok:!0,abs:i,rel:n}}async function zu(t){let e=H0(t.repoPath,t.relPath);if(!e.ok)return{ok:!1,error:e.error};if($a.default.existsSync(e.abs)&&!t.overwrite)return{ok:!1,error:`${e.rel} already exists in this checkout`};$a.default.mkdirSync(Gs.default.dirname(e.abs),{recursive:!0}),$a.default.writeFileSync(e.abs,t.content.endsWith(`
1162
1172
  `)?t.content:t.content+`
1163
- `);let n=i=>new Promise((o,l)=>{(0,Eu.execFile)("git",["-C",t.repoPath,...i],{timeout:12e4},(c,d,p)=>c?l(new Error(p||c.message)):o())}),r="";try{r=await new Promise((i,o)=>(0,Eu.execFile)("git",["-C",t.repoPath,"rev-parse","--abbrev-ref","HEAD"],{timeout:2e4},(l,c,d)=>l?o(new Error(d||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 Xr=R(require("node:fs"),1),Au=R(require("node:path"),1),Ra=require("node:child_process"),pg=require("node:util");Ee();oi();Os();Ar();Dt();jt();var fg=R(Re(),1),hg=(0,pg.promisify)(Ra.execFile);function g0(t){try{return new URL(t).host}catch{return t}}function y0(t){try{return(0,Ra.execFileSync)("git",["-C",t,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim()}catch{return null}}async function Aa(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=g0(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 v=new Le(o);try{let _=await v.myself();s.push({name:"jira-auth",ok:!0,detail:`authenticated as ${_.displayName} on ${f} (${w})`});try{await v.search(`project = "${e.jiraProjectKey}" ORDER BY created DESC`,1),s.push({name:"jira-project",ok:!0,detail:`project ${e.jiraProjectKey} is readable on ${f}`})}catch(I){s.push({name:"jira-project",ok:!1,detail:`cannot read project ${e.jiraProjectKey} on ${f}: ${Di(I)}`})}}catch(_){s.push({name:"jira-auth",ok:!1,detail:`Jira auth failed on ${f}: ${Di(_)}`})}}}let c=t.repos[e.repoName];if(c&&Xr.default.existsSync(c.path)){let f=Au.default.join(c.path,"CLAUDE.md"),w=Xr.default.existsSync(f)&&Xr.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 v=Ii(c.path);s.push({name:"deploy-doc",kind:"content",ok:v!==null,detail:v?`${v.path} present - deploy suggestions will follow it`:"MISSING: DEPLOY.md (or .ticketpilot/deploy.md). Environments can't be created until the repo documents how it deploys.",...v?{}:{fixNote:"Only needed if this project will deploy from Allwright. The setup wizard can draft DEPLOY.md the same way it drafts CLAUDE.md - describe how you deploy today (the commands you actually run), and the agent proposes steps a human saves. Skip it if you only want tickets to become pull requests."}})}if(!c)s.push({name:"repo-path",ok:!1,detail:`no local path mapped for repo "${e.repoName}" - run: allwright repo add "${e.repoName}" /path/to/checkout`});else if(!Xr.default.existsSync(c.path))s.push({name:"repo-path",ok:!1,detail:`path does not exist: ${c.path}`});else{let f=Xr.default.existsSync(Au.default.join(c.path,".git"));s.push({name:"repo-path",ok:!0,detail:`${c.path}${f?" (git checkout)":" (warning: not a git checkout)"}`})}let d=[...new Set([e.defaultAgent||"claude-code",...r??[]])];for(let f of d){let w=Xe(t,f),v=f==="claude-code"?"claude-code":`agent:${f}`;try{let{stdout:_}=await hg(w,["--version"],{timeout:15e3});s.push({name:v,ok:!0,detail:_.trim().slice(0,100)})}catch(_){s.push({name:v,ok:!1,detail:`cannot run "${w}" for agent "${f}": ${Di(_)}`,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 hg("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: ${Di(f)}`})}let p=Ue(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 ${fg.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(()=>(Tt(),Pr)),w=new f(p),v=await w.whoami(),_=c&&Xr.default.existsSync(c.path)?y0(c.path):null,I=_?_t(_):null;if(!I)s.push({name:"github-token",ok:!0,detail:`authenticated as ${v} - repo access not checked (no local checkout yet)`});else{let E=await w.repoAccess(I.owner,I.repo);s.push({name:"github-token",ok:E.ok&&E.canPush,detail:E.ok?E.canPush?`${v} has push access to ${I.owner}/${I.repo}`:`${v} can read ${I.owner}/${I.repo} but NOT push to it - implement rules will fail at the push`:`${v} cannot see ${I.owner}/${I.repo}: ${E.error}`,...E.ok&&E.canPush?{}:{fix:[`allwright github set "${e.repoName}"`],fixNote:`Two ways: edit the existing PAT on GitHub and add ${I.owner}/${I.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:Di(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=$t(t,e.repoName,f.name),v=f.requiredSecrets.filter(_=>!w[_]&&!process.env[_]);s.push({name:`env:${f.name}`,ok:v.length===0,detail:v.length?`missing secret(s): ${v.join(", ")} - allwright env set "${e.repoName}" "${f.name}" ${v[0]}=...`:`${f.steps.length} step(s), ${f.requiredSecrets.length} secret(s) present`+(f.branch?`, deploys origin/${f.branch}`:"")})}}return s}function Di(t){return(t instanceof Error?t.message:String(t)).slice(0,300)}zt();Xo();oa();Ou();var $0=300,Lg=9e5,P0=45e3,Ug=6,N0="You stopped because the session hit its turn limit - nothing failed. Continue exactly where you left off. Do not re-read what you already know or repeat work already done; be economical with tool calls. You are close to the end of the budget for this question, so ANSWER NOW with what you have, marking anything you could not verify - a useful partial answer beats none. Finish exactly as the original instructions asked.",O0="You stopped because the session hit its turn limit - nothing failed, and there is still time on this question. Continue exactly where you left off. Do not re-read what you already know or repeat work already done; be economical with tool calls, and go where the evidence is rather than reading broadly. Finish exactly as the original instructions asked.",j0=15e4,M0=3e5;function z0(t){try{let{packs:e,lessons:n}=Ts("compose",t),r=[e.map(s=>`### ${s.name}
1173
+ `);let n=i=>new Promise((o,l)=>{(0,Mu.execFile)("git",["-C",t.repoPath,...i],{timeout:12e4},(c,d,p)=>c?l(new Error(p||c.message)):o())}),r="";try{r=await new Promise((i,o)=>(0,Mu.execFile)("git",["-C",t.repoPath,"rev-parse","--abbrev-ref","HEAD"],{timeout:2e4},(l,c,d)=>l?o(new Error(d||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 ts=E(require("node:fs"),1),Du=E(require("node:path"),1),Pa=require("node:child_process"),xg=require("node:util");Ae();ci();Ms();$r();xt();Lt();var Ig=E(Re(),1),Tg=(0,xg.promisify)(Pa.execFile);function K0(t){try{return new URL(t).host}catch{return t}}function G0(t){try{return(0,Pa.execFileSync)("git",["-C",t,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim()}catch{return null}}async function Na(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=K0(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 v=new Ue(o);try{let _=await v.myself();s.push({name:"jira-auth",ok:!0,detail:`authenticated as ${_.displayName} on ${f} (${w})`});try{await v.search(`project = "${e.jiraProjectKey}" ORDER BY created DESC`,1),s.push({name:"jira-project",ok:!0,detail:`project ${e.jiraProjectKey} is readable on ${f}`})}catch(I){s.push({name:"jira-project",ok:!1,detail:`cannot read project ${e.jiraProjectKey} on ${f}: ${qi(I)}`})}}catch(_){s.push({name:"jira-auth",ok:!1,detail:`Jira auth failed on ${f}: ${qi(_)}`})}}}let c=t.repos[e.repoName];if(c&&ts.default.existsSync(c.path)){let f=Du.default.join(c.path,"CLAUDE.md"),w=ts.default.existsSync(f)&&ts.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 v=Ai(c.path);s.push({name:"deploy-doc",kind:"content",ok:v!==null,detail:v?`${v.path} present - deploy suggestions will follow it`:"MISSING: DEPLOY.md (or .ticketpilot/deploy.md). Environments can't be created until the repo documents how it deploys.",...v?{}:{fixNote:"Only needed if this project will deploy from Allwright. The setup wizard can draft DEPLOY.md the same way it drafts CLAUDE.md - describe how you deploy today (the commands you actually run), and the agent proposes steps a human saves. Skip it if you only want tickets to become pull requests."}})}if(!c)s.push({name:"repo-path",ok:!1,detail:`no local path mapped for repo "${e.repoName}" - run: allwright repo add "${e.repoName}" /path/to/checkout`});else if(!ts.default.existsSync(c.path))s.push({name:"repo-path",ok:!1,detail:`path does not exist: ${c.path}`});else{let f=ts.default.existsSync(Du.default.join(c.path,".git"));s.push({name:"repo-path",ok:!0,detail:`${c.path}${f?" (git checkout)":" (warning: not a git checkout)"}`})}let d=[...new Set([e.defaultAgent||"claude-code",...r??[]])];for(let f of d){let w=Be(t,f),v=f==="claude-code"?"claude-code":`agent:${f}`;try{let{stdout:_}=await Tg(w,["--version"],{timeout:15e3});s.push({name:v,ok:!0,detail:_.trim().slice(0,100)})}catch(_){s.push({name:v,ok:!1,detail:`cannot run "${w}" for agent "${f}": ${qi(_)}`,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 Tg("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: ${qi(f)}`})}let p=qe(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 ${Ig.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(()=>(It(),jr)),w=new f(p),v=await w.whoami(),_=c&&ts.default.existsSync(c.path)?G0(c.path):null,I=_?St(_):null;if(!I)s.push({name:"github-token",ok:!0,detail:`authenticated as ${v} - repo access not checked (no local checkout yet)`});else{let R=await w.repoAccess(I.owner,I.repo);s.push({name:"github-token",ok:R.ok&&R.canPush,detail:R.ok?R.canPush?`${v} has push access to ${I.owner}/${I.repo}`:`${v} can read ${I.owner}/${I.repo} but NOT push to it - implement rules will fail at the push`:`${v} cannot see ${I.owner}/${I.repo}: ${R.error}`,...R.ok&&R.canPush?{}:{fix:[`allwright github set "${e.repoName}"`],fixNote:`Two ways: edit the existing PAT on GitHub and add ${I.owner}/${I.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:qi(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=Ot(t,e.repoName,f.name),v=f.requiredSecrets.filter(_=>!w[_]&&!process.env[_]);s.push({name:`env:${f.name}`,ok:v.length===0,detail:v.length?`missing secret(s): ${v.join(", ")} - allwright env set "${e.repoName}" "${f.name}" ${v[0]}=...`:`${f.steps.length} step(s), ${f.requiredSecrets.length} secret(s) present`+(f.branch?`, deploys origin/${f.branch}`:"")})}}return s}function qi(t){return(t instanceof Error?t.message:String(t)).slice(0,300)}qt();na();ua();Bu();var kT=300,fy=9e5,_T=45e3,my=6,ST="You stopped because the session hit its turn limit - nothing failed. Continue exactly where you left off. Do not re-read what you already know or repeat work already done; be economical with tool calls. You are close to the end of the budget for this question, so ANSWER NOW with what you have, marking anything you could not verify - a useful partial answer beats none. Finish exactly as the original instructions asked.",TT="You stopped because the session hit its turn limit - nothing failed, and there is still time on this question. Continue exactly where you left off. Do not re-read what you already know or repeat work already done; be economical with tool calls, and go where the evidence is rather than reading broadly. Finish exactly as the original instructions asked.",xT=15e4,IT=3e5;function RT(t){try{let{packs:e,lessons:n}=Is("compose",t),r=[e.map(s=>`### ${s.name}
1164
1174
  ${s.content}`).join(`
1165
1175
 
1166
1176
  `).slice(0,4e3),n.trim().slice(-4e3)].filter(Boolean).join(`
@@ -1168,15 +1178,15 @@ ${s.content}`).join(`
1168
1178
  `).trim();return r?`
1169
1179
  HOUSE RULES FOR TICKETS here - taught by this team, follow them over the generic guidance above when they conflict:
1170
1180
  ${r}
1171
- `:""}catch{return""}}function D0(t){let e=t.map(r=>r.trim()).filter(Boolean).join(`
1181
+ `:""}catch{return""}}function ET(t){let e=t.map(r=>r.trim()).filter(Boolean).join(`
1172
1182
 
1173
1183
  `);return`**This answer is incomplete** - the agent ran out of turns before it finished. Below is what it had worked out so far; ask a narrower question, or make it a ticket so a full run can take it.
1174
1184
 
1175
1185
  ${e.length>8e3?`\u2026
1176
1186
 
1177
- ${e.slice(-8e3)}`:e}`}var Pe=new td;Pe.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(vo);function qg(t){y.info(`Create the token at ${Se.GITHUB_TOKEN_PERMISSIONS.where}`);for(let e of Se.GITHUB_TOKEN_PERMISSIONS.steps)y.info(` - ${e}`);y.info(Se.GITHUB_TOKEN_PERMISSIONS.note),y.info(`Then paste it below for ${t}.`)}Pe.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",Ki.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=Fn.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=ph(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=fh(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=tl.parse({controlPlaneUrl:r,runnerName:t.name,jira:l});if(c.jira){let d=await new Le(c.jira).myself();y.info(`Jira credential OK - authenticated as ${d.displayName}`)}c=await th(c,s),y.info(`Enrolled as runner "${c.runnerName}" (${c.runnerId})`),y.info(`Credentials saved to ${Xt()} (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 zu=Pe.command("repo").description("Map control-plane repo names to local checkouts");zu.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=he(),s=pn.default.resolve(e.replace(/^~(?=\/|$)/,Ki.default.homedir()));if(!n.force){if(!rt.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(!rt.default.existsSync(pn.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},we(r),y.info(`mapped repo "${t}" -> ${s}`);try{let{originUrl:i}=await Promise.resolve().then(()=>(jt(),ch));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?`)}fn()||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.`)});zu.command("list").description("Show configured repo mappings").action(()=>{let t=he(),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 Fg=Pe.command("claude").description("Per-user Claude login profiles - each teammate's runs bill their OWN Claude account");Fg.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=he(),n=e.claudeProfiles[t]?.configDir??`${Xt().replace(/runner\.json$/,"")}claude-profiles/${t}`;rt.default.mkdirSync(n,{recursive:!0,mode:448}),e.claudeProfiles[t]={configDir:n},we(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,mn.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}".`),fn()});Fg.command("list").description("Show configured Claude profiles and whether each looks logged in").action(()=>{let t=he(),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=rt.default.existsSync(r.configDir)&&rt.default.readdirSync(r.configDir).length>0;y.info(`${n} -> ${r.configDir} ${s?"(logged in)":"(NOT logged in yet)"}`)}});zu.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=he();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),we(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 Du=Pe.command("service").description("Run the runner as a system service (starts on boot, restarts on crash)");Du.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(`
1178
- `+Ml(jl()));return}wh(y)});Du.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(()=>vh(y));Du.command("status").description("systemctl status for the runner service").action(()=>{(0,mn.spawn)("systemctl",["status","allwright","--no-pager"],{stdio:"inherit"}).on("exit",e=>process.exit(e??0))});Pe.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,mn.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 Ws=Pe.command("jira").description("Per-repo Jira site overrides - for projects living on a different Atlassian site");Ws.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=he();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=sm(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 Le(l).myself();if(e.repos[t].jira=l,we(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 Le(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.`)}fn();return}catch{y.info(`The token already on this server does not work on ${r} - asking for one that does.`)}}let o=Fn.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},v=await new Le(w).myself();y.info(`Jira credential OK - authenticated as ${v.displayName} on ${c}`),e.repos[t].jira=w,we(e),y.info(`Saved: repo "${t}" now polls ${c} (other repos keep the runner-wide credential)`),fn()}finally{o.close()}});Ws.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=he(),e=Fn.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 Le(l).myself();t.jira=l,we(t),y.info(`Jira credential OK - authenticated as ${c.displayName} on ${s}`),y.info(`Saved to ${Xt()} (mode 600, this machine only). Repo overrides are untouched.`),fn()}finally{e.close()}});Ws.command("show").description("Show which Jira site each repo uses (never prints tokens)").action(()=>{let t=he();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)"}`)});Ws.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=he(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=Fn.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(d=>d.jira)].filter(d=>!!d),l=new Set,c=!1;for(let d of o)if(!l.has(d.baseUrl)){l.add(d.baseUrl);try{let p=await new Le({baseUrl:d.baseUrl,email:s,apiToken:i}).myself();y.info(`${d.baseUrl}: OK - authenticated as ${p.displayName}`),c=!0}catch{y.warn(`${d.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},we(e),y.info(`Saved. Dashboard actions by ${n} now post to Jira as ${s}. No restart needed.`)}finally{r.close()}});Ws.command("user-list").description("Show which Allwright users have their own Jira credential here (never prints tokens)").action(()=>{let t=he(),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}`)});Ws.command("user-remove <ticketpilotEmail>").description("Delete a person's stored Jira credential").action(t=>{let e=he(),n=t.trim().toLowerCase();if(!e.jiraUsers[n])throw new Error(`no credential stored for ${n}`);delete e.jiraUsers[n],we(e),y.info(`Removed. Dashboard actions by ${n} will now be refused until a new credential is added.`)});var Zs=Pe.command("github").description("GitHub credential for implement-mode rules");Zs.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=Fn.default.createInterface({input:process.stdin,output:process.stdout});try{let n=t.token??void qg("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(()=>(Tt(),Pr)),s=await new r(n).whoami(),i=he();i.github={token:n,login:s},we(i),y.info(`GitHub token OK - authenticated as ${s}`),y.info(`Saved to ${Xt()} (mode 600, this machine only)`)}finally{e.close()}});Zs.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=he();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&&rt.default.existsSync(r))try{let i=(0,mn.execFileSync)("git",["-C",r,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim(),o=_t(i);if(o){let{GitHubClient:l}=await Promise.resolve().then(()=>(Tt(),Pr)),c=new l(n),d=await c.repoAccess(o.owner,o.repo);if(d.ok&&d.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=Fn.default.createInterface({input:process.stdin,output:process.stdout});try{qg(`"${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(()=>(Tt(),Pr)),l=await new o(i).whoami();e.repos[t].github={token:i,login:l},we(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()}});Zs.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=he(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=Fn.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(()=>(Tt(),Pr)),o=await new i(s).whoami();e.githubUsers[n]={token:s,login:o},we(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()}});Zs.command("user-list").description("Show which Allwright users have their own GitHub token here (never prints tokens)").action(()=>{let t=he(),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`)});Zs.command("user-remove <ticketpilotEmail>").description("Delete a person's stored GitHub token (their runs fall back to the shared token)").action(t=>{let e=he(),n=t.trim().toLowerCase();if(!e.githubUsers[n])throw new Error(`no GitHub token stored for ${n}`);delete e.githubUsers[n],we(e),y.info(`Removed. ${n}'s runs use the repo/runner-wide token again.`)});Zs.command("show").description("Show which GitHub token each repo and person would use (never prints tokens)").action(()=>{let t=he();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 Lu=Pe.command("audit").description("Recurring specialist audits on this runner");Lu.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=he();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}],we(r),y.info(`Scheduled: ${e} audit of "${t}" every ${s}h. Restart the runner to apply.`)});Lu.command("schedules").description("List scheduled audits").action(()=>{let t=he();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`)});Lu.command("unschedule <repoName> <role>").description("Remove a scheduled audit").action((t,e)=>{let n=he(),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");we(n),y.info("Removed. Restart the runner to apply.")});var Uu=Pe.command("deploy").description("Deployment settings for this machine");Uu.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=he();t.deploy={enabled:!0},we(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."),fn()});Uu.command("disable").description("Stop this runner from executing any deploy steps").action(()=>{let t=he();t.deploy={enabled:!1},we(t),y.info("deployments DISABLED on this runner"),fn()});Uu.command("status").description("Show whether deployments are enabled here, and which env secrets are stored").action(()=>{let t=he();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 $a=Pe.command("env").description("Per-environment deploy secrets. Values stay on this machine, like your Jira token.");$a.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=he(),s=ro(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 d=l.slice(0,c).trim();i.secrets[d]=l.slice(c+1),o.push(d)}r.environments[s]=i,we(r),y.info(`stored ${o.length} secret(s) for ${s}: ${o.join(", ")}`),y.info(`Saved to ${Xt()} (mode 600, this machine only)`),fn()});$a.command("prepare <repoName> <envName>").description("Stand the environment up: systemd unit (nvm-aware PATH, crash-loop limit), scoped passwordless restart for deploys, and a proxy site block when --url is given - Caddy or nginx, whichever is RUNNING on this machine (it never installs a second proxy). 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 proxy").option("--proxy <proxy>","caddy | nginx | none (default: detect the running one; a flag that contradicts the running proxy is refused - two proxies cannot share :80/:443)").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=he().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(()=>($g(),Cg));await o({repoName:t,envName:e,dir:pn.default.resolve(i.replace(/^~(?=\/|$)/,Ki.default.homedir())),port:n.port?Number(n.port):void 0,publicUrl:n.url,proxy:n.proxy,dryRun:!!n.dryRun})});$a.command("unset <repoName> <envName> <names...>").description("Remove stored secrets for an environment").action((t,e,n)=>{let r=he(),s=ro(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,we(r),y.info(`removed ${n.join(", ")} from ${s}`)});$a.command("list").description("Show which environments have secrets stored here (names only, never values)").action(()=>{let t=he(),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)"}`)});Pe.command("export [file]").description("Back up ALL runner state (config+secrets, knowledge, audits, chats) to one tarball").action(t=>{try{let e=yd(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 ${pn.default.basename(e.file)}`)}catch(e){y.error(e instanceof Error?e.message:String(e)),process.exitCode=1}});Pe.command("import <file>").description("Restore runner state from an `export` tarball (existing config is kept as a .bak dir)").action(t=>{let e=ar();if(e&&lr(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=bd(t);y.info(`Restored ${n.restored.length} entries into ${se()}`),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}});Pe.command("test").alias("doctor").description("Check local setup: Jira auth, repo mappings, Claude Code binary").action(async()=>{let t=he(),e=Object.keys(t.repos),n=io(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 Aa(t,i),l=!so(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 d=c.ok?"PASS":"FAIL";(c.ok?y.info:y.error)(`[${d}] ${c.name}: ${c.detail}`),s&&=c.ok}}s||(process.exitCode=1)});function fn(){let t=ar()??ds();if(t&&lr(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?Rd(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 L0(t){if(!t.runnerToken)throw new Error("runner not enrolled - run `allwright init`");let e=Ed();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",il);let n=t.jira?new Le(t.jira):Nl(),r=new Map,s=u=>{let m=t.repos[u]?.jira;if(!m)return n;let g=r.get(u);return g||(g=new Le(m),r.set(u,g)),g},i=new Map,o=(u,m)=>{let g=hh(ke()??t,u,m);switch(g.kind){case"legacy":return{jira:s(u),authored:!1};case"self":return{jira:s(u),authored:!0};case"missing":return{error:g.error};case"user":{let x=`${g.creds.baseUrl}:${g.creds.email}:${g.creds.apiToken.slice(-6)}`,P=i.get(x);return P||(P=new Le(g.creds),i.set(x,P)),{jira:P,authored:!0}}}},l=new URL("/api/runner/ws",t.controlPlaneUrl);l.protocol=l.protocol==="https:"?"wss:":"ws:";let c=[],d=[],p=[],f,w=null,v={cfg:t,jiraFor:s,transport:null},_=new Set,I=async(u,m,g)=>{if(!(m.length<2))for(let x=0;x<m.length;x++){let{text:P,changed:O}=gh(g[x]??"",m);O&&await u.updateDescription(m[x],P).then(()=>y.info(`Compose: rewrote sibling ticket refs in ${m[x]} to real keys`)).catch(Z=>y.warn(`Compose: could not rewrite refs in ${m[x]}: ${Z instanceof Error?Z.message:Z}`))}},E=u=>{let m=c.find(x=>x.id===u),g=m&&t.repos[m.repoName];return m&&g?{project:m,repoPath:g.path}:null},C=u=>{let m=c.find(P=>P.id===u),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 x=Object.keys(t.repos).join(", ")||"(none)";return`${g} has no local checkout for "${m.name}" (repo "${m.repoName}"). Repos mapped here: ${x}. 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`},Y={cfg:t,jiraFor:s,get transport(){return v.transport},lookup:(u,m)=>{let g=E(u),x=p.find(P=>P.projectId===u&&P.name===m);return g&&x?{...g,environment:x}:null}},X=new Map,$=new Set,b=new Ia(l.toString(),t.runnerToken,{runnerVersion:vo},{onConfig:u=>{c=u.projects,rm(u.projects),d=u.rules,p=u.environments,cf(u.publicIp),f.setConfig(u.projects,u.rules,u.pollingPaused,u.environments)},onDeployFix:async u=>{let m=E(u.projectId);if(!m){b.sendDeploySuggestResult(u.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:C(u.projectId)});return}let g=Ce(t,m.project,"assist");if("error"in g){b.sendDeploySuggestResult(u.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:g.error});return}y.info(`investigating failed deploy of "${u.environmentName}" (step: ${u.failedStep||"?"})`);let x=await jc({agent:g,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:u.environmentName,steps:u.steps,failedStep:u.failedStep,errorText:u.errorText,cfg:t});b.sendDeploySuggestResult(u.requestId,x)},onProjectTest:async u=>{let m=c.find(x=>x.id===u.projectId);if(!m){b.sendProjectTestResult(u.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 Aa(ke()??t,m,p.filter(x=>x.projectId===m.id),d.filter(x=>x.projectId===m.id).map(x=>"agent"in x.action?x.action.agent:"").filter(Boolean));b.sendProjectTestResult(u.requestId,g.every(x=>x.ok),g)},onRuleDiagnose:async u=>{let m=d.find(B=>B.id===u.ruleId),g=m&&c.find(B=>B.id===m.projectId);if(!m||!g){b.sendRuleDiagnoseResult(u.requestId,{checks:[{name:"config",ok:!1,detail:"rule not in this runner's synced config yet"}],matchedCount:0,excludedCount:0,excludedSample:[]});return}y.info(`diagnosing rule "${m.name}"`);let x=await Aa(ke()??t,g,m.action.type==="deploy"?p.filter(B=>B.projectId===g.id):[]),P=m.action.type==="implement"?x:x.filter(B=>B.name!=="github-token"),{matchedCount:O,excludedCount:Z,excludedSample:W}=await f.diagnoseRule(m,g);b.sendRuleDiagnoseResult(u.requestId,{checks:P,matchedCount:O,excludedCount:Z,excludedSample:W})},onCancel:u=>{Mp(u)?y.info(`run ${u} stopped from the dashboard`):y.warn(`cancel requested for run ${u}, but nothing is running under that id here - it likely finished already`)},onApproved:(u,m)=>{if(ta(u)){Pc(Y,u).catch(g=>y.error(`deploy approval crashed for ${u}: ${g instanceof Error?g.stack:g}`));return}vi(v,u,m).catch(g=>y.error(`approval handling crashed for ${u}: ${g instanceof Error?g.stack:g}`))},onRetryPush:u=>{let m=Ho(u),g=()=>Gp(v,u).catch(x=>y.error(`retry push crashed for ${u}: ${x instanceof Error?x.stack:x}`));m?f.runOnRepoQueue(m.baseRepoPath,g):g()},onRejected:u=>{if(ta(u)){Nc(Y,u).catch(m=>y.error(`deploy rejection crashed for ${u}: ${m instanceof Error?m.stack:m}`));return}Kp(v,u).catch(m=>y.error(`rejection handling crashed for ${u}: ${m instanceof Error?m.stack:m}`))},onDeployStart:u=>{let m=`${u.runId}#${u.attempt}`;if(_.has(m))return;_.add(m);let g=E(u.projectId);if(!g){let x=C(u.projectId);y.error(`deploy ${u.runId}: ${x}`),b.send({type:"run.status",runId:u.runId,status:"failed",error:x});return}y.info(`deploy ${u.runId} requested from the dashboard: ${u.issueKey} \u2192 ${u.environment.name}`),f.runOnEnvironmentQueue(u.environment.id,()=>Ti({runId:u.runId,project:g.project,environment:u.environment,issueKey:u.issueKey,issueSummary:u.issueSummary,repoPath:g.repoPath,cfg:t,jira:s(g.project.repoName),transport:b,requestedBy:u.requestedBy}).catch(x=>y.error(`deploy crashed for ${u.runId}: ${x instanceof Error?x.stack:x}`)))},onDeploySuggest:async u=>{let m=E(u.projectId);if(!m){b.sendDeploySuggestResult(u.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:C(u.projectId)});return}let g=Ce(t,m.project,"assist");if("error"in g){b.sendDeploySuggestResult(u.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:g.error});return}y.info(`asking ${g.adapter.displayName} for "${u.environmentName}" deploy steps in ${m.repoPath}`);let x=await Mc({agent:g,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:u.environmentName,notes:u.notes,timeoutSeconds:u.timeoutSeconds,cfg:t});b.sendDeploySuggestResult(u.requestId,x)},onEnvPreflight:async u=>{let m=E(u.projectId);if(!m){b.sendEnvPreflightResult(u.requestId,{ok:!1,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project"}]});return}let g=await Oc({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:u.environmentName,steps:u.steps,requiredSecrets:u.requiredSecrets,workdir:u.workdir,branch:u.branch,publicUrl:u.publicUrl,cfg:t});b.sendEnvPreflightResult(u.requestId,g)},onSelfMigrationApply:async u=>{let m=E(u.projectId);if(!m){b.sendSelfMigrationApplyResult(u.requestId,{ok:!1,file:u.file,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project",fix:[]}],output:"",error:C(u.projectId)});return}y.info(`applying migration ${u.file} for "${u.environmentName}"`);let g=await om({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:u.environmentName,file:u.file,urlSecret:u.urlSecret,cfg:t});y.info(g.ok?`migration ${u.file} applied`:`migration ${u.file} failed: ${g.error}`),b.sendSelfMigrationApplyResult(u.requestId,g)},onAutopilotPlan:async u=>{try{let m=E(u.projectId);if(!m){b.sendAutopilotPlanResult(u.requestId,{ok:!1,error:C(u.projectId)});return}let g=s(m.project.repoName),x=[];for(let D of u.issueKeys)try{let ue=await g.getIssue(D);x.push(`${D}: ${ue.summary}
1179
- ${(ue.description||"").slice(0,500)}`)}catch{x.push(`${D}: (could not read from Jira)`)}let P=Ce(t,m.project,"assist");if("error"in P){b.sendAutopilotPlanResult(u.requestId,{ok:!1,error:P.error});return}let O=`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.
1187
+ ${e.slice(-8e3)}`:e}`}var $e=new ud;$e.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(So);function gy(t){g.info(`Create the token at ${ke.GITHUB_TOKEN_PERMISSIONS.where}`);for(let e of ke.GITHUB_TOKEN_PERMISSIONS.steps)g.info(` - ${e}`);g.info(ke.GITHUB_TOKEN_PERMISSIONS.note),g.info(`Then paste it below for ${t}.`)}$e.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",Zi.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=Kn.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=_h(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=Sh(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=dl.parse({controlPlaneUrl:r,runnerName:t.name,jira:l});if(c.jira){let d=await new Ue(c.jira).myself();g.info(`Jira credential OK - authenticated as ${d.displayName}`)}c=await uh(c,s),g.info(`Enrolled as runner "${c.runnerName}" (${c.runnerId})`),g.info(`Credentials saved to ${nn()} (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()}});var Gu=$e.command("repo").description("Map control-plane repo names to local checkouts");Gu.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=de(),s=yn.default.resolve(e.replace(/^~(?=\/|$)/,Zi.default.homedir()));if(!n.force){if(!it.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(!it.default.existsSync(yn.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},ye(r),g.info(`mapped repo "${t}" -> ${s}`);try{let{originUrl:i}=await Promise.resolve().then(()=>(Lt(),bh));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?`)}Vt()||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.`)});Gu.command("list").description("Show configured repo mappings").action(()=>{let t=de(),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 yy=$e.command("claude").description("Per-user Claude login profiles - each teammate's runs bill their OWN Claude account");yy.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=de(),n=e.claudeProfiles[t]?.configDir??`${nn().replace(/runner\.json$/,"")}claude-profiles/${t}`;it.default.mkdirSync(n,{recursive:!0,mode:448}),e.claudeProfiles[t]={configDir:n},ye(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,bn.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}".`),Vt()});yy.command("list").description("Show configured Claude profiles and whether each looks logged in").action(()=>{let t=de(),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=it.default.existsSync(r.configDir)&&it.default.readdirSync(r.configDir).length>0;g.info(`${n} -> ${r.configDir} ${s?"(logged in)":"(NOT logged in yet)"}`)}});Gu.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=de();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),ye(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 Wu=$e.command("service").description("Run the runner as a system service (starts on boot, restarts on crash)");Wu.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(`
1188
+ `+Gl(Kl()));return}Eh(g)});Wu.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(()=>Ah(g));Wu.command("status").description("systemctl status for the runner service").action(()=>{(0,bn.spawn)("systemctl",["status","allwright","--no-pager"],{stdio:"inherit"}).on("exit",e=>process.exit(e??0))});$e.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,bn.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 Vs=$e.command("jira").description("Per-repo Jira site overrides - for projects living on a different Atlassian site");Vs.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=de();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=gm(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 Ue(l).myself();if(e.repos[t].jira=l,ye(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 Ue(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.`)}Vt();return}catch{g.info(`The token already on this server does not work on ${r} - asking for one that does.`)}}let o=Kn.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},v=await new Ue(w).myself();g.info(`Jira credential OK - authenticated as ${v.displayName} on ${c}`),e.repos[t].jira=w,ye(e),g.info(`Saved: repo "${t}" now polls ${c} (other repos keep the runner-wide credential)`),Vt()}finally{o.close()}});Vs.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=de(),e=Kn.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 Ue(l).myself();t.jira=l,ye(t),g.info(`Jira credential OK - authenticated as ${c.displayName} on ${s}`),g.info(`Saved to ${nn()} (mode 600, this machine only). Repo overrides are untouched.`),Vt()}finally{e.close()}});Vs.command("show").description("Show which Jira site each repo uses (never prints tokens)").action(()=>{let t=de();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)"}`)});Vs.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=de(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=Kn.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(d=>d.jira)].filter(d=>!!d),l=new Set,c=!1;for(let d of o)if(!l.has(d.baseUrl)){l.add(d.baseUrl);try{let p=await new Ue({baseUrl:d.baseUrl,email:s,apiToken:i}).myself();g.info(`${d.baseUrl}: OK - authenticated as ${p.displayName}`),c=!0}catch{g.warn(`${d.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},ye(e),g.info(`Saved. Dashboard actions by ${n} now post to Jira as ${s}. No restart needed.`)}finally{r.close()}});Vs.command("user-list").description("Show which Allwright users have their own Jira credential here (never prints tokens)").action(()=>{let t=de(),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}`)});Vs.command("user-remove <ticketpilotEmail>").description("Delete a person's stored Jira credential").action(t=>{let e=de(),n=t.trim().toLowerCase();if(!e.jiraUsers[n])throw new Error(`no credential stored for ${n}`);delete e.jiraUsers[n],ye(e),g.info(`Removed. Dashboard actions by ${n} will now be refused until a new credential is added.`)});var Js=$e.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=Kn.default.createInterface({input:process.stdin,output:process.stdout});try{let n=t.token??void gy("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(()=>(It(),jr)),s=await new r(n).whoami(),i=de();i.github={token:n,login:s},ye(i),g.info(`GitHub token OK - authenticated as ${s}`),g.info(`Saved to ${nn()} (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=de();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&&it.default.existsSync(r))try{let i=(0,bn.execFileSync)("git",["-C",r,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim(),o=St(i);if(o){let{GitHubClient:l}=await Promise.resolve().then(()=>(It(),jr)),c=new l(n),d=await c.repoAccess(o.owner,o.repo);if(d.ok&&d.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=Kn.default.createInterface({input:process.stdin,output:process.stdout});try{gy(`"${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(()=>(It(),jr)),l=await new o(i).whoami();e.repos[t].github={token:i,login:l},ye(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()}});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=de(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=Kn.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(()=>(It(),jr)),o=await new i(s).whoami();e.githubUsers[n]={token:s,login:o},ye(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()}});Js.command("user-list").description("Show which Allwright users have their own GitHub token here (never prints tokens)").action(()=>{let t=de(),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`)});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=de(),n=t.trim().toLowerCase();if(!e.githubUsers[n])throw new Error(`no GitHub token stored for ${n}`);delete e.githubUsers[n],ye(e),g.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=de();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 Zu=$e.command("audit").description("Recurring specialist audits on this runner");Zu.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=de();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}],ye(r),g.info(`Scheduled: ${e} audit of "${t}" every ${s}h. Restart the runner to apply.`)});Zu.command("schedules").description("List scheduled audits").action(()=>{let t=de();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`)});Zu.command("unschedule <repoName> <role>").description("Remove a scheduled audit").action((t,e)=>{let n=de(),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");ye(n),g.info("Removed. Restart the runner to apply.")});var Vu=$e.command("deploy").description("Deployment settings for this machine");Vu.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=de();t.deploy={enabled:!0},ye(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."),Vt()});Vu.command("disable").description("Stop this runner from executing any deploy steps").action(()=>{let t=de();t.deploy={enabled:!1},ye(t),g.info("deployments DISABLED on this runner"),Vt()});Vu.command("status").description("Show whether deployments are enabled here, and which env secrets are stored").action(()=>{let t=de();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 Ua=$e.command("env").description("Per-environment deploy secrets. Values stay on this machine, like your Jira token.");Ua.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=de(),s=oo(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 d=l.slice(0,c).trim();i.secrets[d]=l.slice(c+1),o.push(d)}r.environments[s]=i,ye(r),g.info(`stored ${o.length} secret(s) for ${s}: ${o.join(", ")}`),g.info(`Saved to ${nn()} (mode 600, this machine only)`),Vt()});Ua.command("prepare <repoName> <envName>").description("Stand the environment up: systemd unit (nvm-aware PATH, crash-loop limit), scoped passwordless restart for deploys, and a proxy site block when --url is given - Caddy or nginx, whichever is RUNNING on this machine (it never installs a second proxy). 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 proxy").option("--proxy <proxy>","caddy | nginx | none (default: detect the running one; a flag that contradicts the running proxy is refused - two proxies cannot share :80/:443)").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=de().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(()=>(Bg(),Fg));await o({repoName:t,envName:e,dir:yn.default.resolve(i.replace(/^~(?=\/|$)/,Zi.default.homedir())),port:n.port?Number(n.port):void 0,publicUrl:n.url,proxy:n.proxy,dryRun:!!n.dryRun})});Ua.command("unset <repoName> <envName> <names...>").description("Remove stored secrets for an environment").action((t,e,n)=>{let r=de(),s=oo(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,ye(r),g.info(`removed ${n.join(", ")} from ${s}`)});Ua.command("list").description("Show which environments have secrets stored here (names only, never values)").action(()=>{let t=de(),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)"}`)});$e.command("export [file]").description("Back up ALL runner state (config+secrets, knowledge, audits, chats) to one tarball").action(t=>{try{let e=Id(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 ${yn.default.basename(e.file)}`)}catch(e){g.error(e instanceof Error?e.message:String(e)),process.exitCode=1}});$e.command("import <file>").description("Restore runner state from an `export` tarball (existing config is kept as a .bak dir)").action(t=>{let e=cr();if(e&&ur(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=Rd(t);g.info(`Restored ${n.restored.length} entries into ${ie()}`),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}});$e.command("operator <action>").description("THIS MACHINE's lock on operator mode (Compose running commands here): on | off | status | log").action(t=>{let e=de();if(t==="on"||t==="off"){e.operatorEnabled=t==="on",ye(e),t==="on"?g.info("operator mode ENABLED on this machine. Dashboard users who also hold the 'Operator mode' permission can now let the Compose agent run commands here as this runner's user, inside a consented, time-boxed session. Every tool call is recorded (`allwright operator log`). Turn it off any time: `allwright operator off`."):g.info("operator mode DISABLED on this machine - Compose is back to read-only here."),Vt();return}if(t==="status"){g.info(e.operatorEnabled?"operator mode is ENABLED on this machine (allwright operator off to disable).":"operator mode is DISABLED on this machine (allwright operator on to enable).");return}if(t==="log"){let n=lm();if(!n.length){g.info("no operator turns have run on this machine.");return}for(let r of n){g.info(`${r.at} ${r.userName||r.userId||"someone"} [${r.sessionId}] asked: ${r.ask}`);for(let s of r.commands)g.info(` - ${s}`)}return}g.error(`unknown action "${t}" - use on | off | status | log`),process.exitCode=1});$e.command("test").alias("doctor").description("Check local setup: Jira auth, repo mappings, Claude Code binary").action(async()=>{let t=de(),e=Object.keys(t.repos),n=lo(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 Na(t,i),l=!ao(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 d=c.ok?"PASS":"FAIL";(c.ok?g.info:g.error)(`[${d}] ${c.name}: ${c.detail}`),s&&=c.ok}}s||(process.exitCode=1)});function Vt(){let t=cr()??ps();if(t&&ur(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?zd(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 AT(t){if(!t.runnerToken)throw new Error("runner not enrolled - run `allwright init`");let e=Md();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",ml);let n=t.jira?new Ue(t.jira):Bl(),r=new Map,s=u=>{let m=t.repos[u]?.jira;if(!m)return n;let y=r.get(u);return y||(y=new Ue(m),r.set(u,y)),y},i=new Map,o=(u,m)=>{let y=kh(ve()??t,u,m);switch(y.kind){case"legacy":return{jira:s(u),authored:!1};case"self":return{jira:s(u),authored:!0};case"missing":return{error:y.error};case"user":{let x=`${y.creds.baseUrl}:${y.creds.email}:${y.creds.apiToken.slice(-6)}`,M=i.get(x);return M||(M=new Ue(y.creds),i.set(x,M)),{jira:M,authored:!0}}}},l=new URL("/api/runner/ws",t.controlPlaneUrl);l.protocol=l.protocol==="https:"?"wss:":"ws:";let c=[],d=[],p=[],f,w=null,v={cfg:t,jiraFor:s,transport:null},_=new Set,I=async(u,m,y)=>{if(!(m.length<2))for(let x=0;x<m.length;x++){let{text:M,changed:P}=xh(y[x]??"",m);P&&await u.updateDescription(m[x],M).then(()=>g.info(`Compose: rewrote sibling ticket refs in ${m[x]} to real keys`)).catch(Y=>g.warn(`Compose: could not rewrite refs in ${m[x]}: ${Y instanceof Error?Y.message:Y}`))}},R=u=>{let m=c.find(x=>x.id===u),y=m&&t.repos[m.repoName];return m&&y?{project:m,repoPath:y.path}:null},C=u=>{let m=c.find(M=>M.id===u),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 x=Object.keys(t.repos).join(", ")||"(none)";return`${y} has no local checkout for "${m.name}" (repo "${m.repoName}"). Repos mapped here: ${x}. 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`},V={cfg:t,jiraFor:s,get transport(){return v.transport},lookup:(u,m)=>{let y=R(u),x=p.find(M=>M.projectId===u&&M.name===m);return y&&x?{...y,environment:x}:null}},J=new Map,$=new Set,b=new Ca(l.toString(),t.runnerToken,{runnerVersion:So},{onConfig:u=>{c=u.projects,mm(u.projects),d=u.rules,p=u.environments,bf(u.publicIp),f.setConfig(u.projects,u.rules,u.pollingPaused,u.environments)},onDeployFix:async u=>{let m=R(u.projectId);if(!m){b.sendDeploySuggestResult(u.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:C(u.projectId)});return}let y=Ce(t,m.project,"assist");if("error"in y){b.sendDeploySuggestResult(u.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:y.error});return}g.info(`investigating failed deploy of "${u.environmentName}" (step: ${u.failedStep||"?"})`);let x=await Hc({agent:y,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:u.environmentName,steps:u.steps,failedStep:u.failedStep,errorText:u.errorText,cfg:t});b.sendDeploySuggestResult(u.requestId,x)},onProjectTest:async u=>{let m=c.find(x=>x.id===u.projectId);if(!m){b.sendProjectTestResult(u.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 Na(ve()??t,m,p.filter(x=>x.projectId===m.id),d.filter(x=>x.projectId===m.id).map(x=>"agent"in x.action?x.action.agent:"").filter(Boolean));b.sendProjectTestResult(u.requestId,y.every(x=>x.ok),y)},onRuleDiagnose:async u=>{let m=d.find(q=>q.id===u.ruleId),y=m&&c.find(q=>q.id===m.projectId);if(!m||!y){b.sendRuleDiagnoseResult(u.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 x=await Na(ve()??t,y,m.action.type==="deploy"?p.filter(q=>q.projectId===y.id):[]),M=m.action.type==="implement"?x:x.filter(q=>q.name!=="github-token"),{matchedCount:P,excludedCount:Y,excludedSample:B}=await f.diagnoseRule(m,y);b.sendRuleDiagnoseResult(u.requestId,{checks:M,matchedCount:P,excludedCount:Y,excludedSample:B})},onCancel:u=>{Kp(u)?g.info(`run ${u} stopped from the dashboard`):g.warn(`cancel requested for run ${u}, but nothing is running under that id here - it likely finished already`)},onApproved:(u,m)=>{if(ia(u)){qc(V,u).catch(y=>g.error(`deploy approval crashed for ${u}: ${y instanceof Error?y.stack:y}`));return}Si(v,u,m).catch(y=>g.error(`approval handling crashed for ${u}: ${y instanceof Error?y.stack:y}`))},onRetryPush:u=>{let m=Wo(u),y=()=>tf(v,u).catch(x=>g.error(`retry push crashed for ${u}: ${x instanceof Error?x.stack:x}`));m?f.runOnRepoQueue(m.baseRepoPath,y):y()},onRejected:u=>{if(ia(u)){Fc(V,u).catch(m=>g.error(`deploy rejection crashed for ${u}: ${m instanceof Error?m.stack:m}`));return}ef(v,u).catch(m=>g.error(`rejection handling crashed for ${u}: ${m instanceof Error?m.stack:m}`))},onDeployStart:u=>{let m=`${u.runId}#${u.attempt}`;if(_.has(m))return;_.add(m);let y=R(u.projectId);if(!y){let x=C(u.projectId);g.error(`deploy ${u.runId}: ${x}`),b.send({type:"run.status",runId:u.runId,status:"failed",error:x});return}g.info(`deploy ${u.runId} requested from the dashboard: ${u.issueKey} \u2192 ${u.environment.name}`),f.runOnEnvironmentQueue(u.environment.id,()=>Ri({runId:u.runId,project:y.project,environment:u.environment,issueKey:u.issueKey,issueSummary:u.issueSummary,repoPath:y.repoPath,cfg:t,jira:s(y.project.repoName),transport:b,requestedBy:u.requestedBy}).catch(x=>g.error(`deploy crashed for ${u.runId}: ${x instanceof Error?x.stack:x}`)))},onDeploySuggest:async u=>{let m=R(u.projectId);if(!m){b.sendDeploySuggestResult(u.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:C(u.projectId)});return}let y=Ce(t,m.project,"assist");if("error"in y){b.sendDeploySuggestResult(u.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:y.error});return}g.info(`asking ${y.adapter.displayName} for "${u.environmentName}" deploy steps in ${m.repoPath}`);let x=await Kc({agent:y,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:u.environmentName,notes:u.notes,timeoutSeconds:u.timeoutSeconds,cfg:t});b.sendDeploySuggestResult(u.requestId,x)},onEnvPreflight:async u=>{let m=R(u.projectId);if(!m){b.sendEnvPreflightResult(u.requestId,{ok:!1,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project"}]});return}let y=await Bc({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:u.environmentName,steps:u.steps,requiredSecrets:u.requiredSecrets,workdir:u.workdir,branch:u.branch,publicUrl:u.publicUrl,cfg:t});b.sendEnvPreflightResult(u.requestId,y)},onSelfMigrationApply:async u=>{let m=R(u.projectId);if(!m){b.sendSelfMigrationApplyResult(u.requestId,{ok:!1,file:u.file,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project",fix:[]}],output:"",error:C(u.projectId)});return}g.info(`applying migration ${u.file} for "${u.environmentName}"`);let y=await bm({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:u.environmentName,file:u.file,urlSecret:u.urlSecret,cfg:t});g.info(y.ok?`migration ${u.file} applied`:`migration ${u.file} failed: ${y.error}`),b.sendSelfMigrationApplyResult(u.requestId,y)},onAutopilotPlan:async u=>{try{let m=R(u.projectId);if(!m){b.sendAutopilotPlanResult(u.requestId,{ok:!1,error:C(u.projectId)});return}let y=s(m.project.repoName),x=[];for(let D of u.issueKeys)try{let ce=await y.getIssue(D);x.push(`${D}: ${ce.summary}
1189
+ ${(ce.description||"").slice(0,500)}`)}catch{x.push(`${D}: (could not read from Jira)`)}let M=Ce(t,m.project,"assist");if("error"in M){b.sendAutopilotPlanResult(u.requestId,{ok:!1,error:M.error});return}let P=`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.
1180
1190
 
1181
1191
  `+x.join(`
1182
1192
 
@@ -1189,44 +1199,49 @@ Rules:
1189
1199
  - "order": every key exactly once. Prerequisites before the work that needs them.
1190
1200
  - "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.
1191
1201
  - "dependencies": ONLY hard prerequisites, where the blocked ticket CANNOT pass if the other failed. An empty list is the normal answer.
1192
- - "reasoning": 2-3 short lines a person can check your plan against.`,Z=await P.adapter.run({repoPath:m.repoPath,prompt:O,timeoutSeconds:90,bin:P.bin,mode:"read_only",maxTurns:3,model:P.adapter.fastModel,sessionId:(0,qn.randomUUID)(),onLog:()=>{}}),W=Vc(Z.resultText,u.issueKeys);if(!W){b.sendAutopilotPlanResult(u.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(()=>(oa(),Ef));B({batchId:u.batchId,projectId:u.projectId,order:W.order,chains:W.chains,dependencies:W.dependencies,reasoning:W.reasoning}),b.sendAutopilotPlanResult(u.requestId,{ok:!0,...W})}catch(m){b.sendAutopilotPlanResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onChatDiagnostic:async u=>{try{let{runDiagnostic:m}=await Promise.resolve().then(()=>(Ou(),bg)),g=await m({command:u.command,args:u.args});y.info(`chat diagnostic (user-approved): ${g.commandLine}`),b.sendChatDiagnosticResult(u.requestId,g)}catch(m){b.sendChatDiagnosticResult(u.requestId,{ok:!1,output:m instanceof Error?m.message:String(m)})}},onChatStepRun:async u=>{let m=Y.lookup(u.projectId,u.environmentName);if(!m){b.sendChatStepRunResult(u.requestId,{ok:!1,error:`this runner has no environment "${u.environmentName}" for that project`});return}let{environment:g}=m,x=g.steps[u.stepIndex];if(!x||x.name!==u.stepName){b.sendChatStepRunResult(u.requestId,{ok:!1,error:`step ${u.stepIndex+1} of "${g.name}" is ${x?`"${x.name}"`:"not there"} on this machine, not "${u.stepName}" - the recipe changed since the chat read it. Reopen the environment and ask again.`});return}let P=`${u.projectId}:${g.name}:${u.stepIndex}`;if($.has(P)){b.sendChatStepRunResult(u.requestId,{ok:!1,stepName:x.name,error:"that step is already running here - wait for it to finish"});return}$.add(P),y.info(`chat step re-run (user-approved): [${g.name}] ${x.name}`);try{let{runSavedStep:O}=await Promise.resolve().then(()=>(Os(),If)),Z=await O({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:g.name,workdir:g.workdir,branch:g.branch,step:x,cfg:t,timeoutMs:Math.min(g.timeoutSeconds*1e3,M0)});b.sendChatStepRunResult(u.requestId,{ok:!0,stepName:x.name,...Z})}catch(O){b.sendChatStepRunResult(u.requestId,{ok:!1,stepName:x.name,error:O instanceof Error?O.message:String(O)})}finally{$.delete(P)}},onChatCancel:u=>{let m=X.get(u.turnId);m&&(m.abort(),y.info(`chat turn ${u.turnId} stopped from the dashboard`))},onChatTurn:async u=>{let m=E(u.projectId);if(!m){b.sendChatTurnResult(u.requestId,{ok:!1,sessionId:u.sessionId??"",reply:"",error:C(u.projectId)});return}let g=u.sessionId||(0,qn.randomUUID)(),x=!u.sessionId;if(!x&&u.userId){let Te=Ms(g)?.ownerUserId??"";if(Te&&Te!==u.userId){b.sendChatTurnResult(u.requestId,{ok:!1,sessionId:g,reply:"",error:"this chat belongs to someone else - you can read it, but only its owner can continue it. Start your own chat for this."});return}}let P=u.operator===!0;if(P&&!t.operatorEnabled){b.sendChatTurnResult(u.requestId,{ok:!1,sessionId:g,reply:"",error:"operator mode is not enabled on this machine. Whoever administers the server must run `allwright operator on` there once (and `allwright operator off` turns it back off) - a dashboard permission alone is deliberately not enough."});return}let O=x?0:Ms(g)?.messages.length??0,Z=!1,W=0,B="";if(!x&&O>=Bf){let Te=await Gf(m,g,t);if(Te)Z=!0,W=O,B=Te,g=(0,qn.randomUUID)(),x=!0,y.info(`chat compacted: ${O} message(s) summarized into a fresh session`);else if(O>=Hf){b.sendChatTurnResult(u.requestId,{ok:!1,sessionId:g,reply:"",error:"this chat is very long and could not be compacted automatically - start a new chat (it keeps the repo knowledge; only the conversation resets)."});return}}let D=u.files.length?kd(m.repoPath,u.requestId,u.files):null,ue=(0,Se.replyPreferenceAppendix)({language:u.replyLanguage,languageInstruction:u.replyLanguageInstruction,style:u.replyStyle})+(0,Se.pendingMigrationsAppendix)(u.pendingMigrations)+(0,Se.deployTargetsAppendix)(u.environments)+(0,Se.savedStepChecksAppendix)(u.environmentSteps)+(0,Se.composeCommandAppendix)(u.command),V=z0(m.repoPath);Fo(m,t);let ae="```",xe=x?`You are the project assistant for "${m.project.name}" - this working directory is its repository, and you have read-only access.
1202
+ - "reasoning": 2-3 short lines a person can check your plan against.`,Y=await M.adapter.run({repoPath:m.repoPath,prompt:P,timeoutSeconds:90,bin:M.bin,mode:"read_only",maxTurns:3,model:M.adapter.fastModel,sessionId:(0,Hn.randomUUID)(),onLog:()=>{}}),B=su(Y.resultText,u.issueKeys);if(!B){b.sendAutopilotPlanResult(u.requestId,{ok:!1,error:"the planner's answer could not be parsed - the queue keeps its given order"});return}let{saveBatchPlan:q}=await Promise.resolve().then(()=>(ua(),Mf));q({batchId:u.batchId,projectId:u.projectId,order:B.order,chains:B.chains,dependencies:B.dependencies,reasoning:B.reasoning}),b.sendAutopilotPlanResult(u.requestId,{ok:!0,...B})}catch(m){b.sendAutopilotPlanResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onChatDiagnostic:async u=>{try{let{runDiagnostic:m}=await Promise.resolve().then(()=>(Bu(),Cg)),y=await m({command:u.command,args:u.args});g.info(`chat diagnostic (user-approved): ${y.commandLine}`),b.sendChatDiagnosticResult(u.requestId,y)}catch(m){b.sendChatDiagnosticResult(u.requestId,{ok:!1,output:m instanceof Error?m.message:String(m)})}},onChatStepRun:async u=>{let m=V.lookup(u.projectId,u.environmentName);if(!m){b.sendChatStepRunResult(u.requestId,{ok:!1,error:`this runner has no environment "${u.environmentName}" for that project`});return}let{environment:y}=m,x=y.steps[u.stepIndex];if(!x||x.name!==u.stepName){b.sendChatStepRunResult(u.requestId,{ok:!1,error:`step ${u.stepIndex+1} of "${y.name}" is ${x?`"${x.name}"`:"not there"} on this machine, not "${u.stepName}" - the recipe changed since the chat read it. Reopen the environment and ask again.`});return}let M=`${u.projectId}:${y.name}:${u.stepIndex}`;if($.has(M)){b.sendChatStepRunResult(u.requestId,{ok:!1,stepName:x.name,error:"that step is already running here - wait for it to finish"});return}$.add(M),g.info(`chat step re-run (user-approved): [${y.name}] ${x.name}`);try{let{runSavedStep:P}=await Promise.resolve().then(()=>(Ms(),Of)),Y=await P({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:y.name,workdir:y.workdir,branch:y.branch,step:x,cfg:t,timeoutMs:Math.min(y.timeoutSeconds*1e3,IT)});b.sendChatStepRunResult(u.requestId,{ok:!0,stepName:x.name,...Y})}catch(P){b.sendChatStepRunResult(u.requestId,{ok:!1,stepName:x.name,error:P instanceof Error?P.message:String(P)})}finally{$.delete(M)}},onChatCancel:u=>{let m=J.get(u.turnId);m&&(m.abort(),g.info(`chat turn ${u.turnId} stopped from the dashboard`))},onChatTurn:async u=>{let m=R(u.projectId);if(!m){b.sendChatTurnResult(u.requestId,{ok:!1,sessionId:u.sessionId??"",reply:"",error:C(u.projectId)});return}let y=u.sessionId||(0,Hn.randomUUID)(),x=!u.sessionId,M=u.sessionId?Gr(u.sessionId):null,P=M?.agentId||u.agentId||m.project.defaultAgent||ke.DEFAULT_AGENT_ID;if(!x&&u.userId){let Ie=M?.ownerUserId??"";if(Ie&&Ie!==u.userId){b.sendChatTurnResult(u.requestId,{ok:!1,sessionId:y,reply:"",error:"this chat belongs to someone else - you can read it, but only its owner can continue it. Start your own chat for this."});return}}let Y=u.operator===!0;if(Y&&!t.operatorEnabled){b.sendChatTurnResult(u.requestId,{ok:!1,sessionId:y,reply:"",error:"operator mode is not enabled on this machine. Whoever administers the server must run `allwright operator on` there once (and `allwright operator off` turns it back off) - a dashboard permission alone is deliberately not enough."});return}let B=x?0:M?.messages.length??0,q=!1,D=0,ce="";if(!x&&B>=Xf){let Ie=await tm(m,y,t);if(Ie)q=!0,D=B,ce=Ie,y=(0,Hn.randomUUID)(),x=!0,g.info(`chat compacted: ${B} message(s) summarized into a fresh session`);else if(B>=Qf){b.sendChatTurnResult(u.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 Z=u.files.length?Cd(m.repoPath,u.requestId,u.files):null,re=(0,ke.replyPreferenceAppendix)({language:u.replyLanguage,languageInstruction:u.replyLanguageInstruction,style:u.replyStyle})+(0,ke.pendingMigrationsAppendix)(u.pendingMigrations)+(0,ke.deployTargetsAppendix)(u.environments)+(0,ke.savedStepChecksAppendix)(u.environmentSteps)+(0,ke.composeCommandAppendix)(u.command),xe=RT(m.repoPath);Ko(m,t);let Pe="```",Ke=x?`You are the project assistant for "${m.project.name}" - this working directory is its repository, and you have read-only access.
1193
1203
 
1194
1204
  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.
1195
1205
  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.
1196
1206
 
1197
- `+(P?"":`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:
1198
- ${ae}diagnose
1207
+ `+(Y?"":`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:
1208
+ ${Pe}diagnose
1199
1209
  {"command": "<id>", "args": {...}, "why": "one line the user reads before approving"}
1200
- ${ae}
1210
+ ${Pe}
1201
1211
  Catalogue (nothing else exists):
1202
- ${Nu()}
1203
- 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.`)+Se.TICKET_RULES_APPENDIX+`
1212
+ ${Fu()}
1213
+ 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.`)+ke.TICKET_RULES_APPENDIX+`
1204
1214
 
1205
- `+V+di(m.project.repoName)+Wf+(B?`
1215
+ `+xe+fi(m.project.repoName)+rm+(ce?`
1206
1216
 
1207
1217
  This conversation was already running and has been compacted. Everything agreed so far, in summary form - treat it as established, do not re-ask:
1208
- ${B}
1209
- `:"")+ue+`
1210
- ${u.userName||"The user"} says: ${u.message}`+(D?.section??""):ue+Se.TICKET_RULES_APPENDIX+`
1218
+ ${ce}
1219
+ `:"")+re+`
1220
+ ${u.userName||"The user"} says: ${u.message}`+(Z?.section??""):re+ke.TICKET_RULES_APPENDIX+`
1211
1221
 
1212
- `+V+`
1213
- ${u.userName||"The user"} says: ${u.message}`+(D?.section??""),Ne=0,Be=0,Bn=new Date;Uf(u.projectId,g,u.message,u.files.map(Te=>Te.name),Bn.toISOString(),u.userId),b.send({type:"chat.session",requestId:u.requestId,sessionId:g});let st=[],fe=[],J;try{let Te=Ce(t,m.project,P?"operator":"chat");if("error"in Te){ca(g),b.sendChatTurnResult(u.requestId,{ok:!1,sessionId:g,reply:"",error:Te.error});return}let Hn=new AbortController;X.set(u.requestId,Hn);let Hg=Date.now(),qu={repoPath:m.repoPath,prompt:xe,signal:Hn.signal,timeoutSeconds:$0,bin:Te.bin,mode:P?"operator":"read_only",maxTurns:25,model:u.model||Te.adapter.fastModel,sessionId:g,resume:!x,onLog:(je,it)=>{je==="agent"&&(st.push(it.slice(0,4e3)),b.send({type:"chat.stream",requestId:u.requestId,seq:Ne++,text:it.slice(0,8e3)}))},onTool:(je,it)=>{P&&(fe.push(`${je}: ${it}`),st.push(`${je}: ${it}`.slice(0,4e3))),b.send({type:"chat.activity",requestId:u.requestId,seq:Be++,verb:je,target:it})},onUsage:je=>{b.send({type:"chat.usage",requestId:u.requestId,inputTokens:Math.round(je.inputTokens),outputTokens:Math.round(je.outputTokens),cacheReadTokens:je.cacheReadTokens===void 0?void 0:Math.round(je.cacheReadTokens),turns:je.turns})}};J=await Te.adapter.run(qu);let Pa=0;for(;!J.ok&&J.turnLimitHit&&!J.cancelled&&Te.adapter.capabilities.sessionResume&&Pa<Ug;){let je=Lg-(Date.now()-Hg);if(je<P0)break;Pa++,y.info(`chat turn ${u.requestId}: turn limit hit - resuming the same session (resume ${Pa}/${Ug}, ${Math.round(je/1e3)}s left)`);let it=await Te.adapter.run({...qu,prompt:je<=j0?N0:O0,resume:!0,timeoutSeconds:Math.floor(je/1e3)});it.costUsd+=J.costUsd,it.inputTokens+=J.inputTokens,it.outputTokens+=J.outputTokens,it.cacheReadTokens+=J.cacheReadTokens,J=it}!J.ok&&(J.turnLimitHit||J.timedOut)&&!J.resultText.trim()&&st.length&&(J.resultText=D0(st))}finally{if(X.delete(u.requestId),D&&rt.default.rmSync(D.dir,{recursive:!0,force:!0}),P&&fe.length)try{Yf({projectId:u.projectId,sessionId:g,userId:u.userId,userName:u.userName,ask:u.message,commands:fe})}catch(Te){y.warn(`operator ledger write failed: ${Te instanceof Error?Te.message:Te}`)}}if(J.cancelled){ca(g),b.sendChatTurnResult(u.requestId,{ok:!1,sessionId:g,reply:"",error:"stopped by you - the reply was cut off and nothing was saved to this chat",inputTokens:J.inputTokens,outputTokens:J.outputTokens,cacheReadTokens:J.cacheReadTokens});return}if(!J.ok&&J.timedOut&&(J.error=`this has been running for ${Math.round(Lg/6e4)} minutes, so I stopped to check in - nothing is lost. What it had worked out is below; say "continue" and it picks up in the same session, exactly where it left off. If it is really a job rather than a question, make it a ticket instead: a full run has hours, and can change code and open a PR.`),J.ok||J.resultText.trim()){let Te=st.filter(Hn=>Hn.trim()&&!J.resultText.trim().startsWith(Hn.trim()));J.ok||(J.resultText=`${J.resultText.trim()}
1222
+ `+xe+`
1223
+ ${u.userName||"The user"} says: ${u.message}`+(Z?.section??""),Ys=0,wn=0,fe=new Date;Vf(u.projectId,y,u.message,u.files.map(Ie=>Ie.name),fe.toISOString(),u.userId,P),b.send({type:"chat.session",requestId:u.requestId,sessionId:y});let Ze=[],qa=[],ne;try{let Ie=Ce(t,m.project,Y?"operator":"chat",P);if("error"in Ie){pa(y),b.sendChatTurnResult(u.requestId,{ok:!1,sessionId:y,reply:"",error:Ie.error});return}let Gn=new AbortController;J.set(u.requestId,Gn);let wy=Date.now(),Ju={repoPath:m.repoPath,prompt:Ke,signal:Gn.signal,timeoutSeconds:kT,bin:Ie.bin,mode:Y?"operator":"read_only_web",maxTurns:25,model:u.model||Ie.adapter.fastModel,sessionId:y,resume:!x,onLog:(Me,ot)=>{Me==="agent"&&(Ze.push(ot.slice(0,4e3)),b.send({type:"chat.stream",requestId:u.requestId,seq:Ys++,text:ot.slice(0,8e3)}))},onTool:(Me,ot)=>{Y&&(qa.push(`${Me}: ${ot}`),Ze.push(`${Me}: ${ot}`.slice(0,4e3))),b.send({type:"chat.activity",requestId:u.requestId,seq:wn++,verb:Me,target:ot})},onUsage:Me=>{b.send({type:"chat.usage",requestId:u.requestId,inputTokens:Math.round(Me.inputTokens),outputTokens:Math.round(Me.outputTokens),cacheReadTokens:Me.cacheReadTokens===void 0?void 0:Math.round(Me.cacheReadTokens),turns:Me.turns})}};ne=await Ie.adapter.run(Ju);let Fa=0;for(;!ne.ok&&ne.turnLimitHit&&!ne.cancelled&&Ie.adapter.capabilities.sessionResume&&Fa<my;){let Me=fy-(Date.now()-wy);if(Me<_T)break;Fa++,g.info(`chat turn ${u.requestId}: turn limit hit - resuming the same session (resume ${Fa}/${my}, ${Math.round(Me/1e3)}s left)`);let ot=await Ie.adapter.run({...Ju,prompt:Me<=xT?ST:TT,resume:!0,timeoutSeconds:Math.floor(Me/1e3)});ot.costUsd+=ne.costUsd,ot.inputTokens+=ne.inputTokens,ot.outputTokens+=ne.outputTokens,ot.cacheReadTokens+=ne.cacheReadTokens,ne=ot}!ne.ok&&(ne.turnLimitHit||ne.timedOut)&&!ne.resultText.trim()&&Ze.length&&(ne.resultText=ET(Ze))}finally{if(J.delete(u.requestId),Z&&it.default.rmSync(Z.dir,{recursive:!0,force:!0}),Y&&qa.length)try{am({projectId:u.projectId,sessionId:y,userId:u.userId,userName:u.userName,ask:u.message,commands:qa})}catch(Ie){g.warn(`operator ledger write failed: ${Ie instanceof Error?Ie.message:Ie}`)}}if(ne.cancelled){pa(y),b.sendChatTurnResult(u.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&&ne.timedOut&&(ne.error=`this has been running for ${Math.round(fy/6e4)} minutes, so I stopped to check in - nothing is lost. What it had worked out is below; say "continue" and it picks up in the same session, exactly where it left off. If it is really a job rather than a question, make it a ticket instead: a full run has hours, and can change code and open a PR.`),ne.ok||ne.resultText.trim()){let Ie=Ze.filter(Gn=>Gn.trim()&&!ne.resultText.trim().startsWith(Gn.trim()));ne.ok||(ne.resultText=`${ne.resultText.trim()}
1214
1224
 
1215
1225
  ---
1216
- _Unfinished: ${J.error||"the turn ended early"}._`),qf(u.projectId,g,u.message,J.resultText,Te,u.files.map(Hn=>Hn.name),{askedAt:Bn.toISOString(),ms:Date.now()-Bn.getTime(),tokens:(J.inputTokens??0)+(J.outputTokens??0)},u.userId)}else ca(g);let Bg=(J.inputTokens??0)+(J.cacheReadTokens??0);b.sendChatTurnResult(u.requestId,{contextTokens:Bg,contextLimit:Kf(J.model||u.model||""),compacted:Z,compactedMessages:W,ok:J.ok,sessionId:g,reply:J.resultText,outputTruncated:!!J.outputTruncated,error:J.ok?void 0:J.error??"the agent produced no reply",inputTokens:J.inputTokens,outputTokens:J.outputTokens,cacheReadTokens:J.cacheReadTokens,costUsd:J.costUsd,model:J.model??""})},onChatList:u=>{b.sendChatListResult(u.requestId,Ff(u.projectId))},onRepoDocs:u=>{let m=E(u.projectId);if(!m){b.sendRepoDocsResult(u.requestId,{ok:!1,docs:[],error:C(u.projectId)});return}b.sendRepoDocsResult(u.requestId,{ok:!0,docs:Qf(m.repoPath)})},onRepoDocRead:u=>{let m=E(u.projectId);if(!m){b.sendRepoDocReadResult(u.requestId,{ok:!1,path:u.path,content:"",truncated:!1,error:C(u.projectId)});return}let g=em(m.repoPath,u.path);b.sendRepoDocReadResult(u.requestId,{ok:g.ok,path:g.ok?g.path:u.path,content:g.ok?g.content:"",truncated:g.ok?g.truncated:!1,error:g.ok?void 0:g.error})},onChatLoad:u=>{let m=Ms(u.sessionId);b.sendChatLoadResult(u.requestId,{ok:m!==null,projectId:m?.projectId??"",ownerUserId:m?.ownerUserId??"",messages:m?.messages??[],error:m?void 0:"chat not found on this runner (pruned or never existed)"})},onBoardFetch:async u=>{let m=E(u.projectId);if(!m){b.sendBoardFetchResult(u.requestId,{ok:!1,columns:[],error:C(u.projectId)});return}try{let g=s(m.project.repoName),x;try{x=await g.searchBoard(`project = "${m.project.jiraProjectKey}" ORDER BY Rank ASC`,100)}catch{x=await g.searchBoard(`project = "${m.project.jiraProjectKey}" ORDER BY updated DESC`,100)}let P=await g.boardColumns(m.project.jiraProjectKey),O;if(P){O=P.map(B=>({name:B.name,issues:[]}));let W=new Map;for(let B of x){let D=P.findIndex(V=>V.statusIds.includes(B.statusId)),ue={key:B.key,summary:B.summary,labels:B.labels};if(D>=0)O[D].issues.push(ue);else{let V=W.get(B.status)??[];V.push(ue),W.set(B.status,V)}}for(let[B,D]of W)O.push({name:B,issues:D})}else{let W=ae=>ae.trim().toLowerCase(),B=new Map,D=new Map;for(let ae of x){let xe=W(ae.status);B.has(xe)||B.set(xe,ae.status.trim());let Ne=D.get(xe)??[];Ne.push({key:ae.key,summary:ae.summary,labels:ae.labels}),D.set(xe,Ne)}let ue=[];try{ue=await g.projectStatuses(m.project.jiraProjectKey)}catch{}let V=[];for(let ae of ue){let xe=W(ae);!V.includes(xe)&&D.has(xe)&&V.push(xe)}for(let ae of D.keys())V.includes(ae)||V.push(ae);O=V.map(ae=>({name:B.get(ae)??ae,issues:D.get(ae)??[]}))}let Z=t.repos[m.project.repoName]?.jira??t.jira;b.sendBoardFetchResult(u.requestId,{ok:!0,browseBaseUrl:(Z?.baseUrl??"").replace(/\/+$/,""),columns:O})}catch(g){b.sendBoardFetchResult(u.requestId,{ok:!1,columns:[],error:g instanceof Error?g.message:String(g)})}},onBoardTrigger:async u=>{let m=E(u.projectId);if(!m){b.sendBoardTriggerResult(u.requestId,{ok:!1,error:C(u.projectId)});return}try{let g=s(m.project.repoName),x=u.comment.trim()?o(m.project.repoName,u.requestedByEmail):{jira:g,authored:!1};if(x.error!==void 0){b.sendBoardTriggerResult(u.requestId,{ok:!1,error:x.error});return}if(u.reimplement){let P=await g.getIssue(u.issueKey),O=P.comments.filter(B=>pt(B.body)),Z=O.length?Math.max(...O.map(B=>new Date(B.created).getTime())):0;if(!P.comments.some(B=>!pt(B.body)&&new Date(B.created).getTime()>Z)){b.sendBoardTriggerResult(u.requestId,{ok:!1,error:`${u.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(u.issueKey,{remove:["agent-implemented"]})}u.removeLabel.trim()&&await g.editLabels(u.issueKey,{remove:[u.removeLabel.trim()]}),u.comment.trim()&&await x.jira.addTriggerComment(u.issueKey,`${u.comment.trim()}`+(!x.authored&&u.requestedBy?`
1226
+ _Unfinished: ${ne.error||"the turn ended early"}._`),Jf(u.projectId,y,u.message,ne.resultText,Ie,u.files.map(Gn=>Gn.name),{askedAt:fe.toISOString(),ms:Date.now()-fe.getTime(),tokens:(ne.inputTokens??0)+(ne.outputTokens??0)},u.userId,P)}else pa(y);let by=(ne.inputTokens??0)+(ne.cacheReadTokens??0);b.sendChatTurnResult(u.requestId,{contextTokens:by,contextLimit:em(ne.model||u.model||""),compacted:q,compactedMessages:D,ok:ne.ok,sessionId:y,reply:ne.resultText,outputTruncated:!!ne.outputTruncated,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:u=>{b.sendChatListResult(u.requestId,Yf(u.projectId))},onRepoDocs:u=>{let m=R(u.projectId);if(!m){b.sendRepoDocsResult(u.requestId,{ok:!1,docs:[],error:C(u.projectId)});return}b.sendRepoDocsResult(u.requestId,{ok:!0,docs:dm(m.repoPath)})},onRepoDocRead:u=>{let m=R(u.projectId);if(!m){b.sendRepoDocReadResult(u.requestId,{ok:!1,path:u.path,content:"",truncated:!1,error:C(u.projectId)});return}let y=hm(m.repoPath,u.path);b.sendRepoDocReadResult(u.requestId,{ok:y.ok,path:y.ok?y.path:u.path,content:y.ok?y.content:"",truncated:y.ok?y.truncated:!1,error:y.ok?void 0:y.error})},onChatLoad:u=>{let m=Gr(u.sessionId);b.sendChatLoadResult(u.requestId,{ok:m!==null,projectId:m?.projectId??"",ownerUserId:m?.ownerUserId??"",agentId:m?.agentId??"",messages:m?.messages??[],error:m?void 0:"chat not found on this runner (pruned or never existed)"})},onBoardFetch:async u=>{let m=R(u.projectId);if(!m){b.sendBoardFetchResult(u.requestId,{ok:!1,columns:[],error:C(u.projectId)});return}try{let y=s(m.project.repoName),x;try{x=await y.searchBoard(`project = "${m.project.jiraProjectKey}" ORDER BY Rank ASC`,100)}catch{x=await y.searchBoard(`project = "${m.project.jiraProjectKey}" ORDER BY updated DESC`,100)}let M=await y.boardColumns(m.project.jiraProjectKey),P;if(M){P=M.map(q=>({name:q.name,issues:[]}));let B=new Map;for(let q of x){let D=M.findIndex(Z=>Z.statusIds.includes(q.statusId)),ce={key:q.key,summary:q.summary,labels:q.labels};if(D>=0)P[D].issues.push(ce);else{let Z=B.get(q.status)??[];Z.push(ce),B.set(q.status,Z)}}for(let[q,D]of B)P.push({name:q,issues:D})}else{let B=re=>re.trim().toLowerCase(),q=new Map,D=new Map;for(let re of x){let xe=B(re.status);q.has(xe)||q.set(xe,re.status.trim());let Pe=D.get(xe)??[];Pe.push({key:re.key,summary:re.summary,labels:re.labels}),D.set(xe,Pe)}let ce=[];try{ce=await y.projectStatuses(m.project.jiraProjectKey)}catch{}let Z=[];for(let re of ce){let xe=B(re);!Z.includes(xe)&&D.has(xe)&&Z.push(xe)}for(let re of D.keys())Z.includes(re)||Z.push(re);P=Z.map(re=>({name:q.get(re)??re,issues:D.get(re)??[]}))}let Y=t.repos[m.project.repoName]?.jira??t.jira;b.sendBoardFetchResult(u.requestId,{ok:!0,browseBaseUrl:(Y?.baseUrl??"").replace(/\/+$/,""),columns:P})}catch(y){b.sendBoardFetchResult(u.requestId,{ok:!1,columns:[],error:y instanceof Error?y.message:String(y)})}},onBoardTrigger:async u=>{let m=R(u.projectId);if(!m){b.sendBoardTriggerResult(u.requestId,{ok:!1,error:C(u.projectId)});return}try{let y=s(m.project.repoName),x=u.comment.trim()?o(m.project.repoName,u.requestedByEmail):{jira:y,authored:!1};if(x.error!==void 0){b.sendBoardTriggerResult(u.requestId,{ok:!1,error:x.error});return}if(u.reimplement){let M=await y.getIssue(u.issueKey),P=M.comments.filter(q=>ft(q.body)),Y=P.length?Math.max(...P.map(q=>new Date(q.created).getTime())):0;if(!M.comments.some(q=>!ft(q.body)&&new Date(q.created).getTime()>Y)){b.sendBoardTriggerResult(u.requestId,{ok:!1,error:`${u.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(u.issueKey,{remove:["agent-implemented"]})}u.removeLabel.trim()&&await y.editLabels(u.issueKey,{remove:[u.removeLabel.trim()]}),u.comment.trim()&&await x.jira.addTriggerComment(u.issueKey,`${u.comment.trim()}`+(!x.authored&&u.requestedBy?`
1217
1227
 
1218
- _(requested by ${u.requestedBy} via Allwright)_`:"")),y.info(`Board action on ${u.issueKey}`+(u.comment?` comment "${u.comment.trim()}"`:"")+(u.removeLabel?` -label ${u.removeLabel}`:"")+(u.requestedBy?` by ${u.requestedBy}`:"")),b.sendBoardTriggerResult(u.requestId,{ok:!0})}catch(g){b.sendBoardTriggerResult(u.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onChatCreateTicket:async u=>{let m=E(u.projectId);if(!m){b.sendChatCreateTicketResult(u.requestId,{ok:!1,issueKey:"",error:C(u.projectId)});return}try{let g=o(m.project.repoName,u.requestedByEmail);if(g.error!==void 0){b.sendChatCreateTicketResult(u.requestId,{ok:!1,issueKey:"",error:g.error});return}let x=`
1228
+ _(requested by ${u.requestedBy} via Allwright)_`:"")),g.info(`Board action on ${u.issueKey}`+(u.comment?` comment "${u.comment.trim()}"`:"")+(u.removeLabel?` -label ${u.removeLabel}`:"")+(u.requestedBy?` by ${u.requestedBy}`:"")),b.sendBoardTriggerResult(u.requestId,{ok:!0})}catch(y){b.sendBoardTriggerResult(u.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onChatCreateTicket:async u=>{let m=R(u.projectId);if(!m){b.sendChatCreateTicketResult(u.requestId,{ok:!1,issueKey:"",error:C(u.projectId)});return}try{let y=o(m.project.repoName,u.requestedByEmail);if(y.error!==void 0){b.sendChatCreateTicketResult(u.requestId,{ok:!1,issueKey:"",error:y.error});return}let x=`
1219
1229
 
1220
1230
  ---
1221
- _Created via Allwright Compose`+(!g.authored&&u.requestedBy?` by ${u.requestedBy}`:"")+", drafted with the project agent._";if(u.asEpic&&u.createAs!=="epic_with_children"&&u.children.length){let Z=u.createAs==="separate_epics"?"Epic":"Task",W=[],B=[];for(let D of u.children){let ue=(D.description||"(no description)")+x,V=await g.jira.createIssue(m.project.jiraProjectKey,D.summary,ue,Z);W.push(V.key),B.push(ue)}await I(g.jira,W,B),y.info(`Compose created ${W.length} standalone ${Z.toLowerCase()}(s)`),b.sendChatCreateTicketResult(u.requestId,{ok:!0,issueKey:W[0]??"",childKeys:W});return}let{key:P}=await g.jira.createIssue(m.project.jiraProjectKey,u.summary,(u.description||"(no description)")+x,u.asEpic?"Epic":"Task");u.files.length&&await g.jira.addAttachments(P,u.files.map(Z=>({name:Z.name,content:Buffer.from(Z.contentBase64,"base64")}))).then(()=>y.info(`Compose attached ${u.files.length} file(s) to ${P}`)).catch(Z=>y.warn(`Compose could not attach files to ${P}: ${Z instanceof Error?Z.message:Z}`));let O=[];if(u.asEpic){let Z=[];for(let W of u.children){let B=(W.description||"(no description)")+x,D=await g.jira.createIssue(m.project.jiraProjectKey,W.summary,B,"Task",P);O.push(D.key),Z.push(B)}await I(g.jira,O,Z),y.info(`Compose created epic ${P} with ${O.length} child ticket(s)`),b.sendChatCreateTicketResult(u.requestId,{ok:!0,issueKey:P,childKeys:O});return}u.triggerComment.trim()&&await g.jira.addTriggerComment(P,`${u.triggerComment.trim()}`+(!g.authored&&u.requestedBy?`
1231
+ _Created via Allwright Compose`+(!y.authored&&u.requestedBy?` by ${u.requestedBy}`:"")+", drafted with the project agent._",M="";if(u.chatSessionId&&(!u.asEpic||u.createAs==="epic_with_children")){let B=Gr(u.chatSessionId)?.ownerUserId??"";if(!B||!u.userId||B===u.userId){let q=await nm(m,u.chatSessionId,t);q&&(M=`
1222
1232
 
1223
- _(requested by ${u.requestedBy} via Allwright)_`:"")),y.info(`Compose created ${P}`+(u.requestedBy?` for ${u.requestedBy}`:"")+(u.triggerComment?` with trigger "${u.triggerComment.trim()}"`:"")),b.sendChatCreateTicketResult(u.requestId,{ok:!0,issueKey:P})}catch(g){b.sendChatCreateTicketResult(u.requestId,{ok:!1,issueKey:"",error:g instanceof Error?g.message:String(g)})}},onAuditStart:async u=>{let m=E(u.projectId);if(!m){b.sendAuditStartResult(u.requestId,{ok:!1,error:C(u.projectId)});return}try{y.info(`Audit (${u.role}) starting on ${m.project.repoName}`+(u.scope.kind!=="repo"?` scoped to ${u.scope.kind}:${u.scope.ref}`:""));let g=Ce(t,m.project,"assist");if("error"in g){b.sendAuditStartResult(u.requestId,{ok:!1,error:g.error});return}let x=await Es({projectId:u.projectId,repoPath:m.repoPath,role:u.role,scope:u.scope,detailLevel:u.detailLevel,model:u.model,agent:g,jira:s(m.project.repoName),baseUrl:u.baseUrl});if(!x.ok){b.sendAuditStartResult(u.requestId,{ok:!1,error:x.error});return}b.sendAuditStartResult(u.requestId,{ok:!0,audit:x.audit})}catch(g){b.sendAuditStartResult(u.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onAuditList:async u=>{try{b.sendAuditListResult(u.requestId,{ok:!0,audits:Oh(u.projectId)})}catch(m){b.sendAuditListResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditExplain:async u=>{try{let m=Hl(u.projectId,u.auditId),g=m?.findings.find(B=>B.id===u.findingId);if(!m||!g){b.sendAuditExplainResult(u.requestId,{ok:!1,error:"that finding is not on this runner any more"});return}let x=E(u.projectId);if(!x){b.sendAuditExplainResult(u.requestId,{ok:!1,error:C(u.projectId)});return}let P=Ce(t,x.project,"assist");if("error"in P){b.sendAuditExplainResult(u.requestId,{ok:!1,error:P.error});return}let O=`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.
1233
+ ----
1234
+ *Context from the Compose chat this ticket came from (machine-summarized ${new Date().toISOString().slice(0,10)} - the code may have moved since; verify against the repo):*
1224
1235
 
1225
- FINDING (${g.severity}${g.ruleId?`, rule ${g.ruleId}`:""}):
1226
- ${g.title}
1227
- `+g.evidence.map(B=>`- ${B.file}${B.line?`:${B.line}`:""} ${B.note}`.trim()).join(`
1228
- `)+(g.fix?`
1229
- Proposed fix: ${g.fix}`:"")+`
1236
+ ${q}`)}}if(u.asEpic&&u.createAs!=="epic_with_children"&&u.children.length){let B=u.createAs==="separate_epics"?"Epic":"Task",q=[],D=[];for(let ce of u.children){let Z=(ce.description||"(no description)")+x,re=await y.jira.createIssue(m.project.jiraProjectKey,ce.summary,Z,B);q.push(re.key),D.push(Z)}await I(y.jira,q,D),g.info(`Compose created ${q.length} standalone ${B.toLowerCase()}(s)`),b.sendChatCreateTicketResult(u.requestId,{ok:!0,issueKey:q[0]??"",childKeys:q});return}let{key:P}=await y.jira.createIssue(m.project.jiraProjectKey,u.summary,(u.description||"(no description)")+M+x,u.asEpic?"Epic":"Task");u.files.length&&await y.jira.addAttachments(P,u.files.map(B=>({name:B.name,content:Buffer.from(B.contentBase64,"base64")}))).then(()=>g.info(`Compose attached ${u.files.length} file(s) to ${P}`)).catch(B=>g.warn(`Compose could not attach files to ${P}: ${B instanceof Error?B.message:B}`));let Y=[];if(u.asEpic){let B=[];for(let q of u.children){let D=(q.description||"(no description)")+x,ce=await y.jira.createIssue(m.project.jiraProjectKey,q.summary,D,"Task",P);Y.push(ce.key),B.push(D)}await I(y.jira,Y,B),g.info(`Compose created epic ${P} with ${Y.length} child ticket(s)`),b.sendChatCreateTicketResult(u.requestId,{ok:!0,issueKey:P,childKeys:Y});return}u.triggerComment.trim()&&await y.jira.addTriggerComment(P,`${u.triggerComment.trim()}`+(!y.authored&&u.requestedBy?`
1237
+
1238
+ _(requested by ${u.requestedBy} via Allwright)_`:"")),g.info(`Compose created ${P}`+(u.requestedBy?` for ${u.requestedBy}`:"")+(u.triggerComment?` with trigger "${u.triggerComment.trim()}"`:"")),b.sendChatCreateTicketResult(u.requestId,{ok:!0,issueKey:P})}catch(y){b.sendChatCreateTicketResult(u.requestId,{ok:!1,issueKey:"",error:y instanceof Error?y.message:String(y)})}},onAuditStart:async u=>{let m=R(u.projectId);if(!m){b.sendAuditStartResult(u.requestId,{ok:!1,error:C(u.projectId)});return}try{g.info(`Audit (${u.role}) starting on ${m.project.repoName}`+(u.scope.kind!=="repo"?` scoped to ${u.scope.kind}:${u.scope.ref}`:""));let y=Ce(t,m.project,"assist");if("error"in y){b.sendAuditStartResult(u.requestId,{ok:!1,error:y.error});return}let x=await As({projectId:u.projectId,repoPath:m.repoPath,role:u.role,scope:u.scope,detailLevel:u.detailLevel,model:u.model,agent:y,jira:s(m.project.repoName),baseUrl:u.baseUrl});if(!x.ok){b.sendAuditStartResult(u.requestId,{ok:!1,error:x.error});return}b.sendAuditStartResult(u.requestId,{ok:!0,audit:x.audit})}catch(y){b.sendAuditStartResult(u.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onAuditList:async u=>{try{b.sendAuditListResult(u.requestId,{ok:!0,audits:Bh(u.projectId)})}catch(m){b.sendAuditListResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditExplain:async u=>{try{let m=ec(u.projectId,u.auditId),y=m?.findings.find(q=>q.id===u.findingId);if(!m||!y){b.sendAuditExplainResult(u.requestId,{ok:!1,error:"that finding is not on this runner any more"});return}let x=R(u.projectId);if(!x){b.sendAuditExplainResult(u.requestId,{ok:!1,error:C(u.projectId)});return}let M=Ce(t,x.project,"assist");if("error"in M){b.sendAuditExplainResult(u.requestId,{ok:!1,error:M.error});return}let P=`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.
1239
+
1240
+ FINDING (${y.severity}${y.ruleId?`, rule ${y.ruleId}`:""}):
1241
+ ${y.title}
1242
+ `+y.evidence.map(q=>`- ${q.file}${q.line?`:${q.line}`:""} ${q.note}`.trim()).join(`
1243
+ `)+(y.fix?`
1244
+ Proposed fix: ${y.fix}`:"")+`
1230
1245
 
1231
1246
  You may Read the cited files to understand the context - do NOT search for new problems; you are explaining this one, not auditing.
1232
1247
 
@@ -1235,7 +1250,7 @@ Answer in EXACTLY these four short sections, plain words, no jargon without an i
1235
1250
  **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.
1236
1251
  **How urgent:** now / before the next release / when convenient - and why.
1237
1252
  **What fixing it takes:** rough size (an hour, a day, a project) and whether anything visible to users changes.
1238
- Nothing else - no preamble, no code.`,Z=await P.adapter.run({repoPath:x.repoPath,prompt:O,timeoutSeconds:120,bin:P.bin,mode:"read_only",maxTurns:8,sessionId:(0,qn.randomUUID)(),onLog:()=>{}}),W=Z.resultText.trim();if(!Z.ok||!W){b.sendAuditExplainResult(u.requestId,{ok:!1,error:Z.error??"the agent returned nothing - try again"});return}b.sendAuditExplainResult(u.requestId,{ok:!0,explanation:W})}catch(m){b.sendAuditExplainResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditGet:async u=>{try{let m=Hl(u.projectId,u.auditId);if(!m){b.sendAuditGetResult(u.requestId,{ok:!1,error:"audit not found on this runner"});return}b.sendAuditGetResult(u.requestId,{ok:!0,audit:m})}catch(m){b.sendAuditGetResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditReview:async u=>{try{let m=Bl(u.projectId,u.auditId,{selected:u.selected,ticketed:u.ticketed,verdicts:u.verdicts,verdictBy:u.verdictBy});if(!m){b.sendAuditReviewResult(u.requestId,{ok:!1,error:"audit not found on this runner"});return}let g=E(u.projectId);if(g&&u.verdicts.length){let x=[];for(let P of u.verdicts){if(P.verdict==="valid"||m.lessonsWritten.includes(P.findingId))continue;let O=m.findings.find(Z=>Z.id===P.findingId);O&&(Zl(g.repoPath,m.role,Hh(O,P.verdict,P.note,u.verdictBy)),x.push(P.findingId),y.info(`Lesson written (${m.role}): ${P.verdict} - ${O.title.slice(0,60)}`))}x.length&&(m=Bl(u.projectId,u.auditId,{markLessonsWritten:x})??m)}b.sendAuditReviewResult(u.requestId,{ok:!0,audit:m})}catch(m){b.sendAuditReviewResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onKnowledgeList:async u=>{let m=E(u.projectId);if(!m){b.sendKnowledgeListResult(u.requestId,{ok:!1,error:C(u.projectId)});return}try{b.sendKnowledgeListResult(u.requestId,{ok:!0,files:Gh(m.repoPath)})}catch(g){b.sendKnowledgeListResult(u.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onKnowledgeSave:async u=>{let m=E(u.projectId);if(!m){b.sendKnowledgeSaveResult(u.requestId,{ok:!1,error:C(u.projectId)});return}try{u.append?Zl(m.repoPath,u.role,Kh(u.content,u.by),u.level):Wh(m.repoPath,u.role,u.level,u.source,u.name,u.content),y.info(`Knowledge ${u.append?"taught":"saved"}: ${u.role}/${u.level}/${u.name}`),b.sendKnowledgeSaveResult(u.requestId,{ok:!0})}catch(g){b.sendKnowledgeSaveResult(u.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onEpicList:async u=>{let m=E(u.projectId);if(!m){b.sendEpicListResult(u.requestId,{ok:!1,error:C(u.projectId)});return}try{let g=s(m.project.repoName);if(u.epicKey){let x=await g.epicChildren(u.epicKey);b.sendEpicListResult(u.requestId,{ok:!0,children:x})}else{let x=await g.searchEpics(m.project.jiraProjectKey);b.sendEpicListResult(u.requestId,{ok:!0,epics:x})}}catch(g){b.sendEpicListResult(u.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onEpicSuggest:async u=>{let m=E(u.projectId);if(!m){b.sendEpicSuggestResult(u.requestId,{ok:!1,error:C(u.projectId)});return}try{let g=s(m.project.repoName),x=await g.epicChildren(u.epicKey),P=_h(x);if(!P.length){b.sendEpicSuggestResult(u.requestId,{ok:!1,error:`every child of ${u.epicKey} is already done or in an agent's hands - nothing to sequence`});return}if(P.length===1){b.sendEpicSuggestResult(u.requestId,{ok:!0,issueKey:P[0].key,reason:"It's the only pending ticket left in this epic.",considered:1});return}let O=await Promise.all(P.slice(0,12).map(async ue=>{try{let V=await g.getIssue(ue.key);return{...ue,description:V.description}}catch{return{...ue,description:""}}})),Z=(await g.getIssue(u.epicKey).catch(()=>null))?.summary??"";y.info(`Epic suggest: weighing ${O.length} pending children of ${u.epicKey}`);let W=Ce(t,m.project,"assist");if("error"in W){b.sendEpicSuggestResult(u.requestId,{ok:!1,error:W.error});return}let B=await W.adapter.run({repoPath:m.repoPath,prompt:Sh(u.epicKey,Z,O),timeoutSeconds:150,bin:W.bin,mode:"read_only",maxTurns:20,sessionId:(0,qn.randomUUID)(),model:u.model||"claude-sonnet-5",onLog:()=>{}}),D=Th(B.resultText,O.map(ue=>ue.key));if("error"in D){b.sendEpicSuggestResult(u.requestId,{ok:!1,error:D.error});return}y.info(`Epic suggest: ${u.epicKey} -> do ${D.issueKey} first`),b.sendEpicSuggestResult(u.requestId,{ok:!0,issueKey:D.issueKey,reason:D.reason,considered:O.length})}catch(g){b.sendEpicSuggestResult(u.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onTeamCreds:async u=>{try{let m=ke()??t;if(m.github?.token&&!m.github.login)try{let{GitHubClient:x}=await Promise.resolve().then(()=>(Tt(),Pr));m.github.login=await new x(m.github.token).whoami(),we(m)}catch{}let g=mh(m,u.emails);b.sendTeamCredsResult(u.requestId,{ok:!0,...g})}catch(m){b.sendTeamCredsResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRepoUnmap:u=>{try{let m=ke();if(!m){b.sendRepoUnmapResult(u.requestId,{ok:!1,error:"this runner has no config file"});return}let g=m.repos[u.repoName];if(!g){b.sendRepoUnmapResult(u.requestId,{ok:!0,removedPath:""});return}let x=g.path;delete m.repos[u.repoName];for(let P of Object.keys(m.environments).filter(O=>O.startsWith(`${u.repoName}:`)))delete m.environments[P];m.auditSchedules=m.auditSchedules.filter(P=>P.repoName!==u.repoName),we(m),fn(),y.info(`Unmapped "${u.repoName}" (was ${x}) - its project was deleted on the dashboard. The checkout on disk was NOT touched.`),b.sendRepoUnmapResult(u.requestId,{ok:!0,removedPath:x})}catch(m){b.sendRepoUnmapResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupRecheck:u=>{try{let m=E(u.projectId);if(!m){b.sendSetupRecheckResult(u.requestId,{ok:!1,error:C(u.projectId)});return}b.sendSetupRecheckResult(u.requestId,{ok:!0,checks:af({repoPath:m.repoPath,environments:u.environments})})}catch(m){b.sendSetupRecheckResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupStatus:async u=>{try{let m=ke()??t,{buildSetupReport:g}=await Promise.resolve().then(()=>(Dg(),zg)),x=await g(m,u.repoNames,t);b.sendSetupStatusResult(u.requestId,{ok:!0,...x})}catch(m){b.sendSetupStatusResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdGenerate:async u=>{try{let m=E(u.projectId);if(!m){b.sendSetupClaudeMdGenerateResult(u.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=u.kind==="deploy"?"DEPLOY.md":u.kind==="design"?"DESIGN.md":"CLAUDE.md";y.info(`Setup: drafting ${g} for ${m.project.repoName}`);let x="Explore this repository and draft the content of a CLAUDE.md file for its repo root - the memory file AI agents read before working on tickets here. Cover: what the product does (one paragraph), the tech stack, how the code is organized (key directories and what lives in them), exact commands to install dependencies / build / run tests, code conventions worth following, and gotchas a newcomer would trip over. Under 150 lines, factual, no marketing language, nothing you cannot verify from the code. Reply with ONLY the file content - no preamble, no fences around the whole thing.",P=`Inspect this repository (deploy scripts, CI files, server configs, package scripts) and draft the content of a DEPLOY.md deploy contract for its repo root. An automation tool will follow it LITERALLY, so only write what you can verify from the repo. IMPORTANT: you are running ON the machine where deploys will execute - commands are plain local commands, no ssh wrapper, unless the repo clearly documents a different target machine. For each environment that VERIFIABLY exists: name, branch, exact deploy commands, secrets as $NAMES only (never values), pre/post checks (post-restart checks must wait and retry - services report active before their port binds). Where you cannot verify something (hosts, service names, ports), write it with a clear "VERIFY:" marker so the human fills it in during review, instead of guessing. State explicitly which environments do NOT exist.
1253
+ Nothing else - no preamble, no code.`,Y=await M.adapter.run({repoPath:x.repoPath,prompt:P,timeoutSeconds:120,bin:M.bin,mode:"read_only",maxTurns:8,sessionId:(0,Hn.randomUUID)(),onLog:()=>{}}),B=Y.resultText.trim();if(!Y.ok||!B){b.sendAuditExplainResult(u.requestId,{ok:!1,error:Y.error??"the agent returned nothing - try again"});return}b.sendAuditExplainResult(u.requestId,{ok:!0,explanation:B})}catch(m){b.sendAuditExplainResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditGet:async u=>{try{let m=ec(u.projectId,u.auditId);if(!m){b.sendAuditGetResult(u.requestId,{ok:!1,error:"audit not found on this runner"});return}b.sendAuditGetResult(u.requestId,{ok:!0,audit:m})}catch(m){b.sendAuditGetResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditReview:async u=>{try{let m=Ql(u.projectId,u.auditId,{selected:u.selected,ticketed:u.ticketed,verdicts:u.verdicts,verdictBy:u.verdictBy});if(!m){b.sendAuditReviewResult(u.requestId,{ok:!1,error:"audit not found on this runner"});return}let y=R(u.projectId);if(y&&u.verdicts.length){let x=[];for(let M of u.verdicts){if(M.verdict==="valid"||m.lessonsWritten.includes(M.findingId))continue;let P=m.findings.find(Y=>Y.id===M.findingId);P&&(sc(y.repoPath,m.role,Qh(P,M.verdict,M.note,u.verdictBy)),x.push(M.findingId),g.info(`Lesson written (${m.role}): ${M.verdict} - ${P.title.slice(0,60)}`))}x.length&&(m=Ql(u.projectId,u.auditId,{markLessonsWritten:x})??m)}b.sendAuditReviewResult(u.requestId,{ok:!0,audit:m})}catch(m){b.sendAuditReviewResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onKnowledgeList:async u=>{let m=R(u.projectId);if(!m){b.sendKnowledgeListResult(u.requestId,{ok:!1,error:C(u.projectId)});return}try{b.sendKnowledgeListResult(u.requestId,{ok:!0,files:tp(m.repoPath)})}catch(y){b.sendKnowledgeListResult(u.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onKnowledgeSave:async u=>{let m=R(u.projectId);if(!m){b.sendKnowledgeSaveResult(u.requestId,{ok:!1,error:C(u.projectId)});return}try{u.append?sc(m.repoPath,u.role,ep(u.content,u.by),u.level):np(m.repoPath,u.role,u.level,u.source,u.name,u.content),g.info(`Knowledge ${u.append?"taught":"saved"}: ${u.role}/${u.level}/${u.name}`),b.sendKnowledgeSaveResult(u.requestId,{ok:!0})}catch(y){b.sendKnowledgeSaveResult(u.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onEpicList:async u=>{let m=R(u.projectId);if(!m){b.sendEpicListResult(u.requestId,{ok:!1,error:C(u.projectId)});return}try{let y=s(m.project.repoName);if(u.epicKey){let x=await y.epicChildren(u.epicKey);b.sendEpicListResult(u.requestId,{ok:!0,children:x})}else{let x=await y.searchEpics(m.project.jiraProjectKey);b.sendEpicListResult(u.requestId,{ok:!0,epics:x})}}catch(y){b.sendEpicListResult(u.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onEpicSuggest:async u=>{let m=R(u.projectId);if(!m){b.sendEpicSuggestResult(u.requestId,{ok:!1,error:C(u.projectId)});return}try{let y=s(m.project.repoName),x=await y.epicChildren(u.epicKey),M=$h(x);if(!M.length){b.sendEpicSuggestResult(u.requestId,{ok:!1,error:`every child of ${u.epicKey} is already done or in an agent's hands - nothing to sequence`});return}if(M.length===1){b.sendEpicSuggestResult(u.requestId,{ok:!0,issueKey:M[0].key,reason:"It's the only pending ticket left in this epic.",considered:1});return}let P=await Promise.all(M.slice(0,12).map(async ce=>{try{let Z=await y.getIssue(ce.key);return{...ce,description:Z.description}}catch{return{...ce,description:""}}})),Y=(await y.getIssue(u.epicKey).catch(()=>null))?.summary??"";g.info(`Epic suggest: weighing ${P.length} pending children of ${u.epicKey}`);let B=Ce(t,m.project,"assist");if("error"in B){b.sendEpicSuggestResult(u.requestId,{ok:!1,error:B.error});return}let q=await B.adapter.run({repoPath:m.repoPath,prompt:Ph(u.epicKey,Y,P),timeoutSeconds:150,bin:B.bin,mode:"read_only",maxTurns:20,sessionId:(0,Hn.randomUUID)(),model:u.model||"claude-sonnet-5",onLog:()=>{}}),D=Nh(q.resultText,P.map(ce=>ce.key));if("error"in D){b.sendEpicSuggestResult(u.requestId,{ok:!1,error:D.error});return}g.info(`Epic suggest: ${u.epicKey} -> do ${D.issueKey} first`),b.sendEpicSuggestResult(u.requestId,{ok:!0,issueKey:D.issueKey,reason:D.reason,considered:P.length})}catch(y){b.sendEpicSuggestResult(u.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onTeamCreds:async u=>{try{let m=ve()??t;if(m.github?.token&&!m.github.login)try{let{GitHubClient:x}=await Promise.resolve().then(()=>(It(),jr));m.github.login=await new x(m.github.token).whoami(),ye(m)}catch{}let y=Th(m,u.emails);b.sendTeamCredsResult(u.requestId,{ok:!0,...y})}catch(m){b.sendTeamCredsResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRepoUnmap:u=>{try{let m=ve();if(!m){b.sendRepoUnmapResult(u.requestId,{ok:!1,error:"this runner has no config file"});return}let y=m.repos[u.repoName];if(!y){b.sendRepoUnmapResult(u.requestId,{ok:!0,removedPath:""});return}let x=y.path;delete m.repos[u.repoName];for(let M of Object.keys(m.environments).filter(P=>P.startsWith(`${u.repoName}:`)))delete m.environments[M];m.auditSchedules=m.auditSchedules.filter(M=>M.repoName!==u.repoName),ye(m),Vt(),g.info(`Unmapped "${u.repoName}" (was ${x}) - its project was deleted on the dashboard. The checkout on disk was NOT touched.`),b.sendRepoUnmapResult(u.requestId,{ok:!0,removedPath:x})}catch(m){b.sendRepoUnmapResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupRecheck:u=>{try{let m=R(u.projectId);if(!m){b.sendSetupRecheckResult(u.requestId,{ok:!1,error:C(u.projectId)});return}b.sendSetupRecheckResult(u.requestId,{ok:!0,checks:gf({repoPath:m.repoPath,environments:u.environments})})}catch(m){b.sendSetupRecheckResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onServerInventory:async u=>{try{let{collectServerInventory:m}=await Promise.resolve().then(()=>(Qg(),Xg)),y=await m(ve()??t);b.sendServerInventoryResult(u.requestId,{ok:!0,...y})}catch(m){b.sendServerInventoryResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m),checkouts:[],services:[],containers:[],ports:[],processes:[]})}},onSetupStatus:async u=>{try{let m=ve()??t,{buildSetupReport:y}=await Promise.resolve().then(()=>(py(),hy)),x=await y(m,u.repoNames,t);b.sendSetupStatusResult(u.requestId,{ok:!0,...x})}catch(m){b.sendSetupStatusResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdGenerate:async u=>{try{let m=R(u.projectId);if(!m){b.sendSetupClaudeMdGenerateResult(u.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let y=u.kind==="deploy"?"DEPLOY.md":u.kind==="design"?"DESIGN.md":"CLAUDE.md";g.info(`Setup: drafting ${y} for ${m.project.repoName}`);let x="Explore this repository and draft the content of a CLAUDE.md file for its repo root - the memory file AI agents read before working on tickets here. Cover: what the product does (one paragraph), the tech stack, how the code is organized (key directories and what lives in them), exact commands to install dependencies / build / run tests, code conventions worth following, and gotchas a newcomer would trip over. Under 150 lines, factual, no marketing language, nothing you cannot verify from the code. Reply with ONLY the file content - no preamble, no fences around the whole thing.",M=`Inspect this repository (deploy scripts, CI files, server configs, package scripts) and draft the content of a DEPLOY.md deploy contract for its repo root. An automation tool will follow it LITERALLY, so only write what you can verify from the repo. IMPORTANT: you are running ON the machine where deploys will execute - commands are plain local commands, no ssh wrapper, unless the repo clearly documents a different target machine. For each environment that VERIFIABLY exists: name, branch, exact deploy commands, secrets as $NAMES only (never values), pre/post checks (post-restart checks must wait and retry - services report active before their port binds). Where you cannot verify something (hosts, service names, ports), write it with a clear "VERIFY:" marker so the human fills it in during review, instead of guessing. State explicitly which environments do NOT exist.
1239
1254
 
1240
1255
  Ten things decide whether this document can actually be run:
1241
1256
  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.
@@ -1252,16 +1267,16 @@ Ten things decide whether this document can actually be run:
1252
1267
  Reply with ONLY the file content - no preamble, no fences around the whole thing.`+(u.environments.length?`
1253
1268
 
1254
1269
  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:
1255
- `+u.environments.map(V=>`- ${V.name}`+(V.branch?` (branch ${V.branch})`:"")+(V.publicUrl?` serves ${V.publicUrl}`:" - no URL given")+(V.onThisRunner?", its deploy commands run ON THIS MACHINE, in "+(V.workdir?`${V.workdir}`:V.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(`
1270
+ `+u.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(`
1256
1271
  `)+`
1257
- If the repo shows no evidence of how one of them deploys, still write its section with VERIFY: markers rather than dropping it.`:"")+(u.kind==="deploy"?_c({repoPath:m.repoPath,urls:u.environments.map(V=>V.publicUrl).filter(Boolean)})+Si(m.repoPath):""),O=`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.`,Z=`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.
1272
+ If the repo shows no evidence of how one of them deploys, still write its section with VERIFY: markers rather than dropping it.`:"")+(u.kind==="deploy"?$c({repoPath:m.repoPath,urls:u.environments.map(Z=>Z.publicUrl).filter(Boolean)})+Ii(m.repoPath):""),P=`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.`,Y=`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.
1258
1273
 
1259
1274
  BLOCKERS AS REPORTED:
1260
- `+u.blockers.map((V,ae)=>`${ae+1}. ${V}`).join(`
1275
+ `+u.blockers.map((Z,re)=>`${re+1}. ${Z}`).join(`
1261
1276
  `)+(u.machineState.length?`
1262
1277
 
1263
1278
  WHAT THE MACHINE SAYS RIGHT NOW - checked seconds ago, and NEWER than the list above, which came from a document written earlier:
1264
- `+u.machineState.map(V=>`- ${V}`).join(`
1279
+ `+u.machineState.map(Z=>`- ${Z}`).join(`
1265
1280
  `)+`
1266
1281
  Anything the list asks for that is ALREADY TRUE here gets one line - "already done, nothing to do" and what proves it - and no commands at all. Re-explaining a fix somebody has already carried out is how a tool tells them it was not paying attention. If the two disagree, the machine is right.`:"")+`
1267
1282
 
@@ -1293,8 +1308,8 @@ Rules, and they matter more than completeness:
1293
1308
  Reply with ONLY the guide - no preamble.`+(u.environments.length?`
1294
1309
 
1295
1310
  THE ENVIRONMENTS AS ALLWRIGHT HAS THEM TODAY - your instructions have to end with these matching reality:
1296
- `+u.environments.map(V=>`- ${V.name}`+(V.branch?` (branch ${V.branch})`:"")+(V.publicUrl?` serves ${V.publicUrl}`:"")+(V.onThisRunner?", deploy commands run ON THIS MACHINE, in "+(V.workdir?V.workdir:V.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(`
1297
- `):"")+_c({repoPath:m.repoPath,urls:u.environments.map(V=>V.publicUrl).filter(Boolean)})+Si(m.repoPath),W=Ce(t,m.project,"assist");if("error"in W){b.sendSetupClaudeMdGenerateResult(u.requestId,{ok:!1,content:"",error:W.error});return}let B=0,D=await W.adapter.run({repoPath:m.repoPath,prompt:u.kind==="deploy"?P:u.kind==="design"?O:u.kind==="unblock"?Z:x,timeoutSeconds:600,bin:W.bin,mode:"read_only",maxTurns:40,sessionId:(0,qn.randomUUID)(),onLog:(V,ae)=>{V==="agent"&&u.streamId&&b.send({type:"chat.stream",requestId:u.streamId,seq:B++,text:ae.slice(0,8e3)})}}),ue=D.resultText.trim();if(!ue){b.sendSetupClaudeMdGenerateResult(u.requestId,{ok:!1,error:"the agent returned no content - try again"});return}D.outputTruncated&&y.warn(`Setup: the ${g} draft was cut off at the agent's output limit - ${ue.length} chars, incomplete`),b.sendSetupClaudeMdGenerateResult(u.requestId,{ok:!0,content:ue,truncated:!!D.outputTruncated})}catch(m){b.sendSetupClaudeMdGenerateResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupAsk:async u=>{try{let m=E(u.projectId);if(!m){b.sendSetupAskResult(u.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=Ce(t,m.project,"assist");if("error"in g){b.sendSetupAskResult(u.requestId,{ok:!1,error:g.error});return}y.info(`Setup: question about "${u.subject.slice(0,60)}" (${m.project.repoName})`);let x="Someone is at a terminal on THIS machine, part-way through fixing one setup problem in Allwright, and has a question about it. Answer that question and stop."+(u.subject?`
1311
+ `+u.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(`
1312
+ `):"")+$c({repoPath:m.repoPath,urls:u.environments.map(Z=>Z.publicUrl).filter(Boolean)})+Ii(m.repoPath),B=Ce(t,m.project,"assist");if("error"in B){b.sendSetupClaudeMdGenerateResult(u.requestId,{ok:!1,content:"",error:B.error});return}let q=0,D=await B.adapter.run({repoPath:m.repoPath,prompt:u.kind==="deploy"?M:u.kind==="design"?P:u.kind==="unblock"?Y:x,timeoutSeconds:600,bin:B.bin,mode:"read_only",maxTurns:40,sessionId:(0,Hn.randomUUID)(),onLog:(Z,re)=>{Z==="agent"&&u.streamId&&b.send({type:"chat.stream",requestId:u.streamId,seq:q++,text:re.slice(0,8e3)})}}),ce=D.resultText.trim();if(!ce){b.sendSetupClaudeMdGenerateResult(u.requestId,{ok:!1,error:"the agent returned no content - try again"});return}D.outputTruncated&&g.warn(`Setup: the ${y} draft was cut off at the agent's output limit - ${ce.length} chars, incomplete`),b.sendSetupClaudeMdGenerateResult(u.requestId,{ok:!0,content:ce,truncated:!!D.outputTruncated})}catch(m){b.sendSetupClaudeMdGenerateResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupAsk:async u=>{try{let m=R(u.projectId);if(!m){b.sendSetupAskResult(u.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let y=Ce(t,m.project,"assist");if("error"in y){b.sendSetupAskResult(u.requestId,{ok:!1,error:y.error});return}g.info(`Setup: question about "${u.subject.slice(0,60)}" (${m.project.repoName})`);let x="Someone is at a terminal on THIS machine, part-way through fixing one setup problem in Allwright, and has a question about it. Answer that question and stop."+(u.subject?`
1298
1313
 
1299
1314
  WHAT THEY ARE WORKING ON:
1300
1315
  ${u.subject}`:"")+(u.command?`
@@ -1303,11 +1318,11 @@ THE COMMAND THE SCREEN GAVE THEM:
1303
1318
  ${u.command}`:"")+(u.machineState.length?`
1304
1319
 
1305
1320
  WHAT THIS MACHINE ANSWERED AT THE LAST CHECK - seconds ago, and more reliable than anything you infer from the repository. If it disagrees with what you would have guessed, it wins:
1306
- `+u.machineState.map(Z=>`- ${Z}`).join(`
1321
+ `+u.machineState.map(Y=>`- ${Y}`).join(`
1307
1322
  `):"")+(u.history.length?`
1308
1323
 
1309
1324
  EARLIER IN THIS SAME BOX:
1310
- `+u.history.map(Z=>`${Z.role==="user"?"THEM":"YOU"}: ${Z.text}`).join(`
1325
+ `+u.history.map(Y=>`${Y.role==="user"?"THEM":"YOU"}: ${Y.text}`).join(`
1311
1326
 
1312
1327
  `):"")+`
1313
1328
 
@@ -1316,4 +1331,4 @@ ${u.question}
1316
1331
 
1317
1332
  HOW TO ANSWER. You have READ-ONLY access to this repository and no shell: you cannot run anything, so never claim to have checked something you could only have run. Give the cause in one or two sentences, then the exact command or file edit that moves them forward, in a fenced block. Under 150 words unless the question genuinely needs more. No preamble, no summary of what they asked, no encouragement.
1318
1333
 
1319
- Stay on the ONE problem above. If their error is actually a different problem, say which in a single line and stop - do not start fixing it. If the honest answer is that you cannot tell from here, say that and name the one command whose output would settle it. A confident guess about someone's production server is the worst thing you can hand them.`,O=(await g.adapter.run({repoPath:m.repoPath,prompt:x,timeoutSeconds:120,bin:g.bin,mode:"read_only",maxTurns:6,sessionId:(0,qn.randomUUID)(),onLog:()=>{}})).resultText.trim();b.sendSetupAskResult(u.requestId,O?{ok:!0,answer:O}:{ok:!1,error:"the agent returned nothing - ask again, or rephrase"})}catch(m){b.sendSetupAskResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdSave:async u=>{try{let m=E(u.projectId);if(!m){b.sendSetupClaudeMdSaveResult(u.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=u.kind==="deploy"?"DEPLOY.md":u.kind==="design"?"DESIGN.md":"CLAUDE.md",x=await Ru({repoPath:m.repoPath,relPath:g,content:u.content,overwrite:u.overwrite,commitMessage:`Add ${g} (agent-drafted, human-approved via Allwright)`});x.ok&&y.info(`Setup: wrote human-approved ${g} to ${m.repoPath} - ${x.note}`),b.sendSetupClaudeMdSaveResult(u.requestId,x)}catch(m){b.sendSetupClaudeMdSaveResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRepoDocSave:async u=>{try{let m=E(u.projectId);if(!m){b.sendRepoDocSaveResult(u.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=await Ru({repoPath:m.repoPath,relPath:u.relPath,content:u.content,overwrite:u.overwrite,commitMessage:`Add ${u.relPath.trim()} (written in Allwright Compose, human-approved)`});g.ok&&y.info(`Saved approved doc ${u.relPath} into ${m.repoPath}`),b.sendRepoDocSaveResult(u.requestId,g)}catch(m){b.sendRepoDocSaveResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditStats:u=>{try{b.sendAuditStatsResult(u.requestId,{ok:!0,byProject:jh(u.projectIds,u.since)})}catch(m){b.sendAuditStatsResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRunnerUpdate:async u=>{if(!process.env.INVOCATION_ID){b.sendRunnerUpdateResult(u.requestId,{ok:!1,error:"this runner is not running as a systemd service, so it cannot restart itself after updating. On the machine run: allwright update && allwright stop && allwright start"});return}let m=()=>{y.info("Installing allwright@latest");let x=pn.default.dirname(process.execPath),P=rt.default.existsSync(pn.default.join(x,"npm"))?pn.default.join(x,"npm"):"npm";(0,mn.execFile)(P,["install","-g","allwright@latest"],{timeout:18e4,env:{...process.env,PATH:`${x}:${process.env.PATH??""}`}},(O,Z,W)=>{if(O){b.sendRunnerUpdateResult(u.requestId,{ok:!1,error:`npm install failed: ${(W||O.message).slice(0,300)} - on the machine run: allwright update && sudo systemctl restart allwright`});return}b.sendRunnerUpdateResult(u.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){b.sendRunnerUpdateResult(u.requestId,{ok:!0,scheduled:!0,note:"an update is already scheduled and will install once the current work finishes"});return}let g=f.busyCount;b.sendRunnerUpdateResult(u.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)/chat turn(s) to finish`),w=setInterval(()=>{f.idle&&(clearInterval(w),w=null,m())},5e3)},onRunnerUninstall:u=>{if(!f.idle){b.sendRunnerUninstallResult(u.requestId,{ok:!1,error:`${f.busyCount} run(s)/deploy(s)/chat turn(s) are executing on this machine right now - nothing was uninstalled.`});return}let m;try{m=Ul()}catch(x){b.sendRunnerUninstallResult(u.requestId,{ok:!1,error:x instanceof Error?x.message:String(x)});return}let g=m.problems.length===0;if(b.sendRunnerUninstallResult(u.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(()=>{Ll(),process.exit(0)},1500)},onTestFix:async u=>{let m=g=>b.sendTestFixResult(u.requestId,{ok:!1,note:g});try{let g=As(u.runId);if(!g){m("this runner no longer has that PR on file - it may have been decided already");return}let x=t.repos[g.repoName];if(!x){m(`no local checkout mapped for "${g.repoName}" on this machine`);return}let P=Ue(t,g.repoName);if(!P){m("no GitHub token on this runner for that repo");return}let O=await new Fe(P).getPullRequest(g.owner,g.repo,g.prNumber);if(!O){m("that pull request no longer exists on GitHub");return}if(O.merged||O.state==="closed"){m("that pull request is already merged or closed - there is nothing left to fix");return}let Z=c.find(ue=>ue.repoName===g.repoName),W=g.nextDecisionSeq??1e5,B=(ue,V)=>{b.send({type:"run.log",runId:u.runId,seq:W++,ts:new Date().toISOString(),level:ue,message:V}),g.nextDecisionSeq=W,xt(g)},D=await Nf({cfg:t,repoPath:x.path,branch:g.branch,baseBranch:O.baseRef||"main",issueKey:g.issueKey,agentId:Z?.defaultAgent||Se.DEFAULT_AGENT_ID,configDir:g.agentConfigDir,failedTests:u.failedTests,timeoutSeconds:900,onLog:B});D.ok&&D.headSha&&(g.headSha=D.headSha,xt(g),b.send({type:"run.status",runId:u.runId,status:"awaiting_approval",headSha:D.headSha,failedTests:D.remaining??[],...D.testsPassed!==void 0?{testsPassed:D.testsPassed}:{},...D.testsTotal!==void 0?{testsTotal:D.testsTotal}:{},...D.costUsd!==void 0?{costUsd:D.costUsd}:{},...D.inputTokens!==void 0?{inputTokens:D.inputTokens}:{},...D.outputTokens!==void 0?{outputTokens:D.outputTokens}:{}})),ft(x.path,{issueKey:g.issueKey,runId:u.runId,title:D.ok?D.headSha?(D.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:D.note.slice(0,500)}),b.sendTestFixResult(u.requestId,D)}catch(g){m(g instanceof Error?g.message.slice(0,300):String(g))}},onRunAnswer:async u=>{try{let m=await f.answerPendingInput(u.runId,u.text,u.answeredBy);b.sendRunAnswerResult(u.requestId,m)}catch(m){b.sendRunAnswerResult(u.requestId,{ok:!1,error:m instanceof Error?m.message.slice(0,300):String(m)})}},onResolveConflict:async u=>{let m=g=>b.sendResolveConflictResult(u.requestId,{ok:!1,note:g});try{let g=As(u.runId);if(!g){m("this runner no longer has that PR on file - it may have been decided already");return}let x=t.repos[g.repoName];if(!x){m(`no local checkout mapped for "${g.repoName}" on this machine`);return}let P=Ue(t,g.repoName);if(!P){m("no GitHub token on this runner for that repo");return}let O=await new Fe(P).getPullRequest(g.owner,g.repo,g.prNumber);if(!O){m("that pull request no longer exists on GitHub");return}if(!O.baseRef){m("GitHub did not report the PR's base branch, so there is nothing to merge in");return}let Z=c.find(ue=>ue.repoName===g.repoName),W=g.nextDecisionSeq??1e5,B=(ue,V)=>{b.send({type:"run.log",runId:u.runId,seq:W++,ts:new Date().toISOString(),level:ue,message:V}),g.nextDecisionSeq=W,xt(g)},D=await $f({cfg:t,repoPath:x.path,branch:g.branch,baseBranch:O.baseRef,issueKey:g.issueKey,agentId:Z?.defaultAgent||Se.DEFAULT_AGENT_ID,configDir:g.agentConfigDir,timeoutSeconds:900,onLog:B});D.ok&&D.headSha&&(g.headSha=D.headSha,g.conflictNotified=!1,xt(g),b.send({type:"run.pr.conflict",runId:u.runId,conflicted:!1}),b.send({type:"run.status",runId:u.runId,status:"awaiting_approval",headSha:D.headSha,...D.costUsd!==void 0?{costUsd:D.costUsd}:{},...D.inputTokens!==void 0?{inputTokens:D.inputTokens}:{},...D.outputTokens!==void 0?{outputTokens:D.outputTokens}:{}})),b.sendResolveConflictResult(u.requestId,D)}catch(g){m(g instanceof Error?g.message.slice(0,300):String(g))}},onAgentProfiles:u=>{try{let m=x=>{try{return rt.default.existsSync(x)&&rt.default.readdirSync(x).length>0}catch{return!1}},g=Object.entries(t.claudeProfiles).map(([x,P])=>({agent:"claude-code",name:x,loggedIn:m(P.configDir)}));b.sendAgentProfilesResult(u.requestId,{ok:!0,profiles:g,defaultLoggedIn:m(pn.default.join(Ki.default.homedir(),".claude")),agentsWithoutProfiles:Se.REGISTERED_AGENTS.filter(x=>!x.capabilities.loginProfiles).map(x=>x.id)})}catch(m){b.sendAgentProfilesResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onJiraUsers:async u=>{try{let m=await n.searchUsers(u.query);b.sendJiraUsersResult(u.requestId,{ok:!0,users:m})}catch(m){b.sendJiraUsersResult(u.requestId,{ok:!1,users:[],error:m instanceof Error?m.message:String(m)})}}});v.transport=b,f=new la(t,s,b),f.setExternalBusy(()=>X.size);let U=Object.values(Or()).filter(u=>u.kind==="implement").map(u=>u.repoPath);_l(Object.values(t.repos).map(u=>u.path),U).catch(()=>{}),b.start(),f.start();let j=()=>{y.info("shutting down"),w&&clearInterval(w),b.stop(),xd(process.pid),il(),process.exit(0)},H=!1,q=()=>{if(H){y.warn("second stop signal - exiting NOW; the interrupted run will be marked failed"),j();return}if(H=!0,f.stop(),f.idle){j();return}y.info(`stop requested - no new work will start; waiting for ${f.busyCount} active run(s)/deploy(s)/chat turn(s) to finish. Send the signal again to kill them immediately.`);let u=setInterval(()=>{f.idle&&(clearInterval(u),j())},3e3)};process.on("SIGINT",q),process.on("SIGTERM",q),process.on("SIGHUP",()=>{try{let u=he();for(let m of Object.keys(t))delete t[m];Object.assign(t,u),n=u.jira?new Le(u.jira):Nl(),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(u){y.error(`config reload failed - keeping the running config: ${u instanceof Error?u.message:String(u)}`)}})}Pe.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=he();if(t.foreground){L0(e);return}let n=ar();if(n&&lr(n)){y.info(`already running in the background (pid ${n}). Use \`allwright status\` or \`stop\`.`);return}let r=ds();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=_d(),i=(0,mn.spawn)(process.execPath,[process.argv[1],"start","--foreground"],{detached:!0,stdio:["ignore",s,s]});i.unref(),Td(i.pid),y.info(`Runner started in the background (pid ${i.pid}).`),y.info(`Logs: ${co()}`),y.info("It will keep polling Jira until you run `allwright stop` - closing this terminal is fine.")});Pe.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=ar();if(!e||!lr(e)){y.info("no background runner is running"),e&&rt.default.rmSync(us(),{force:!0});return}if(t.force){process.kill(e,"SIGKILL"),rt.default.rmSync(us(),{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.`)});Pe.command("status").description("Check whether the background runner is running").action(()=>{let t=ar();t&&lr(t)?y.info(`running in the background (pid ${t})`):y.info("not running")});Pe.parseAsync().catch(t=>{y.error(t instanceof Error?t.message:String(t)),process.exit(1)});
1334
+ Stay on the ONE problem above. If their error is actually a different problem, say which in a single line and stop - do not start fixing it. If the honest answer is that you cannot tell from here, say that and name the one command whose output would settle it. A confident guess about someone's production server is the worst thing you can hand them.`,P=(await y.adapter.run({repoPath:m.repoPath,prompt:x,timeoutSeconds:120,bin:y.bin,mode:"read_only",maxTurns:6,sessionId:(0,Hn.randomUUID)(),onLog:()=>{}})).resultText.trim();b.sendSetupAskResult(u.requestId,P?{ok:!0,answer:P}:{ok:!1,error:"the agent returned nothing - ask again, or rephrase"})}catch(m){b.sendSetupAskResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdSave:async u=>{try{let m=R(u.projectId);if(!m){b.sendSetupClaudeMdSaveResult(u.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let y=u.kind==="deploy"?"DEPLOY.md":u.kind==="design"?"DESIGN.md":"CLAUDE.md",x=await zu({repoPath:m.repoPath,relPath:y,content:u.content,overwrite:u.overwrite,commitMessage:`Add ${y} (agent-drafted, human-approved via Allwright)`});x.ok&&g.info(`Setup: wrote human-approved ${y} to ${m.repoPath} - ${x.note}`),b.sendSetupClaudeMdSaveResult(u.requestId,x)}catch(m){b.sendSetupClaudeMdSaveResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRepoDocSave:async u=>{try{let m=R(u.projectId);if(!m){b.sendRepoDocSaveResult(u.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let y=await zu({repoPath:m.repoPath,relPath:u.relPath,content:u.content,overwrite:u.overwrite,commitMessage:`Add ${u.relPath.trim()} (written in Allwright Compose, human-approved)`});y.ok&&g.info(`Saved approved doc ${u.relPath} into ${m.repoPath}`),b.sendRepoDocSaveResult(u.requestId,y)}catch(m){b.sendRepoDocSaveResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditStats:u=>{try{b.sendAuditStatsResult(u.requestId,{ok:!0,byProject:Hh(u.projectIds,u.since)})}catch(m){b.sendAuditStatsResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRunnerUpdate:async u=>{if(!process.env.INVOCATION_ID){b.sendRunnerUpdateResult(u.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 x=yn.default.dirname(process.execPath),M=it.default.existsSync(yn.default.join(x,"npm"))?yn.default.join(x,"npm"):"npm";(0,bn.execFile)(M,["install","-g","allwright@latest"],{timeout:18e4,env:{...process.env,PATH:`${x}:${process.env.PATH??""}`}},(P,Y,B)=>{if(P){b.sendRunnerUpdateResult(u.requestId,{ok:!1,error:`npm install failed: ${(B||P.message).slice(0,300)} - on the machine run: allwright update && sudo systemctl restart allwright`});return}b.sendRunnerUpdateResult(u.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){b.sendRunnerUpdateResult(u.requestId,{ok:!0,scheduled:!0,note:"an update is already scheduled and will install once the current work finishes"});return}let y=f.busyCount;b.sendRunnerUpdateResult(u.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)/chat turn(s) to finish`),w=setInterval(()=>{f.idle&&(clearInterval(w),w=null,m())},5e3)},onRunnerUninstall:u=>{if(!f.idle){b.sendRunnerUninstallResult(u.requestId,{ok:!1,error:`${f.busyCount} run(s)/deploy(s)/chat turn(s) are executing on this machine right now - nothing was uninstalled.`});return}let m;try{m=Jl()}catch(x){b.sendRunnerUninstallResult(u.requestId,{ok:!1,error:x instanceof Error?x.message:String(x)});return}let y=m.problems.length===0;if(b.sendRunnerUninstallResult(u.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(()=>{Vl(),process.exit(0)},1500)},onTestFix:async u=>{let m=y=>b.sendTestFixResult(u.requestId,{ok:!1,note:y});try{let y=$s(u.runId);if(!y){m("this runner no longer has that PR on file - it may have been decided already");return}let x=t.repos[y.repoName];if(!x){m(`no local checkout mapped for "${y.repoName}" on this machine`);return}let M=qe(t,y.repoName);if(!M){m("no GitHub token on this runner for that repo");return}let P=await new He(M).getPullRequest(y.owner,y.repo,y.prNumber);if(!P){m("that pull request no longer exists on GitHub");return}if(P.merged||P.state==="closed"){m("that pull request is already merged or closed - there is nothing left to fix");return}let Y=c.find(ce=>ce.repoName===y.repoName),B=y.nextDecisionSeq??1e5,q=(ce,Z)=>{b.send({type:"run.log",runId:u.runId,seq:B++,ts:new Date().toISOString(),level:ce,message:Z}),y.nextDecisionSeq=B,Rt(y)},D=await Ff({cfg:t,repoPath:x.path,branch:y.branch,baseBranch:P.baseRef||"main",issueKey:y.issueKey,agentId:Y?.defaultAgent||ke.DEFAULT_AGENT_ID,configDir:y.agentConfigDir,failedTests:u.failedTests,timeoutSeconds:900,onLog:q});D.ok&&D.headSha&&(y.headSha=D.headSha,Rt(y),b.send({type:"run.status",runId:u.runId,status:"awaiting_approval",headSha:D.headSha,failedTests:D.remaining??[],...D.testsPassed!==void 0?{testsPassed:D.testsPassed}:{},...D.testsTotal!==void 0?{testsTotal:D.testsTotal}:{},...D.costUsd!==void 0?{costUsd:D.costUsd}:{},...D.inputTokens!==void 0?{inputTokens:D.inputTokens}:{},...D.outputTokens!==void 0?{outputTokens:D.outputTokens}:{}})),mt(x.path,{issueKey:y.issueKey,runId:u.runId,title:D.ok?D.headSha?(D.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:D.note.slice(0,500)}),b.sendTestFixResult(u.requestId,D)}catch(y){m(y instanceof Error?y.message.slice(0,300):String(y))}},onRunAnswer:async u=>{try{let m=await f.answerPendingInput(u.runId,u.text,u.answeredBy);b.sendRunAnswerResult(u.requestId,m)}catch(m){b.sendRunAnswerResult(u.requestId,{ok:!1,error:m instanceof Error?m.message.slice(0,300):String(m)})}},onResolveConflict:async u=>{let m=y=>b.sendResolveConflictResult(u.requestId,{ok:!1,note:y});try{let y=$s(u.runId);if(!y){m("this runner no longer has that PR on file - it may have been decided already");return}let x=t.repos[y.repoName];if(!x){m(`no local checkout mapped for "${y.repoName}" on this machine`);return}let M=qe(t,y.repoName);if(!M){m("no GitHub token on this runner for that repo");return}let P=await new He(M).getPullRequest(y.owner,y.repo,y.prNumber);if(!P){m("that pull request no longer exists on GitHub");return}if(!P.baseRef){m("GitHub did not report the PR's base branch, so there is nothing to merge in");return}let Y=c.find(ce=>ce.repoName===y.repoName),B=y.nextDecisionSeq??1e5,q=(ce,Z)=>{b.send({type:"run.log",runId:u.runId,seq:B++,ts:new Date().toISOString(),level:ce,message:Z}),y.nextDecisionSeq=B,Rt(y)},D=await Uf({cfg:t,repoPath:x.path,branch:y.branch,baseBranch:P.baseRef,issueKey:y.issueKey,agentId:Y?.defaultAgent||ke.DEFAULT_AGENT_ID,configDir:y.agentConfigDir,timeoutSeconds:900,onLog:q});D.ok&&D.headSha&&(y.headSha=D.headSha,y.conflictNotified=!1,Rt(y),b.send({type:"run.pr.conflict",runId:u.runId,conflicted:!1}),b.send({type:"run.status",runId:u.runId,status:"awaiting_approval",headSha:D.headSha,...D.costUsd!==void 0?{costUsd:D.costUsd}:{},...D.inputTokens!==void 0?{inputTokens:D.inputTokens}:{},...D.outputTokens!==void 0?{outputTokens:D.outputTokens}:{}})),b.sendResolveConflictResult(u.requestId,D)}catch(y){m(y instanceof Error?y.message.slice(0,300):String(y))}},onAgentProfiles:u=>{try{let m=x=>{try{return it.default.existsSync(x)&&it.default.readdirSync(x).length>0}catch{return!1}},y=Object.entries(t.claudeProfiles).map(([x,M])=>({agent:"claude-code",name:x,loggedIn:m(M.configDir)}));b.sendAgentProfilesResult(u.requestId,{ok:!0,profiles:y,defaultLoggedIn:m(yn.default.join(Zi.default.homedir(),".claude")),agentsWithoutProfiles:ke.REGISTERED_AGENTS.filter(x=>!x.capabilities.loginProfiles).map(x=>x.id)})}catch(m){b.sendAgentProfilesResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onJiraUsers:async u=>{try{let m=await n.searchUsers(u.query);b.sendJiraUsersResult(u.requestId,{ok:!0,users:m})}catch(m){b.sendJiraUsersResult(u.requestId,{ok:!1,users:[],error:m instanceof Error?m.message:String(m)})}}});v.transport=b,f=new ha(t,s,b),f.setExternalBusy(()=>J.size);let U=Object.values(Mr()).filter(u=>u.kind==="implement").map(u=>u.repoPath);Pl(Object.values(t.repos).map(u=>u.path),U).catch(()=>{}),b.start(),f.start();let j=()=>{g.info("shutting down"),w&&clearInterval(w),b.stop(),jd(process.pid),ml(),process.exit(0)},K=!1,F=()=>{if(K){g.warn("second stop signal - exiting NOW; the interrupted run will be marked failed"),j();return}if(K=!0,f.stop(),f.idle){j();return}g.info(`stop requested - no new work will start; waiting for ${f.busyCount} active run(s)/deploy(s)/chat turn(s) to finish. Send the signal again to kill them immediately.`);let u=setInterval(()=>{f.idle&&(clearInterval(u),j())},3e3)};process.on("SIGINT",F),process.on("SIGTERM",F),process.on("SIGHUP",()=>{try{let u=de();for(let m of Object.keys(t))delete t[m];Object.assign(t,u),n=u.jira?new Ue(u.jira):Bl(),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(u){g.error(`config reload failed - keeping the running config: ${u instanceof Error?u.message:String(u)}`)}})}$e.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=de();if(t.foreground){AT(e);return}let n=cr();if(n&&ur(n)){g.info(`already running in the background (pid ${n}). Use \`allwright status\` or \`stop\`.`);return}let r=ps();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=$d(),i=(0,bn.spawn)(process.execPath,[process.argv[1],"start","--foreground"],{detached:!0,stdio:["ignore",s,s]});i.unref(),Nd(i.pid),g.info(`Runner started in the background (pid ${i.pid}).`),g.info(`Logs: ${po()}`),g.info("It will keep polling Jira until you run `allwright stop` - closing this terminal is fine.")});$e.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=cr();if(!e||!ur(e)){g.info("no background runner is running"),e&&it.default.rmSync(hs(),{force:!0});return}if(t.force){process.kill(e,"SIGKILL"),it.default.rmSync(hs(),{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.`)});$e.command("status").description("Check whether the background runner is running").action(()=>{let t=cr();t&&ur(t)?g.info(`running in the background (pid ${t})`):g.info("not running")});$e.parseAsync().catch(t=>{g.error(t instanceof Error?t.message:String(t)),process.exit(1)});