allwright 1.77.0 → 1.78.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 +184 -173
  2. package/package.json +1 -1
package/bin/allwright.js CHANGED
@@ -1,27 +1,27 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Qm=Object.create;var fa=Object.defineProperty;var eg=Object.getOwnPropertyDescriptor;var tg=Object.getOwnPropertyNames;var ng=Object.getPrototypeOf,rg=Object.prototype.hasOwnProperty;var we=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var ce=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}},fn=(t,e)=>{for(var n in e)fa(t,n,{get:e[n],enumerable:!0})},sg=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of tg(e))!rg.call(t,s)&&s!==n&&fa(t,s,{get:()=>e[s],enumerable:!(r=eg(e,s))||r.enumerable});return t};var R=(t,e,n)=>(n=t!=null?Qm(ng(t)):{},sg(e||!t||!t.__esModule?fa(n,"default",{value:t,enumerable:!0}):n,t));var Fs=ce(ga=>{var $i=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}},ma=class extends $i{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};ga.CommanderError=$i;ga.InvalidArgumentError=ma});var Pi=ce(ba=>{var{InvalidArgumentError:ig}=Fs(),ya=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 ig(`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 og(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}ba.Argument=ya;ba.humanReadableArgName=og});var va=ce(du=>{var{humanReadableArgName:ag}=Pi(),wa=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=>ag(r)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(n?" "+n:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,n){return n.visibleCommands(e).reduce((r,s)=>Math.max(r,n.subcommandTerm(s).length),0)}longestOptionTermLength(e,n){return n.visibleOptions(e).reduce((r,s)=>Math.max(r,n.optionTerm(s).length),0)}longestGlobalOptionTermLength(e,n){return n.visibleGlobalOptions(e).reduce((r,s)=>Math.max(r,n.optionTerm(s).length),0)}longestArgumentTermLength(e,n){return n.visibleArguments(e).reduce((r,s)=>Math.max(r,n.argumentTerm(s).length),0)}commandUsage(e){let n=e._name;e._aliases[0]&&(n=n+"|"+e._aliases[0]);let r="";for(let s=e.parent;s;s=s.parent)r=s.name()+" "+r;return r+n+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let n=[];return e.argChoices&&n.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&n.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&n.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&n.push(`env: ${e.envVar}`),n.length>0?`${e.description} (${n.join(", ")})`:e.description}argumentDescription(e){let n=[];if(e.argChoices&&n.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&n.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),n.length>0){let r=`(${n.join(", ")})`;return e.description?`${e.description} ${r}`:r}return e.description}formatHelp(e,n){let r=n.padWidth(e,n),s=n.helpWidth||80,i=2,o=2;function l(k,x){if(x){let E=`${k.padEnd(r+o)}${x}`;return n.wrap(E,s-i,r+o)}return k}function c(k){return k.join(`
3
- `).replace(/^/gm," ".repeat(i))}let u=[`Usage: ${n.commandUsage(e)}`,""],p=n.commandDescription(e);p.length>0&&(u=u.concat([n.wrap(p,s,0),""]));let f=n.visibleArguments(e).map(k=>l(n.argumentTerm(k),n.argumentDescription(k)));f.length>0&&(u=u.concat(["Arguments:",c(f),""]));let w=n.visibleOptions(e).map(k=>l(n.optionTerm(k),n.optionDescription(k)));if(w.length>0&&(u=u.concat(["Options:",c(w),""])),this.showGlobalOptions){let k=n.visibleGlobalOptions(e).map(x=>l(n.optionTerm(x),n.optionDescription(x)));k.length>0&&(u=u.concat(["Global Options:",c(k),""]))}let v=n.visibleCommands(e).map(k=>l(n.subcommandTerm(k),n.subcommandDescription(k)));return v.length>0&&(u=u.concat(["Commands:",c(v),""])),u.join(`
4
- `)}padWidth(e,n){return Math.max(n.longestOptionTermLength(e,n),n.longestGlobalOptionTermLength(e,n),n.longestSubcommandTermLength(e,n),n.longestArgumentTermLength(e,n))}wrap(e,n,r,s=40){let i=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",o=new RegExp(`[\\n][${i}]+`);if(e.match(o))return e;let l=n-r;if(l<s)return e;let c=e.slice(0,r),u=e.slice(r).replace(`\r
2
+ "use strict";var Qm=Object.create;var fa=Object.defineProperty;var eg=Object.getOwnPropertyDescriptor;var tg=Object.getOwnPropertyNames;var ng=Object.getPrototypeOf,rg=Object.prototype.hasOwnProperty;var we=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var ce=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}},fn=(t,e)=>{for(var n in e)fa(t,n,{get:e[n],enumerable:!0})},sg=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of tg(e))!rg.call(t,s)&&s!==n&&fa(t,s,{get:()=>e[s],enumerable:!(r=eg(e,s))||r.enumerable});return t};var R=(t,e,n)=>(n=t!=null?Qm(ng(t)):{},sg(e||!t||!t.__esModule?fa(n,"default",{value:t,enumerable:!0}):n,t));var Fs=ce(ga=>{var $i=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}},ma=class extends $i{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};ga.CommanderError=$i;ga.InvalidArgumentError=ma});var Pi=ce(ba=>{var{InvalidArgumentError:ig}=Fs(),ya=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 ig(`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 og(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}ba.Argument=ya;ba.humanReadableArgName=og});var va=ce(du=>{var{humanReadableArgName:ag}=Pi(),wa=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=>ag(r)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(n?" "+n:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,n){return n.visibleCommands(e).reduce((r,s)=>Math.max(r,n.subcommandTerm(s).length),0)}longestOptionTermLength(e,n){return n.visibleOptions(e).reduce((r,s)=>Math.max(r,n.optionTerm(s).length),0)}longestGlobalOptionTermLength(e,n){return n.visibleGlobalOptions(e).reduce((r,s)=>Math.max(r,n.optionTerm(s).length),0)}longestArgumentTermLength(e,n){return n.visibleArguments(e).reduce((r,s)=>Math.max(r,n.argumentTerm(s).length),0)}commandUsage(e){let n=e._name;e._aliases[0]&&(n=n+"|"+e._aliases[0]);let r="";for(let s=e.parent;s;s=s.parent)r=s.name()+" "+r;return r+n+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let n=[];return e.argChoices&&n.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&n.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&n.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&n.push(`env: ${e.envVar}`),n.length>0?`${e.description} (${n.join(", ")})`:e.description}argumentDescription(e){let n=[];if(e.argChoices&&n.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&n.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),n.length>0){let r=`(${n.join(", ")})`;return e.description?`${e.description} ${r}`:r}return e.description}formatHelp(e,n){let r=n.padWidth(e,n),s=n.helpWidth||80,i=2,o=2;function l(k,E){if(E){let I=`${k.padEnd(r+o)}${E}`;return n.wrap(I,s-i,r+o)}return k}function c(k){return k.join(`
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(k=>l(n.argumentTerm(k),n.argumentDescription(k)));f.length>0&&(d=d.concat(["Arguments:",c(f),""]));let w=n.visibleOptions(e).map(k=>l(n.optionTerm(k),n.optionDescription(k)));if(w.length>0&&(d=d.concat(["Options:",c(w),""])),this.showGlobalOptions){let k=n.visibleGlobalOptions(e).map(E=>l(n.optionTerm(E),n.optionDescription(E)));k.length>0&&(d=d.concat(["Global Options:",c(k),""]))}let v=n.visibleCommands(e).map(k=>l(n.subcommandTerm(k),n.subcommandDescription(k)));return v.length>0&&(d=d.concat(["Commands:",c(v),""])),d.join(`
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"),k=u.match(v)||[];return c+k.map((x,E)=>x===`
8
- `?"":(E>0?p:"")+x.trimEnd()).join(`
7
+ |.{1,${l-1}}([${w}]|$)|[^${w}]+?([${w}]|$)`,"g"),k=d.match(v)||[];return c+k.map((E,I)=>E===`
8
+ `?"":(I>0?p:"")+E.trimEnd()).join(`
9
9
  `)}};du.Help=wa});var Ta=ce(Sa=>{var{InvalidArgumentError:lg}=Fs(),ka=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=ug(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 lg(`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 cg(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},_a=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 cg(t){return t.split("-").reduce((e,n)=>e+n[0].toUpperCase()+n.slice(1))}function ug(t){let e,n,r=t.split(/[ |,]+/);return r.length>1&&!/^[[<]/.test(r[1])&&(e=r.shift()),n=r.shift(),!e&&/^-[^-]$/.test(n)&&(e=n,n=void 0),{shortFlag:e,longFlag:n}}Sa.Option=ka;Sa.DualOptions=_a});var pu=ce(hu=>{function dg(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 hg(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=dg(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]}?)`:""}hu.suggestSimilar=hg});var bu=ce(yu=>{var pg=require("node:events").EventEmitter,xa=require("node:child_process"),qt=require("node:path"),Ia=require("node:fs"),ve=require("node:process"),{Argument:fg,humanReadableArgName:mg}=Pi(),{CommanderError:Ea}=Fs(),{Help:gg}=va(),{Option:fu,DualOptions:yg}=Ta(),{suggestSimilar:mu}=pu(),Ra=class t extends pg{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 gg,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
11
+ (Did you mean ${r[0]}?)`:""}hu.suggestSimilar=hg});var bu=ce(yu=>{var pg=require("node:events").EventEmitter,xa=require("node:child_process"),qt=require("node:path"),Ea=require("node:fs"),ve=require("node:process"),{Argument:fg,humanReadableArgName:mg}=Pi(),{CommanderError:Ia}=Fs(),{Help:gg}=va(),{Option:fu,DualOptions:yg}=Ta(),{suggestSimilar:mu}=pu(),Ra=class t extends pg{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 gg,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
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 fg(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 Ea(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 fu(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 fu)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(n,r);if(o.makeOptionMandatory(!!e.mandatory),typeof s=="function")o.default(i).argParser(s);else if(s instanceof RegExp){let l=s;s=(c,u)=>{let p=l.exec(c);return p?p[0]:u},o.default(i).argParser(s)}else o.default(s);return this.addOption(o)}option(e,n,r,s){return this._optionEx({},e,n,r,s)}requiredOption(e,n,r,s){return this._optionEx({mandatory:!0},e,n,r,s)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,n){return this.setOptionValueWithSource(e,n,void 0)}setOptionValueWithSource(e,n,r){return this._storeOptionsAsProperties?this[e]=n:this._optionValues[e]=n,this._optionValueSources[e]=r,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let n;return this._getCommandAndAncestors().forEach(r=>{r.getOptionValueSource(e)!==void 0&&(n=r.getOptionValueSource(e))}),n}_prepareUserArgs(e,n){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(n=n||{},e===void 0&&n.from===void 0){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=qt.resolve(p,f);if(Ia.existsSync(w))return w;if(s.includes(qt.extname(f)))return;let v=s.find(k=>Ia.existsSync(`${w}${k}`));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=Ia.realpathSync(this._scriptPath)}catch{p=this._scriptPath}l=qt.resolve(qt.dirname(p),l)}if(l){let p=i(l,o);if(!p&&!e._executableFile&&this._scriptPath){let f=qt.basename(this._scriptPath,qt.extname(this._scriptPath));f!==this._name&&(p=i(l,`${f}-${e._name}`))}o=p||o}r=s.includes(qt.extname(o));let c;ve.platform!=="win32"?r?(n.unshift(o),n=gu(ve.execArgv).concat(n),c=xa.spawn(ve.argv[0],n,{stdio:"inherit"})):c=xa.spawn(o,n,{stdio:"inherit"}):(n.unshift(o),n=gu(ve.execArgv).concat(n),c=xa.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 u=this._exitCallback;c.on("close",p=>{p=p??1,u?u(new Ea(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
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 Ia(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 fu(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 fu)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=qt.resolve(p,f);if(Ea.existsSync(w))return w;if(s.includes(qt.extname(f)))return;let v=s.find(k=>Ea.existsSync(`${w}${k}`));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=Ea.realpathSync(this._scriptPath)}catch{p=this._scriptPath}l=qt.resolve(qt.dirname(p),l)}if(l){let p=i(l,o);if(!p&&!e._executableFile&&this._scriptPath){let f=qt.basename(this._scriptPath,qt.extname(this._scriptPath));f!==this._name&&(p=i(l,`${f}-${e._name}`))}o=p||o}r=s.includes(qt.extname(o));let c;ve.platform!=="win32"?r?(n.unshift(o),n=gu(ve.execArgv).concat(n),c=xa.spawn(ve.argv[0],n,{stdio:"inherit"})):c=xa.spawn(o,n,{stdio:"inherit"}):(n.unshift(o),n=gu(ve.execArgv).concat(n),c=xa.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 Ia(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
15
15
  - if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
16
16
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
17
- - ${f}`;throw new Error(w)}else if(p.code==="EACCES")throw new Error(`'${o}' not executable`);if(!u)ve.exit(1);else{let f=new Ea(1,"commander.executeSubCommandAsync","(error)");f.nestedError=p,u(f)}}),this.runningCommand=c}_dispatchSubcommand(e,n,r){let s=this._findCommand(e);s||this.help({error:!0});let i;return i=this._chainOrCallSubCommandHook(i,s,"preSubcommand"),i=this._chainOrCall(i,()=>{if(s._executableHandler)this._executeSubCommand(s,n.concat(r));else return s._parseCommand(n,r)}),i}_dispatchHelpCommand(e){e||this.help();let n=this._findCommand(e);return n&&!n._executableHandler&&n.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,n)=>{e.required&&this.args[n]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(r,s,i)=>{let o=s;if(s!==null&&r.parseArg){let l=`error: command-argument value '${s}' is invalid for argument '${r.name()}'.`;o=this._callParseArg(r,s,i,l)}return o};this._checkNumberOfArguments();let n=[];this.registeredArguments.forEach((r,s)=>{let i=r.defaultValue;r.variadic?s<this.args.length?(i=this.args.slice(s),r.parseArg&&(i=i.reduce((o,l)=>e(r,l,o),r.defaultValue))):i===void 0&&(i=[]):s<this.args.length&&(i=this.args[s],r.parseArg&&(i=e(r,i,r.defaultValue))),n[s]=i}),this.processedArgs=n}_chainOrCall(e,n){return e&&e.then&&typeof e.then=="function"?e.then(()=>n()):n()}_chainOrCallHooks(e,n){let r=e,s=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[n]!==void 0).forEach(i=>{i._lifeCycleHooks[n].forEach(o=>{s.push({hookedCommand:i,callback:o})})}),n==="postAction"&&s.reverse(),s.forEach(i=>{r=this._chainOrCall(r,()=>i.callback(i.hookedCommand,this))}),r}_chainOrCallSubCommandHook(e,n,r){let s=e;return this._lifeCycleHooks[r]!==void 0&&this._lifeCycleHooks[r].forEach(i=>{s=this._chainOrCall(s,()=>i(this,n))}),s}_parseCommand(e,n){let r=this.parseOptions(n);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(r.operands),n=r.unknown,this.args=e.concat(n),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),n);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(n),this._dispatchSubcommand(this._defaultCommandName,e,n);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(r.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{r.unknown.length>0&&this.unknownOption(r.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){s(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(i,e,n)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(i))s(),this._processArguments(),this.parent.emit(i,e,n);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,n);this.listenerCount("command:*")?this.emit("command:*",e,n):this.commands.length?this.unknownCommand():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(n=>n._name===e||n._aliases.includes(e))}_findOption(e){return this.options.find(n=>n.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(n=>{n.mandatory&&e.getOptionValue(n.attributeName())===void 0&&e.missingMandatoryOptionValue(n)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(r=>{let s=r.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});e.filter(r=>r.conflictsWith.length>0).forEach(r=>{let s=e.find(i=>r.conflictsWith.includes(i.attributeName()));s&&this._conflictingOption(r,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let n=[],r=[],s=n,i=e.slice();function o(c){return c.length>1&&c[0]==="-"}let l=null;for(;i.length;){let c=i.shift();if(c==="--"){s===r&&s.push(c),s.push(...i);break}if(l&&!o(c)){this.emit(`option:${l.name()}`,c);continue}if(l=null,o(c)){let u=this._findOption(c);if(u){if(u.required){let p=i.shift();p===void 0&&this.optionMissingArgument(u),this.emit(`option:${u.name()}`,p)}else if(u.optional){let p=null;i.length>0&&!o(i[0])&&(p=i.shift()),this.emit(`option:${u.name()}`,p)}else this.emit(`option:${u.name()}`);l=u.variadic?u:null;continue}}if(c.length>2&&c[0]==="-"&&c[1]!=="-"){let u=this._findOption(`-${c[1]}`);if(u){u.required||u.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${u.name()}`,c.slice(2)):(this.emit(`option:${u.name()}`),i.unshift(`-${c.slice(2)}`));continue}}if(/^--[^=]+=/.test(c)){let u=c.indexOf("="),p=this._findOption(c.slice(0,u));if(p&&(p.required||p.optional)){this.emit(`option:${p.name()}`,c.slice(u+1));continue}}if(o(c)&&(s=r),(this._enablePositionalOptions||this._passThroughOptions)&&n.length===0&&r.length===0){if(this._findCommand(c)){n.push(c),i.length>0&&r.push(...i);break}else if(this._getHelpCommand()&&c===this._getHelpCommand().name()){n.push(c),i.length>0&&n.push(...i);break}else if(this._defaultCommandName){r.push(c),i.length>0&&r.push(...i);break}}if(this._passThroughOptions){s.push(c),i.length>0&&s.push(...i);break}s.push(c)}return{operands:n,unknown:r}}opts(){if(this._storeOptionsAsProperties){let e={},n=this.options.length;for(let r=0;r<n;r++){let s=this.options[r].attributeName();e[s]=s===this._versionOptionName?this._version:this[s]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,n)=>Object.assign(e,n.opts()),{})}error(e,n){this._outputConfiguration.outputError(`${e}
17
+ - ${f}`;throw new Error(w)}else if(p.code==="EACCES")throw new Error(`'${o}' not executable`);if(!d)ve.exit(1);else{let f=new Ia(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 yg(this.options),n=r=>this.getOptionValue(r)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(r));this.options.filter(r=>r.implied!==void 0&&n(r.attributeName())&&e.valueFromOption(this.getOptionValue(r.attributeName()),r)).forEach(r=>{Object.keys(r.implied).filter(s=>!n(s)).forEach(s=>{this.setOptionValueWithSource(s,r.implied[s],"implied")})})}missingArgument(e){let n=`error: missing required argument '${e}'`;this.error(n,{code:"commander.missingArgument"})}optionMissingArgument(e){let n=`error: option '${e.flags}' argument missing`;this.error(n,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let n=`error: required option '${e.flags}' not specified`;this.error(n,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,n){let r=o=>{let l=o.attributeName(),c=this.getOptionValue(l),u=this.options.find(f=>f.negate&&l===f.attributeName()),p=this.options.find(f=>!f.negate&&l===f.attributeName());return u&&(u.presetArg===void 0&&c===!1||u.presetArg!==void 0&&c===u.presetArg)?u:p||o},s=o=>{let l=r(o),c=l.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${l.envVar}'`:`option '${l.flags}'`},i=`error: ${s(e)} cannot be used with ${s(n)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let n="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],i=this;do{let o=i.createHelp().visibleOptions(i).filter(l=>l.long).map(l=>l.long);s=s.concat(o),i=i.parent}while(i&&!i._enablePositionalOptions);n=mu(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=mu(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}
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 yg(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=mu(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=mu(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
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=>mg(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=qt.basename(e,qt.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.
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 gu(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})}yu.Command=Ra});var _u=ce(st=>{var{Argument:wu}=Pi(),{Command:Aa}=bu(),{CommanderError:bg,InvalidArgumentError:vu}=Fs(),{Help:wg}=va(),{Option:ku}=Ta();st.program=new Aa;st.createCommand=t=>new Aa(t);st.createOption=(t,e)=>new ku(t,e);st.createArgument=(t,e)=>new wu(t,e);st.Command=Aa;st.Option=ku;st.Argument=wu;st.Help=wg;st.CommanderError=bg;st.InvalidArgumentError=vu;st.InvalidOptionArgumentError=vu});var ae,Ca,L,Et,Bs=we(()=>{(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})(ae||(ae={}));(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Ca||(Ca={}));L=ae.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Et=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,vg,Ke,Ni=we(()=>{Bs();A=ae.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"]),vg=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ke=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(i){return i.message},r={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)r._errors.push(n(o));else{let l=r,c=0;for(;c<o.path.length;){let u=o.path[c];c===o.path.length-1?(l[u]=l[u]||{_errors:[]},l[u]._errors.push(n(o))):l[u]=l[u]||{_errors:[]},l=l[u],c++}}};return s(this),r}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ae.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()}};Ke.create=t=>new Ke(t)});var kg,Ft,$a=we(()=>{Ni();Bs();kg=(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,ae.jsonStringifyReplacer)}`;break;case A.unrecognized_keys:n=`Unrecognized key(s) in object: ${ae.joinValues(t.keys,", ")}`;break;case A.invalid_union:n="Invalid input";break;case A.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ae.joinValues(t.options)}`;break;case A.invalid_enum_value:n=`Invalid enum value. Expected ${ae.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}"`:ae.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,ae.assertNever(t)}return{message:n}},Ft=kg});function _g(t){xu=t}function Vr(){return xu}var xu,ji=we(()=>{$a();xu=Ft});function M(t,e){let n=Vr(),r=Hs({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Ft?void 0:Ft].filter(s=>!!s)});t.common.issues.push(r)}var Hs,Sg,Ce,J,qn,Oe,Oi,Mi,mn,Yr,Pa=we(()=>{ji();$a();Hs=t=>{let{data:e,path:n,errorMaps:r,issueData:s}=t,i=[...n,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let l="",c=r.filter(u=>!!u).slice().reverse();for(let u of c)l=u(o,{data:e,defaultError:l}).message;return{...s,path:i,message:l}},Sg=[];Ce=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 J;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 J;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}}},J=Object.freeze({status:"aborted"}),qn=t=>({status:"dirty",value:t}),Oe=t=>({status:"valid",value:t}),Oi=t=>t.status==="aborted",Mi=t=>t.status==="dirty",mn=t=>t.status==="valid",Yr=t=>typeof Promise<"u"&&t instanceof Promise});var Iu=we(()=>{});var H,Eu=we(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(H||(H={}))});function ee(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:s}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,l)=>{let{message:c}=t;return o.code==="invalid_enum_value"?{message:c??l.defaultError}:typeof l.data>"u"?{message:c??r??l.defaultError}:o.code!=="invalid_type"?{message:l.defaultError}:{message:c??n??l.defaultError}},description:s}}function $u(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function Ug(t){return new RegExp(`^${$u(t)}$`)}function Pu(t){let e=`${Cu}T${$u(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function qg(t,e){return!!((e==="v4"||!e)&&Ng.test(t)||(e==="v6"||!e)&&Og.test(t))}function Fg(t,e){if(!Ag.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function Bg(t,e){return!!((e==="v4"||!e)&&jg.test(t)||(e==="v6"||!e)&&Mg.test(t))}function Hg(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 Jr(t){if(t instanceof Ge){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=it.create(Jr(r))}return new Ge({...t._def,shape:()=>e})}else return t instanceof Kt?new Kt({...t._def,type:Jr(t.element)}):t instanceof it?it.create(Jr(t.unwrap())):t instanceof At?At.create(Jr(t.unwrap())):t instanceof Rt?Rt.create(t.items.map(e=>Jr(e))):t}function ja(t,e){let n=Et(t),r=Et(e);if(t===e)return{valid:!0,data:t};if(n===L.object&&r===L.object){let s=ae.objectKeys(e),i=ae.objectKeys(t).filter(l=>s.indexOf(l)!==-1),o={...t,...e};for(let l of i){let c=ja(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=ja(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 Nu(t,e){return new Xn({values:t,typeName:X.ZodEnum,...ee(e)})}function Au(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function ju(t,e={},n){return t?yn.create().superRefine((r,s)=>{let i=t(r);if(i instanceof Promise)return i.then(o=>{if(!o){let l=Au(e,r),c=l.fatal??n??!0;s.addIssue({code:"custom",...l,fatal:c})}});if(!i){let o=Au(e,r),l=o.fatal??n??!0;s.addIssue({code:"custom",...o,fatal:l})}}):yn.create()}var ot,Ru,se,Tg,xg,Ig,Eg,Rg,Ag,Cg,$g,Pg,Na,Ng,jg,Og,Mg,Dg,zg,Cu,Lg,gn,Fn,Bn,Hn,Kn,Xr,Gn,Wn,yn,Ht,bt,Qr,Kt,Ge,Zn,Bt,Di,Vn,Rt,zi,es,ts,Li,Yn,Jn,Xn,Qn,bn,at,it,At,er,tr,ns,Kg,Ks,Gs,nr,Gg,X,Wg,Ou,Mu,Zg,Vg,Du,Yg,Jg,Xg,Qg,ey,ty,ny,ry,sy,iy,oy,ay,ly,cy,uy,dy,hy,py,fy,my,gy,yy,by,wy,vy,ky,_y,Sy,Ty,xy,Iy,Ey,Ry,Ay,zu=we(()=>{Ni();ji();Eu();Pa();Bs();ot=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}},Ru=(t,e)=>{if(mn(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 Ke(t.common.issues);return this._error=n,this._error}}};se=class{get description(){return this._def.description}_getType(e){return Et(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:Et(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ce,ctx:{common:e.parent.common,data:e.data,parsedType:Et(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(Yr(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:Et(e)},s=this._parseSync({data:e,path:r.path,parent:r});return Ru(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Et(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return mn(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=>mn(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:Et(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(Yr(s)?s:Promise.resolve(s));return Ru(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 at({schema:this,typeName:X.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 it.create(this,this._def)}nullable(){return At.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Kt.create(this)}promise(){return bn.create(this,this._def)}or(e){return Zn.create([this,e],this._def)}and(e){return Vn.create(this,e,this._def)}transform(e){return new at({...ee(this._def),schema:this,typeName:X.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new er({...ee(this._def),innerType:this,defaultValue:n,typeName:X.ZodDefault})}brand(){return new Ks({typeName:X.ZodBranded,type:this,...ee(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new tr({...ee(this._def),innerType:this,catchValue:n,typeName:X.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Gs.create(this,e)}readonly(){return nr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Tg=/^c[^\s-]{8,}$/i,xg=/^[0-9a-z]+$/,Ig=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Eg=/^[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,Rg=/^[a-z0-9_-]{21}$/i,Ag=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Cg=/^[-+]?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)?)??$/,$g=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Pg="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ng=/^(?:(?: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])$/,jg=/^(?:(?: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])$/,Og=/^(([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]))$/,Mg=/^(([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])$/,Dg=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,zg=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Cu="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Lg=new RegExp(`^${Cu}$`);gn=class t extends se{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==L.string){let i=this._getOrReturnCtx(e);return M(i,{code:A.invalid_type,expected:L.string,received:i.parsedType}),J}let r=new Ce,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),M(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),M(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?M(s,{code:A.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):l&&M(s,{code:A.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")$g.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"email",code:A.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Na||(Na=new RegExp(Pg,"u")),Na.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"emoji",code:A.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")Eg.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"uuid",code:A.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")Rg.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"nanoid",code:A.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")Tg.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"cuid",code:A.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")xg.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"cuid2",code:A.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")Ig.test(e.data)||(s=this._getOrReturnCtx(e,s),M(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),M(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),M(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),M(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),M(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),M(s,{code:A.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Pu(i).test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{code:A.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?Lg.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{code:A.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Ug(i).test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{code:A.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?Cg.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"duration",code:A.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?qg(e.data,i.version)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"ip",code:A.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?Fg(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"jwt",code:A.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?Bg(e.data,i.version)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"cidr",code:A.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?Dg.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"base64",code:A.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?zg.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"base64url",code:A.invalid_string,message:i.message}),r.dirty()):ae.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,...H.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...H.errToObj(e)})}url(e){return this._addCheck({kind:"url",...H.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...H.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...H.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...H.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...H.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...H.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...H.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...H.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...H.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...H.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...H.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...H.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...H.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...H.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...H.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...H.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...H.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...H.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...H.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...H.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...H.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...H.errToObj(n)})}nonempty(e){return this.min(1,H.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}};gn.create=t=>new gn({checks:[],typeName:X.ZodString,coerce:t?.coerce??!1,...ee(t)});Fn=class t extends se{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 M(i,{code:A.invalid_type,expected:L.number,received:i.parsedType}),J}let r,s=new Ce;for(let i of this._def.checks)i.kind==="int"?ae.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),M(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),M(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),M(r,{code:A.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Hg(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),M(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),M(r,{code:A.not_finite,message:i.message}),s.dirty()):ae.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,H.toString(n))}gt(e,n){return this.setLimit("min",e,!1,H.toString(n))}lte(e,n){return this.setLimit("max",e,!0,H.toString(n))}lt(e,n){return this.setLimit("max",e,!1,H.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:H.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:H.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:H.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:H.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:H.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:H.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:H.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:H.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:H.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:H.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"&&ae.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)}};Fn.create=t=>new Fn({checks:[],typeName:X.ZodNumber,coerce:t?.coerce||!1,...ee(t)});Bn=class t extends se{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 Ce;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),M(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),M(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),M(r,{code:A.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):ae.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return M(n,{code:A.invalid_type,expected:L.bigint,received:n.parsedType}),J}gte(e,n){return this.setLimit("min",e,!0,H.toString(n))}gt(e,n){return this.setLimit("min",e,!1,H.toString(n))}lte(e,n){return this.setLimit("max",e,!0,H.toString(n))}lt(e,n){return this.setLimit("max",e,!1,H.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:H.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:H.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:H.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:H.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:H.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:H.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}};Bn.create=t=>new Bn({checks:[],typeName:X.ZodBigInt,coerce:t?.coerce??!1,...ee(t)});Hn=class extends se{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==L.boolean){let r=this._getOrReturnCtx(e);return M(r,{code:A.invalid_type,expected:L.boolean,received:r.parsedType}),J}return Oe(e.data)}};Hn.create=t=>new Hn({typeName:X.ZodBoolean,coerce:t?.coerce||!1,...ee(t)});Kn=class t extends se{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==L.date){let i=this._getOrReturnCtx(e);return M(i,{code:A.invalid_type,expected:L.date,received:i.parsedType}),J}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return M(i,{code:A.invalid_date}),J}let r=new Ce,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),M(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),M(s,{code:A.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):ae.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:H.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:H.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}};Kn.create=t=>new Kn({checks:[],coerce:t?.coerce||!1,typeName:X.ZodDate,...ee(t)});Xr=class extends se{_parse(e){if(this._getType(e)!==L.symbol){let r=this._getOrReturnCtx(e);return M(r,{code:A.invalid_type,expected:L.symbol,received:r.parsedType}),J}return Oe(e.data)}};Xr.create=t=>new Xr({typeName:X.ZodSymbol,...ee(t)});Gn=class extends se{_parse(e){if(this._getType(e)!==L.undefined){let r=this._getOrReturnCtx(e);return M(r,{code:A.invalid_type,expected:L.undefined,received:r.parsedType}),J}return Oe(e.data)}};Gn.create=t=>new Gn({typeName:X.ZodUndefined,...ee(t)});Wn=class extends se{_parse(e){if(this._getType(e)!==L.null){let r=this._getOrReturnCtx(e);return M(r,{code:A.invalid_type,expected:L.null,received:r.parsedType}),J}return Oe(e.data)}};Wn.create=t=>new Wn({typeName:X.ZodNull,...ee(t)});yn=class extends se{constructor(){super(...arguments),this._any=!0}_parse(e){return Oe(e.data)}};yn.create=t=>new yn({typeName:X.ZodAny,...ee(t)});Ht=class extends se{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Oe(e.data)}};Ht.create=t=>new Ht({typeName:X.ZodUnknown,...ee(t)});bt=class extends se{_parse(e){let n=this._getOrReturnCtx(e);return M(n,{code:A.invalid_type,expected:L.never,received:n.parsedType}),J}};bt.create=t=>new bt({typeName:X.ZodNever,...ee(t)});Qr=class extends se{_parse(e){if(this._getType(e)!==L.undefined){let r=this._getOrReturnCtx(e);return M(r,{code:A.invalid_type,expected:L.void,received:r.parsedType}),J}return Oe(e.data)}};Qr.create=t=>new Qr({typeName:X.ZodVoid,...ee(t)});Kt=class t extends se{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==L.array)return M(n,{code:A.invalid_type,expected:L.array,received:n.parsedType}),J;if(s.exactLength!==null){let o=n.data.length>s.exactLength.value,l=n.data.length<s.exactLength.value;(o||l)&&(M(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&&(M(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&&(M(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 ot(n,o,n.path,l)))).then(o=>Ce.mergeArray(r,o));let i=[...n.data].map((o,l)=>s.type._parseSync(new ot(n,o,n.path,l)));return Ce.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:H.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:H.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:H.toString(n)}})}nonempty(e){return this.min(1,e)}};Kt.create=(t,e)=>new Kt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:X.ZodArray,...ee(e)});Ge=class t extends se{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=ae.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==L.object){let u=this._getOrReturnCtx(e);return M(u,{code:A.invalid_type,expected:L.object,received:u.parsedType}),J}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),l=[];if(!(this._def.catchall instanceof bt&&this._def.unknownKeys==="strip"))for(let u in s.data)o.includes(u)||l.push(u);let c=[];for(let u of o){let p=i[u],f=s.data[u];c.push({key:{status:"valid",value:u},value:p._parse(new ot(s,f,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof bt){let u=this._def.unknownKeys;if(u==="passthrough")for(let p of l)c.push({key:{status:"valid",value:p},value:{status:"valid",value:s.data[p]}});else if(u==="strict")l.length>0&&(M(s,{code:A.unrecognized_keys,keys:l}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let p of l){let f=s.data[p];c.push({key:{status:"valid",value:p},value:u._parse(new ot(s,f,s.path,p)),alwaysSet:p in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let u=[];for(let p of c){let f=await p.key,w=await p.value;u.push({key:f,value:w,alwaysSet:p.alwaysSet})}return u}).then(u=>Ce.mergeObjectSync(r,u)):Ce.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return H.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:H.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:X.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 ae.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 ae.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return Jr(this)}partial(e){let n={};for(let r of ae.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 ae.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof it;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return Nu(ae.objectKeys(this.shape))}};Ge.create=(t,e)=>new Ge({shape:()=>t,unknownKeys:"strip",catchall:bt.create(),typeName:X.ZodObject,...ee(e)});Ge.strictCreate=(t,e)=>new Ge({shape:()=>t,unknownKeys:"strict",catchall:bt.create(),typeName:X.ZodObject,...ee(e)});Ge.lazycreate=(t,e)=>new Ge({shape:t,unknownKeys:"strip",catchall:bt.create(),typeName:X.ZodObject,...ee(e)});Zn=class extends se{_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 Ke(l.ctx.common.issues));return M(n,{code:A.invalid_union,unionErrors:o}),J}if(n.common.async)return Promise.all(r.map(async i=>{let o={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let c of r){let u={...n,common:{...n.common,issues:[]},parent:null},p=c._parseSync({data:n.data,path:n.path,parent:u});if(p.status==="valid")return p;p.status==="dirty"&&!i&&(i={result:p,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let l=o.map(c=>new Ke(c));return M(n,{code:A.invalid_union,unionErrors:l}),J}}get options(){return this._def.options}};Zn.create=(t,e)=>new Zn({options:t,typeName:X.ZodUnion,...ee(e)});Bt=t=>t instanceof Yn?Bt(t.schema):t instanceof at?Bt(t.innerType()):t instanceof Jn?[t.value]:t instanceof Xn?t.options:t instanceof Qn?ae.objectValues(t.enum):t instanceof er?Bt(t._def.innerType):t instanceof Gn?[void 0]:t instanceof Wn?[null]:t instanceof it?[void 0,...Bt(t.unwrap())]:t instanceof At?[null,...Bt(t.unwrap())]:t instanceof Ks||t instanceof nr?Bt(t.unwrap()):t instanceof tr?Bt(t._def.innerType):[],Di=class t extends se{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==L.object)return M(n,{code:A.invalid_type,expected:L.object,received:n.parsedType}),J;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}):(M(n,{code:A.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),J)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let s=new Map;for(let i of n){let o=Bt(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let l of o){if(s.has(l))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(l)}`);s.set(l,i)}}return new t({typeName:X.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...ee(r)})}};Vn=class extends se{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=(i,o)=>{if(Oi(i)||Oi(o))return J;let l=ja(i.value,o.value);return l.valid?((Mi(i)||Mi(o))&&n.dirty(),{status:n.value,value:l.data}):(M(r,{code:A.invalid_intersection_types}),J)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Vn.create=(t,e,n)=>new Vn({left:t,right:e,typeName:X.ZodIntersection,...ee(n)});Rt=class t extends se{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==L.array)return M(r,{code:A.invalid_type,expected:L.array,received:r.parsedType}),J;if(r.data.length<this._def.items.length)return M(r,{code:A.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),J;!this._def.rest&&r.data.length>this._def.items.length&&(M(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 ot(r,o,r.path,l)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>Ce.mergeArray(n,o)):Ce.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Rt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Rt({items:t,typeName:X.ZodTuple,rest:null,...ee(e)})};zi=class t extends se{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 M(r,{code:A.invalid_type,expected:L.object,received:r.parsedType}),J;let s=[],i=this._def.keyType,o=this._def.valueType;for(let l in r.data)s.push({key:i._parse(new ot(r,l,r.path,l)),value:o._parse(new ot(r,r.data[l],r.path,l)),alwaysSet:l in r.data});return r.common.async?Ce.mergeObjectAsync(n,s):Ce.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof se?new t({keyType:e,valueType:n,typeName:X.ZodRecord,...ee(r)}):new t({keyType:gn.create(),valueType:e,typeName:X.ZodRecord,...ee(n)})}},es=class extends se{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 M(r,{code:A.invalid_type,expected:L.map,received:r.parsedType}),J;let s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([l,c],u)=>({key:s._parse(new ot(r,l,r.path,[u,"key"])),value:i._parse(new ot(r,c,r.path,[u,"value"]))}));if(r.common.async){let l=new Map;return Promise.resolve().then(async()=>{for(let c of o){let u=await c.key,p=await c.value;if(u.status==="aborted"||p.status==="aborted")return J;(u.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(u.value,p.value)}return{status:n.value,value:l}})}else{let l=new Map;for(let c of o){let u=c.key,p=c.value;if(u.status==="aborted"||p.status==="aborted")return J;(u.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(u.value,p.value)}return{status:n.value,value:l}}}};es.create=(t,e,n)=>new es({valueType:e,keyType:t,typeName:X.ZodMap,...ee(n)});ts=class t extends se{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==L.set)return M(r,{code:A.invalid_type,expected:L.set,received:r.parsedType}),J;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(M(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&&(M(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 u=new Set;for(let p of c){if(p.status==="aborted")return J;p.status==="dirty"&&n.dirty(),u.add(p.value)}return{status:n.value,value:u}}let l=[...r.data.values()].map((c,u)=>i._parse(new ot(r,c,r.path,u)));return r.common.async?Promise.all(l).then(c=>o(c)):o(l)}min(e,n){return new t({...this._def,minSize:{value:e,message:H.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:H.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};ts.create=(t,e)=>new ts({valueType:t,minSize:null,maxSize:null,typeName:X.ZodSet,...ee(e)});Li=class t extends se{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==L.function)return M(n,{code:A.invalid_type,expected:L.function,received:n.parsedType}),J;function r(l,c){return Hs({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Vr(),Ft].filter(u=>!!u),issueData:{code:A.invalid_arguments,argumentsError:c}})}function s(l,c){return Hs({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Vr(),Ft].filter(u=>!!u),issueData:{code:A.invalid_return_type,returnTypeError:c}})}let i={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof bn){let l=this;return Oe(async function(...c){let u=new Ke([]),p=await l._def.args.parseAsync(c,i).catch(v=>{throw u.addIssue(r(c,v)),u}),f=await Reflect.apply(o,this,p);return await l._def.returns._def.type.parseAsync(f,i).catch(v=>{throw u.addIssue(s(f,v)),u})})}else{let l=this;return Oe(function(...c){let u=l._def.args.safeParse(c,i);if(!u.success)throw new Ke([r(c,u.error)]);let p=Reflect.apply(o,this,u.data),f=l._def.returns.safeParse(p,i);if(!f.success)throw new Ke([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:Rt.create(e).rest(Ht.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||Rt.create([]).rest(Ht.create()),returns:n||Ht.create(),typeName:X.ZodFunction,...ee(r)})}},Yn=class extends se{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})}};Yn.create=(t,e)=>new Yn({getter:t,typeName:X.ZodLazy,...ee(e)});Jn=class extends se{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return M(n,{received:n.data,code:A.invalid_literal,expected:this._def.value}),J}return{status:"valid",value:e.data}}get value(){return this._def.value}};Jn.create=(t,e)=>new Jn({value:t,typeName:X.ZodLiteral,...ee(e)});Xn=class t extends se{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return M(n,{expected:ae.joinValues(r),received:n.parsedType,code:A.invalid_type}),J}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 M(n,{received:n.data,code:A.invalid_enum_value,options:r}),J}return Oe(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})}};Xn.create=Nu;Qn=class extends se{_parse(e){let n=ae.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==L.string&&r.parsedType!==L.number){let s=ae.objectValues(n);return M(r,{expected:ae.joinValues(s),received:r.parsedType,code:A.invalid_type}),J}if(this._cache||(this._cache=new Set(ae.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=ae.objectValues(n);return M(r,{received:r.data,code:A.invalid_enum_value,options:s}),J}return Oe(e.data)}get enum(){return this._def.values}};Qn.create=(t,e)=>new Qn({values:t,typeName:X.ZodNativeEnum,...ee(e)});bn=class extends se{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==L.promise&&n.common.async===!1)return M(n,{code:A.invalid_type,expected:L.promise,received:n.parsedType}),J;let r=n.parsedType===L.promise?n.data:Promise.resolve(n.data);return Oe(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};bn.create=(t,e)=>new bn({type:t,typeName:X.ZodPromise,...ee(e)});at=class extends se{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===X.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=>{M(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 J;let c=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return c.status==="aborted"?J:c.status==="dirty"?qn(c.value):n.value==="dirty"?qn(c.value):c});{if(n.value==="aborted")return J;let l=this._def.schema._parseSync({data:o,path:r.path,parent:r});return l.status==="aborted"?J:l.status==="dirty"?qn(l.value):n.value==="dirty"?qn(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"?J:(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"?J:(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(!mn(o))return J;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=>mn(o)?Promise.resolve(s.transform(o.value,i)).then(l=>({status:n.value,value:l})):J);ae.assertNever(s)}};at.create=(t,e,n)=>new at({schema:t,typeName:X.ZodEffects,effect:e,...ee(n)});at.createWithPreprocess=(t,e,n)=>new at({schema:e,effect:{type:"preprocess",transform:t},typeName:X.ZodEffects,...ee(n)});it=class extends se{_parse(e){return this._getType(e)===L.undefined?Oe(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};it.create=(t,e)=>new it({innerType:t,typeName:X.ZodOptional,...ee(e)});At=class extends se{_parse(e){return this._getType(e)===L.null?Oe(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};At.create=(t,e)=>new At({innerType:t,typeName:X.ZodNullable,...ee(e)});er=class extends se{_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}};er.create=(t,e)=>new er({innerType:t,typeName:X.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ee(e)});tr=class extends se{_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 Yr(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Ke(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ke(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};tr.create=(t,e)=>new tr({innerType:t,typeName:X.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ee(e)});ns=class extends se{_parse(e){if(this._getType(e)!==L.nan){let r=this._getOrReturnCtx(e);return M(r,{code:A.invalid_type,expected:L.nan,received:r.parsedType}),J}return{status:"valid",value:e.data}}};ns.create=t=>new ns({typeName:X.ZodNaN,...ee(t)});Kg=Symbol("zod_brand"),Ks=class extends se{_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}},Gs=class t extends se{_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"?J:i.status==="dirty"?(n.dirty(),qn(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"?J: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:X.ZodPipeline})}},nr=class extends se{_parse(e){let n=this._def.innerType._parse(e),r=s=>(mn(s)&&(s.value=Object.freeze(s.value)),s);return Yr(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};nr.create=(t,e)=>new nr({innerType:t,typeName:X.ZodReadonly,...ee(e)});Gg={object:Ge.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"})(X||(X={}));Wg=(t,e={message:`Input not instance of ${t.name}`})=>ju(n=>n instanceof t,e),Ou=gn.create,Mu=Fn.create,Zg=ns.create,Vg=Bn.create,Du=Hn.create,Yg=Kn.create,Jg=Xr.create,Xg=Gn.create,Qg=Wn.create,ey=yn.create,ty=Ht.create,ny=bt.create,ry=Qr.create,sy=Kt.create,iy=Ge.create,oy=Ge.strictCreate,ay=Zn.create,ly=Di.create,cy=Vn.create,uy=Rt.create,dy=zi.create,hy=es.create,py=ts.create,fy=Li.create,my=Yn.create,gy=Jn.create,yy=Xn.create,by=Qn.create,wy=bn.create,vy=at.create,ky=it.create,_y=At.create,Sy=at.createWithPreprocess,Ty=Gs.create,xy=()=>Ou().optional(),Iy=()=>Mu().optional(),Ey=()=>Du().optional(),Ry={string:(t=>gn.create({...t,coerce:!0})),number:(t=>Fn.create({...t,coerce:!0})),boolean:(t=>Hn.create({...t,coerce:!0})),bigint:(t=>Bn.create({...t,coerce:!0})),date:(t=>Kn.create({...t,coerce:!0}))},Ay=J});var _={};fn(_,{BRAND:()=>Kg,DIRTY:()=>qn,EMPTY_PATH:()=>Sg,INVALID:()=>J,NEVER:()=>Ay,OK:()=>Oe,ParseStatus:()=>Ce,Schema:()=>se,ZodAny:()=>yn,ZodArray:()=>Kt,ZodBigInt:()=>Bn,ZodBoolean:()=>Hn,ZodBranded:()=>Ks,ZodCatch:()=>tr,ZodDate:()=>Kn,ZodDefault:()=>er,ZodDiscriminatedUnion:()=>Di,ZodEffects:()=>at,ZodEnum:()=>Xn,ZodError:()=>Ke,ZodFirstPartyTypeKind:()=>X,ZodFunction:()=>Li,ZodIntersection:()=>Vn,ZodIssueCode:()=>A,ZodLazy:()=>Yn,ZodLiteral:()=>Jn,ZodMap:()=>es,ZodNaN:()=>ns,ZodNativeEnum:()=>Qn,ZodNever:()=>bt,ZodNull:()=>Wn,ZodNullable:()=>At,ZodNumber:()=>Fn,ZodObject:()=>Ge,ZodOptional:()=>it,ZodParsedType:()=>L,ZodPipeline:()=>Gs,ZodPromise:()=>bn,ZodReadonly:()=>nr,ZodRecord:()=>zi,ZodSchema:()=>se,ZodSet:()=>ts,ZodString:()=>gn,ZodSymbol:()=>Xr,ZodTransformer:()=>at,ZodTuple:()=>Rt,ZodType:()=>se,ZodUndefined:()=>Gn,ZodUnion:()=>Zn,ZodUnknown:()=>Ht,ZodVoid:()=>Qr,addIssueToContext:()=>M,any:()=>ey,array:()=>sy,bigint:()=>Vg,boolean:()=>Du,coerce:()=>Ry,custom:()=>ju,date:()=>Yg,datetimeRegex:()=>Pu,defaultErrorMap:()=>Ft,discriminatedUnion:()=>ly,effect:()=>vy,enum:()=>yy,function:()=>fy,getErrorMap:()=>Vr,getParsedType:()=>Et,instanceof:()=>Wg,intersection:()=>cy,isAborted:()=>Oi,isAsync:()=>Yr,isDirty:()=>Mi,isValid:()=>mn,late:()=>Gg,lazy:()=>my,literal:()=>gy,makeIssue:()=>Hs,map:()=>hy,nan:()=>Zg,nativeEnum:()=>by,never:()=>ny,null:()=>Qg,nullable:()=>_y,number:()=>Mu,object:()=>iy,objectUtil:()=>Ca,oboolean:()=>Ey,onumber:()=>Iy,optional:()=>ky,ostring:()=>xy,pipeline:()=>Ty,preprocess:()=>Sy,promise:()=>wy,quotelessJson:()=>vg,record:()=>dy,set:()=>py,setErrorMap:()=>_g,strictObject:()=>oy,string:()=>Ou,symbol:()=>Jg,transformer:()=>vy,tuple:()=>uy,undefined:()=>Xg,union:()=>ay,unknown:()=>ty,util:()=>ae,void:()=>ry});var Oa=we(()=>{ji();Pa();Iu();Bs();zu();Ni()});var rs=we(()=>{Oa();Oa()});function le(){let t=process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR;if(t)return t;let e=qi.default.join(Ui.default.homedir(),".config","allwright"),n=qi.default.join(Ui.default.homedir(),".config","ticketpilot");return!Gt.default.existsSync(e)&&Gt.default.existsSync(n)?n:e}function Wt(){return qi.default.join(le(),"runner.json")}function ke(){let t=Wt();if(!Gt.default.existsSync(t))return null;let e=JSON.parse(Gt.default.readFileSync(t,"utf8"));return Ma.parse(e)}function be(t){let e=le();Gt.default.mkdirSync(e,{recursive:!0,mode:448});let n=Wt(),r=n+".tmp";Gt.default.writeFileSync(r,JSON.stringify(t,null,2)+`
24
- `,{mode:384}),Gt.default.renameSync(r,n),Gt.default.chmodSync(n,384)}function Fi(t,e){return`${t}:${e}`}function Zt(t,e,n){return t.environments[Fi(e,n)]?.secrets??{}}function Bi(t,e){return t.repos[e]?.jira??t.jira}function Hi(t){return!t.jira&&!Object.values(t.repos).some(e=>e.jira)}function ue(){let t=ke();if(!t)throw new Error(`No runner config found at ${Wt()}. Run \`allwright init\` first.`);return t}var Gt,Ui,qi,Lu,Ma,$e=we(()=>{"use strict";Gt=R(require("node:fs"),1),Ui=R(require("node:os"),1),qi=R(require("node:path"),1);rs();Lu=_.object({baseUrl:_.string().url(),email:_.string().email(),apiToken:_.string().min(1)}),Ma=_.object({controlPlaneUrl:_.string().url(),runnerId:_.string().optional(),runnerToken:_.string().optional(),runnerName:_.string().default(Ui.default.hostname()),jira:Lu.optional(),repos:_.record(_.object({path:_.string(),jira:Lu.optional(),github:_.object({token:_.string().min(1),login:_.string().optional()}).optional()})).default({}),github:_.object({token:_.string().min(1),login:_.string().optional()}).optional(),githubUsers:_.record(_.object({token:_.string().min(1),login:_.string().optional()})).default({}),deploy:_.object({enabled:_.boolean().default(!1)}).default({enabled:!1}),environments:_.record(_.object({secrets:_.record(_.string()).default({})})).default({}),claudeProfiles:_.record(_.object({configDir:_.string()})).default({}),claudeBin:_.string().default("claude"),agents:_.record(_.object({bin:_.string()})).default({}),jiraUsers:_.record(_.object({email:_.string().email(),apiToken:_.string().min(1)})).default({}),auditSchedules:_.array(_.object({repoName:_.string(),role:_.enum(["security","testing"]),intervalHours:_.number().int().min(6).max(720)})).default([]),pollIntervalSeconds:_.number().int().min(10).max(600).default(30)})});var Ws=ce(pe=>{"use strict";Object.defineProperty(pe,"__esModule",{value:!0});pe.getParsedType=pe.ZodParsedType=pe.objectUtil=pe.util=void 0;var Ua;(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})(Ua||(pe.util=Ua={}));var Yu;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Yu||(pe.objectUtil=Yu={}));pe.ZodParsedType=Ua.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var Dy=t=>{switch(typeof t){case"undefined":return pe.ZodParsedType.undefined;case"string":return pe.ZodParsedType.string;case"number":return Number.isNaN(t)?pe.ZodParsedType.nan:pe.ZodParsedType.number;case"boolean":return pe.ZodParsedType.boolean;case"function":return pe.ZodParsedType.function;case"bigint":return pe.ZodParsedType.bigint;case"symbol":return pe.ZodParsedType.symbol;case"object":return Array.isArray(t)?pe.ZodParsedType.array:t===null?pe.ZodParsedType.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?pe.ZodParsedType.promise:typeof Map<"u"&&t instanceof Map?pe.ZodParsedType.map:typeof Set<"u"&&t instanceof Set?pe.ZodParsedType.set:typeof Date<"u"&&t instanceof Date?pe.ZodParsedType.date:pe.ZodParsedType.object;default:return pe.ZodParsedType.unknown}};pe.getParsedType=Dy});var Yi=ce(kn=>{"use strict";Object.defineProperty(kn,"__esModule",{value:!0});kn.ZodError=kn.quotelessJson=kn.ZodIssueCode=void 0;var Ju=Ws();kn.ZodIssueCode=Ju.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 zy=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");kn.quotelessJson=zy;var Zs=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(i){return i.message},r={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)r._errors.push(n(o));else{let l=r,c=0;for(;c<o.path.length;){let u=o.path[c];c===o.path.length-1?(l[u]=l[u]||{_errors:[]},l[u]._errors.push(n(o))):l[u]=l[u]||{_errors:[]},l=l[u],c++}}};return s(this),r}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ju.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()}};kn.ZodError=Zs;Zs.create=t=>new Zs(t)});var Fa=ce(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});var Me=Yi(),ir=Ws(),Ly=(t,e)=>{let n;switch(t.code){case Me.ZodIssueCode.invalid_type:t.received===ir.ZodParsedType.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case Me.ZodIssueCode.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,ir.util.jsonStringifyReplacer)}`;break;case Me.ZodIssueCode.unrecognized_keys:n=`Unrecognized key(s) in object: ${ir.util.joinValues(t.keys,", ")}`;break;case Me.ZodIssueCode.invalid_union:n="Invalid input";break;case Me.ZodIssueCode.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ir.util.joinValues(t.options)}`;break;case Me.ZodIssueCode.invalid_enum_value:n=`Invalid enum value. Expected ${ir.util.joinValues(t.options)}, received '${t.received}'`;break;case Me.ZodIssueCode.invalid_arguments:n="Invalid function arguments";break;case Me.ZodIssueCode.invalid_return_type:n="Invalid function return type";break;case Me.ZodIssueCode.invalid_date:n="Invalid date";break;case Me.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}"`:ir.util.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case Me.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 Me.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 Me.ZodIssueCode.custom:n="Invalid input";break;case Me.ZodIssueCode.invalid_intersection_types:n="Intersection results could not be merged";break;case Me.ZodIssueCode.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case Me.ZodIssueCode.not_finite:n="Number must be finite";break;default:n=e.defaultError,ir.util.assertNever(t)}return{message:n}};qa.default=Ly});var Ji=ce(_n=>{"use strict";var Uy=_n&&_n.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(_n,"__esModule",{value:!0});_n.defaultErrorMap=void 0;_n.setErrorMap=qy;_n.getErrorMap=Fy;var Xu=Uy(Fa());_n.defaultErrorMap=Xu.default;var Qu=Xu.default;function qy(t){Qu=t}function Fy(){return Qu}});var Ha=ce(de=>{"use strict";var By=de&&de.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(de,"__esModule",{value:!0});de.isAsync=de.isValid=de.isDirty=de.isAborted=de.OK=de.DIRTY=de.INVALID=de.ParseStatus=de.EMPTY_PATH=de.makeIssue=void 0;de.addIssueToContext=Gy;var Hy=Ji(),ed=By(Fa()),Ky=t=>{let{data:e,path:n,errorMaps:r,issueData:s}=t,i=[...n,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let l="",c=r.filter(u=>!!u).slice().reverse();for(let u of c)l=u(o,{data:e,defaultError:l}).message;return{...s,path:i,message:l}};de.makeIssue=Ky;de.EMPTY_PATH=[];function Gy(t,e){let n=(0,Hy.getErrorMap)(),r=(0,de.makeIssue)({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===ed.default?void 0:ed.default].filter(s=>!!s)});t.common.issues.push(r)}var Ba=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 de.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 de.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}}};de.ParseStatus=Ba;de.INVALID=Object.freeze({status:"aborted"});var Wy=t=>({status:"dirty",value:t});de.DIRTY=Wy;var Zy=t=>({status:"valid",value:t});de.OK=Zy;var Vy=t=>t.status==="aborted";de.isAborted=Vy;var Yy=t=>t.status==="dirty";de.isDirty=Yy;var Jy=t=>t.status==="valid";de.isValid=Jy;var Xy=t=>typeof Promise<"u"&&t instanceof Promise;de.isAsync=Xy});var nd=ce(td=>{"use strict";Object.defineProperty(td,"__esModule",{value:!0})});var sd=ce(Xi=>{"use strict";Object.defineProperty(Xi,"__esModule",{value:!0});Xi.errorUtil=void 0;var rd;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(rd||(Xi.errorUtil=rd={}))});var gd=ce(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=cd;S.custom=dd;var N=Yi(),Qi=Ji(),G=sd(),T=Ha(),O=Ws(),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}},id=(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 te(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 ne=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 id(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 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: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: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 $t.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Jt.create(this)}promise(){return xn.create(this,this._def)}or(e){return hr.create([this,e],this._def)}and(e){return pr.create(this,e,this._def)}transform(e){return new et({...te(this._def),schema:this,typeName:Q.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new br({...te(this._def),innerType:this,defaultValue:n,typeName:Q.ZodDefault})}brand(){return new Vs({typeName:Q.ZodBranded,type:this,...te(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new wr({...te(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 Ys.create(this,e)}readonly(){return vr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};S.ZodType=ne;S.Schema=ne;S.ZodSchema=ne;var Qy=/^c[^\s-]{8,}$/i,eb=/^[0-9a-z]+$/,tb=/^[0-9A-HJKMNP-TV-Z]{26}$/i,nb=/^[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,rb=/^[a-z0-9_-]{21}$/i,sb=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ib=/^[-+]?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)?)??$/,ob=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ab="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ka,lb=/^(?:(?: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])$/,cb=/^(?:(?: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])$/,ub=/^(([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]))$/,db=/^(([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])$/,hb=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,pb=/^([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])))",fb=new RegExp(`^${ad}$`);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 mb(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 gb(t,e){return!!((e==="v4"||!e)&&lb.test(t)||(e==="v6"||!e)&&ub.test(t))}function yb(t,e){if(!sb.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 bb(t,e){return!!((e==="v4"||!e)&&cb.test(t)||(e==="v6"||!e)&&db.test(t))}var Sn=class t extends ne{_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")ob.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")Ka||(Ka=new RegExp(ab,"u")),Ka.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")nb.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")rb.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")Qy.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")eb.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")tb.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"?cd(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"?fb.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"?mb(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"?ib.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"?gb(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"?yb(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"?bb(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"?hb.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"?pb.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,...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=Sn;Sn.create=t=>new Sn({checks:[],typeName:Q.ZodString,coerce:t?.coerce??!1,...te(t)});function wb(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 or=class t extends ne{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"?wb(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,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"&&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=or;or.create=t=>new or({checks:[],typeName:Q.ZodNumber,coerce:t?.coerce||!1,...te(t)});var ar=class t extends ne{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,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=ar;ar.create=t=>new ar({checks:[],typeName:Q.ZodBigInt,coerce:t?.coerce??!1,...te(t)});var lr=class extends ne{_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=lr;lr.create=t=>new lr({typeName:Q.ZodBoolean,coerce:t?.coerce||!1,...te(t)});var cr=class t extends ne{_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: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=cr;cr.create=t=>new cr({checks:[],coerce:t?.coerce||!1,typeName:Q.ZodDate,...te(t)});var cs=class extends ne{_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=cs;cs.create=t=>new cs({typeName:Q.ZodSymbol,...te(t)});var ur=class extends ne{_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=ur;ur.create=t=>new ur({typeName:Q.ZodUndefined,...te(t)});var dr=class extends ne{_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=dr;dr.create=t=>new dr({typeName:Q.ZodNull,...te(t)});var Tn=class extends ne{constructor(){super(...arguments),this._any=!0}_parse(e){return(0,T.OK)(e.data)}};S.ZodAny=Tn;Tn.create=t=>new Tn({typeName:Q.ZodAny,...te(t)});var Yt=class extends ne{constructor(){super(...arguments),this._unknown=!0}_parse(e){return(0,T.OK)(e.data)}};S.ZodUnknown=Yt;Yt.create=t=>new Yt({typeName:Q.ZodUnknown,...te(t)});var wt=class extends ne{_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=wt;wt.create=t=>new wt({typeName:Q.ZodNever,...te(t)});var us=class extends ne{_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=us;us.create=t=>new us({typeName:Q.ZodVoid,...te(t)});var Jt=class t extends ne{_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 ct(n,o,n.path,l)))).then(o=>T.ParseStatus.mergeArray(r,o));let i=[...n.data].map((o,l)=>s.type._parseSync(new ct(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=Jt;Jt.create=(t,e)=>new Jt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Q.ZodArray,...te(e)});function ls(t){if(t instanceof We){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=lt.create(ls(r))}return new We({...t._def,shape:()=>e})}else return t instanceof Jt?new Jt({...t._def,type:ls(t.element)}):t instanceof lt?lt.create(ls(t.unwrap())):t instanceof $t?$t.create(ls(t.unwrap())):t instanceof Ct?Ct.create(t.items.map(e=>ls(e))):t}var We=class t extends ne{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 u=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(u,{code:N.ZodIssueCode.invalid_type,expected:O.ZodParsedType.object,received:u.parsedType}),T.INVALID}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),l=[];if(!(this._def.catchall instanceof wt&&this._def.unknownKeys==="strip"))for(let u in s.data)o.includes(u)||l.push(u);let c=[];for(let u of o){let p=i[u],f=s.data[u];c.push({key:{status:"valid",value:u},value:p._parse(new ct(s,f,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof wt){let u=this._def.unknownKeys;if(u==="passthrough")for(let p of l)c.push({key:{status:"valid",value:p},value:{status:"valid",value:s.data[p]}});else if(u==="strict")l.length>0&&((0,T.addIssueToContext)(s,{code:N.ZodIssueCode.unrecognized_keys,keys:l}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let p of l){let f=s.data[p];c.push({key:{status:"valid",value:p},value:u._parse(new ct(s,f,s.path,p)),alwaysSet:p in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let u=[];for(let p of c){let f=await p.key,w=await p.value;u.push({key:f,value:w,alwaysSet:p.alwaysSet})}return u}).then(u=>T.ParseStatus.mergeObjectSync(r,u)):T.ParseStatus.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return 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: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 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 ls(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 lt;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return ud(O.util.objectKeys(this.shape))}};S.ZodObject=We;We.create=(t,e)=>new We({shape:()=>t,unknownKeys:"strip",catchall:wt.create(),typeName:Q.ZodObject,...te(e)});We.strictCreate=(t,e)=>new We({shape:()=>t,unknownKeys:"strict",catchall:wt.create(),typeName:Q.ZodObject,...te(e)});We.lazycreate=(t,e)=>new We({shape:t,unknownKeys:"strip",catchall:wt.create(),typeName:Q.ZodObject,...te(e)});var hr=class extends ne{_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 u={...n,common:{...n.common,issues:[]},parent:null},p=c._parseSync({data:n.data,path:n.path,parent:u});if(p.status==="valid")return p;p.status==="dirty"&&!i&&(i={result:p,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let l=o.map(c=>new 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=hr;hr.create=(t,e)=>new hr({options:t,typeName:Q.ZodUnion,...te(e)});var Vt=t=>t instanceof fr?Vt(t.schema):t instanceof et?Vt(t.innerType()):t instanceof mr?[t.value]:t instanceof gr?t.options:t instanceof yr?O.util.objectValues(t.enum):t instanceof br?Vt(t._def.innerType):t instanceof ur?[void 0]:t instanceof dr?[null]:t instanceof lt?[void 0,...Vt(t.unwrap())]:t instanceof $t?[null,...Vt(t.unwrap())]:t instanceof Vs||t instanceof vr?Vt(t.unwrap()):t instanceof wr?Vt(t._def.innerType):[],eo=class t extends ne{_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=Vt(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,...te(r)})}};S.ZodDiscriminatedUnion=eo;function Ga(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=Ga(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=Ga(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 pr=class extends ne{_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=Ga(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=pr;pr.create=(t,e,n)=>new pr({left:t,right:e,typeName:Q.ZodIntersection,...te(n)});var Ct=class t extends ne{_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 ct(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=Ct;Ct.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ct({items:t,typeName:Q.ZodTuple,rest:null,...te(e)})};var to=class t extends ne{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 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?T.ParseStatus.mergeObjectAsync(n,s):T.ParseStatus.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof ne?new t({keyType:e,valueType:n,typeName:Q.ZodRecord,...te(r)}):new t({keyType:Sn.create(),valueType:e,typeName:Q.ZodRecord,...te(n)})}};S.ZodRecord=to;var ds=class extends ne{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],u)=>({key:s._parse(new ct(r,l,r.path,[u,"key"])),value:i._parse(new ct(r,c,r.path,[u,"value"]))}));if(r.common.async){let l=new Map;return Promise.resolve().then(async()=>{for(let c of o){let u=await c.key,p=await c.value;if(u.status==="aborted"||p.status==="aborted")return T.INVALID;(u.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(u.value,p.value)}return{status:n.value,value:l}})}else{let l=new Map;for(let c of o){let u=c.key,p=c.value;if(u.status==="aborted"||p.status==="aborted")return T.INVALID;(u.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(u.value,p.value)}return{status:n.value,value:l}}}};S.ZodMap=ds;ds.create=(t,e,n)=>new ds({valueType:e,keyType:t,typeName:Q.ZodMap,...te(n)});var hs=class t extends ne{_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 u=new Set;for(let p of c){if(p.status==="aborted")return T.INVALID;p.status==="dirty"&&n.dirty(),u.add(p.value)}return{status:n.value,value:u}}let l=[...r.data.values()].map((c,u)=>i._parse(new ct(r,c,r.path,u)));return r.common.async?Promise.all(l).then(c=>o(c)):o(l)}min(e,n){return new t({...this._def,minSize:{value:e,message: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=hs;hs.create=(t,e)=>new hs({valueType:t,minSize:null,maxSize:null,typeName:Q.ZodSet,...te(e)});var no=class t extends ne{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,Qi.getErrorMap)(),Qi.defaultErrorMap].filter(u=>!!u),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,Qi.getErrorMap)(),Qi.defaultErrorMap].filter(u=>!!u),issueData:{code:N.ZodIssueCode.invalid_return_type,returnTypeError:c}})}let i={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof xn){let l=this;return(0,T.OK)(async function(...c){let u=new N.ZodError([]),p=await l._def.args.parseAsync(c,i).catch(v=>{throw u.addIssue(r(c,v)),u}),f=await Reflect.apply(o,this,p);return await l._def.returns._def.type.parseAsync(f,i).catch(v=>{throw u.addIssue(s(f,v)),u})})}else{let l=this;return(0,T.OK)(function(...c){let u=l._def.args.safeParse(c,i);if(!u.success)throw new N.ZodError([r(c,u.error)]);let p=Reflect.apply(o,this,u.data),f=l._def.returns.safeParse(p,i);if(!f.success)throw new 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:Ct.create(e).rest(Yt.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||Ct.create([]).rest(Yt.create()),returns:n||Yt.create(),typeName:Q.ZodFunction,...te(r)})}};S.ZodFunction=no;var fr=class extends ne{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=fr;fr.create=(t,e)=>new fr({getter:t,typeName:Q.ZodLazy,...te(e)});var mr=class extends ne{_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=mr;mr.create=(t,e)=>new mr({value:t,typeName:Q.ZodLiteral,...te(e)});function ud(t,e){return new gr({values:t,typeName:Q.ZodEnum,...te(e)})}var gr=class t extends ne{_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=gr;gr.create=ud;var yr=class extends ne{_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=yr;yr.create=(t,e)=>new yr({values:t,typeName:Q.ZodNativeEnum,...te(e)});var xn=class extends ne{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=xn;xn.create=(t,e)=>new xn({type:t,typeName:Q.ZodPromise,...te(e)});var et=class extends ne{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=>{(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=et;S.ZodTransformer=et;et.create=(t,e,n)=>new et({schema:t,typeName:Q.ZodEffects,effect:e,...te(n)});et.createWithPreprocess=(t,e,n)=>new et({schema:e,effect:{type:"preprocess",transform:t},typeName:Q.ZodEffects,...te(n)});var lt=class extends ne{_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=lt;lt.create=(t,e)=>new lt({innerType:t,typeName:Q.ZodOptional,...te(e)});var $t=class extends ne{_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=$t;$t.create=(t,e)=>new $t({innerType:t,typeName:Q.ZodNullable,...te(e)});var br=class extends ne{_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=br;br.create=(t,e)=>new br({innerType:t,typeName:Q.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...te(e)});var wr=class extends ne{_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=wr;wr.create=(t,e)=>new wr({innerType:t,typeName:Q.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...te(e)});var ps=class extends ne{_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=ps;ps.create=t=>new ps({typeName:Q.ZodNaN,...te(t)});S.BRAND=Symbol("zod_brand");var Vs=class extends ne{_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=Vs;var Ys=class t extends ne{_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:Q.ZodPipeline})}};S.ZodPipeline=Ys;var vr=class extends ne{_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=vr;vr.create=(t,e)=>new vr({innerType:t,typeName:Q.ZodReadonly,...te(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?Tn.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})}}):Tn.create()}S.late={object:We.lazycreate};var Q;(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||(S.ZodFirstPartyTypeKind=Q={}));var vb=(t,e={message:`Input not instance of ${t.name}`})=>dd(n=>n instanceof t,e);S.instanceof=vb;var hd=Sn.create;S.string=hd;var pd=or.create;S.number=pd;var kb=ps.create;S.nan=kb;var _b=ar.create;S.bigint=_b;var fd=lr.create;S.boolean=fd;var Sb=cr.create;S.date=Sb;var Tb=cs.create;S.symbol=Tb;var xb=ur.create;S.undefined=xb;var Ib=dr.create;S.null=Ib;var Eb=Tn.create;S.any=Eb;var Rb=Yt.create;S.unknown=Rb;var Ab=wt.create;S.never=Ab;var Cb=us.create;S.void=Cb;var $b=Jt.create;S.array=$b;var Pb=We.create;S.object=Pb;var Nb=We.strictCreate;S.strictObject=Nb;var jb=hr.create;S.union=jb;var Ob=eo.create;S.discriminatedUnion=Ob;var Mb=pr.create;S.intersection=Mb;var Db=Ct.create;S.tuple=Db;var zb=to.create;S.record=zb;var Lb=ds.create;S.map=Lb;var Ub=hs.create;S.set=Ub;var qb=no.create;S.function=qb;var Fb=fr.create;S.lazy=Fb;var Bb=mr.create;S.literal=Bb;var Hb=gr.create;S.enum=Hb;var Kb=yr.create;S.nativeEnum=Kb;var Gb=xn.create;S.promise=Gb;var md=et.create;S.effect=md;S.transformer=md;var Wb=lt.create;S.optional=Wb;var Zb=$t.create;S.nullable=Zb;var Vb=et.createWithPreprocess;S.preprocess=Vb;var Yb=Ys.create;S.pipeline=Yb;var Jb=()=>hd().optional();S.ostring=Jb;var Xb=()=>pd().optional();S.onumber=Xb;var Qb=()=>fd().optional();S.oboolean=Qb;S.coerce={string:(t=>Sn.create({...t,coerce:!0})),number:(t=>or.create({...t,coerce:!0})),boolean:(t=>lr.create({...t,coerce:!0})),bigint:(t=>ar.create({...t,coerce:!0})),date:(t=>cr.create({...t,coerce:!0}))};S.NEVER=T.INVALID});var Wa=ce(ut=>{"use strict";var ew=ut&&ut.__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]})),fs=ut&&ut.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&ew(e,t,n)};Object.defineProperty(ut,"__esModule",{value:!0});fs(Ji(),ut);fs(Ha(),ut);fs(nd(),ut);fs(Ws(),ut);fs(gd(),ut);fs(Yi(),ut)});var wd=ce(Ze=>{"use strict";var yd=Ze&&Ze.__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]})),tw=Ze&&Ze.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),nw=Ze&&Ze.__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 tw(e,t),e},rw=Ze&&Ze.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&yd(e,t,n)};Object.defineProperty(Ze,"__esModule",{value:!0});Ze.z=void 0;var bd=nw(Wa());Ze.z=bd;rw(Wa(),Ze);Ze.default=bd});var xe=ce(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.ChatFile=h.TeamCredsResultMsg=h.TeamCredsMsg=h.KnowledgeSaveResultMsg=h.KnowledgeSaveMsg=h.KnowledgeListResultMsg=h.KnowledgeFile=h.KnowledgeListMsg=h.AuditReviewResultMsg=h.AuditReviewMsg=h.AuditGetResultMsg=h.AuditGetMsg=h.AuditExplainResultMsg=h.AuditExplainMsg=h.ChatCancelMsg=h.ChatDiagnosticResultMsg=h.ChatDiagnosticMsg=h.AuditListResultMsg=h.AuditStatsResultMsg=h.AuditStatsMsg=h.AuditListMsg=h.AuditStartResultMsg=h.AuditStartMsg=h.AuditRecord=h.AuditFinding=h.AuditDetailLevel=h.AuditScope=h.AuditSeverity=h.KnowledgeRole=h.AuditRole=h.EpicSuggestResultMsg=h.EpicSuggestMsg=h.EpicListResultMsg=h.EpicChild=h.EpicListMsg=h.BoardTriggerResultMsg=h.BoardTriggerMsg=h.BoardFetchResultMsg=h.BoardFetchMsg=h.RepoDocReadResultMsg=h.RepoDocReadMsg=h.RepoDocsResultMsg=h.RepoDocsMsg=h.ChatLoadResultMsg=h.TICKET_RULES_APPENDIX=h.COMPOSE_COMMANDS=h.REPLY_STYLES=h.BUILTIN_REPLY_LANGUAGES=h.ChatLoadMsg=h.ChatListResultMsg=void 0;h.RunApprovedMsg=h.RunCancelMsg=h.RuleDiagnoseMsg=h.ProjectTestMsg=h.RunClaimResultMsg=h.ConfigMsg=h.HelloAckMsg=h.RunnerToServerMsg=h.AutopilotReportMsg=h.AutopilotNextResultMsg=h.AutopilotPlanResultMsg=h.AutopilotPlanMsg=h.AutopilotNextMsg=h.RunnerUninstallResultMsg=h.RunnerUpdateResultMsg=h.AgentProfilesResultMsg=h.AgentProfilesMsg=h.RunPrConflictMsg=h.RunResolveConflictResultMsg=h.RunAnswerResultMsg=h.RunAnswerMsg=h.RunTestFixResultMsg=h.RunTestFixMsg=h.RunResolveConflictMsg=h.RunnerUninstallMsg=h.RunnerUpdateMsg=h.RepoDocSaveResultMsg=h.RepoDocSaveMsg=h.SetupClaudeMdSaveResultMsg=h.SetupClaudeMdSaveMsg=h.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=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=void 0;h.missingAgentCapabilities=sw;h.replyPreferenceAppendix=ow;h.pendingMigrationsAppendix=aw;h.deployTargetsAppendix=lw;h.composeCommandAppendix=cw;h.isSelfMigrationFilename=uw;h.parseRunnerMsg=dw;h.parseServerMsg=hw;var a=wd();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.81";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 sw(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 iw=t=>t.includes(h.NEEDS_INPUT_COMMENT_MARKER)||h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS.some(e=>t.includes(e));h.needsInputMarkerIn=iw;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)})).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 ow(t){let e=[],n=(t.language??"").trim();if(n){let s=h.BUILTIN_REPLY_LANGUAGES.find(i=>i.name.toLowerCase()===n.toLowerCase());e.push((t.languageInstruction??"").trim()||s?.instruction||`Write your prose in ${n}.`),e.push("Code, file paths, identifiers, commands, error text and log output stay exactly as they are - only your own prose changes language."),e.push("The ```ticket block is the exception: its summary and description are ALWAYS written in English, because the ticket is read by other people and by the implementing agent.")}let r=h.REPLY_STYLES.find(s=>s.id===(t.style??"").trim());return r&&e.push(r.instruction),e.length?`
23
+ `)}),this}_outputHelpIfRequested(e){let n=this._getHelpOption();n&&e.find(s=>n.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function gu(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})}yu.Command=Ra});var _u=ce(st=>{var{Argument:wu}=Pi(),{Command:Aa}=bu(),{CommanderError:bg,InvalidArgumentError:vu}=Fs(),{Help:wg}=va(),{Option:ku}=Ta();st.program=new Aa;st.createCommand=t=>new Aa(t);st.createOption=(t,e)=>new ku(t,e);st.createArgument=(t,e)=>new wu(t,e);st.Command=Aa;st.Option=ku;st.Argument=wu;st.Help=wg;st.CommanderError=bg;st.InvalidArgumentError=vu;st.InvalidOptionArgumentError=vu});var ae,Ca,L,It,Bs=we(()=>{(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})(ae||(ae={}));(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Ca||(Ca={}));L=ae.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),It=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 C,vg,Ke,Ni=we(()=>{Bs();C=ae.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"]),vg=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ke=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,ae.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()}};Ke.create=t=>new Ke(t)});var kg,Ft,$a=we(()=>{Ni();Bs();kg=(t,e)=>{let n;switch(t.code){case C.invalid_type:t.received===L.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case C.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,ae.jsonStringifyReplacer)}`;break;case C.unrecognized_keys:n=`Unrecognized key(s) in object: ${ae.joinValues(t.keys,", ")}`;break;case C.invalid_union:n="Invalid input";break;case C.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ae.joinValues(t.options)}`;break;case C.invalid_enum_value:n=`Invalid enum value. Expected ${ae.joinValues(t.options)}, received '${t.received}'`;break;case C.invalid_arguments:n="Invalid function arguments";break;case C.invalid_return_type:n="Invalid function return type";break;case C.invalid_date:n="Invalid date";break;case C.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}"`:ae.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case C.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 C.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 C.custom:n="Invalid input";break;case C.invalid_intersection_types:n="Intersection results could not be merged";break;case C.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case C.not_finite:n="Number must be finite";break;default:n=e.defaultError,ae.assertNever(t)}return{message:n}},Ft=kg});function _g(t){xu=t}function Vr(){return xu}var xu,Oi=we(()=>{$a();xu=Ft});function M(t,e){let n=Vr(),r=Hs({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Ft?void 0:Ft].filter(s=>!!s)});t.common.issues.push(r)}var Hs,Sg,Ce,J,qn,je,ji,Mi,mn,Yr,Pa=we(()=>{Oi();$a();Hs=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}},Sg=[];Ce=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 J;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 J;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}}},J=Object.freeze({status:"aborted"}),qn=t=>({status:"dirty",value:t}),je=t=>({status:"valid",value:t}),ji=t=>t.status==="aborted",Mi=t=>t.status==="dirty",mn=t=>t.status==="valid",Yr=t=>typeof Promise<"u"&&t instanceof Promise});var Eu=we(()=>{});var H,Iu=we(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(H||(H={}))});function ee(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:s}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,l)=>{let{message:c}=t;return o.code==="invalid_enum_value"?{message:c??l.defaultError}:typeof l.data>"u"?{message:c??r??l.defaultError}:o.code!=="invalid_type"?{message:l.defaultError}:{message:c??n??l.defaultError}},description:s}}function $u(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function Ug(t){return new RegExp(`^${$u(t)}$`)}function Pu(t){let e=`${Cu}T${$u(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function qg(t,e){return!!((e==="v4"||!e)&&Ng.test(t)||(e==="v6"||!e)&&jg.test(t))}function Fg(t,e){if(!Ag.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function Bg(t,e){return!!((e==="v4"||!e)&&Og.test(t)||(e==="v6"||!e)&&Mg.test(t))}function Hg(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 Jr(t){if(t instanceof Ge){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=it.create(Jr(r))}return new Ge({...t._def,shape:()=>e})}else return t instanceof Kt?new Kt({...t._def,type:Jr(t.element)}):t instanceof it?it.create(Jr(t.unwrap())):t instanceof At?At.create(Jr(t.unwrap())):t instanceof Rt?Rt.create(t.items.map(e=>Jr(e))):t}function Oa(t,e){let n=It(t),r=It(e);if(t===e)return{valid:!0,data:t};if(n===L.object&&r===L.object){let s=ae.objectKeys(e),i=ae.objectKeys(t).filter(l=>s.indexOf(l)!==-1),o={...t,...e};for(let l of i){let c=Oa(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=Oa(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 Nu(t,e){return new Xn({values:t,typeName:X.ZodEnum,...ee(e)})}function Au(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function Ou(t,e={},n){return t?yn.create().superRefine((r,s)=>{let i=t(r);if(i instanceof Promise)return i.then(o=>{if(!o){let l=Au(e,r),c=l.fatal??n??!0;s.addIssue({code:"custom",...l,fatal:c})}});if(!i){let o=Au(e,r),l=o.fatal??n??!0;s.addIssue({code:"custom",...o,fatal:l})}}):yn.create()}var ot,Ru,se,Tg,xg,Eg,Ig,Rg,Ag,Cg,$g,Pg,Na,Ng,Og,jg,Mg,Dg,zg,Cu,Lg,gn,Fn,Bn,Hn,Kn,Xr,Gn,Wn,yn,Ht,bt,Qr,Kt,Ge,Zn,Bt,Di,Vn,Rt,zi,es,ts,Li,Yn,Jn,Xn,Qn,bn,at,it,At,er,tr,ns,Kg,Ks,Gs,nr,Gg,X,Wg,ju,Mu,Zg,Vg,Du,Yg,Jg,Xg,Qg,ey,ty,ny,ry,sy,iy,oy,ay,ly,cy,uy,dy,hy,py,fy,my,gy,yy,by,wy,vy,ky,_y,Sy,Ty,xy,Ey,Iy,Ry,Ay,zu=we(()=>{Ni();Oi();Iu();Pa();Bs();ot=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}},Ru=(t,e)=>{if(mn(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 Ke(t.common.issues);return this._error=n,this._error}}};se=class{get description(){return this._def.description}_getType(e){return It(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:It(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ce,ctx:{common:e.parent.common,data:e.data,parsedType:It(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(Yr(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:It(e)},s=this._parseSync({data:e,path:r.path,parent:r});return Ru(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:It(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return mn(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=>mn(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:It(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(Yr(s)?s:Promise.resolve(s));return Ru(r,i)}refine(e,n){let r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,i)=>{let o=e(s),l=()=>i.addIssue({code:C.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 at({schema:this,typeName:X.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 it.create(this,this._def)}nullable(){return At.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Kt.create(this)}promise(){return bn.create(this,this._def)}or(e){return Zn.create([this,e],this._def)}and(e){return Vn.create(this,e,this._def)}transform(e){return new at({...ee(this._def),schema:this,typeName:X.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new er({...ee(this._def),innerType:this,defaultValue:n,typeName:X.ZodDefault})}brand(){return new Ks({typeName:X.ZodBranded,type:this,...ee(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new tr({...ee(this._def),innerType:this,catchValue:n,typeName:X.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Gs.create(this,e)}readonly(){return nr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Tg=/^c[^\s-]{8,}$/i,xg=/^[0-9a-z]+$/,Eg=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ig=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Rg=/^[a-z0-9_-]{21}$/i,Ag=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Cg=/^[-+]?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)?)??$/,$g=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Pg="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ng=/^(?:(?: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])$/,Og=/^(?:(?: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])$/,jg=/^(([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]))$/,Mg=/^(([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])$/,Dg=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,zg=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Cu="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Lg=new RegExp(`^${Cu}$`);gn=class t extends se{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==L.string){let i=this._getOrReturnCtx(e);return M(i,{code:C.invalid_type,expected:L.string,received:i.parsedType}),J}let r=new Ce,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),M(s,{code:C.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),M(s,{code:C.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?M(s,{code:C.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):l&&M(s,{code:C.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")$g.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"email",code:C.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Na||(Na=new RegExp(Pg,"u")),Na.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"emoji",code:C.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")Ig.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"uuid",code:C.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")Rg.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"nanoid",code:C.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")Tg.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"cuid",code:C.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")xg.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"cuid2",code:C.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")Eg.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"ulid",code:C.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),M(s,{validation:"url",code:C.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),M(s,{validation:"regex",code:C.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),M(s,{code:C.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),M(s,{code:C.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),M(s,{code:C.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Pu(i).test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{code:C.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?Lg.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{code:C.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Ug(i).test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{code:C.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?Cg.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"duration",code:C.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?qg(e.data,i.version)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"ip",code:C.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?Fg(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"jwt",code:C.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?Bg(e.data,i.version)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"cidr",code:C.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?Dg.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"base64",code:C.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?zg.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"base64url",code:C.invalid_string,message:i.message}),r.dirty()):ae.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:C.invalid_string,...H.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...H.errToObj(e)})}url(e){return this._addCheck({kind:"url",...H.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...H.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...H.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...H.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...H.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...H.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...H.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...H.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...H.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...H.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...H.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...H.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...H.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...H.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...H.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...H.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...H.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...H.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...H.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...H.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...H.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...H.errToObj(n)})}nonempty(e){return this.min(1,H.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}};gn.create=t=>new gn({checks:[],typeName:X.ZodString,coerce:t?.coerce??!1,...ee(t)});Fn=class t extends se{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 M(i,{code:C.invalid_type,expected:L.number,received:i.parsedType}),J}let r,s=new Ce;for(let i of this._def.checks)i.kind==="int"?ae.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),M(r,{code:C.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),M(r,{code:C.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),M(r,{code:C.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Hg(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),M(r,{code:C.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),M(r,{code:C.not_finite,message:i.message}),s.dirty()):ae.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,H.toString(n))}gt(e,n){return this.setLimit("min",e,!1,H.toString(n))}lte(e,n){return this.setLimit("max",e,!0,H.toString(n))}lt(e,n){return this.setLimit("max",e,!1,H.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:H.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:H.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:H.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:H.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:H.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:H.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:H.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:H.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:H.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:H.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"&&ae.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)}};Fn.create=t=>new Fn({checks:[],typeName:X.ZodNumber,coerce:t?.coerce||!1,...ee(t)});Bn=class t extends se{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 Ce;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),M(r,{code:C.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),M(r,{code:C.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),M(r,{code:C.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):ae.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return M(n,{code:C.invalid_type,expected:L.bigint,received:n.parsedType}),J}gte(e,n){return this.setLimit("min",e,!0,H.toString(n))}gt(e,n){return this.setLimit("min",e,!1,H.toString(n))}lte(e,n){return this.setLimit("max",e,!0,H.toString(n))}lt(e,n){return this.setLimit("max",e,!1,H.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:H.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:H.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:H.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:H.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:H.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:H.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}};Bn.create=t=>new Bn({checks:[],typeName:X.ZodBigInt,coerce:t?.coerce??!1,...ee(t)});Hn=class extends se{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==L.boolean){let r=this._getOrReturnCtx(e);return M(r,{code:C.invalid_type,expected:L.boolean,received:r.parsedType}),J}return je(e.data)}};Hn.create=t=>new Hn({typeName:X.ZodBoolean,coerce:t?.coerce||!1,...ee(t)});Kn=class t extends se{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==L.date){let i=this._getOrReturnCtx(e);return M(i,{code:C.invalid_type,expected:L.date,received:i.parsedType}),J}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return M(i,{code:C.invalid_date}),J}let r=new Ce,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),M(s,{code:C.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),M(s,{code:C.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):ae.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:H.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:H.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}};Kn.create=t=>new Kn({checks:[],coerce:t?.coerce||!1,typeName:X.ZodDate,...ee(t)});Xr=class extends se{_parse(e){if(this._getType(e)!==L.symbol){let r=this._getOrReturnCtx(e);return M(r,{code:C.invalid_type,expected:L.symbol,received:r.parsedType}),J}return je(e.data)}};Xr.create=t=>new Xr({typeName:X.ZodSymbol,...ee(t)});Gn=class extends se{_parse(e){if(this._getType(e)!==L.undefined){let r=this._getOrReturnCtx(e);return M(r,{code:C.invalid_type,expected:L.undefined,received:r.parsedType}),J}return je(e.data)}};Gn.create=t=>new Gn({typeName:X.ZodUndefined,...ee(t)});Wn=class extends se{_parse(e){if(this._getType(e)!==L.null){let r=this._getOrReturnCtx(e);return M(r,{code:C.invalid_type,expected:L.null,received:r.parsedType}),J}return je(e.data)}};Wn.create=t=>new Wn({typeName:X.ZodNull,...ee(t)});yn=class extends se{constructor(){super(...arguments),this._any=!0}_parse(e){return je(e.data)}};yn.create=t=>new yn({typeName:X.ZodAny,...ee(t)});Ht=class extends se{constructor(){super(...arguments),this._unknown=!0}_parse(e){return je(e.data)}};Ht.create=t=>new Ht({typeName:X.ZodUnknown,...ee(t)});bt=class extends se{_parse(e){let n=this._getOrReturnCtx(e);return M(n,{code:C.invalid_type,expected:L.never,received:n.parsedType}),J}};bt.create=t=>new bt({typeName:X.ZodNever,...ee(t)});Qr=class extends se{_parse(e){if(this._getType(e)!==L.undefined){let r=this._getOrReturnCtx(e);return M(r,{code:C.invalid_type,expected:L.void,received:r.parsedType}),J}return je(e.data)}};Qr.create=t=>new Qr({typeName:X.ZodVoid,...ee(t)});Kt=class t extends se{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==L.array)return M(n,{code:C.invalid_type,expected:L.array,received:n.parsedType}),J;if(s.exactLength!==null){let o=n.data.length>s.exactLength.value,l=n.data.length<s.exactLength.value;(o||l)&&(M(n,{code:o?C.too_big:C.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&&(M(n,{code:C.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&&(M(n,{code:C.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 ot(n,o,n.path,l)))).then(o=>Ce.mergeArray(r,o));let i=[...n.data].map((o,l)=>s.type._parseSync(new ot(n,o,n.path,l)));return Ce.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:H.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:H.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:H.toString(n)}})}nonempty(e){return this.min(1,e)}};Kt.create=(t,e)=>new Kt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:X.ZodArray,...ee(e)});Ge=class t extends se{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=ae.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 M(d,{code:C.invalid_type,expected:L.object,received:d.parsedType}),J}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),l=[];if(!(this._def.catchall instanceof bt&&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 ot(s,f,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof bt){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&&(M(s,{code:C.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 ot(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=>Ce.mergeObjectSync(r,d)):Ce.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return H.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:H.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:X.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 ae.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 ae.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return Jr(this)}partial(e){let n={};for(let r of ae.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 ae.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof it;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return Nu(ae.objectKeys(this.shape))}};Ge.create=(t,e)=>new Ge({shape:()=>t,unknownKeys:"strip",catchall:bt.create(),typeName:X.ZodObject,...ee(e)});Ge.strictCreate=(t,e)=>new Ge({shape:()=>t,unknownKeys:"strict",catchall:bt.create(),typeName:X.ZodObject,...ee(e)});Ge.lazycreate=(t,e)=>new Ge({shape:t,unknownKeys:"strip",catchall:bt.create(),typeName:X.ZodObject,...ee(e)});Zn=class extends se{_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 Ke(l.ctx.common.issues));return M(n,{code:C.invalid_union,unionErrors:o}),J}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 Ke(c));return M(n,{code:C.invalid_union,unionErrors:l}),J}}get options(){return this._def.options}};Zn.create=(t,e)=>new Zn({options:t,typeName:X.ZodUnion,...ee(e)});Bt=t=>t instanceof Yn?Bt(t.schema):t instanceof at?Bt(t.innerType()):t instanceof Jn?[t.value]:t instanceof Xn?t.options:t instanceof Qn?ae.objectValues(t.enum):t instanceof er?Bt(t._def.innerType):t instanceof Gn?[void 0]:t instanceof Wn?[null]:t instanceof it?[void 0,...Bt(t.unwrap())]:t instanceof At?[null,...Bt(t.unwrap())]:t instanceof Ks||t instanceof nr?Bt(t.unwrap()):t instanceof tr?Bt(t._def.innerType):[],Di=class t extends se{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==L.object)return M(n,{code:C.invalid_type,expected:L.object,received:n.parsedType}),J;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}):(M(n,{code:C.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),J)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let s=new Map;for(let i of n){let o=Bt(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let l of o){if(s.has(l))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(l)}`);s.set(l,i)}}return new t({typeName:X.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...ee(r)})}};Vn=class extends se{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=(i,o)=>{if(ji(i)||ji(o))return J;let l=Oa(i.value,o.value);return l.valid?((Mi(i)||Mi(o))&&n.dirty(),{status:n.value,value:l.data}):(M(r,{code:C.invalid_intersection_types}),J)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Vn.create=(t,e,n)=>new Vn({left:t,right:e,typeName:X.ZodIntersection,...ee(n)});Rt=class t extends se{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==L.array)return M(r,{code:C.invalid_type,expected:L.array,received:r.parsedType}),J;if(r.data.length<this._def.items.length)return M(r,{code:C.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),J;!this._def.rest&&r.data.length>this._def.items.length&&(M(r,{code:C.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 ot(r,o,r.path,l)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>Ce.mergeArray(n,o)):Ce.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Rt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Rt({items:t,typeName:X.ZodTuple,rest:null,...ee(e)})};zi=class t extends se{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 M(r,{code:C.invalid_type,expected:L.object,received:r.parsedType}),J;let s=[],i=this._def.keyType,o=this._def.valueType;for(let l in r.data)s.push({key:i._parse(new ot(r,l,r.path,l)),value:o._parse(new ot(r,r.data[l],r.path,l)),alwaysSet:l in r.data});return r.common.async?Ce.mergeObjectAsync(n,s):Ce.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof se?new t({keyType:e,valueType:n,typeName:X.ZodRecord,...ee(r)}):new t({keyType:gn.create(),valueType:e,typeName:X.ZodRecord,...ee(n)})}},es=class extends se{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 M(r,{code:C.invalid_type,expected:L.map,received:r.parsedType}),J;let s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([l,c],d)=>({key:s._parse(new ot(r,l,r.path,[d,"key"])),value:i._parse(new ot(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 J;(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 J;(d.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(d.value,p.value)}return{status:n.value,value:l}}}};es.create=(t,e,n)=>new es({valueType:e,keyType:t,typeName:X.ZodMap,...ee(n)});ts=class t extends se{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==L.set)return M(r,{code:C.invalid_type,expected:L.set,received:r.parsedType}),J;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(M(r,{code:C.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&&(M(r,{code:C.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 J;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 ot(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:H.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:H.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};ts.create=(t,e)=>new ts({valueType:t,minSize:null,maxSize:null,typeName:X.ZodSet,...ee(e)});Li=class t extends se{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==L.function)return M(n,{code:C.invalid_type,expected:L.function,received:n.parsedType}),J;function r(l,c){return Hs({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Vr(),Ft].filter(d=>!!d),issueData:{code:C.invalid_arguments,argumentsError:c}})}function s(l,c){return Hs({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Vr(),Ft].filter(d=>!!d),issueData:{code:C.invalid_return_type,returnTypeError:c}})}let i={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof bn){let l=this;return je(async function(...c){let d=new Ke([]),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 je(function(...c){let d=l._def.args.safeParse(c,i);if(!d.success)throw new Ke([r(c,d.error)]);let p=Reflect.apply(o,this,d.data),f=l._def.returns.safeParse(p,i);if(!f.success)throw new Ke([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:Rt.create(e).rest(Ht.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||Rt.create([]).rest(Ht.create()),returns:n||Ht.create(),typeName:X.ZodFunction,...ee(r)})}},Yn=class extends se{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})}};Yn.create=(t,e)=>new Yn({getter:t,typeName:X.ZodLazy,...ee(e)});Jn=class extends se{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return M(n,{received:n.data,code:C.invalid_literal,expected:this._def.value}),J}return{status:"valid",value:e.data}}get value(){return this._def.value}};Jn.create=(t,e)=>new Jn({value:t,typeName:X.ZodLiteral,...ee(e)});Xn=class t extends se{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return M(n,{expected:ae.joinValues(r),received:n.parsedType,code:C.invalid_type}),J}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 M(n,{received:n.data,code:C.invalid_enum_value,options:r}),J}return je(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})}};Xn.create=Nu;Qn=class extends se{_parse(e){let n=ae.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==L.string&&r.parsedType!==L.number){let s=ae.objectValues(n);return M(r,{expected:ae.joinValues(s),received:r.parsedType,code:C.invalid_type}),J}if(this._cache||(this._cache=new Set(ae.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=ae.objectValues(n);return M(r,{received:r.data,code:C.invalid_enum_value,options:s}),J}return je(e.data)}get enum(){return this._def.values}};Qn.create=(t,e)=>new Qn({values:t,typeName:X.ZodNativeEnum,...ee(e)});bn=class extends se{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==L.promise&&n.common.async===!1)return M(n,{code:C.invalid_type,expected:L.promise,received:n.parsedType}),J;let r=n.parsedType===L.promise?n.data:Promise.resolve(n.data);return je(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};bn.create=(t,e)=>new bn({type:t,typeName:X.ZodPromise,...ee(e)});at=class extends se{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===X.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=>{M(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 J;let c=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return c.status==="aborted"?J:c.status==="dirty"?qn(c.value):n.value==="dirty"?qn(c.value):c});{if(n.value==="aborted")return J;let l=this._def.schema._parseSync({data:o,path:r.path,parent:r});return l.status==="aborted"?J:l.status==="dirty"?qn(l.value):n.value==="dirty"?qn(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"?J:(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"?J:(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(!mn(o))return J;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=>mn(o)?Promise.resolve(s.transform(o.value,i)).then(l=>({status:n.value,value:l})):J);ae.assertNever(s)}};at.create=(t,e,n)=>new at({schema:t,typeName:X.ZodEffects,effect:e,...ee(n)});at.createWithPreprocess=(t,e,n)=>new at({schema:e,effect:{type:"preprocess",transform:t},typeName:X.ZodEffects,...ee(n)});it=class extends se{_parse(e){return this._getType(e)===L.undefined?je(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};it.create=(t,e)=>new it({innerType:t,typeName:X.ZodOptional,...ee(e)});At=class extends se{_parse(e){return this._getType(e)===L.null?je(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};At.create=(t,e)=>new At({innerType:t,typeName:X.ZodNullable,...ee(e)});er=class extends se{_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}};er.create=(t,e)=>new er({innerType:t,typeName:X.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ee(e)});tr=class extends se{_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 Yr(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Ke(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ke(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};tr.create=(t,e)=>new tr({innerType:t,typeName:X.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ee(e)});ns=class extends se{_parse(e){if(this._getType(e)!==L.nan){let r=this._getOrReturnCtx(e);return M(r,{code:C.invalid_type,expected:L.nan,received:r.parsedType}),J}return{status:"valid",value:e.data}}};ns.create=t=>new ns({typeName:X.ZodNaN,...ee(t)});Kg=Symbol("zod_brand"),Ks=class extends se{_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}},Gs=class t extends se{_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"?J:i.status==="dirty"?(n.dirty(),qn(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"?J: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:X.ZodPipeline})}},nr=class extends se{_parse(e){let n=this._def.innerType._parse(e),r=s=>(mn(s)&&(s.value=Object.freeze(s.value)),s);return Yr(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};nr.create=(t,e)=>new nr({innerType:t,typeName:X.ZodReadonly,...ee(e)});Gg={object:Ge.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"})(X||(X={}));Wg=(t,e={message:`Input not instance of ${t.name}`})=>Ou(n=>n instanceof t,e),ju=gn.create,Mu=Fn.create,Zg=ns.create,Vg=Bn.create,Du=Hn.create,Yg=Kn.create,Jg=Xr.create,Xg=Gn.create,Qg=Wn.create,ey=yn.create,ty=Ht.create,ny=bt.create,ry=Qr.create,sy=Kt.create,iy=Ge.create,oy=Ge.strictCreate,ay=Zn.create,ly=Di.create,cy=Vn.create,uy=Rt.create,dy=zi.create,hy=es.create,py=ts.create,fy=Li.create,my=Yn.create,gy=Jn.create,yy=Xn.create,by=Qn.create,wy=bn.create,vy=at.create,ky=it.create,_y=At.create,Sy=at.createWithPreprocess,Ty=Gs.create,xy=()=>ju().optional(),Ey=()=>Mu().optional(),Iy=()=>Du().optional(),Ry={string:(t=>gn.create({...t,coerce:!0})),number:(t=>Fn.create({...t,coerce:!0})),boolean:(t=>Hn.create({...t,coerce:!0})),bigint:(t=>Bn.create({...t,coerce:!0})),date:(t=>Kn.create({...t,coerce:!0}))},Ay=J});var _={};fn(_,{BRAND:()=>Kg,DIRTY:()=>qn,EMPTY_PATH:()=>Sg,INVALID:()=>J,NEVER:()=>Ay,OK:()=>je,ParseStatus:()=>Ce,Schema:()=>se,ZodAny:()=>yn,ZodArray:()=>Kt,ZodBigInt:()=>Bn,ZodBoolean:()=>Hn,ZodBranded:()=>Ks,ZodCatch:()=>tr,ZodDate:()=>Kn,ZodDefault:()=>er,ZodDiscriminatedUnion:()=>Di,ZodEffects:()=>at,ZodEnum:()=>Xn,ZodError:()=>Ke,ZodFirstPartyTypeKind:()=>X,ZodFunction:()=>Li,ZodIntersection:()=>Vn,ZodIssueCode:()=>C,ZodLazy:()=>Yn,ZodLiteral:()=>Jn,ZodMap:()=>es,ZodNaN:()=>ns,ZodNativeEnum:()=>Qn,ZodNever:()=>bt,ZodNull:()=>Wn,ZodNullable:()=>At,ZodNumber:()=>Fn,ZodObject:()=>Ge,ZodOptional:()=>it,ZodParsedType:()=>L,ZodPipeline:()=>Gs,ZodPromise:()=>bn,ZodReadonly:()=>nr,ZodRecord:()=>zi,ZodSchema:()=>se,ZodSet:()=>ts,ZodString:()=>gn,ZodSymbol:()=>Xr,ZodTransformer:()=>at,ZodTuple:()=>Rt,ZodType:()=>se,ZodUndefined:()=>Gn,ZodUnion:()=>Zn,ZodUnknown:()=>Ht,ZodVoid:()=>Qr,addIssueToContext:()=>M,any:()=>ey,array:()=>sy,bigint:()=>Vg,boolean:()=>Du,coerce:()=>Ry,custom:()=>Ou,date:()=>Yg,datetimeRegex:()=>Pu,defaultErrorMap:()=>Ft,discriminatedUnion:()=>ly,effect:()=>vy,enum:()=>yy,function:()=>fy,getErrorMap:()=>Vr,getParsedType:()=>It,instanceof:()=>Wg,intersection:()=>cy,isAborted:()=>ji,isAsync:()=>Yr,isDirty:()=>Mi,isValid:()=>mn,late:()=>Gg,lazy:()=>my,literal:()=>gy,makeIssue:()=>Hs,map:()=>hy,nan:()=>Zg,nativeEnum:()=>by,never:()=>ny,null:()=>Qg,nullable:()=>_y,number:()=>Mu,object:()=>iy,objectUtil:()=>Ca,oboolean:()=>Iy,onumber:()=>Ey,optional:()=>ky,ostring:()=>xy,pipeline:()=>Ty,preprocess:()=>Sy,promise:()=>wy,quotelessJson:()=>vg,record:()=>dy,set:()=>py,setErrorMap:()=>_g,strictObject:()=>oy,string:()=>ju,symbol:()=>Jg,transformer:()=>vy,tuple:()=>uy,undefined:()=>Xg,union:()=>ay,unknown:()=>ty,util:()=>ae,void:()=>ry});var ja=we(()=>{Oi();Pa();Eu();Bs();zu();Ni()});var rs=we(()=>{ja();ja()});function le(){let t=process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR;if(t)return t;let e=qi.default.join(Ui.default.homedir(),".config","allwright"),n=qi.default.join(Ui.default.homedir(),".config","ticketpilot");return!Gt.default.existsSync(e)&&Gt.default.existsSync(n)?n:e}function Wt(){return qi.default.join(le(),"runner.json")}function ke(){let t=Wt();if(!Gt.default.existsSync(t))return null;let e=JSON.parse(Gt.default.readFileSync(t,"utf8"));return Ma.parse(e)}function be(t){let e=le();Gt.default.mkdirSync(e,{recursive:!0,mode:448});let n=Wt(),r=n+".tmp";Gt.default.writeFileSync(r,JSON.stringify(t,null,2)+`
24
+ `,{mode:384}),Gt.default.renameSync(r,n),Gt.default.chmodSync(n,384)}function Fi(t,e){return`${t}:${e}`}function Zt(t,e,n){return t.environments[Fi(e,n)]?.secrets??{}}function Bi(t,e){return t.repos[e]?.jira??t.jira}function Hi(t){return!t.jira&&!Object.values(t.repos).some(e=>e.jira)}function ue(){let t=ke();if(!t)throw new Error(`No runner config found at ${Wt()}. Run \`allwright init\` first.`);return t}var Gt,Ui,qi,Lu,Ma,$e=we(()=>{"use strict";Gt=R(require("node:fs"),1),Ui=R(require("node:os"),1),qi=R(require("node:path"),1);rs();Lu=_.object({baseUrl:_.string().url(),email:_.string().email(),apiToken:_.string().min(1)}),Ma=_.object({controlPlaneUrl:_.string().url(),runnerId:_.string().optional(),runnerToken:_.string().optional(),runnerName:_.string().default(Ui.default.hostname()),jira:Lu.optional(),repos:_.record(_.object({path:_.string(),jira:Lu.optional(),github:_.object({token:_.string().min(1),login:_.string().optional()}).optional()})).default({}),github:_.object({token:_.string().min(1),login:_.string().optional()}).optional(),githubUsers:_.record(_.object({token:_.string().min(1),login:_.string().optional()})).default({}),deploy:_.object({enabled:_.boolean().default(!1)}).default({enabled:!1}),environments:_.record(_.object({secrets:_.record(_.string()).default({})})).default({}),claudeProfiles:_.record(_.object({configDir:_.string()})).default({}),claudeBin:_.string().default("claude"),agents:_.record(_.object({bin:_.string()})).default({}),jiraUsers:_.record(_.object({email:_.string().email(),apiToken:_.string().min(1)})).default({}),auditSchedules:_.array(_.object({repoName:_.string(),role:_.enum(["security","testing"]),intervalHours:_.number().int().min(6).max(720)})).default([]),pollIntervalSeconds:_.number().int().min(10).max(600).default(30)})});var Ws=ce(pe=>{"use strict";Object.defineProperty(pe,"__esModule",{value:!0});pe.getParsedType=pe.ZodParsedType=pe.objectUtil=pe.util=void 0;var Ua;(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})(Ua||(pe.util=Ua={}));var Yu;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Yu||(pe.objectUtil=Yu={}));pe.ZodParsedType=Ua.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var Dy=t=>{switch(typeof t){case"undefined":return pe.ZodParsedType.undefined;case"string":return pe.ZodParsedType.string;case"number":return Number.isNaN(t)?pe.ZodParsedType.nan:pe.ZodParsedType.number;case"boolean":return pe.ZodParsedType.boolean;case"function":return pe.ZodParsedType.function;case"bigint":return pe.ZodParsedType.bigint;case"symbol":return pe.ZodParsedType.symbol;case"object":return Array.isArray(t)?pe.ZodParsedType.array:t===null?pe.ZodParsedType.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?pe.ZodParsedType.promise:typeof Map<"u"&&t instanceof Map?pe.ZodParsedType.map:typeof Set<"u"&&t instanceof Set?pe.ZodParsedType.set:typeof Date<"u"&&t instanceof Date?pe.ZodParsedType.date:pe.ZodParsedType.object;default:return pe.ZodParsedType.unknown}};pe.getParsedType=Dy});var Yi=ce(kn=>{"use strict";Object.defineProperty(kn,"__esModule",{value:!0});kn.ZodError=kn.quotelessJson=kn.ZodIssueCode=void 0;var Ju=Ws();kn.ZodIssueCode=Ju.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 zy=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");kn.quotelessJson=zy;var Zs=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,Ju.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()}};kn.ZodError=Zs;Zs.create=t=>new Zs(t)});var Fa=ce(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});var Me=Yi(),ir=Ws(),Ly=(t,e)=>{let n;switch(t.code){case Me.ZodIssueCode.invalid_type:t.received===ir.ZodParsedType.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case Me.ZodIssueCode.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,ir.util.jsonStringifyReplacer)}`;break;case Me.ZodIssueCode.unrecognized_keys:n=`Unrecognized key(s) in object: ${ir.util.joinValues(t.keys,", ")}`;break;case Me.ZodIssueCode.invalid_union:n="Invalid input";break;case Me.ZodIssueCode.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ir.util.joinValues(t.options)}`;break;case Me.ZodIssueCode.invalid_enum_value:n=`Invalid enum value. Expected ${ir.util.joinValues(t.options)}, received '${t.received}'`;break;case Me.ZodIssueCode.invalid_arguments:n="Invalid function arguments";break;case Me.ZodIssueCode.invalid_return_type:n="Invalid function return type";break;case Me.ZodIssueCode.invalid_date:n="Invalid date";break;case Me.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}"`:ir.util.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case Me.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 Me.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 Me.ZodIssueCode.custom:n="Invalid input";break;case Me.ZodIssueCode.invalid_intersection_types:n="Intersection results could not be merged";break;case Me.ZodIssueCode.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case Me.ZodIssueCode.not_finite:n="Number must be finite";break;default:n=e.defaultError,ir.util.assertNever(t)}return{message:n}};qa.default=Ly});var Ji=ce(_n=>{"use strict";var Uy=_n&&_n.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(_n,"__esModule",{value:!0});_n.defaultErrorMap=void 0;_n.setErrorMap=qy;_n.getErrorMap=Fy;var Xu=Uy(Fa());_n.defaultErrorMap=Xu.default;var Qu=Xu.default;function qy(t){Qu=t}function Fy(){return Qu}});var Ha=ce(de=>{"use strict";var By=de&&de.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(de,"__esModule",{value:!0});de.isAsync=de.isValid=de.isDirty=de.isAborted=de.OK=de.DIRTY=de.INVALID=de.ParseStatus=de.EMPTY_PATH=de.makeIssue=void 0;de.addIssueToContext=Gy;var Hy=Ji(),ed=By(Fa()),Ky=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}};de.makeIssue=Ky;de.EMPTY_PATH=[];function Gy(t,e){let n=(0,Hy.getErrorMap)(),r=(0,de.makeIssue)({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===ed.default?void 0:ed.default].filter(s=>!!s)});t.common.issues.push(r)}var Ba=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 de.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 de.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}}};de.ParseStatus=Ba;de.INVALID=Object.freeze({status:"aborted"});var Wy=t=>({status:"dirty",value:t});de.DIRTY=Wy;var Zy=t=>({status:"valid",value:t});de.OK=Zy;var Vy=t=>t.status==="aborted";de.isAborted=Vy;var Yy=t=>t.status==="dirty";de.isDirty=Yy;var Jy=t=>t.status==="valid";de.isValid=Jy;var Xy=t=>typeof Promise<"u"&&t instanceof Promise;de.isAsync=Xy});var nd=ce(td=>{"use strict";Object.defineProperty(td,"__esModule",{value:!0})});var sd=ce(Xi=>{"use strict";Object.defineProperty(Xi,"__esModule",{value:!0});Xi.errorUtil=void 0;var rd;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(rd||(Xi.errorUtil=rd={}))});var gd=ce(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=cd;S.custom=dd;var N=Yi(),Qi=Ji(),G=sd(),T=Ha(),O=Ws(),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}},id=(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 te(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 ne=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 id(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 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: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: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 $t.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Jt.create(this)}promise(){return xn.create(this,this._def)}or(e){return hr.create([this,e],this._def)}and(e){return pr.create(this,e,this._def)}transform(e){return new et({...te(this._def),schema:this,typeName:Q.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new br({...te(this._def),innerType:this,defaultValue:n,typeName:Q.ZodDefault})}brand(){return new Vs({typeName:Q.ZodBranded,type:this,...te(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new wr({...te(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 Ys.create(this,e)}readonly(){return vr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};S.ZodType=ne;S.Schema=ne;S.ZodSchema=ne;var Qy=/^c[^\s-]{8,}$/i,eb=/^[0-9a-z]+$/,tb=/^[0-9A-HJKMNP-TV-Z]{26}$/i,nb=/^[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,rb=/^[a-z0-9_-]{21}$/i,sb=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ib=/^[-+]?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)?)??$/,ob=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ab="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ka,lb=/^(?:(?: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])$/,cb=/^(?:(?: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])$/,ub=/^(([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]))$/,db=/^(([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])$/,hb=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,pb=/^([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])))",fb=new RegExp(`^${ad}$`);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 mb(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 gb(t,e){return!!((e==="v4"||!e)&&lb.test(t)||(e==="v6"||!e)&&ub.test(t))}function yb(t,e){if(!sb.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 bb(t,e){return!!((e==="v4"||!e)&&cb.test(t)||(e==="v6"||!e)&&db.test(t))}var Sn=class t extends ne{_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")ob.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")Ka||(Ka=new RegExp(ab,"u")),Ka.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")nb.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")rb.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")Qy.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")eb.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")tb.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"?cd(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"?fb.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"?mb(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"?ib.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"?gb(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"?yb(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"?bb(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"?hb.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"?pb.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,...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=Sn;Sn.create=t=>new Sn({checks:[],typeName:Q.ZodString,coerce:t?.coerce??!1,...te(t)});function wb(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 or=class t extends ne{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"?wb(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,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"&&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=or;or.create=t=>new or({checks:[],typeName:Q.ZodNumber,coerce:t?.coerce||!1,...te(t)});var ar=class t extends ne{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,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=ar;ar.create=t=>new ar({checks:[],typeName:Q.ZodBigInt,coerce:t?.coerce??!1,...te(t)});var lr=class extends ne{_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=lr;lr.create=t=>new lr({typeName:Q.ZodBoolean,coerce:t?.coerce||!1,...te(t)});var cr=class t extends ne{_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: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=cr;cr.create=t=>new cr({checks:[],coerce:t?.coerce||!1,typeName:Q.ZodDate,...te(t)});var cs=class extends ne{_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=cs;cs.create=t=>new cs({typeName:Q.ZodSymbol,...te(t)});var ur=class extends ne{_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=ur;ur.create=t=>new ur({typeName:Q.ZodUndefined,...te(t)});var dr=class extends ne{_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=dr;dr.create=t=>new dr({typeName:Q.ZodNull,...te(t)});var Tn=class extends ne{constructor(){super(...arguments),this._any=!0}_parse(e){return(0,T.OK)(e.data)}};S.ZodAny=Tn;Tn.create=t=>new Tn({typeName:Q.ZodAny,...te(t)});var Yt=class extends ne{constructor(){super(...arguments),this._unknown=!0}_parse(e){return(0,T.OK)(e.data)}};S.ZodUnknown=Yt;Yt.create=t=>new Yt({typeName:Q.ZodUnknown,...te(t)});var wt=class extends ne{_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=wt;wt.create=t=>new wt({typeName:Q.ZodNever,...te(t)});var us=class extends ne{_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=us;us.create=t=>new us({typeName:Q.ZodVoid,...te(t)});var Jt=class t extends ne{_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 ct(n,o,n.path,l)))).then(o=>T.ParseStatus.mergeArray(r,o));let i=[...n.data].map((o,l)=>s.type._parseSync(new ct(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=Jt;Jt.create=(t,e)=>new Jt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Q.ZodArray,...te(e)});function ls(t){if(t instanceof We){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=lt.create(ls(r))}return new We({...t._def,shape:()=>e})}else return t instanceof Jt?new Jt({...t._def,type:ls(t.element)}):t instanceof lt?lt.create(ls(t.unwrap())):t instanceof $t?$t.create(ls(t.unwrap())):t instanceof Ct?Ct.create(t.items.map(e=>ls(e))):t}var We=class t extends ne{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 wt&&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 wt){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 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=>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: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 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 ls(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 lt;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return ud(O.util.objectKeys(this.shape))}};S.ZodObject=We;We.create=(t,e)=>new We({shape:()=>t,unknownKeys:"strip",catchall:wt.create(),typeName:Q.ZodObject,...te(e)});We.strictCreate=(t,e)=>new We({shape:()=>t,unknownKeys:"strict",catchall:wt.create(),typeName:Q.ZodObject,...te(e)});We.lazycreate=(t,e)=>new We({shape:t,unknownKeys:"strip",catchall:wt.create(),typeName:Q.ZodObject,...te(e)});var hr=class extends ne{_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=hr;hr.create=(t,e)=>new hr({options:t,typeName:Q.ZodUnion,...te(e)});var Vt=t=>t instanceof fr?Vt(t.schema):t instanceof et?Vt(t.innerType()):t instanceof mr?[t.value]:t instanceof gr?t.options:t instanceof yr?O.util.objectValues(t.enum):t instanceof br?Vt(t._def.innerType):t instanceof ur?[void 0]:t instanceof dr?[null]:t instanceof lt?[void 0,...Vt(t.unwrap())]:t instanceof $t?[null,...Vt(t.unwrap())]:t instanceof Vs||t instanceof vr?Vt(t.unwrap()):t instanceof wr?Vt(t._def.innerType):[],eo=class t extends ne{_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=Vt(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,...te(r)})}};S.ZodDiscriminatedUnion=eo;function Ga(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=Ga(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=Ga(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 pr=class extends ne{_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=Ga(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=pr;pr.create=(t,e,n)=>new pr({left:t,right:e,typeName:Q.ZodIntersection,...te(n)});var Ct=class t extends ne{_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 ct(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=Ct;Ct.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ct({items:t,typeName:Q.ZodTuple,rest:null,...te(e)})};var to=class t extends ne{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 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?T.ParseStatus.mergeObjectAsync(n,s):T.ParseStatus.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof ne?new t({keyType:e,valueType:n,typeName:Q.ZodRecord,...te(r)}):new t({keyType:Sn.create(),valueType:e,typeName:Q.ZodRecord,...te(n)})}};S.ZodRecord=to;var ds=class extends ne{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 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 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=ds;ds.create=(t,e,n)=>new ds({valueType:e,keyType:t,typeName:Q.ZodMap,...te(n)});var hs=class t extends ne{_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 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.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=hs;hs.create=(t,e)=>new hs({valueType:t,minSize:null,maxSize:null,typeName:Q.ZodSet,...te(e)});var no=class t extends ne{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,Qi.getErrorMap)(),Qi.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,Qi.getErrorMap)(),Qi.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 xn){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:Ct.create(e).rest(Yt.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||Ct.create([]).rest(Yt.create()),returns:n||Yt.create(),typeName:Q.ZodFunction,...te(r)})}};S.ZodFunction=no;var fr=class extends ne{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=fr;fr.create=(t,e)=>new fr({getter:t,typeName:Q.ZodLazy,...te(e)});var mr=class extends ne{_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=mr;mr.create=(t,e)=>new mr({value:t,typeName:Q.ZodLiteral,...te(e)});function ud(t,e){return new gr({values:t,typeName:Q.ZodEnum,...te(e)})}var gr=class t extends ne{_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=gr;gr.create=ud;var yr=class extends ne{_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=yr;yr.create=(t,e)=>new yr({values:t,typeName:Q.ZodNativeEnum,...te(e)});var xn=class extends ne{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=xn;xn.create=(t,e)=>new xn({type:t,typeName:Q.ZodPromise,...te(e)});var et=class extends ne{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=>{(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=et;S.ZodTransformer=et;et.create=(t,e,n)=>new et({schema:t,typeName:Q.ZodEffects,effect:e,...te(n)});et.createWithPreprocess=(t,e,n)=>new et({schema:e,effect:{type:"preprocess",transform:t},typeName:Q.ZodEffects,...te(n)});var lt=class extends ne{_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=lt;lt.create=(t,e)=>new lt({innerType:t,typeName:Q.ZodOptional,...te(e)});var $t=class extends ne{_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=$t;$t.create=(t,e)=>new $t({innerType:t,typeName:Q.ZodNullable,...te(e)});var br=class extends ne{_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=br;br.create=(t,e)=>new br({innerType:t,typeName:Q.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...te(e)});var wr=class extends ne{_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=wr;wr.create=(t,e)=>new wr({innerType:t,typeName:Q.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...te(e)});var ps=class extends ne{_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=ps;ps.create=t=>new ps({typeName:Q.ZodNaN,...te(t)});S.BRAND=Symbol("zod_brand");var Vs=class extends ne{_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=Vs;var Ys=class t extends ne{_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:Q.ZodPipeline})}};S.ZodPipeline=Ys;var vr=class extends ne{_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=vr;vr.create=(t,e)=>new vr({innerType:t,typeName:Q.ZodReadonly,...te(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?Tn.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})}}):Tn.create()}S.late={object:We.lazycreate};var Q;(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||(S.ZodFirstPartyTypeKind=Q={}));var vb=(t,e={message:`Input not instance of ${t.name}`})=>dd(n=>n instanceof t,e);S.instanceof=vb;var hd=Sn.create;S.string=hd;var pd=or.create;S.number=pd;var kb=ps.create;S.nan=kb;var _b=ar.create;S.bigint=_b;var fd=lr.create;S.boolean=fd;var Sb=cr.create;S.date=Sb;var Tb=cs.create;S.symbol=Tb;var xb=ur.create;S.undefined=xb;var Eb=dr.create;S.null=Eb;var Ib=Tn.create;S.any=Ib;var Rb=Yt.create;S.unknown=Rb;var Ab=wt.create;S.never=Ab;var Cb=us.create;S.void=Cb;var $b=Jt.create;S.array=$b;var Pb=We.create;S.object=Pb;var Nb=We.strictCreate;S.strictObject=Nb;var Ob=hr.create;S.union=Ob;var jb=eo.create;S.discriminatedUnion=jb;var Mb=pr.create;S.intersection=Mb;var Db=Ct.create;S.tuple=Db;var zb=to.create;S.record=zb;var Lb=ds.create;S.map=Lb;var Ub=hs.create;S.set=Ub;var qb=no.create;S.function=qb;var Fb=fr.create;S.lazy=Fb;var Bb=mr.create;S.literal=Bb;var Hb=gr.create;S.enum=Hb;var Kb=yr.create;S.nativeEnum=Kb;var Gb=xn.create;S.promise=Gb;var md=et.create;S.effect=md;S.transformer=md;var Wb=lt.create;S.optional=Wb;var Zb=$t.create;S.nullable=Zb;var Vb=et.createWithPreprocess;S.preprocess=Vb;var Yb=Ys.create;S.pipeline=Yb;var Jb=()=>hd().optional();S.ostring=Jb;var Xb=()=>pd().optional();S.onumber=Xb;var Qb=()=>fd().optional();S.oboolean=Qb;S.coerce={string:(t=>Sn.create({...t,coerce:!0})),number:(t=>or.create({...t,coerce:!0})),boolean:(t=>lr.create({...t,coerce:!0})),bigint:(t=>ar.create({...t,coerce:!0})),date:(t=>cr.create({...t,coerce:!0}))};S.NEVER=T.INVALID});var Wa=ce(ut=>{"use strict";var ew=ut&&ut.__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]})),fs=ut&&ut.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&ew(e,t,n)};Object.defineProperty(ut,"__esModule",{value:!0});fs(Ji(),ut);fs(Ha(),ut);fs(nd(),ut);fs(Ws(),ut);fs(gd(),ut);fs(Yi(),ut)});var wd=ce(Ze=>{"use strict";var yd=Ze&&Ze.__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]})),tw=Ze&&Ze.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),nw=Ze&&Ze.__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 tw(e,t),e},rw=Ze&&Ze.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&yd(e,t,n)};Object.defineProperty(Ze,"__esModule",{value:!0});Ze.z=void 0;var bd=nw(Wa());Ze.z=bd;rw(Wa(),Ze);Ze.default=bd});var xe=ce(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.ChatFile=h.TeamCredsResultMsg=h.TeamCredsMsg=h.KnowledgeSaveResultMsg=h.KnowledgeSaveMsg=h.KnowledgeListResultMsg=h.KnowledgeFile=h.KnowledgeListMsg=h.AuditReviewResultMsg=h.AuditReviewMsg=h.AuditGetResultMsg=h.AuditGetMsg=h.AuditExplainResultMsg=h.AuditExplainMsg=h.ChatCancelMsg=h.ChatDiagnosticResultMsg=h.ChatDiagnosticMsg=h.AuditListResultMsg=h.AuditStatsResultMsg=h.AuditStatsMsg=h.AuditListMsg=h.AuditStartResultMsg=h.AuditStartMsg=h.AuditRecord=h.AuditFinding=h.AuditDetailLevel=h.AuditScope=h.AuditSeverity=h.KnowledgeRole=h.AuditRole=h.EpicSuggestResultMsg=h.EpicSuggestMsg=h.EpicListResultMsg=h.EpicChild=h.EpicListMsg=h.BoardTriggerResultMsg=h.BoardTriggerMsg=h.BoardFetchResultMsg=h.BoardFetchMsg=h.RepoDocReadResultMsg=h.RepoDocReadMsg=h.RepoDocsResultMsg=h.RepoDocsMsg=h.ChatLoadResultMsg=h.TICKET_RULES_APPENDIX=h.COMPOSE_COMMANDS=h.REPLY_STYLES=h.BUILTIN_REPLY_LANGUAGES=h.ChatLoadMsg=h.ChatListResultMsg=void 0;h.RunApprovedMsg=h.RunCancelMsg=h.RuleDiagnoseMsg=h.ProjectTestMsg=h.RunClaimResultMsg=h.ConfigMsg=h.HelloAckMsg=h.RunnerToServerMsg=h.AutopilotReportMsg=h.AutopilotNextResultMsg=h.AutopilotPlanResultMsg=h.AutopilotPlanMsg=h.AutopilotNextMsg=h.RunnerUninstallResultMsg=h.RunnerUpdateResultMsg=h.AgentProfilesResultMsg=h.AgentProfilesMsg=h.RunPrConflictMsg=h.RunResolveConflictResultMsg=h.RunAnswerResultMsg=h.RunAnswerMsg=h.RunTestFixResultMsg=h.RunTestFixMsg=h.RunResolveConflictMsg=h.RunnerUninstallMsg=h.RunnerUpdateMsg=h.RepoDocSaveResultMsg=h.RepoDocSaveMsg=h.SetupClaudeMdSaveResultMsg=h.SetupClaudeMdSaveMsg=h.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=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=void 0;h.missingAgentCapabilities=sw;h.replyPreferenceAppendix=ow;h.pendingMigrationsAppendix=aw;h.deployTargetsAppendix=lw;h.composeCommandAppendix=cw;h.isSelfMigrationFilename=uw;h.parseRunnerMsg=dw;h.parseServerMsg=hw;var a=wd();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.81";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 sw(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 iw=t=>t.includes(h.NEEDS_INPUT_COMMENT_MARKER)||h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS.some(e=>t.includes(e));h.needsInputMarkerIn=iw;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)})).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 ow(t){let e=[],n=(t.language??"").trim();if(n){let s=h.BUILTIN_REPLY_LANGUAGES.find(i=>i.name.toLowerCase()===n.toLowerCase());e.push((t.languageInstruction??"").trim()||s?.instruction||`Write your prose in ${n}.`),e.push("Code, file paths, identifiers, commands, error text and log output stay exactly as they are - only your own prose changes language."),e.push("The ```ticket block is the exception: its summary and description are ALWAYS written in English, because the ticket is read by other people and by the implementing agent.")}let r=h.REPLY_STYLES.find(s=>s.id===(t.style??"").trim());return r&&e.push(r.instruction),e.length?`
25
25
 
26
26
  HOW TO WRITE THE REPLY - the person you are answering chose this, so it applies to every reply in this conversation:
27
27
  - ${e.join(`
@@ -324,9 +324,9 @@ Rules for the steps:
324
324
  - Prefer commands that are safe to re-run; a deploy may be retried.
325
325
  - 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.
326
326
  - Order matters: install, build, test (if cheap), then release.
327
- - If you genuinely cannot tell how this repo is deployed, return an empty "steps" array and explain what is missing in "notes".`});var Ad={};fn(Ad,{DELETE_MANIFEST_FILE:()=>Xt,MAX_CHANGED_FILES:()=>In,MAX_CHANGED_LINES:()=>En,abortMerge:()=>Cn,applyDeleteManifest:()=>ms,branchForIssue:()=>rl,branchSha:()=>lo,branchesDiffer:()=>dl,checkDiffSafety:()=>An,checkoutBranchInWorktree:()=>sl,commitAll:()=>_r,commitMergeResolution:()=>ll,commitsBetween:()=>tl,deleteStaleBranch:()=>Xa,diffAgainstDefault:()=>co,envCheckoutPath:()=>Rd,envCheckoutsRoot:()=>Ed,fetchBase:()=>Rn,findConflictMarkers:()=>uo,headSha:()=>Ve,mergeBaseIntoWorktree:()=>al,mergeTicketBranch:()=>ol,originUrl:()=>Tr,parseOwnerRepo:()=>vt,prepareEnvCheckout:()=>il,previousDeliveryForIssue:()=>Ya,pruneWorktrees:()=>nl,pushBranch:()=>Sr,pushEnvBranch:()=>ul,pushWipBranch:()=>Za,remoteBranchExists:()=>Ja,removeWorktree:()=>Pt,resetHard:()=>gs,servedBranchTip:()=>el,statusSnapshot:()=>Va,unresolvedAmong:()=>cl,worktreeAdd:()=>Qa,worktreeAddExisting:()=>Xs,worktreeFingerprint:()=>ao,worktreesRoot:()=>Qt});async function q(t,e,n={}){try{let{stdout:r}=await xd("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 ms(t){let e={deleted:[],refused:[]},n=me.default.join(t,Xt);if(!Ee.default.existsSync(n))return e;let r=me.default.resolve(t),s=Ee.default.readFileSync(n,"utf8").split(`
328
- `).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#"));for(let i of s.slice(0,200)){if(me.default.isAbsolute(i)){e.refused.push(`${i} - absolute paths are not allowed`);continue}let o=me.default.resolve(r,i);if(o!==r&&!o.startsWith(r+me.default.sep)){e.refused.push(`${i} - escapes the worktree`);continue}let l=me.default.relative(r,o).split(me.default.sep).join("/");if(l===Xt)continue;if(Id.some(u=>u.test(l))){e.refused.push(`${i} - protected path (CI/hook files are never touched)`);continue}let c;try{c=Ee.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{Ee.default.rmSync(o),e.deleted.push(l)}catch(u){e.refused.push(`${i} - ${u instanceof Error?u.message:"delete failed"}`)}}return Ee.default.rmSync(n,{force:!0}),e}async function Za(t,e){await q(t,["push","--force","origin",`HEAD:refs/heads/${e}`],{timeoutMs:3e5})}async function ao(t){let e=await q(t,["status","--porcelain"]),n=await q(t,["diff","--numstat"]),r=e.split(`
329
- `).filter(s=>s.startsWith("??")).map(s=>s.slice(3).trim()).slice(0,500).map(s=>{try{let i=Ee.default.statSync(me.default.join(t,s));return`${s}:${i.size}:${i.mtimeMs}`}catch{return s}}).join(`
327
+ - If you genuinely cannot tell how this repo is deployed, return an empty "steps" array and explain what is missing in "notes".`});var Ad={};fn(Ad,{DELETE_MANIFEST_FILE:()=>Xt,MAX_CHANGED_FILES:()=>En,MAX_CHANGED_LINES:()=>In,abortMerge:()=>Cn,applyDeleteManifest:()=>ms,branchForIssue:()=>rl,branchSha:()=>lo,branchesDiffer:()=>dl,checkDiffSafety:()=>An,checkoutBranchInWorktree:()=>sl,commitAll:()=>_r,commitMergeResolution:()=>ll,commitsBetween:()=>tl,deleteStaleBranch:()=>Xa,diffAgainstDefault:()=>co,envCheckoutPath:()=>Rd,envCheckoutsRoot:()=>Id,fetchBase:()=>Rn,findConflictMarkers:()=>uo,headSha:()=>Ve,mergeBaseIntoWorktree:()=>al,mergeTicketBranch:()=>ol,originUrl:()=>Tr,parseOwnerRepo:()=>vt,prepareEnvCheckout:()=>il,previousDeliveryForIssue:()=>Ya,pruneWorktrees:()=>nl,pushBranch:()=>Sr,pushEnvBranch:()=>ul,pushWipBranch:()=>Za,remoteBranchExists:()=>Ja,removeWorktree:()=>Pt,resetHard:()=>gs,servedBranchTip:()=>el,statusSnapshot:()=>Va,unresolvedAmong:()=>cl,worktreeAdd:()=>Qa,worktreeAddExisting:()=>Xs,worktreeFingerprint:()=>ao,worktreesRoot:()=>Qt});async function q(t,e,n={}){try{let{stdout:r}=await xd("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 ms(t){let e={deleted:[],refused:[]},n=me.default.join(t,Xt);if(!Ie.default.existsSync(n))return e;let r=me.default.resolve(t),s=Ie.default.readFileSync(n,"utf8").split(`
328
+ `).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#"));for(let i of s.slice(0,200)){if(me.default.isAbsolute(i)){e.refused.push(`${i} - absolute paths are not allowed`);continue}let o=me.default.resolve(r,i);if(o!==r&&!o.startsWith(r+me.default.sep)){e.refused.push(`${i} - escapes the worktree`);continue}let l=me.default.relative(r,o).split(me.default.sep).join("/");if(l===Xt)continue;if(Ed.some(d=>d.test(l))){e.refused.push(`${i} - protected path (CI/hook files are never touched)`);continue}let c;try{c=Ie.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{Ie.default.rmSync(o),e.deleted.push(l)}catch(d){e.refused.push(`${i} - ${d instanceof Error?d.message:"delete failed"}`)}}return Ie.default.rmSync(n,{force:!0}),e}async function Za(t,e){await q(t,["push","--force","origin",`HEAD:refs/heads/${e}`],{timeoutMs:3e5})}async function ao(t){let e=await q(t,["status","--porcelain"]),n=await q(t,["diff","--numstat"]),r=e.split(`
329
+ `).filter(s=>s.startsWith("??")).map(s=>s.slice(3).trim()).slice(0,500).map(s=>{try{let i=Ie.default.statSync(me.default.join(t,s));return`${s}:${i.size}:${i.mtimeMs}`}catch{return s}}).join(`
330
330
  `);return`${e}
331
331
  --
332
332
  ${n}
@@ -336,30 +336,30 @@ ${r}`}async function Va(t){let e=(await q(t,["rev-parse","--abbrev-ref","HEAD"])
336
336
  `),o=s.length>15?`
337
337
  (\u2026 ${s.length-15} more)`:"";return`branch ${e} @ ${n}
338
338
  working tree: ${s.length?`
339
- ${i}${o}`:"clean"}`}function Qt(){let t=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(Ee.default.existsSync(me.default.join(kr.default.homedir(),".cache","ticketpilot"))?me.default.join(kr.default.homedir(),".cache","ticketpilot"):me.default.join(kr.default.homedir(),".cache","allwright"));return me.default.join(t,"worktrees")}async function Ya(t,e,n,r=40){if(!n.trim()||!e.trim())return null;let s=await q(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 q(t,["show","--name-only","--format=",i]).then(c=>c.split(`
340
- `).map(u=>u.trim()).filter(Boolean)).catch(()=>[]);return{sha:i,subject:o,files:l.slice(0,r),more:Math.max(0,l.length-r)}}async function Ja(t,e){try{return(await q(t,["ls-remote","--heads","origin",e])).trim().length>0}catch{return null}}async function Rn(t,e){try{await q(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 Xa(t,e){try{let n=await q(t,["worktree","list","--porcelain"]),r=Qt(),s=null;for(let i of n.split(`
341
- `))i.startsWith("worktree ")&&(s=i.slice(9).trim()),i===`branch refs/heads/${e}`&&s&&s.startsWith(r)&&await q(t,["worktree","remove","--force",s]);await q(t,["worktree","prune"])}catch{}try{await q(t,["branch","-D",e])}catch{}}async function Qa(t,e,n,r){Ee.default.mkdirSync(me.default.dirname(e),{recursive:!0,mode:448}),await q(t,["worktree","add","-b",n,e,`origin/${r}`])}async function _r(t,e){if(await q(t,["add","-A"]),!(await q(t,["status","--porcelain"])).trim())throw new Error("Claude wrote no changes - nothing to commit");await q(t,["-c",`user.name=${io}`,"-c",`user.email=${oo}`,"commit","-m",e])}async function An(t,e){let r=(await q(t,["diff","--name-only",`origin/${e}...HEAD`])).split(`
342
- `).filter(Boolean),s=r.filter(u=>Id.some(p=>p.test(u))),i=await q(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<=In&&o+l<=En,files:r.length,insertions:o,deletions:l,forbidden:s}}async function Sr(t,e){await q(t,["fetch","--prune","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],{timeoutMs:12e4}).catch(()=>q(t,["update-ref","-d",`refs/remotes/origin/${e}`]).catch(()=>{})),await q(t,["push","--force-with-lease","-u","origin",e],{timeoutMs:3e5})}async function Ve(t){return(await q(t,["rev-parse","HEAD"])).trim()}async function el(t,e){let n=await q(t,["fetch","origin",e],{timeoutMs:12e4}).then(()=>!0).catch(()=>!1),r=async s=>q(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 tl(t,e,n){return q(t,["rev-list","--count",`${e}..${n}`]).then(r=>r.trim()).catch(()=>"")}async function lo(t,e){try{return(await q(t,["rev-parse","--verify",`refs/heads/${e}`])).trim()}catch{return null}}async function gs(t,e){await q(t,["reset","--hard",e])}async function Pt(t,e){try{await q(t,["worktree","remove","--force",e])}catch{Ee.default.rmSync(e,{recursive:!0,force:!0})}}async function nl(t,e=[]){let n=new Set(e.map(s=>me.default.basename(me.default.resolve(s))).filter(s=>s.length>0)),r=Qt();if(Ee.default.existsSync(r))for(let s of Ee.default.readdirSync(r))n.has(s)||Ee.default.rmSync(me.default.join(r,s),{recursive:!0,force:!0});for(let s of t)try{await q(s,["worktree","prune"])}catch{}}async function rl(t,e){return await q(t,["fetch","origin","--prune"]).catch(()=>{}),(await q(t,["branch","-r","--list",`*${e}*`])).split(`
343
- `).map(s=>s.trim()).filter(s=>s&&!s.includes("->"))[0]??null}async function co(t,e,n=6e4){let s=(await q(t,["symbolic-ref","refs/remotes/origin/HEAD"]).catch(()=>"")).trim().replace("refs/remotes/","")||"origin/main",i=await q(t,["diff","--stat",`${s}...${e}`]),o=await q(t,["diff",`${s}...${e}`]);return{base:s,stat:i.slice(0,4e3),diff:o.slice(0,n)}}function Ed(){let t=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(Ee.default.existsSync(me.default.join(kr.default.homedir(),".cache","ticketpilot"))?me.default.join(kr.default.homedir(),".cache","ticketpilot"):me.default.join(kr.default.homedir(),".cache","allwright"));return me.default.join(t,"env-checkouts")}function _d(t){return t.replace(/[^\w.-]+/g,"_")}async function sl(t,e,n){await q(t,["fetch","origin"],{timeoutMs:3e5}),await q(t,["reset","--hard"]),await q(t,["checkout","-B",e,n])}function Rd(t,e){return me.default.join(Ed(),_d(t),_d(e))}async function il(t){let e=Rd(t.repoName,t.envName);return await q(t.repoPath,["fetch","origin",t.branch],{timeoutMs:3e5}),Ee.default.existsSync(me.default.join(e,".git"))?await q(e,["fetch","origin",t.branch],{timeoutMs:3e5}):(Ee.default.rmSync(e,{recursive:!0,force:!0}),Ee.default.mkdirSync(me.default.dirname(e),{recursive:!0,mode:448}),await q(t.repoPath,["worktree","prune"]).catch(()=>{}),await q(t.repoPath,["worktree","add","--detach",e,`origin/${t.branch}`])),t.attached?await q(e,["checkout","-B",t.branch,`origin/${t.branch}`]):await q(e,["checkout","--force","--detach",`origin/${t.branch}`]),e}async function ol(t,e,n){try{await q(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 q(t,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyMerged:!0}}catch{}try{return await q(t,["-c",`user.name=${io}`,"-c",`user.email=${oo}`,"merge","--no-ff","-m",n,`origin/${e}`]),{ok:!0}}catch(r){return await q(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 al(t,e){await q(t,["fetch","origin",e],{timeoutMs:3e5});try{return await q(t,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyUpToDate:!0}}catch{}try{return await q(t,["-c",`user.name=${io}`,"-c",`user.email=${oo}`,"merge","--no-edit",`origin/${e}`]),{ok:!0,alreadyUpToDate:!1}}catch(n){let s=(await q(t,["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
339
+ ${i}${o}`:"clean"}`}function Qt(){let t=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(Ie.default.existsSync(me.default.join(kr.default.homedir(),".cache","ticketpilot"))?me.default.join(kr.default.homedir(),".cache","ticketpilot"):me.default.join(kr.default.homedir(),".cache","allwright"));return me.default.join(t,"worktrees")}async function Ya(t,e,n,r=40){if(!n.trim()||!e.trim())return null;let s=await q(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 q(t,["show","--name-only","--format=",i]).then(c=>c.split(`
340
+ `).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 Ja(t,e){try{return(await q(t,["ls-remote","--heads","origin",e])).trim().length>0}catch{return null}}async function Rn(t,e){try{await q(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 Xa(t,e){try{let n=await q(t,["worktree","list","--porcelain"]),r=Qt(),s=null;for(let i of n.split(`
341
+ `))i.startsWith("worktree ")&&(s=i.slice(9).trim()),i===`branch refs/heads/${e}`&&s&&s.startsWith(r)&&await q(t,["worktree","remove","--force",s]);await q(t,["worktree","prune"])}catch{}try{await q(t,["branch","-D",e])}catch{}}async function Qa(t,e,n,r){Ie.default.mkdirSync(me.default.dirname(e),{recursive:!0,mode:448}),await q(t,["worktree","add","-b",n,e,`origin/${r}`])}async function _r(t,e){if(await q(t,["add","-A"]),!(await q(t,["status","--porcelain"])).trim())throw new Error("Claude wrote no changes - nothing to commit");await q(t,["-c",`user.name=${io}`,"-c",`user.email=${oo}`,"commit","-m",e])}async function An(t,e){let r=(await q(t,["diff","--name-only",`origin/${e}...HEAD`])).split(`
342
+ `).filter(Boolean),s=r.filter(d=>Ed.some(p=>p.test(d))),i=await q(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<=En&&o+l<=In,files:r.length,insertions:o,deletions:l,forbidden:s}}async function Sr(t,e){await q(t,["fetch","--prune","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],{timeoutMs:12e4}).catch(()=>q(t,["update-ref","-d",`refs/remotes/origin/${e}`]).catch(()=>{})),await q(t,["push","--force-with-lease","-u","origin",e],{timeoutMs:3e5})}async function Ve(t){return(await q(t,["rev-parse","HEAD"])).trim()}async function el(t,e){let n=await q(t,["fetch","origin",e],{timeoutMs:12e4}).then(()=>!0).catch(()=>!1),r=async s=>q(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 tl(t,e,n){return q(t,["rev-list","--count",`${e}..${n}`]).then(r=>r.trim()).catch(()=>"")}async function lo(t,e){try{return(await q(t,["rev-parse","--verify",`refs/heads/${e}`])).trim()}catch{return null}}async function gs(t,e){await q(t,["reset","--hard",e])}async function Pt(t,e){try{await q(t,["worktree","remove","--force",e])}catch{Ie.default.rmSync(e,{recursive:!0,force:!0})}}async function nl(t,e=[]){let n=new Set(e.map(s=>me.default.basename(me.default.resolve(s))).filter(s=>s.length>0)),r=Qt();if(Ie.default.existsSync(r))for(let s of Ie.default.readdirSync(r))n.has(s)||Ie.default.rmSync(me.default.join(r,s),{recursive:!0,force:!0});for(let s of t)try{await q(s,["worktree","prune"])}catch{}}async function rl(t,e){return await q(t,["fetch","origin","--prune"]).catch(()=>{}),(await q(t,["branch","-r","--list",`*${e}*`])).split(`
343
+ `).map(s=>s.trim()).filter(s=>s&&!s.includes("->"))[0]??null}async function co(t,e,n=6e4){let s=(await q(t,["symbolic-ref","refs/remotes/origin/HEAD"]).catch(()=>"")).trim().replace("refs/remotes/","")||"origin/main",i=await q(t,["diff","--stat",`${s}...${e}`]),o=await q(t,["diff",`${s}...${e}`]);return{base:s,stat:i.slice(0,4e3),diff:o.slice(0,n)}}function Id(){let t=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(Ie.default.existsSync(me.default.join(kr.default.homedir(),".cache","ticketpilot"))?me.default.join(kr.default.homedir(),".cache","ticketpilot"):me.default.join(kr.default.homedir(),".cache","allwright"));return me.default.join(t,"env-checkouts")}function _d(t){return t.replace(/[^\w.-]+/g,"_")}async function sl(t,e,n){await q(t,["fetch","origin"],{timeoutMs:3e5}),await q(t,["reset","--hard"]),await q(t,["checkout","-B",e,n])}function Rd(t,e){return me.default.join(Id(),_d(t),_d(e))}async function il(t){let e=Rd(t.repoName,t.envName);return await q(t.repoPath,["fetch","origin",t.branch],{timeoutMs:3e5}),Ie.default.existsSync(me.default.join(e,".git"))?await q(e,["fetch","origin",t.branch],{timeoutMs:3e5}):(Ie.default.rmSync(e,{recursive:!0,force:!0}),Ie.default.mkdirSync(me.default.dirname(e),{recursive:!0,mode:448}),await q(t.repoPath,["worktree","prune"]).catch(()=>{}),await q(t.repoPath,["worktree","add","--detach",e,`origin/${t.branch}`])),t.attached?await q(e,["checkout","-B",t.branch,`origin/${t.branch}`]):await q(e,["checkout","--force","--detach",`origin/${t.branch}`]),e}async function ol(t,e,n){try{await q(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 q(t,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyMerged:!0}}catch{}try{return await q(t,["-c",`user.name=${io}`,"-c",`user.email=${oo}`,"merge","--no-ff","-m",n,`origin/${e}`]),{ok:!0}}catch(r){return await q(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 al(t,e){await q(t,["fetch","origin",e],{timeoutMs:3e5});try{return await q(t,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyUpToDate:!0}}catch{}try{return await q(t,["-c",`user.name=${io}`,"-c",`user.email=${oo}`,"merge","--no-edit",`origin/${e}`]),{ok:!0,alreadyUpToDate:!1}}catch(n){let s=(await q(t,["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
344
344
  `).filter(Boolean);return s.length?{ok:!1,conflicts:s}:(await q(t,["merge","--abort"]).catch(()=>{}),{ok:!1,conflicts:null,reason:n instanceof Error?n.message.slice(0,300):String(n)})}}async function Cn(t){await q(t,["merge","--abort"]).catch(()=>{})}async function ll(t,e){await q(t,["add","-A"]),await q(t,["-c",`user.name=${io}`,"-c",`user.email=${oo}`,"commit","--no-edit","-m",e])}async function cl(t,e){let n=new Set(await uo(t));return e.filter(r=>n.has(r))}async function uo(t){let e=new Set;try{let r=await q(t,["grep","-l","-I","-E","^(<{7}|>{7})( |$)"]);for(let s of r.split(`
345
345
  `).filter(Boolean))e.add(s)}catch{}let n=[];try{n=(await q(t,["grep","-l","-I","-E","^={7}$"])).split(`
346
- `).filter(Boolean).filter(s=>!e.has(s))}catch{}for(let r of n)try{let s=await q(t,["show",`HEAD:${r}`]);/^={7}$/m.test(s)||e.add(r)}catch{e.add(r)}return[...e]}async function Xs(t,e,n){Ee.default.mkdirSync(me.default.dirname(e),{recursive:!0,mode:448}),await q(t,["fetch","origin",n],{timeoutMs:3e5}),await q(t,["worktree","add","--detach",e,`origin/${n}`]),await q(e,["checkout","-B",n,`origin/${n}`])}async function ul(t,e){try{await q(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 dl(t,e,n){try{return await xd("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 Tr(t){return(await q(t,["config","--get","remote.origin.url"])).trim()}function vt(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 Ee,kr,me,Sd,Td,xd,io,oo,In,En,Id,Xt,Nt=we(()=>{"use strict";Ee=R(require("node:fs"),1),kr=R(require("node:os"),1),me=R(require("node:path"),1),Sd=require("node:child_process"),Td=require("node:util"),xd=(0,Td.promisify)(Sd.execFile),io="Allwright Agent",oo="agent@ticketpilot.local",In=200,En=2e4,Id=[/^\.github\/workflows\//,/^\.git\b/,/(^|\/)\.githooks\//];Xt=".ticketpilot-delete"});function po(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 ze(t,e){return t.repos[e]?.github?.token??t.github?.token??null}function Od(t,e){let n=[t.jira,...Object.values(t.repos).map(l=>l.jira)].filter(l=>!!l),r=new Set(n.map(l=>l.email.toLowerCase())),s=!!t.github?.token||Object.values(t.repos).some(l=>l.github?.token),i=t.github?.login??Object.values(t.repos).find(l=>l.github?.login)?.github?.login??"",o=e.map(l=>{let c=l.trim().toLowerCase(),u=t.jiraUsers[c]?"own":r.has(c)?"runner-account":"missing",p=u==="own"?t.jiraUsers[c].email:u==="runner-account"?c:"",f=t.githubUsers[c]?"own":s?"shared":"missing",w=f==="own"?t.githubUsers[c].login??"":f==="shared"?i:"";return{email:c,jira:u,jiraAs:p,github:f,githubAs:w}});return{githubShared:s,sharedGithubLogin:i,entries:o}}var xr=we(()=>{"use strict"});var Al,g,en=we(()=>{"use strict";Al=()=>new Date().toISOString(),g={info:t=>console.log(`${Al()} [info] ${t}`),warn:t=>console.warn(`${Al()} [warn] ${t}`),error:t=>console.error(`${Al()} [error] ${t}`)}});var bh={};fn(bh,{crawlSite:()=>Lw,extractLinks:()=>gh,formatCrawlReport:()=>Uw,pageIssues:()=>yh});function gh(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 yh(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 Lw(t){let e=new URL(t),n=e.origin,r=Date.now(),s={baseUrl:e.toString(),pages:[],notes:[]},i=new Map,o=[e.toString()],l=new Set(o),c=new Map,u=async w=>{let v=Date.now();try{let k=await fetch(w,{redirect:"follow",signal:AbortSignal.timeout(15e3),headers:{"user-agent":"Allwright-functional-audit (reads pages, changes nothing)"}}),x=await k.arrayBuffer(),E=x.byteLength,C=new TextDecoder().decode(x.slice(0,3e6));return{status:k.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:k,ms:x,bytes:E}=await u(w),C=/<title[^>]*>([\s\S]*?)<\/title>/i.exec(k)?.[1]?.trim()??"",V=yh({status:v,html:k,url:w,ms:x});if(v===0&&V.push("did not respond at all (timeout or connection failure)"),s.pages.push({url:w,status:v,ms:x,bytes:E,title:C,linkedFrom:[...i.get(w)??[]].slice(0,3),issues:V}),C&&c.set(C,[...c.get(C)??[],w]),v===200&&k)for(let Y of gh(k,w,n))i.has(Y)||i.set(Y,new Set),i.get(Y).add(w),l.has(Y)||(l.add(Y),o.push(Y))}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 u(new URL("/allwright-crawl-probe-404",n).toString())).status===200&&s.notes.push("an unknown path returns HTTP 200 - a catch-all is answering everything, so broken links on this site LOOK fine to a crawler and to search engines"),o.length&&s.notes.push(`stopped at ${s.pages.length} pages (cap) - ${o.length} discovered links not visited`),s.notes.push("crawled without JavaScript: what curl sees. Client-side rendering, broken interactivity and console errors are NOT covered by this evidence - do not claim they were checked."),s}function Uw(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(`
346
+ `).filter(Boolean).filter(s=>!e.has(s))}catch{}for(let r of n)try{let s=await q(t,["show",`HEAD:${r}`]);/^={7}$/m.test(s)||e.add(r)}catch{e.add(r)}return[...e]}async function Xs(t,e,n){Ie.default.mkdirSync(me.default.dirname(e),{recursive:!0,mode:448}),await q(t,["fetch","origin",n],{timeoutMs:3e5}),await q(t,["worktree","add","--detach",e,`origin/${n}`]),await q(e,["checkout","-B",n,`origin/${n}`])}async function ul(t,e){try{await q(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 dl(t,e,n){try{return await xd("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 Tr(t){return(await q(t,["config","--get","remote.origin.url"])).trim()}function vt(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 Ie,kr,me,Sd,Td,xd,io,oo,En,In,Ed,Xt,Nt=we(()=>{"use strict";Ie=R(require("node:fs"),1),kr=R(require("node:os"),1),me=R(require("node:path"),1),Sd=require("node:child_process"),Td=require("node:util"),xd=(0,Td.promisify)(Sd.execFile),io="Allwright Agent",oo="agent@ticketpilot.local",En=200,In=2e4,Ed=[/^\.github\/workflows\//,/^\.git\b/,/(^|\/)\.githooks\//];Xt=".ticketpilot-delete"});function po(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 ze(t,e){return t.repos[e]?.github?.token??t.github?.token??null}function jd(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 xr=we(()=>{"use strict"});var Al,g,en=we(()=>{"use strict";Al=()=>new Date().toISOString(),g={info:t=>console.log(`${Al()} [info] ${t}`),warn:t=>console.warn(`${Al()} [warn] ${t}`),error:t=>console.error(`${Al()} [error] ${t}`)}});var bh={};fn(bh,{crawlSite:()=>Lw,extractLinks:()=>gh,formatCrawlReport:()=>Uw,pageIssues:()=>yh});function gh(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 yh(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 Lw(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 k=await fetch(w,{redirect:"follow",signal:AbortSignal.timeout(15e3),headers:{"user-agent":"Allwright-functional-audit (reads pages, changes nothing)"}}),E=await k.arrayBuffer(),I=E.byteLength,$=new TextDecoder().decode(E.slice(0,3e6));return{status:k.status,html:$,ms:Date.now()-v,bytes:I}}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:k,ms:E,bytes:I}=await d(w),$=/<title[^>]*>([\s\S]*?)<\/title>/i.exec(k)?.[1]?.trim()??"",V=yh({status:v,html:k,url:w,ms:E});if(v===0&&V.push("did not respond at all (timeout or connection failure)"),s.pages.push({url:w,status:v,ms:E,bytes:I,title:$,linkedFrom:[...i.get(w)??[]].slice(0,3),issues:V}),$&&c.set($,[...c.get($)??[],w]),v===200&&k)for(let Y of gh(k,w,n))i.has(Y)||i.set(Y,new Set),i.get(Y).add(w),l.has(Y)||(l.add(Y),o.push(Y))}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 Uw(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(`
347
347
  `);return`CRAWL OF THE RUNNING SITE (${t.baseUrl}) - gathered by the runner just now, GET only, same-origin only:
348
348
  ${e}
349
349
 
350
350
  SITE-WIDE:
351
351
  ${t.notes.map(n=>`- ${n}`).join(`
352
- `)}`}var wh=we(()=>{"use strict"});var Rr={};fn(Rr,{GitHubClient:()=>qe});var ev,qe,_t=we(()=>{"use strict";ev=process.env.TICKETPILOT_GITHUB_API??"https://api.github.com",qe=class{constructor(e){this.token=e}token;async request(e,n,r){let s=await fetch(`${ev}${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 dp(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 hp(t,e=60){try{return tt.default.readdirSync(t).slice(0,e).map(n=>ui.default.join(t,n)).filter(n=>{try{return tt.default.statSync(n).isFile()}catch{return!1}})}catch{return[]}}function Co(t,e=$v){let n=t.replace(/\/+$/,"");if(!n)return[];let r=[];for(let s of e)for(let i of hp(s)){if(!i.endsWith(".service"))continue;let o=dp(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(`${ui.default.basename(i,".service")} (User=${c})`+(l?` runs: ${l}`:""))}return r}function pp(t,e=cp,n=up){let r=t.map(o=>o.trim().toLowerCase()).filter(Boolean);if(!r.length)return[];let s=[...e,...n.flatMap(o=>hp(o))],i=[];for(let o of s){let l=dp(o);if(!l)continue;let c=l.toLowerCase(),u=r.find(f=>c.includes(f));if(!u)continue;let p=l.split(`
353
- `).filter(f=>/reverse_proxy|proxy_pass|root\s+\*?\s*\//i.test(f)).map(f=>f.trim()).slice(0,8);i.push({file:o,host:u,lines:p})}return i}function fp(t){return`${t.file} mentions ${t.host}`+(t.lines.length?` - routing lines: ${t.lines.join(" | ")}`:" - no routing line found")}function Pv(t,e=cp,n=up){return pp(t,e,n).map(fp)}function mp(t){return t.trim().replace(/\/+$/,"")}function Nv(t){let e=t.trim().replace(/;\s*$/,"").replace(/\{\s*$/,"").trim(),n=/^root\s+(?:\*\s+)?(\S+)$/i.exec(e);return n?.[1]?mp(n[1].replace(/^["']|["']$/g,"")):null}function jv(t,e){let n=mp(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=Nv(s);i&&(i===n||i.startsWith(`${n}/`))&&(r=!0)}return r}function Ov(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 Mv(t){try{let e=tt.default.statSync(t).uid;return(0,Dt.execFileSync)("id",["-nu",String(e)],{encoding:"utf8",timeout:5e3}).trim()||null}catch{return null}}function $o(t){let e=(0,Dt.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(`
354
- `).map(n=>n.split(/\s+/)[1]??"").map(n=>n.replace(/^refs\/heads\//,"")).filter(Boolean)}:Dv(`${e.stderr??""}`,t,Mv(t),e.error?.message)}function Dv(t,e,n,r){let s=Ov(t.trim()),i=s.split(`
352
+ `)}`}var wh=we(()=>{"use strict"});var Rr={};fn(Rr,{GitHubClient:()=>qe});var ev,qe,_t=we(()=>{"use strict";ev=process.env.TICKETPILOT_GITHUB_API??"https://api.github.com",qe=class{constructor(e){this.token=e}token;async request(e,n,r){let s=await fetch(`${ev}${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 dp(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 hp(t,e=60){try{return tt.default.readdirSync(t).slice(0,e).map(n=>ui.default.join(t,n)).filter(n=>{try{return tt.default.statSync(n).isFile()}catch{return!1}})}catch{return[]}}function Co(t,e=$v){let n=t.replace(/\/+$/,"");if(!n)return[];let r=[];for(let s of e)for(let i of hp(s)){if(!i.endsWith(".service"))continue;let o=dp(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(`${ui.default.basename(i,".service")} (User=${c})`+(l?` runs: ${l}`:""))}return r}function pp(t,e=cp,n=up){let r=t.map(o=>o.trim().toLowerCase()).filter(Boolean);if(!r.length)return[];let s=[...e,...n.flatMap(o=>hp(o))],i=[];for(let o of s){let l=dp(o);if(!l)continue;let c=l.toLowerCase(),d=r.find(f=>c.includes(f));if(!d)continue;let p=l.split(`
353
+ `).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 fp(t){return`${t.file} mentions ${t.host}`+(t.lines.length?` - routing lines: ${t.lines.join(" | ")}`:" - no routing line found")}function Pv(t,e=cp,n=up){return pp(t,e,n).map(fp)}function mp(t){return t.trim().replace(/\/+$/,"")}function Nv(t){let e=t.trim().replace(/;\s*$/,"").replace(/\{\s*$/,"").trim(),n=/^root\s+(?:\*\s+)?(\S+)$/i.exec(e);return n?.[1]?mp(n[1].replace(/^["']|["']$/g,"")):null}function Ov(t,e){let n=mp(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=Nv(s);i&&(i===n||i.startsWith(`${n}/`))&&(r=!0)}return r}function jv(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 Mv(t){try{let e=tt.default.statSync(t).uid;return(0,Dt.execFileSync)("id",["-nu",String(e)],{encoding:"utf8",timeout:5e3}).trim()||null}catch{return null}}function $o(t){let e=(0,Dt.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(`
354
+ `).map(n=>n.split(/\s+/)[1]??"").map(n=>n.replace(/^refs\/heads\//,"")).filter(Boolean)}:Dv(`${e.stderr??""}`,t,Mv(t),e.error?.message)}function Dv(t,e,n,r){let s=jv(t.trim()),i=s.split(`
355
355
  `).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 di(t){let e=l=>{try{return(0,Dt.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=$o(t),r=e(["branch","--format=%(refname:short)"]),s=e(["branch","-r","--format=%(refname:short)"]),i=n.ok?n.branches:null,o=[`
356
356
 
357
357
  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(`
358
358
  `).join(", ")}`),s&&o.push(`- remote-tracking refs already fetched here: ${s.split(`
359
359
  `).join(", ")}`),i&&s){let l=new Set(s.split(`
360
- `).map(u=>u.replace(/^origin\//,""))),c=i.filter(u=>!l.has(u));c.length&&o.push(`- exists on origin but NOT fetched here yet: ${c.join(", ")}. This is a \`git fetch\`, not a missing branch - never report it as a blocker.`)}return o.join(`
360
+ `).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(`
361
361
  `)}function zv(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(`
362
- `)[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 Yl(){let t=s=>{try{return(0,Dt.execFileSync)(s,["--version"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}},e=(s,i)=>{try{return(0,Dt.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,u)=>u.indexOf(l)===c&&tt.default.existsSync(l));for(let l of o){let c=t(l);if(!c)continue;let u=l===i?`${s} in the RUNNER's PATH (${l}) - deploy steps run with THIS`:`${s} at ${l}`;n.push(`- ${u}: ${c}`);let p=zv(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 ${ui.default.basename(l)} therefore pins NOTHING.`),w&&tt.default.existsSync(`/usr/bin/${f}`)){let k=t(`/usr/bin/${f}`),x=v;k&&x&&k!==x&&(r=!0)}}else n.push(` ${l} runs under ${p.shebang.slice(2).trim()} (fixed by its shebang).`)}}return n.length?`
362
+ `)[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 Yl(){let t=s=>{try{return(0,Dt.execFileSync)(s,["--version"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}},e=(s,i)=>{try{return(0,Dt.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=zv(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 ${ui.default.basename(l)} therefore pins NOTHING.`),w&&tt.default.existsSync(`/usr/bin/${f}`)){let k=t(`/usr/bin/${f}`),E=v;k&&E&&k!==E&&(r=!0)}}else n.push(` ${l} runs under ${p.shebang.slice(2).trim()} (fixed by its shebang).`)}}return n.length?`
363
363
  - runtime versions (a MISMATCH between the runner's PATH and the system install is a common root cause):
364
364
  ${n.map(s=>` ${s}`).join(`
365
365
  `)}`+(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 Lv(){let t=o=>{try{return(0,Dt.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,Dt.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`
@@ -377,7 +377,7 @@ ABOUT THE MACHINE THIS RUNS ON - gathered by the runner just now, read-only. Tru
377
377
  `+r.map(i=>` - ${i}`).join(`
378
378
  `)+`
379
379
  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(`
380
- `)+Lv()+Yl()}function gp(t){let e=[],n=o=>o.workdir.trim()||t.repoPath,r=$o(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=Co(l),u="";try{u=o.publicUrl?new URL(o.publicUrl).hostname:""}catch{u=""}let p=u?pp([u]):[],f=c.length?void 0:p.find(w=>jv(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,Dt.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}},k=v(w,["rev-parse","HEAD"]),x=o.branch.trim()?v(t.repoPath,["rev-parse",`origin/${o.branch.trim()}`]):null,E=k&&x&&k!==x?v(t.repoPath,["rev-list","--count",`${k}..${x}`]):null;e.push({environment:o.name,question:`The live checkout at ${w} serves the latest ${o.branch.trim()||"commit"}`,ok:k!==null&&(x===null||k===x),blocking:!1,detail:k?x===null?`serving ${k.slice(0,10)}${o.branch.trim()?` (could not resolve origin/${o.branch.trim()} to compare)`:""}`:k===x?`serving ${k.slice(0,10)} = origin/${o.branch.trim()}`:`serving ${k.slice(0,10)}, but origin/${o.branch.trim()} is at ${x.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=u,v=p.map(fp);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=u;if(w){let v="";for(let k of["DEPLOY.md",".ticketpilot/deploy.md","docs/DEPLOY.md"])try{v=tt.default.readFileSync(ui.default.join(l,k),"utf8");break}catch{}if(v){let k=v.includes(w);e.push({environment:o.name,question:`DEPLOY.md mentions ${w}`,ok:k,blocking:!1,detail:k?"":"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 Dt,tt,ui,$v,cp,up,Po=we(()=>{"use strict";Dt=require("node:child_process"),tt=R(require("node:fs"),1),ui=R(require("node:path"),1),$v=["/etc/systemd/system","/lib/systemd/system","/usr/lib/systemd/system"],cp=["/etc/caddy/Caddyfile","/usr/local/etc/caddy/Caddyfile","/etc/nginx/nginx.conf"],up=["/etc/nginx/sites-enabled","/etc/nginx/conf.d","/etc/caddy/conf.d","/etc/caddy/sites-enabled"]});function Ql(t){return t.replace(/([A-Za-z_][A-Za-z0-9_]*)=(\S+)/g,(e,n,r)=>qv.test(n)?`${n}=<redacted>`:e)}function rn(t,e){try{let r=(0,kp.execFileSync)(t,e,{encoding:"utf8",timeout:1e4,maxBuffer:2e6,stdio:["ignore","pipe","pipe"]}).trim();return r?r.slice(0,vp):null}catch(n){let r=n,s=`${r?.stdout??""}${r?.stderr??""}`.trim();return s?s.slice(0,vp):null}}function Fv(t){let e=["/etc/systemd/system","/lib/systemd/system"],n=[];for(let r of e){let s;try{s=Xl.default.readdirSync(r)}catch{continue}for(let i of s)if(i.endsWith(".service"))try{let o=Xl.default.readFileSync(_p.default.join(r,i),"utf8");t&&o.includes(t)&&n.push(i.replace(/\.service$/,""))}catch{}}return[...new Set(n)].slice(0,3)}function Sp(t){let e=t.errorText.slice(-6e3),n=[],r=(o,l)=>{l&&n.push({command:o,output:Ql(l)})},s=Fv(t.repoPath);for(let o of s)r(`systemctl status ${o}`,rn("systemctl",["status",o,"--no-pager","-l"])),r(`journalctl -u ${o} -n 40`,rn("journalctl",["-u",o,"-n","40","--no-pager"])),r(`systemctl show ${o} -p ExecStart -p Environment -p WorkingDirectory -p User`,rn("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",rn("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)`,rn("bash",["-lc",`command -v ${JSON.stringify(o)} || echo "not on this PATH"`])),r("ls of the usual system locations",rn("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",rn("bash",["-lc","df -h | head -10"])),/EACCES|Permission denied|Operation not permitted/i.test(e)&&(r("id",rn("id",[])),r(`ls -ld ${t.repoPath}`,rn("bash",["-lc",`ls -ld ${JSON.stringify(t.repoPath)} 2>&1`]))),n}function Tp(t){return t.length?`
380
+ `)+Lv()+Yl()}function gp(t){let e=[],n=o=>o.workdir.trim()||t.repoPath,r=$o(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=Co(l),d="";try{d=o.publicUrl?new URL(o.publicUrl).hostname:""}catch{d=""}let p=d?pp([d]):[],f=c.length?void 0:p.find(w=>Ov(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=($,V)=>{try{return(0,Dt.execFileSync)("git",V,{cwd:$,encoding:"utf8",timeout:1e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"true"},stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}},k=v(w,["rev-parse","HEAD"]),E=o.branch.trim()?v(t.repoPath,["rev-parse",`origin/${o.branch.trim()}`]):null,I=k&&E&&k!==E?v(t.repoPath,["rev-list","--count",`${k}..${E}`]):null;e.push({environment:o.name,question:`The live checkout at ${w} serves the latest ${o.branch.trim()||"commit"}`,ok:k!==null&&(E===null||k===E),blocking:!1,detail:k?E===null?`serving ${k.slice(0,10)}${o.branch.trim()?` (could not resolve origin/${o.branch.trim()} to compare)`:""}`:k===E?`serving ${k.slice(0,10)} = origin/${o.branch.trim()}`:`serving ${k.slice(0,10)}, but origin/${o.branch.trim()} is at ${E.slice(0,10)}`+(I?` - ${I} 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(fp);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 k of["DEPLOY.md",".ticketpilot/deploy.md","docs/DEPLOY.md"])try{v=tt.default.readFileSync(ui.default.join(l,k),"utf8");break}catch{}if(v){let k=v.includes(w);e.push({environment:o.name,question:`DEPLOY.md mentions ${w}`,ok:k,blocking:!1,detail:k?"":"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 Dt,tt,ui,$v,cp,up,Po=we(()=>{"use strict";Dt=require("node:child_process"),tt=R(require("node:fs"),1),ui=R(require("node:path"),1),$v=["/etc/systemd/system","/lib/systemd/system","/usr/lib/systemd/system"],cp=["/etc/caddy/Caddyfile","/usr/local/etc/caddy/Caddyfile","/etc/nginx/nginx.conf"],up=["/etc/nginx/sites-enabled","/etc/nginx/conf.d","/etc/caddy/conf.d","/etc/caddy/sites-enabled"]});function Ql(t){return t.replace(/([A-Za-z_][A-Za-z0-9_]*)=(\S+)/g,(e,n,r)=>qv.test(n)?`${n}=<redacted>`:e)}function rn(t,e){try{let r=(0,kp.execFileSync)(t,e,{encoding:"utf8",timeout:1e4,maxBuffer:2e6,stdio:["ignore","pipe","pipe"]}).trim();return r?r.slice(0,vp):null}catch(n){let r=n,s=`${r?.stdout??""}${r?.stderr??""}`.trim();return s?s.slice(0,vp):null}}function Fv(t){let e=["/etc/systemd/system","/lib/systemd/system"],n=[];for(let r of e){let s;try{s=Xl.default.readdirSync(r)}catch{continue}for(let i of s)if(i.endsWith(".service"))try{let o=Xl.default.readFileSync(_p.default.join(r,i),"utf8");t&&o.includes(t)&&n.push(i.replace(/\.service$/,""))}catch{}}return[...new Set(n)].slice(0,3)}function Sp(t){let e=t.errorText.slice(-6e3),n=[],r=(o,l)=>{l&&n.push({command:o,output:Ql(l)})},s=Fv(t.repoPath);for(let o of s)r(`systemctl status ${o}`,rn("systemctl",["status",o,"--no-pager","-l"])),r(`journalctl -u ${o} -n 40`,rn("journalctl",["-u",o,"-n","40","--no-pager"])),r(`systemctl show ${o} -p ExecStart -p Environment -p WorkingDirectory -p User`,rn("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",rn("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)`,rn("bash",["-lc",`command -v ${JSON.stringify(o)} || echo "not on this PATH"`])),r("ls of the usual system locations",rn("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",rn("bash",["-lc","df -h | head -10"])),/EACCES|Permission denied|Operation not permitted/i.test(e)&&(r("id",rn("id",[])),r(`ls -ld ${t.repoPath}`,rn("bash",["-lc",`ls -ld ${JSON.stringify(t.repoPath)} 2>&1`]))),n}function Tp(t){return t.length?`
381
381
 
382
382
  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.
383
383
 
@@ -386,15 +386,15 @@ ${e.output}`).join(`
386
386
 
387
387
  `)+`
388
388
 
389
- 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 kp,Xl,_p,vp,qv,ec=we(()=>{"use strict";kp=require("node:child_process"),Xl=R(require("node:fs"),1),_p=R(require("node:path"),1),vp=4e3,qv=/(TOKEN|KEY|SECRET|PASSWORD|PASSWD|CREDENTIAL|AUTH|COOKIE|SESSION)/i});var Lp={};fn(Lp,{MAX_CHAIN_DEPTH:()=>lc,breakChain:()=>hc,breakSingleModeChain:()=>gc,chainOf:()=>uc,chainSessionFor:()=>qo,loadBatchPlan:()=>cc,nextMemberWillChain:()=>yc,parsePlanAnswer:()=>bc,recordChainSession:()=>dc,recordSingleModeSession:()=>fc,saveBatchPlan:()=>ik,singleModeChainIntact:()=>mc,singleModeSessionFor:()=>pc});function ik(t){As.default.mkdirSync(ac(),{recursive:!0,mode:448}),As.default.writeFileSync(Uo.default.join(ac(),`${t.batchId}.json`),JSON.stringify(t,null,2),{mode:384})}function cc(t){if(!t)return null;try{return JSON.parse(As.default.readFileSync(Uo.default.join(ac(),`${t}.json`),"utf8"))}catch{return null}}function uc(t,e){return t?t.chains.find(n=>n.includes(e)&&n.length>1)??null:null}function qo(t,e,n){let r=e.indexOf(n);if(r<=0)return null;let s=sn.get(Lo(t,e));return!s||s.lastIssue!==e[r-1]||s.depth>=lc||!As.default.existsSync(s.worktreePath)?null:s}function dc(t,e,n,r){let s=sn.get(Lo(t,e));sn.set(Lo(t,e),{sessionId:r.sessionId,worktreePath:r.worktreePath,depth:(s?.depth??0)+1,lastIssue:n})}function hc(t,e){sn.delete(Lo(t,e))}function pc(t){let e=sn.get(hi(t));return!e||e.depth>=lc||!As.default.existsSync(e.worktreePath)?null:e}function fc(t,e,n,r){let s=sn.get(hi(t));sn.set(hi(t),{sessionId:n.sessionId,worktreePath:n.worktreePath,depth:r?(s?.depth??0)+1:1,lastIssue:e})}function mc(t,e){return sn.get(hi(t))?.lastIssue===e}function gc(t){sn.delete(hi(t))}function yc(t,e){if(!t)return!1;let n=t.indexOf(e);return n!==-1&&n<t.length-1}function bc(t,e){let n=/```(?:json)?\s*\n([\s\S]*?)```/.exec(t)??/(\{[\s\S]*\})/.exec(t);if(!n)return null;let r;try{r=JSON.parse(n[1])}catch{return null}let s=r,i=new Set(e),o=Array.isArray(s.order)?s.order.filter(p=>typeof p=="string"):[];if(o.length!==e.length||!o.every(p=>i.has(p))||new Set(o).size!==o.length)return null;let l=(Array.isArray(s.chains)?s.chains:[]).map(p=>Array.isArray(p)?p.filter(f=>typeof f=="string"&&i.has(f)):[]).filter(p=>p.length>1),c=(Array.isArray(s.dependencies)?s.dependencies:[]).map(p=>Array.isArray(p)?p:[]).filter(p=>p.length===2&&typeof p[0]=="string"&&typeof p[1]=="string"&&i.has(p[0])&&i.has(p[1])&&p[0]!==p[1]),u=typeof s.reasoning=="string"?s.reasoning.slice(0,1e3):"";return{order:o,chains:l,dependencies:c,reasoning:u}}var As,Uo,lc,ac,sn,Lo,hi,Fo=we(()=>{"use strict";As=R(require("node:fs"),1),Uo=R(require("node:path"),1);$e();lc=3,ac=()=>Uo.default.join(le(),"autopilot-plans");sn=new Map,Lo=(t,e)=>`${t}:${e[0]}`;hi=t=>`${t}:__single__`});var on=ce((rI,wf)=>{"use strict";var yf=["nodebuffer","arraybuffer","fragments"],bf=typeof Blob<"u";bf&&yf.push("blob");wf.exports={BINARY_TYPES:yf,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:bf,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var mi=ce((sI,Wo)=>{"use strict";var{EMPTY_BUFFER:Rk}=on(),Ec=Buffer[Symbol.species];function Ak(t,e){if(t.length===0)return Rk;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 Ec(n.buffer,n.byteOffset,r):n}function vf(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function kf(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function Ck(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Rc(t){if(Rc.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Ec(t):ArrayBuffer.isView(t)?e=new Ec(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Rc.readOnly=!1),e}Wo.exports={concat:Ak,mask:vf,toArrayBuffer:Ck,toBuffer:Rc,unmask:kf};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");Wo.exports.mask=function(e,n,r,s,i){i<48?vf(e,n,r,s,i):t.mask(e,n,r,s,i)},Wo.exports.unmask=function(e,n){e.length<32?kf(e,n):t.unmask(e,n)}}catch{}});var Tf=ce((iI,Sf)=>{"use strict";var _f=Symbol("kDone"),Ac=Symbol("kRun"),Cc=class{constructor(e){this[_f]=()=>{this.pending--,this[Ac]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ac]()}[Ac](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[_f])}}};Sf.exports=Cc});var Ps=ce((oI,Rf)=>{"use strict";var gi=require("zlib"),xf=mi(),$k=Tf(),{kStatusCode:If}=on(),Pk=Buffer[Symbol.species],Nk=Buffer.from([0,0,255,255]),Vo=Symbol("permessage-deflate"),an=Symbol("total-length"),Cs=Symbol("callback"),Mn=Symbol("buffers"),$s=Symbol("error"),Zo,$c=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,!Zo){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Zo=new $k(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[Cs];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){Zo.add(s=>{this._decompress(e,n,(i,o)=>{s(),r(i,o)})})}compress(e,n,r){Zo.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"?gi.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=gi.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Vo]=this,this._inflate[an]=0,this._inflate[Mn]=[],this._inflate.on("error",Ok),this._inflate.on("data",Ef)}this._inflate[Cs]=r,this._inflate.write(e),n&&this._inflate.write(Nk),this._inflate.flush(()=>{let i=this._inflate[$s];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=xf.concat(this._inflate[Mn],this._inflate[an]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[an]=0,this._inflate[Mn]=[],n&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,n,r){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?gi.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=gi.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[an]=0,this._deflate[Mn]=[],this._deflate.on("data",jk)}this._deflate[Cs]=r,this._deflate.write(e),this._deflate.flush(gi.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=xf.concat(this._deflate[Mn],this._deflate[an]);n&&(i=new Pk(i.buffer,i.byteOffset,i.length-4)),this._deflate[Cs]=null,this._deflate[an]=0,this._deflate[Mn]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};Rf.exports=$c;function jk(t){this[Mn].push(t),this[an]+=t.length}function Ef(t){if(this[an]+=t.length,this[Vo]._maxPayload<1||this[an]<=this[Vo]._maxPayload){this[Mn].push(t);return}this[$s]=new RangeError("Max payload size exceeded"),this[$s].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[$s][If]=1009,this.removeListener("data",Ef),this.reset()}function Ok(t){if(this[Vo]._inflate=null,this[$s]){this[Cs](this[$s]);return}t[If]=1007,this[Cs](t)}});var Ns=ce((aI,Yo)=>{"use strict";var{isUtf8:Af}=require("buffer"),{hasBlob:Mk}=on(),Dk=[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 zk(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Pc(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 Lk(t){return Mk&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Yo.exports={isBlob:Lk,isValidStatusCode:zk,isValidUTF8:Pc,tokenChars:Dk};if(Af)Yo.exports.isValidUTF8=function(t){return t.length<24?Pc(t):Af(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");Yo.exports.isValidUTF8=function(e){return e.length<32?Pc(e):t(e)}}catch{}});var Dc=ce((lI,Mf)=>{"use strict";var{Writable:Uk}=require("stream"),Cf=Ps(),{BINARY_TYPES:qk,EMPTY_BUFFER:$f,kStatusCode:Fk,kWebSocket:Bk}=on(),{concat:Nc,toArrayBuffer:Hk,unmask:Kk}=mi(),{isValidStatusCode:Gk,isValidUTF8:Pf}=Ns(),Jo=Buffer[Symbol.species],mt=0,Nf=1,jf=2,Of=3,jc=4,Oc=5,Xo=6,Mc=class extends Uk{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||qk[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[Bk]=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=mt}_write(e,n,r){if(this._opcode===8&&this._state==mt)return r();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){r(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new Jo(r.buffer,r.byteOffset+e,r.length-e),new Jo(r.buffer,r.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let r=this._buffers[0],s=n.length-e;e>=r.length?n.set(this._buffers.shift(),s):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new Jo(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case mt:this.getInfo(e);break;case Nf:this.getPayloadLength16(e);break;case jf:this.getPayloadLength64(e);break;case Of:this.getMask();break;case jc:this.getData(e);break;case Oc:case Xo: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[Cf.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=Nf:this._payloadLength===127?this._state=jf: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=Of:this._state=jc}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=jc}getData(e){let n=$f;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&&Kk(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let r=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(r);return}if(this._compressed){this._state=Oc,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Cf.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===mt&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=mt;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=Nc(r,n):this._binaryType==="arraybuffer"?s=Hk(Nc(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=mt):(this._state=Xo,setImmediate(()=>{this.emit("message",s,!0),this._state=mt,this.startLoop(e)}))}else{let s=Nc(r,n);if(!this._skipUTF8Validation&&!Pf(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Oc||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=mt):(this._state=Xo,setImmediate(()=>{this.emit("message",s,!1),this._state=mt,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,$f),this.end();else{let r=e.readUInt16BE(0);if(!Gk(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new Jo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Pf(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=mt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=mt):(this._state=Xo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=mt,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[Fk]=s,o}};Mf.exports=Mc});var Uc=ce((uI,Lf)=>{"use strict";var{Duplex:cI}=require("stream"),{randomFillSync:Wk}=require("crypto"),{types:{isUint8Array:Zk}}=require("util"),Df=Ps(),{EMPTY_BUFFER:Vk,kWebSocket:Yk,NOOP:Jk}=on(),{isBlob:js,isValidStatusCode:Xk}=Ns(),{mask:zf,toBuffer:Fr}=mi(),gt=Symbol("kByteLength"),Qk=Buffer.alloc(4),Qo=8*1024,Br,Os=Qo,Tt=0,e_=1,t_=2,zc=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=Tt,this.onerror=Jk,this[Yk]=void 0}static frame(e,n){let r,s=!1,i=2,o=!1;n.mask&&(r=n.maskBuffer||Qk,n.generateMask?n.generateMask(r):(Os===Qo&&(Br===void 0&&(Br=Buffer.alloc(Qo)),Wk(Br,0,Qo),Os=0),r[0]=Br[Os++],r[1]=Br[Os++],r[2]=Br[Os++],r[3]=Br[Os++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let l;typeof e=="string"?(!n.mask||o)&&n[gt]!==void 0?l=n[gt]:(e=Buffer.from(e),l=e.length):(l=e.length,s=n.mask&&n.readOnly&&!o);let c=l;l>=65536?(i+=8,c=127):l>125&&(i+=2,c=126);let u=Buffer.allocUnsafe(s?l+i:i);return u[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(u[0]|=64),u[1]=c,c===126?u.writeUInt16BE(l,2):c===127&&(u[2]=u[3]=0,u.writeUIntBE(l,4,6)),n.mask?(u[1]|=128,u[i-4]=r[0],u[i-3]=r[1],u[i-2]=r[2],u[i-1]=r[3],o?[u,e]:s?(zf(e,r,u,i,l),[u]):(zf(e,r,e,0,l),[u,e])):[u,e]}close(e,n,r,s){let i;if(e===void 0)i=Vk;else{if(typeof e!="number"||!Xk(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(Zk(n))i.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[gt]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Tt?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):js(e)?(s=e.size,i=!1):(e=Fr(e),s=e.length,i=Fr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[gt]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};js(e)?this._state!==Tt?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==Tt?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):js(e)?(s=e.size,i=!1):(e=Fr(e),s=e.length,i=Fr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[gt]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};js(e)?this._state!==Tt?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==Tt?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let s=this._extensions[Df.extensionName],i=n.binary?2:1,o=n.compress,l,c;typeof e=="string"?(l=Buffer.byteLength(e),c=!1):js(e)?(l=e.size,c=!1):(e=Fr(e),l=e.length,c=Fr.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=l>=s._threshold),this._compress=o):(o=!1,i=0),n.fin&&(this._firstFragment=!0);let u={[gt]:l,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};js(e)?this._state!==Tt?this.enqueue([this.getBlobData,e,this._compress,u,r]):this.getBlobData(e,this._compress,u,r):this._state!==Tt?this.enqueue([this.dispatch,e,this._compress,u,r]):this.dispatch(e,this._compress,u,r)}getBlobData(e,n,r,s){this._bufferedBytes+=r[gt],this._state=t_,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let l=new Error("The socket was closed while the blob was being read");process.nextTick(Lc,this,l,s);return}this._bufferedBytes-=r[gt];let o=Fr(i);n?this.dispatch(o,n,r,s):(this._state=Tt,this.sendFrame(t.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(n_,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[Df.extensionName];this._bufferedBytes+=r[gt],this._state=e_,i.compress(e,r.fin,(o,l)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");Lc(this,c,s);return}this._bufferedBytes-=r[gt],this._state=Tt,r.readOnly=!1,this.sendFrame(t.frame(l,r),s),this.dequeue()})}dequeue(){for(;this._state===Tt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][gt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][gt],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)}};Lf.exports=zc;function Lc(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 n_(t,e,n){Lc(t,e,n),t.onerror(e)}});var Zf=ce((dI,Wf)=>{"use strict";var{kForOnEventAttribute:yi,kListener:qc}=on(),Uf=Symbol("kCode"),qf=Symbol("kData"),Ff=Symbol("kError"),Bf=Symbol("kMessage"),Hf=Symbol("kReason"),Ms=Symbol("kTarget"),Kf=Symbol("kType"),Gf=Symbol("kWasClean"),ln=class{constructor(e){this[Ms]=null,this[Kf]=e}get target(){return this[Ms]}get type(){return this[Kf]}};Object.defineProperty(ln.prototype,"target",{enumerable:!0});Object.defineProperty(ln.prototype,"type",{enumerable:!0});var Hr=class extends ln{constructor(e,n={}){super(e),this[Uf]=n.code===void 0?0:n.code,this[Hf]=n.reason===void 0?"":n.reason,this[Gf]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Uf]}get reason(){return this[Hf]}get wasClean(){return this[Gf]}};Object.defineProperty(Hr.prototype,"code",{enumerable:!0});Object.defineProperty(Hr.prototype,"reason",{enumerable:!0});Object.defineProperty(Hr.prototype,"wasClean",{enumerable:!0});var Ds=class extends ln{constructor(e,n={}){super(e),this[Ff]=n.error===void 0?null:n.error,this[Bf]=n.message===void 0?"":n.message}get error(){return this[Ff]}get message(){return this[Bf]}};Object.defineProperty(Ds.prototype,"error",{enumerable:!0});Object.defineProperty(Ds.prototype,"message",{enumerable:!0});var bi=class extends ln{constructor(e,n={}){super(e),this[qf]=n.data===void 0?null:n.data}get data(){return this[qf]}};Object.defineProperty(bi.prototype,"data",{enumerable:!0});var r_={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[yi]&&s[qc]===e&&!s[yi])return;let r;if(t==="message")r=function(i,o){let l=new bi("message",{data:o?i:i.toString()});l[Ms]=this,ea(e,this,l)};else if(t==="close")r=function(i,o){let l=new Hr("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});l[Ms]=this,ea(e,this,l)};else if(t==="error")r=function(i){let o=new Ds("error",{error:i,message:i.message});o[Ms]=this,ea(e,this,o)};else if(t==="open")r=function(){let i=new ln("open");i[Ms]=this,ea(e,this,i)};else return;r[yi]=!!n[yi],r[qc]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[qc]===e&&!n[yi]){this.removeListener(t,n);break}}};Wf.exports={CloseEvent:Hr,ErrorEvent:Ds,Event:ln,EventTarget:r_,MessageEvent:bi};function ea(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var ta=ce((hI,Vf)=>{"use strict";var{tokenChars:wi}=Ns();function zt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function s_(t){let e=Object.create(null),n=Object.create(null),r=!1,s=!1,i=!1,o,l,c=-1,u=-1,p=-1,f=0;for(;f<t.length;f++)if(u=t.charCodeAt(f),o===void 0)if(p===-1&&wi[u]===1)c===-1&&(c=f);else if(f!==0&&(u===32||u===9))p===-1&&c!==-1&&(p=f);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f);let v=t.slice(c,p);u===44?(zt(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&&wi[u]===1)c===-1&&(c=f);else if(u===32||u===9)p===-1&&c!==-1&&(p=f);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f),zt(n,t.slice(c,p),!0),u===44&&(zt(e,o,n),n=Object.create(null),o=void 0),c=p=-1}else if(u===61&&c!==-1&&p===-1)l=t.slice(c,f),c=p=-1;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(s){if(wi[u]!==1)throw new SyntaxError(`Unexpected character at index ${f}`);c===-1?c=f:r||(r=!0),s=!1}else if(i)if(wi[u]===1)c===-1&&(c=f);else if(u===34&&c!==-1)i=!1,p=f;else if(u===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(u===34&&t.charCodeAt(f-1)===61)i=!0;else if(p===-1&&wi[u]===1)c===-1&&(c=f);else if(c!==-1&&(u===32||u===9))p===-1&&(p=f);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f);let v=t.slice(c,p);r&&(v=v.replace(/\\/g,""),r=!1),zt(n,l,v),u===44&&(zt(e,o,n),n=Object.create(null),o=void 0),l=void 0,c=p=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);if(c===-1||i||u===32||u===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=f);let w=t.slice(c,p);return o===void 0?zt(e,w,n):(l===void 0?zt(n,w,!0):r?zt(n,l,w.replace(/\\/g,"")):zt(n,l,w),zt(e,o,n)),e}function i_(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(", ")}Vf.exports={format:i_,parse:s_}});var ia=ce((mI,am)=>{"use strict";var o_=require("events"),a_=require("https"),l_=require("http"),Xf=require("net"),c_=require("tls"),{randomBytes:u_,createHash:d_}=require("crypto"),{Duplex:pI,Readable:fI}=require("stream"),{URL:Fc}=require("url"),Dn=Ps(),h_=Dc(),p_=Uc(),{isBlob:f_}=Ns(),{BINARY_TYPES:Yf,CLOSE_TIMEOUT:m_,EMPTY_BUFFER:na,GUID:g_,kForOnEventAttribute:Bc,kListener:y_,kStatusCode:b_,kWebSocket:Re,NOOP:Qf}=on(),{EventTarget:{addEventListener:w_,removeEventListener:v_}}=Zf(),{format:k_,parse:__}=ta(),{toBuffer:S_}=mi(),em=Symbol("kAborted"),Hc=[8,13],cn=["CONNECTING","OPEN","CLOSING","CLOSED"],T_=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ge=class t extends o_{constructor(e,n,r){super(),this._binaryType=Yf[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=na,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]),tm(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Yf.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 h_({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 p_(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[Re]=this,i[Re]=this,e[Re]=this,s.on("conclude",E_),s.on("drain",R_),s.on("error",A_),s.on("message",C_),s.on("ping",$_),s.on("pong",P_),i.onerror=N_,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",sm),e.on("data",sa),e.on("end",im),e.on("error",om),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[Dn.extensionName]&&this._extensions[Dn.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())}),rm(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){Kc(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||na,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){Kc(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||na,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){Kc(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Dn.extensionName]||(s.compress=!1),this._sender.send(e||na,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(ge,"CONNECTING",{enumerable:!0,value:cn.indexOf("CONNECTING")});Object.defineProperty(ge.prototype,"CONNECTING",{enumerable:!0,value:cn.indexOf("CONNECTING")});Object.defineProperty(ge,"OPEN",{enumerable:!0,value:cn.indexOf("OPEN")});Object.defineProperty(ge.prototype,"OPEN",{enumerable:!0,value:cn.indexOf("OPEN")});Object.defineProperty(ge,"CLOSING",{enumerable:!0,value:cn.indexOf("CLOSING")});Object.defineProperty(ge.prototype,"CLOSING",{enumerable:!0,value:cn.indexOf("CLOSING")});Object.defineProperty(ge,"CLOSED",{enumerable:!0,value:cn.indexOf("CLOSED")});Object.defineProperty(ge.prototype,"CLOSED",{enumerable:!0,value:cn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(ge.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(ge.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Bc])return e[y_];return null},set(e){for(let n of this.listeners(t))if(n[Bc]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Bc]:!0})}})});ge.prototype.addEventListener=w_;ge.prototype.removeEventListener=v_;am.exports=ge;function tm(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:m_,protocolVersion:Hc[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,!Hc.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Hc.join(", ")})`);let i;if(e instanceof Fc)i=e;else try{i=new Fc(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),t._url=i.href;let o=i.protocol==="wss:",l=i.protocol==="ws+unix:",c;if(i.protocol!=="ws:"&&!o&&!l?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:l&&!i.pathname?c="The URL's pathname is empty":i.hash&&(c="The URL contains a fragment identifier"),c){let x=new SyntaxError(c);if(t._redirects===0)throw x;ra(t,x);return}let u=o?443:80,p=u_(16).toString("base64"),f=o?a_.request:l_.request,w=new Set,v;if(s.createConnection=s.createConnection||(o?I_:x_),s.defaultPort=s.defaultPort||u,s.port=i.port||u,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(v=new Dn({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=k_({[Dn.extensionName]:v.offer()})),n.length){for(let x of n){if(typeof x!="string"||!T_.test(x)||w.has(x))throw new SyntaxError("An invalid or duplicated subprotocol was specified");w.add(x)}s.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),l){let x=s.path.split(":");s.socketPath=x[0],s.path=x[1]}let k;if(s.followRedirects){if(t._redirects===0){t._originalIpc=l,t._originalSecure=o,t._originalHostOrSocketPath=l?s.socketPath:i.host;let x=r&&r.headers;if(r={...r,headers:{}},x)for(let[E,C]of Object.entries(x))r.headers[E.toLowerCase()]=C}else if(t.listenerCount("redirect")===0){let x=l?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!x||t._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,x||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),k=t._req=f(s),t._redirects&&t.emit("redirect",t.url,k)}else k=t._req=f(s);s.timeout&&k.on("timeout",()=>{nt(t,k,"Opening handshake has timed out")}),k.on("error",x=>{k===null||k[em]||(k=t._req=null,ra(t,x))}),k.on("response",x=>{let E=x.headers.location,C=x.statusCode;if(E&&s.followRedirects&&C>=300&&C<400){if(++t._redirects>s.maxRedirects){nt(t,k,"Maximum redirects exceeded");return}k.abort();let V;try{V=new Fc(E,e)}catch{let b=new SyntaxError(`Invalid URL: ${E}`);ra(t,b);return}tm(t,V,n,r)}else t.emit("unexpected-response",k,x)||nt(t,k,`Unexpected server response: ${x.statusCode}`)}),k.on("upgrade",(x,E,C)=>{if(t.emit("upgrade",x),t.readyState!==ge.CONNECTING)return;k=t._req=null;let V=x.headers.upgrade;if(V===void 0||V.toLowerCase()!=="websocket"){nt(t,E,"Invalid Upgrade header");return}let Y=d_("sha1").update(p+g_).digest("base64");if(x.headers["sec-websocket-accept"]!==Y){nt(t,E,"Invalid Sec-WebSocket-Accept header");return}let b=x.headers["sec-websocket-protocol"],$;if(b!==void 0?w.size?w.has(b)||($="Server sent an invalid subprotocol"):$="Server sent a subprotocol but none was requested":w.size&&($="Server sent no subprotocol"),$){nt(t,E,$);return}b&&(t._protocol=b);let D=x.headers["sec-websocket-extensions"];if(D!==void 0){if(!v){nt(t,E,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let j;try{j=__(D)}catch{nt(t,E,"Invalid Sec-WebSocket-Extensions header");return}let B=Object.keys(j);if(B.length!==1||B[0]!==Dn.extensionName){nt(t,E,"Server indicated an extension that was not requested");return}try{v.accept(j[Dn.extensionName])}catch{nt(t,E,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Dn.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(k,t):k.end()}function ra(t,e){t._readyState=ge.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function x_(t){return t.path=t.socketPath,Xf.connect(t)}function I_(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Xf.isIP(t.host)?"":t.host),c_.connect(t)}function nt(t,e,n){t._readyState=ge.CLOSING;let r=new Error(n);Error.captureStackTrace(r,nt),e.setHeader?(e[em]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ra,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Kc(t,e,n){if(e){let r=f_(e)?e.size:S_(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${cn[t.readyState]})`);process.nextTick(n,r)}}function E_(t,e){let n=this[Re];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[Re]!==void 0&&(n._socket.removeListener("data",sa),process.nextTick(nm,n._socket),t===1005?n.close():n.close(t,e))}function R_(){let t=this[Re];t.isPaused||t._socket.resume()}function A_(t){let e=this[Re];e._socket[Re]!==void 0&&(e._socket.removeListener("data",sa),process.nextTick(nm,e._socket),e.close(t[b_])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Jf(){this[Re].emitClose()}function C_(t,e){this[Re].emit("message",t,e)}function $_(t){let e=this[Re];e._autoPong&&e.pong(t,!this._isServer,Qf),e.emit("ping",t)}function P_(t){this[Re].emit("pong",t)}function nm(t){t.resume()}function N_(t){let e=this[Re];e.readyState!==ge.CLOSED&&(e.readyState===ge.OPEN&&(e._readyState=ge.CLOSING,rm(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function rm(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function sm(){let t=this[Re];if(this.removeListener("close",sm),this.removeListener("data",sa),this.removeListener("end",im),t._readyState=ge.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[Re]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Jf),t._receiver.on("finish",Jf))}function sa(t){this[Re]._receiver.write(t)||this.pause()}function im(){let t=this[Re];t._readyState=ge.CLOSING,t._receiver.end(),this.end()}function om(){let t=this[Re];this.removeListener("error",om),this.on("error",Qf),t&&(t._readyState=ge.CLOSING,this.destroy())}});var dm=ce((yI,um)=>{"use strict";var gI=ia(),{Duplex:j_}=require("stream");function lm(t){t.emit("close")}function O_(){!this.destroyed&&this._writableState.finished&&this.destroy()}function cm(t){this.removeListener("error",cm),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function M_(t,e){let n=!0,r=new j_({...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(lm,r);return}let o=!1;t.once("error",function(c){o=!0,i(c)}),t.once("close",function(){o||i(s),process.nextTick(lm,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",O_),r.on("error",cm),r}um.exports=M_});var Gc=ce((bI,hm)=>{"use strict";var{tokenChars:D_}=Ns();function z_(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&&D_[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}hm.exports={parse:z_}});var wm=ce((vI,bm)=>{"use strict";var L_=require("events"),oa=require("http"),{Duplex:wI}=require("stream"),{createHash:U_}=require("crypto"),pm=ta(),Kr=Ps(),q_=Gc(),F_=ia(),{CLOSE_TIMEOUT:B_,GUID:H_,kWebSocket:K_}=on(),G_=/^[+/0-9A-Za-z]{22}==$/,fm=0,mm=1,ym=2,Wc=class extends L_{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:B_,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:F_,...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=oa.createServer((r,s)=>{let i=oa.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=W_(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=fm}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===ym){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(vi,this);return}if(e&&this.once("close",e),this._state!==mm)if(this._state=mm,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(vi,this):process.nextTick(vi,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{vi(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",gm);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,l=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Gr(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Gr(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!G_.test(i)){Gr(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(l!==13&&l!==8){Gr(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){ki(n,400);return}let c=e.headers["sec-websocket-protocol"],u=new Set;if(c!==void 0)try{u=q_.parse(c)}catch{Gr(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 Kr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let v=pm.parse(p);v[Kr.extensionName]&&(w.accept(v[Kr.extensionName]),f[Kr.extensionName]=w)}catch{Gr(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,k,x,E)=>{if(!v)return ki(n,k||401,x,E);this.completeUpgrade(f,i,u,e,n,r,s)});return}if(!this.options.verifyClient(w))return ki(n,401)}this.completeUpgrade(f,i,u,e,n,r,s)}completeUpgrade(e,n,r,s,i,o,l){if(!i.readable||!i.writable)return i.destroy();if(i[K_])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>fm)return ki(i,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${U_("sha1").update(n+H_).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(r.size){let f=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;f&&(u.push(`Sec-WebSocket-Protocol: ${f}`),p._protocol=f)}if(e[Kr.extensionName]){let f=e[Kr.extensionName].params,w=pm.format({[Kr.extensionName]:[f]});u.push(`Sec-WebSocket-Extensions: ${w}`),p._extensions=e}this.emit("headers",u,s),i.write(u.concat(`\r
389
+ 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 kp,Xl,_p,vp,qv,ec=we(()=>{"use strict";kp=require("node:child_process"),Xl=R(require("node:fs"),1),_p=R(require("node:path"),1),vp=4e3,qv=/(TOKEN|KEY|SECRET|PASSWORD|PASSWD|CREDENTIAL|AUTH|COOKIE|SESSION)/i});var Lp={};fn(Lp,{MAX_CHAIN_DEPTH:()=>lc,breakChain:()=>hc,breakSingleModeChain:()=>gc,chainOf:()=>uc,chainSessionFor:()=>qo,loadBatchPlan:()=>cc,nextMemberWillChain:()=>yc,parsePlanAnswer:()=>bc,recordChainSession:()=>dc,recordSingleModeSession:()=>fc,saveBatchPlan:()=>hk,singleModeChainIntact:()=>mc,singleModeSessionFor:()=>pc});function hk(t){As.default.mkdirSync(ac(),{recursive:!0,mode:448}),As.default.writeFileSync(Uo.default.join(ac(),`${t.batchId}.json`),JSON.stringify(t,null,2),{mode:384})}function cc(t){if(!t)return null;try{return JSON.parse(As.default.readFileSync(Uo.default.join(ac(),`${t}.json`),"utf8"))}catch{return null}}function uc(t,e){return t?t.chains.find(n=>n.includes(e)&&n.length>1)??null:null}function qo(t,e,n){let r=e.indexOf(n);if(r<=0)return null;let s=sn.get(Lo(t,e));return!s||s.lastIssue!==e[r-1]||s.depth>=lc||!As.default.existsSync(s.worktreePath)?null:s}function dc(t,e,n,r){let s=sn.get(Lo(t,e));sn.set(Lo(t,e),{sessionId:r.sessionId,worktreePath:r.worktreePath,depth:(s?.depth??0)+1,lastIssue:n})}function hc(t,e){sn.delete(Lo(t,e))}function pc(t){let e=sn.get(hi(t));return!e||e.depth>=lc||!As.default.existsSync(e.worktreePath)?null:e}function fc(t,e,n,r){let s=sn.get(hi(t));sn.set(hi(t),{sessionId:n.sessionId,worktreePath:n.worktreePath,depth:r?(s?.depth??0)+1:1,lastIssue:e})}function mc(t,e){return sn.get(hi(t))?.lastIssue===e}function gc(t){sn.delete(hi(t))}function yc(t,e){if(!t)return!1;let n=t.indexOf(e);return n!==-1&&n<t.length-1}function bc(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 As,Uo,lc,ac,sn,Lo,hi,Fo=we(()=>{"use strict";As=R(require("node:fs"),1),Uo=R(require("node:path"),1);$e();lc=3,ac=()=>Uo.default.join(le(),"autopilot-plans");sn=new Map,Lo=(t,e)=>`${t}:${e[0]}`;hi=t=>`${t}:__single__`});var on=ce((uE,wf)=>{"use strict";var yf=["nodebuffer","arraybuffer","fragments"],bf=typeof Blob<"u";bf&&yf.push("blob");wf.exports={BINARY_TYPES:yf,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:bf,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var mi=ce((dE,Wo)=>{"use strict";var{EMPTY_BUFFER:jk}=on(),Ic=Buffer[Symbol.species];function Mk(t,e){if(t.length===0)return jk;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 Ic(n.buffer,n.byteOffset,r):n}function vf(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function kf(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function Dk(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Rc(t){if(Rc.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Ic(t):ArrayBuffer.isView(t)?e=new Ic(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Rc.readOnly=!1),e}Wo.exports={concat:Mk,mask:vf,toArrayBuffer:Dk,toBuffer:Rc,unmask:kf};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");Wo.exports.mask=function(e,n,r,s,i){i<48?vf(e,n,r,s,i):t.mask(e,n,r,s,i)},Wo.exports.unmask=function(e,n){e.length<32?kf(e,n):t.unmask(e,n)}}catch{}});var Tf=ce((hE,Sf)=>{"use strict";var _f=Symbol("kDone"),Ac=Symbol("kRun"),Cc=class{constructor(e){this[_f]=()=>{this.pending--,this[Ac]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ac]()}[Ac](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[_f])}}};Sf.exports=Cc});var Ps=ce((pE,Rf)=>{"use strict";var gi=require("zlib"),xf=mi(),zk=Tf(),{kStatusCode:Ef}=on(),Lk=Buffer[Symbol.species],Uk=Buffer.from([0,0,255,255]),Vo=Symbol("permessage-deflate"),an=Symbol("total-length"),Cs=Symbol("callback"),Mn=Symbol("buffers"),$s=Symbol("error"),Zo,$c=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,!Zo){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Zo=new zk(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[Cs];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){Zo.add(s=>{this._decompress(e,n,(i,o)=>{s(),r(i,o)})})}compress(e,n,r){Zo.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"?gi.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=gi.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Vo]=this,this._inflate[an]=0,this._inflate[Mn]=[],this._inflate.on("error",Fk),this._inflate.on("data",If)}this._inflate[Cs]=r,this._inflate.write(e),n&&this._inflate.write(Uk),this._inflate.flush(()=>{let i=this._inflate[$s];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=xf.concat(this._inflate[Mn],this._inflate[an]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[an]=0,this._inflate[Mn]=[],n&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,n,r){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?gi.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=gi.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[an]=0,this._deflate[Mn]=[],this._deflate.on("data",qk)}this._deflate[Cs]=r,this._deflate.write(e),this._deflate.flush(gi.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=xf.concat(this._deflate[Mn],this._deflate[an]);n&&(i=new Lk(i.buffer,i.byteOffset,i.length-4)),this._deflate[Cs]=null,this._deflate[an]=0,this._deflate[Mn]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};Rf.exports=$c;function qk(t){this[Mn].push(t),this[an]+=t.length}function If(t){if(this[an]+=t.length,this[Vo]._maxPayload<1||this[an]<=this[Vo]._maxPayload){this[Mn].push(t);return}this[$s]=new RangeError("Max payload size exceeded"),this[$s].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[$s][Ef]=1009,this.removeListener("data",If),this.reset()}function Fk(t){if(this[Vo]._inflate=null,this[$s]){this[Cs](this[$s]);return}t[Ef]=1007,this[Cs](t)}});var Ns=ce((fE,Yo)=>{"use strict";var{isUtf8:Af}=require("buffer"),{hasBlob:Bk}=on(),Hk=[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 Kk(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Pc(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 Gk(t){return Bk&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Yo.exports={isBlob:Gk,isValidStatusCode:Kk,isValidUTF8:Pc,tokenChars:Hk};if(Af)Yo.exports.isValidUTF8=function(t){return t.length<24?Pc(t):Af(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");Yo.exports.isValidUTF8=function(e){return e.length<32?Pc(e):t(e)}}catch{}});var Dc=ce((mE,Mf)=>{"use strict";var{Writable:Wk}=require("stream"),Cf=Ps(),{BINARY_TYPES:Zk,EMPTY_BUFFER:$f,kStatusCode:Vk,kWebSocket:Yk}=on(),{concat:Nc,toArrayBuffer:Jk,unmask:Xk}=mi(),{isValidStatusCode:Qk,isValidUTF8:Pf}=Ns(),Jo=Buffer[Symbol.species],mt=0,Nf=1,Of=2,jf=3,Oc=4,jc=5,Xo=6,Mc=class extends Wk{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Zk[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[Yk]=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=mt}_write(e,n,r){if(this._opcode===8&&this._state==mt)return r();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){r(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new Jo(r.buffer,r.byteOffset+e,r.length-e),new Jo(r.buffer,r.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let r=this._buffers[0],s=n.length-e;e>=r.length?n.set(this._buffers.shift(),s):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new Jo(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case mt:this.getInfo(e);break;case Nf:this.getPayloadLength16(e);break;case Of:this.getPayloadLength64(e);break;case jf:this.getMask();break;case Oc:this.getData(e);break;case jc:case Xo: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[Cf.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=Nf:this._payloadLength===127?this._state=Of: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=jf:this._state=Oc}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Oc}getData(e){let n=$f;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&&Xk(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=jc,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Cf.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===mt&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=mt;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=Nc(r,n):this._binaryType==="arraybuffer"?s=Jk(Nc(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=mt):(this._state=Xo,setImmediate(()=>{this.emit("message",s,!0),this._state=mt,this.startLoop(e)}))}else{let s=Nc(r,n);if(!this._skipUTF8Validation&&!Pf(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===jc||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=mt):(this._state=Xo,setImmediate(()=>{this.emit("message",s,!1),this._state=mt,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,$f),this.end();else{let r=e.readUInt16BE(0);if(!Qk(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new Jo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Pf(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=mt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=mt):(this._state=Xo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=mt,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[Vk]=s,o}};Mf.exports=Mc});var Uc=ce((yE,Lf)=>{"use strict";var{Duplex:gE}=require("stream"),{randomFillSync:e_}=require("crypto"),{types:{isUint8Array:t_}}=require("util"),Df=Ps(),{EMPTY_BUFFER:n_,kWebSocket:r_,NOOP:s_}=on(),{isBlob:Os,isValidStatusCode:i_}=Ns(),{mask:zf,toBuffer:Fr}=mi(),gt=Symbol("kByteLength"),o_=Buffer.alloc(4),Qo=8*1024,Br,js=Qo,Tt=0,a_=1,l_=2,zc=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=Tt,this.onerror=s_,this[r_]=void 0}static frame(e,n){let r,s=!1,i=2,o=!1;n.mask&&(r=n.maskBuffer||o_,n.generateMask?n.generateMask(r):(js===Qo&&(Br===void 0&&(Br=Buffer.alloc(Qo)),e_(Br,0,Qo),js=0),r[0]=Br[js++],r[1]=Br[js++],r[2]=Br[js++],r[3]=Br[js++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let l;typeof e=="string"?(!n.mask||o)&&n[gt]!==void 0?l=n[gt]:(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?(zf(e,r,d,i,l),[d]):(zf(e,r,e,0,l),[d,e])):[d,e]}close(e,n,r,s){let i;if(e===void 0)i=n_;else{if(typeof e!="number"||!i_(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(t_(n))i.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[gt]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Tt?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):Os(e)?(s=e.size,i=!1):(e=Fr(e),s=e.length,i=Fr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[gt]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Os(e)?this._state!==Tt?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==Tt?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):Os(e)?(s=e.size,i=!1):(e=Fr(e),s=e.length,i=Fr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[gt]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Os(e)?this._state!==Tt?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==Tt?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let s=this._extensions[Df.extensionName],i=n.binary?2:1,o=n.compress,l,c;typeof e=="string"?(l=Buffer.byteLength(e),c=!1):Os(e)?(l=e.size,c=!1):(e=Fr(e),l=e.length,c=Fr.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=l>=s._threshold),this._compress=o):(o=!1,i=0),n.fin&&(this._firstFragment=!0);let d={[gt]:l,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};Os(e)?this._state!==Tt?this.enqueue([this.getBlobData,e,this._compress,d,r]):this.getBlobData(e,this._compress,d,r):this._state!==Tt?this.enqueue([this.dispatch,e,this._compress,d,r]):this.dispatch(e,this._compress,d,r)}getBlobData(e,n,r,s){this._bufferedBytes+=r[gt],this._state=l_,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let l=new Error("The socket was closed while the blob was being read");process.nextTick(Lc,this,l,s);return}this._bufferedBytes-=r[gt];let o=Fr(i);n?this.dispatch(o,n,r,s):(this._state=Tt,this.sendFrame(t.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(c_,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[Df.extensionName];this._bufferedBytes+=r[gt],this._state=a_,i.compress(e,r.fin,(o,l)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");Lc(this,c,s);return}this._bufferedBytes-=r[gt],this._state=Tt,r.readOnly=!1,this.sendFrame(t.frame(l,r),s),this.dequeue()})}dequeue(){for(;this._state===Tt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][gt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][gt],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)}};Lf.exports=zc;function Lc(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 c_(t,e,n){Lc(t,e,n),t.onerror(e)}});var Zf=ce((bE,Wf)=>{"use strict";var{kForOnEventAttribute:yi,kListener:qc}=on(),Uf=Symbol("kCode"),qf=Symbol("kData"),Ff=Symbol("kError"),Bf=Symbol("kMessage"),Hf=Symbol("kReason"),Ms=Symbol("kTarget"),Kf=Symbol("kType"),Gf=Symbol("kWasClean"),ln=class{constructor(e){this[Ms]=null,this[Kf]=e}get target(){return this[Ms]}get type(){return this[Kf]}};Object.defineProperty(ln.prototype,"target",{enumerable:!0});Object.defineProperty(ln.prototype,"type",{enumerable:!0});var Hr=class extends ln{constructor(e,n={}){super(e),this[Uf]=n.code===void 0?0:n.code,this[Hf]=n.reason===void 0?"":n.reason,this[Gf]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Uf]}get reason(){return this[Hf]}get wasClean(){return this[Gf]}};Object.defineProperty(Hr.prototype,"code",{enumerable:!0});Object.defineProperty(Hr.prototype,"reason",{enumerable:!0});Object.defineProperty(Hr.prototype,"wasClean",{enumerable:!0});var Ds=class extends ln{constructor(e,n={}){super(e),this[Ff]=n.error===void 0?null:n.error,this[Bf]=n.message===void 0?"":n.message}get error(){return this[Ff]}get message(){return this[Bf]}};Object.defineProperty(Ds.prototype,"error",{enumerable:!0});Object.defineProperty(Ds.prototype,"message",{enumerable:!0});var bi=class extends ln{constructor(e,n={}){super(e),this[qf]=n.data===void 0?null:n.data}get data(){return this[qf]}};Object.defineProperty(bi.prototype,"data",{enumerable:!0});var u_={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[yi]&&s[qc]===e&&!s[yi])return;let r;if(t==="message")r=function(i,o){let l=new bi("message",{data:o?i:i.toString()});l[Ms]=this,ea(e,this,l)};else if(t==="close")r=function(i,o){let l=new Hr("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});l[Ms]=this,ea(e,this,l)};else if(t==="error")r=function(i){let o=new Ds("error",{error:i,message:i.message});o[Ms]=this,ea(e,this,o)};else if(t==="open")r=function(){let i=new ln("open");i[Ms]=this,ea(e,this,i)};else return;r[yi]=!!n[yi],r[qc]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[qc]===e&&!n[yi]){this.removeListener(t,n);break}}};Wf.exports={CloseEvent:Hr,ErrorEvent:Ds,Event:ln,EventTarget:u_,MessageEvent:bi};function ea(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var ta=ce((wE,Vf)=>{"use strict";var{tokenChars:wi}=Ns();function zt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function d_(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&&wi[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?(zt(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&&wi[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),zt(n,t.slice(c,p),!0),d===44&&(zt(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(wi[d]!==1)throw new SyntaxError(`Unexpected character at index ${f}`);c===-1?c=f:r||(r=!0),s=!1}else if(i)if(wi[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&&wi[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),zt(n,l,v),d===44&&(zt(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?zt(e,w,n):(l===void 0?zt(n,w,!0):r?zt(n,l,w.replace(/\\/g,"")):zt(n,l,w),zt(e,o,n)),e}function h_(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(", ")}Vf.exports={format:h_,parse:d_}});var ia=ce((_E,am)=>{"use strict";var p_=require("events"),f_=require("https"),m_=require("http"),Xf=require("net"),g_=require("tls"),{randomBytes:y_,createHash:b_}=require("crypto"),{Duplex:vE,Readable:kE}=require("stream"),{URL:Fc}=require("url"),Dn=Ps(),w_=Dc(),v_=Uc(),{isBlob:k_}=Ns(),{BINARY_TYPES:Yf,CLOSE_TIMEOUT:__,EMPTY_BUFFER:na,GUID:S_,kForOnEventAttribute:Bc,kListener:T_,kStatusCode:x_,kWebSocket:Re,NOOP:Qf}=on(),{EventTarget:{addEventListener:E_,removeEventListener:I_}}=Zf(),{format:R_,parse:A_}=ta(),{toBuffer:C_}=mi(),em=Symbol("kAborted"),Hc=[8,13],cn=["CONNECTING","OPEN","CLOSING","CLOSED"],$_=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ge=class t extends p_{constructor(e,n,r){super(),this._binaryType=Yf[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=na,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]),tm(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Yf.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 w_({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 v_(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[Re]=this,i[Re]=this,e[Re]=this,s.on("conclude",O_),s.on("drain",j_),s.on("error",M_),s.on("message",D_),s.on("ping",z_),s.on("pong",L_),i.onerror=U_,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",sm),e.on("data",sa),e.on("end",im),e.on("error",om),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[Dn.extensionName]&&this._extensions[Dn.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())}),rm(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){Kc(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||na,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){Kc(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||na,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){Kc(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Dn.extensionName]||(s.compress=!1),this._sender.send(e||na,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(ge,"CONNECTING",{enumerable:!0,value:cn.indexOf("CONNECTING")});Object.defineProperty(ge.prototype,"CONNECTING",{enumerable:!0,value:cn.indexOf("CONNECTING")});Object.defineProperty(ge,"OPEN",{enumerable:!0,value:cn.indexOf("OPEN")});Object.defineProperty(ge.prototype,"OPEN",{enumerable:!0,value:cn.indexOf("OPEN")});Object.defineProperty(ge,"CLOSING",{enumerable:!0,value:cn.indexOf("CLOSING")});Object.defineProperty(ge.prototype,"CLOSING",{enumerable:!0,value:cn.indexOf("CLOSING")});Object.defineProperty(ge,"CLOSED",{enumerable:!0,value:cn.indexOf("CLOSED")});Object.defineProperty(ge.prototype,"CLOSED",{enumerable:!0,value:cn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(ge.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(ge.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Bc])return e[T_];return null},set(e){for(let n of this.listeners(t))if(n[Bc]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Bc]:!0})}})});ge.prototype.addEventListener=E_;ge.prototype.removeEventListener=I_;am.exports=ge;function tm(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:__,protocolVersion:Hc[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,!Hc.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Hc.join(", ")})`);let i;if(e instanceof Fc)i=e;else try{i=new Fc(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 E=new SyntaxError(c);if(t._redirects===0)throw E;ra(t,E);return}let d=o?443:80,p=y_(16).toString("base64"),f=o?f_.request:m_.request,w=new Set,v;if(s.createConnection=s.createConnection||(o?N_:P_),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 Dn({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=R_({[Dn.extensionName]:v.offer()})),n.length){for(let E of n){if(typeof E!="string"||!$_.test(E)||w.has(E))throw new SyntaxError("An invalid or duplicated subprotocol was specified");w.add(E)}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 E=s.path.split(":");s.socketPath=E[0],s.path=E[1]}let k;if(s.followRedirects){if(t._redirects===0){t._originalIpc=l,t._originalSecure=o,t._originalHostOrSocketPath=l?s.socketPath:i.host;let E=r&&r.headers;if(r={...r,headers:{}},E)for(let[I,$]of Object.entries(E))r.headers[I.toLowerCase()]=$}else if(t.listenerCount("redirect")===0){let E=l?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!E||t._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,E||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),k=t._req=f(s),t._redirects&&t.emit("redirect",t.url,k)}else k=t._req=f(s);s.timeout&&k.on("timeout",()=>{nt(t,k,"Opening handshake has timed out")}),k.on("error",E=>{k===null||k[em]||(k=t._req=null,ra(t,E))}),k.on("response",E=>{let I=E.headers.location,$=E.statusCode;if(I&&s.followRedirects&&$>=300&&$<400){if(++t._redirects>s.maxRedirects){nt(t,k,"Maximum redirects exceeded");return}k.abort();let V;try{V=new Fc(I,e)}catch{let b=new SyntaxError(`Invalid URL: ${I}`);ra(t,b);return}tm(t,V,n,r)}else t.emit("unexpected-response",k,E)||nt(t,k,`Unexpected server response: ${E.statusCode}`)}),k.on("upgrade",(E,I,$)=>{if(t.emit("upgrade",E),t.readyState!==ge.CONNECTING)return;k=t._req=null;let V=E.headers.upgrade;if(V===void 0||V.toLowerCase()!=="websocket"){nt(t,I,"Invalid Upgrade header");return}let Y=b_("sha1").update(p+S_).digest("base64");if(E.headers["sec-websocket-accept"]!==Y){nt(t,I,"Invalid Sec-WebSocket-Accept header");return}let b=E.headers["sec-websocket-protocol"],P;if(b!==void 0?w.size?w.has(b)||(P="Server sent an invalid subprotocol"):P="Server sent a subprotocol but none was requested":w.size&&(P="Server sent no subprotocol"),P){nt(t,I,P);return}b&&(t._protocol=b);let D=E.headers["sec-websocket-extensions"];if(D!==void 0){if(!v){nt(t,I,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let j;try{j=A_(D)}catch{nt(t,I,"Invalid Sec-WebSocket-Extensions header");return}let B=Object.keys(j);if(B.length!==1||B[0]!==Dn.extensionName){nt(t,I,"Server indicated an extension that was not requested");return}try{v.accept(j[Dn.extensionName])}catch{nt(t,I,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Dn.extensionName]=v}t.setSocket(I,$,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(k,t):k.end()}function ra(t,e){t._readyState=ge.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function P_(t){return t.path=t.socketPath,Xf.connect(t)}function N_(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Xf.isIP(t.host)?"":t.host),g_.connect(t)}function nt(t,e,n){t._readyState=ge.CLOSING;let r=new Error(n);Error.captureStackTrace(r,nt),e.setHeader?(e[em]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ra,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Kc(t,e,n){if(e){let r=k_(e)?e.size:C_(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${cn[t.readyState]})`);process.nextTick(n,r)}}function O_(t,e){let n=this[Re];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[Re]!==void 0&&(n._socket.removeListener("data",sa),process.nextTick(nm,n._socket),t===1005?n.close():n.close(t,e))}function j_(){let t=this[Re];t.isPaused||t._socket.resume()}function M_(t){let e=this[Re];e._socket[Re]!==void 0&&(e._socket.removeListener("data",sa),process.nextTick(nm,e._socket),e.close(t[x_])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Jf(){this[Re].emitClose()}function D_(t,e){this[Re].emit("message",t,e)}function z_(t){let e=this[Re];e._autoPong&&e.pong(t,!this._isServer,Qf),e.emit("ping",t)}function L_(t){this[Re].emit("pong",t)}function nm(t){t.resume()}function U_(t){let e=this[Re];e.readyState!==ge.CLOSED&&(e.readyState===ge.OPEN&&(e._readyState=ge.CLOSING,rm(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function rm(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function sm(){let t=this[Re];if(this.removeListener("close",sm),this.removeListener("data",sa),this.removeListener("end",im),t._readyState=ge.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[Re]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Jf),t._receiver.on("finish",Jf))}function sa(t){this[Re]._receiver.write(t)||this.pause()}function im(){let t=this[Re];t._readyState=ge.CLOSING,t._receiver.end(),this.end()}function om(){let t=this[Re];this.removeListener("error",om),this.on("error",Qf),t&&(t._readyState=ge.CLOSING,this.destroy())}});var dm=ce((TE,um)=>{"use strict";var SE=ia(),{Duplex:q_}=require("stream");function lm(t){t.emit("close")}function F_(){!this.destroyed&&this._writableState.finished&&this.destroy()}function cm(t){this.removeListener("error",cm),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function B_(t,e){let n=!0,r=new q_({...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(lm,r);return}let o=!1;t.once("error",function(c){o=!0,i(c)}),t.once("close",function(){o||i(s),process.nextTick(lm,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",F_),r.on("error",cm),r}um.exports=B_});var Gc=ce((xE,hm)=>{"use strict";var{tokenChars:H_}=Ns();function K_(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&&H_[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}hm.exports={parse:K_}});var wm=ce((IE,bm)=>{"use strict";var G_=require("events"),oa=require("http"),{Duplex:EE}=require("stream"),{createHash:W_}=require("crypto"),pm=ta(),Kr=Ps(),Z_=Gc(),V_=ia(),{CLOSE_TIMEOUT:Y_,GUID:J_,kWebSocket:X_}=on(),Q_=/^[+/0-9A-Za-z]{22}==$/,fm=0,mm=1,ym=2,Wc=class extends G_{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:Y_,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:V_,...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=oa.createServer((r,s)=>{let i=oa.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=eS(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=fm}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===ym){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(vi,this);return}if(e&&this.once("close",e),this._state!==mm)if(this._state=mm,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(vi,this):process.nextTick(vi,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{vi(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",gm);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,l=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Gr(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Gr(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!Q_.test(i)){Gr(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(l!==13&&l!==8){Gr(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){ki(n,400);return}let c=e.headers["sec-websocket-protocol"],d=new Set;if(c!==void 0)try{d=Z_.parse(c)}catch{Gr(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 Kr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let v=pm.parse(p);v[Kr.extensionName]&&(w.accept(v[Kr.extensionName]),f[Kr.extensionName]=w)}catch{Gr(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,k,E,I)=>{if(!v)return ki(n,k||401,E,I);this.completeUpgrade(f,i,d,e,n,r,s)});return}if(!this.options.verifyClient(w))return ki(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[X_])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>fm)return ki(i,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${W_("sha1").update(n+J_).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[Kr.extensionName]){let f=e[Kr.extensionName].params,w=pm.format({[Kr.extensionName]:[f]});d.push(`Sec-WebSocket-Extensions: ${w}`),p._extensions=e}this.emit("headers",d,s),i.write(d.concat(`\r
390
390
  `).join(`\r
391
- `)),i.removeListener("error",gm),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(vi,this)})),l(p,s)}};bm.exports=Wc;function W_(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let r of Object.keys(e))t.removeListener(r,e[r])}}function vi(t){t._state=ym,t.emit("close")}function gm(){this.destroy()}function ki(t,e,n,r){n=n||oa.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} ${oa.STATUS_CODES[e]}\r
391
+ `)),i.removeListener("error",gm),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(vi,this)})),l(p,s)}};bm.exports=Wc;function eS(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 vi(t){t._state=ym,t.emit("close")}function gm(){this.destroy()}function ki(t,e,n,r){n=n||oa.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} ${oa.STATUS_CODES[e]}\r
392
392
  `+Object.keys(r).map(s=>`${s}: ${r[s]}`).join(`\r
393
393
  `)+`\r
394
394
  \r
395
- `+n)}function Gr(t,e,n,r,s,i){if(t.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,Gr),t.emit("wsClientError",o,n,e)}else ki(n,r,s,i)}});var Rm={};fn(Rm,{CATALOGUE:()=>tu,catalogueForPrompt:()=>nu,describeDiagnostic:()=>pS,runDiagnostic:()=>fS});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(`
396
- `)}function pS(t){let e=tu[t.command];return e?e.describe(t.args??{}):null}async function fS(t){let e=tu[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,Em.execFile)(n[0],n.slice(1),{timeout:dS,maxBuffer:2e6},(i,o,l)=>{let c=`${o??""}${l?`
397
- ${l}`:""}`.trim(),u=Ql(c).slice(0,hS)||(i?String(i.message):"(no output)");s({ok:!0,commandLine:r,output:u})})})}var Em,eu,dS,hS,xm,Im,Qc,yt,da,tu,ru=we(()=>{"use strict";Em=require("node:child_process"),eu=R(require("node:fs"),1);ec();dS=1e4,hS=8e3,xm=/(\/\.(config|claude)\/|\/\.env($|[^a-z])|credentials|\.ssh\/|\.npmrc|runner\.json)/i,Im=/^[a-zA-Z0-9@._-]{1,80}$/,Qc=/^\/[^\0\n]{1,300}$/,yt=t=>typeof t=="string"?t.trim():"",da=(t,e,n)=>{let r=typeof t=="number"?Math.floor(t):n;return r>0&&r<=e?r:n},tu={service_status:{describe:t=>`systemctl status ${yt(t.unit)}`,build:t=>{let e=yt(t.unit);return Im.test(e)?["systemctl","status",e,"--no-pager","-l"]:"refused: that is not a plausible unit name"}},service_logs:{describe:t=>`journalctl -u ${yt(t.unit)} -n ${da(t.lines,200,50)}`,build:t=>{let e=yt(t.unit);return Im.test(e)?["journalctl","-u",e,"-n",String(da(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 ${yt(t.path)}`,build:t=>{let e=yt(t.path);return Qc.test(e)?xm.test(e)?"refused: that path can hold credentials":["ls","-la",e]:"refused: absolute path required"}},read_file:{describe:t=>`head -n ${da(t.lines,200,100)} ${yt(t.path)}`,build:t=>{let e=yt(t.path);if(!Qc.test(e))return"refused: absolute path required";if(xm.test(e))return"refused: that path can hold credentials";try{if(eu.default.statSync(e).size>2e6)return"refused: file too large for a chat"}catch{}return["head","-n",String(da(t.lines,200,100)),e]}},http_check:{describe:t=>`curl -sS -o /dev/null -w '%{http_code}' ${yt(t.url)}`,build:t=>{let e=yt(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 ${yt(t.path)} status + last 3 commits`,build:t=>{let e=yt(t.path);return Qc.test(e)?eu.default.existsSync(`${e}/.git`)?["git","-C",e,"log","--oneline","-3","--decorate"]:"refused: not a git checkout":"refused: absolute path required"}}}});var Um={};fn(Um,{MANAGED_MARKER:()=>Ei,caddyBlock:()=>Ls,checkoutOwner:()=>Lm,detectApp:()=>$m,envPrepare:()=>yS,nginxBlock:()=>Ti,nodeBinDir:()=>Cm,ownsProxyFile:()=>Dm,pickPort:()=>Nm,portsClaimedByUnits:()=>Pm,resolveProxyChoice:()=>zm,spliceCaddyBlock:()=>Mm,spliceManagedBlock:()=>iu,sudoersText:()=>Om,unitSlug:()=>Am,unitText:()=>jm});function Am(t,e){let n=r=>r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return`${n(t)}-${n(e)}`.slice(0,60)}function Cm(t){let e=n=>{try{let r=(0,Ut.execFileSync)(n[0],n.slice(1),{encoding:"utf8",timeout:1e4}).trim();return r?xt.default.dirname(r):null}catch{return null}};return t&&t!==Ii.default.userInfo().username?e(["sudo","-u",t,"bash","-lc","command -v node"]):e(["bash","-lc","command -v node"])}function $m(t){let e=xt.default.join(t,"package.json");if(!ye.default.existsSync(e))return{kind:"unknown",reason:"no package.json - only Node apps are supported so far"};let n;try{n=JSON.parse(ye.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 Pm(){let t=new Set;try{for(let e of ye.default.readdirSync("/etc/systemd/system"))if(e.endsWith(".service"))try{let n=ye.default.readFileSync(xt.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 Nm(t){let e=Pm(),n=r=>new Promise(s=>{let i=su.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 jm(t){return`${Ei}
395
+ `+n)}function Gr(t,e,n,r,s,i){if(t.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,Gr),t.emit("wsClientError",o,n,e)}else ki(n,r,s,i)}});var Rm={};fn(Rm,{CATALOGUE:()=>tu,catalogueForPrompt:()=>nu,describeDiagnostic:()=>vS,runDiagnostic:()=>kS});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(`
396
+ `)}function vS(t){let e=tu[t.command];return e?e.describe(t.args??{}):null}async function kS(t){let e=tu[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,Im.execFile)(n[0],n.slice(1),{timeout:bS,maxBuffer:2e6},(i,o,l)=>{let c=`${o??""}${l?`
397
+ ${l}`:""}`.trim(),d=Ql(c).slice(0,wS)||(i?String(i.message):"(no output)");s({ok:!0,commandLine:r,output:d})})})}var Im,eu,bS,wS,xm,Em,Qc,yt,da,tu,ru=we(()=>{"use strict";Im=require("node:child_process"),eu=R(require("node:fs"),1);ec();bS=1e4,wS=8e3,xm=/(\/\.(config|claude)\/|\/\.env($|[^a-z])|credentials|\.ssh\/|\.npmrc|runner\.json)/i,Em=/^[a-zA-Z0-9@._-]{1,80}$/,Qc=/^\/[^\0\n]{1,300}$/,yt=t=>typeof t=="string"?t.trim():"",da=(t,e,n)=>{let r=typeof t=="number"?Math.floor(t):n;return r>0&&r<=e?r:n},tu={service_status:{describe:t=>`systemctl status ${yt(t.unit)}`,build:t=>{let e=yt(t.unit);return Em.test(e)?["systemctl","status",e,"--no-pager","-l"]:"refused: that is not a plausible unit name"}},service_logs:{describe:t=>`journalctl -u ${yt(t.unit)} -n ${da(t.lines,200,50)}`,build:t=>{let e=yt(t.unit);return Em.test(e)?["journalctl","-u",e,"-n",String(da(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 ${yt(t.path)}`,build:t=>{let e=yt(t.path);return Qc.test(e)?xm.test(e)?"refused: that path can hold credentials":["ls","-la",e]:"refused: absolute path required"}},read_file:{describe:t=>`head -n ${da(t.lines,200,100)} ${yt(t.path)}`,build:t=>{let e=yt(t.path);if(!Qc.test(e))return"refused: absolute path required";if(xm.test(e))return"refused: that path can hold credentials";try{if(eu.default.statSync(e).size>2e6)return"refused: file too large for a chat"}catch{}return["head","-n",String(da(t.lines,200,100)),e]}},http_check:{describe:t=>`curl -sS -o /dev/null -w '%{http_code}' ${yt(t.url)}`,build:t=>{let e=yt(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 ${yt(t.path)} status + last 3 commits`,build:t=>{let e=yt(t.path);return Qc.test(e)?eu.default.existsSync(`${e}/.git`)?["git","-C",e,"log","--oneline","-3","--decorate"]:"refused: not a git checkout":"refused: absolute path required"}}}});var Um={};fn(Um,{MANAGED_MARKER:()=>Ii,caddyBlock:()=>Ls,checkoutOwner:()=>Lm,detectApp:()=>$m,envPrepare:()=>TS,nginxBlock:()=>Ti,nodeBinDir:()=>Cm,ownsProxyFile:()=>Dm,pickPort:()=>Nm,portsClaimedByUnits:()=>Pm,resolveProxyChoice:()=>zm,spliceCaddyBlock:()=>Mm,spliceManagedBlock:()=>iu,sudoersText:()=>jm,unitSlug:()=>Am,unitText:()=>Om});function Am(t,e){let n=r=>r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return`${n(t)}-${n(e)}`.slice(0,60)}function Cm(t){let e=n=>{try{let r=(0,Ut.execFileSync)(n[0],n.slice(1),{encoding:"utf8",timeout:1e4}).trim();return r?xt.default.dirname(r):null}catch{return null}};return t&&t!==Ei.default.userInfo().username?e(["sudo","-u",t,"bash","-lc","command -v node"]):e(["bash","-lc","command -v node"])}function $m(t){let e=xt.default.join(t,"package.json");if(!ye.default.existsSync(e))return{kind:"unknown",reason:"no package.json - only Node apps are supported so far"};let n;try{n=JSON.parse(ye.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 Pm(){let t=new Set;try{for(let e of ye.default.readdirSync("/etc/systemd/system"))if(e.endsWith(".service"))try{let n=ye.default.readFileSync(xt.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 Nm(t){let e=Pm(),n=r=>new Promise(s=>{let i=su.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 Om(t){return`${Ii}
398
398
  [Unit]
399
399
  Description=${t.repoName} ${t.envName} (Allwright-prepared)
400
400
  After=network-online.target
@@ -424,7 +424,7 @@ RestartSec=3
424
424
 
425
425
  [Install]
426
426
  WantedBy=multi-user.target
427
- `}function Om(t){return`${Ei}
427
+ `}function jm(t){return`${Ii}
428
428
  # Exactly two commands, exactly one unit - what a deploy needs and nothing else.
429
429
  ${t.user} ALL=(root) NOPASSWD: /usr/bin/systemctl restart ${t.slug}, /usr/bin/systemctl is-active ${t.slug}
430
430
  `}function Ls(t){return`# BEGIN allwright ${t.slug}
@@ -445,12 +445,12 @@ server {
445
445
  # END allwright ${t.slug}`}function iu(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*$/,"")+`
446
446
 
447
447
  `+n+`
448
- `}function Mm(t,e,n){return iu(t,e,n)}function Dm(t){return t.trim()===""||t.includes("# BEGIN allwright ")||t.includes(Ei)}function zm(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 Lm(t){let e=ye.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,Ut.execFileSync)("id",["-nu",String(e)],{encoding:"utf8",timeout:5e3}).trim()}catch{return Ii.default.userInfo().username}}function _e(t,e){(0,Ut.execFileSync)("sudo",t,{encoding:"utf8",timeout:6e4,...e!==void 0?{input:e}:{},stdio:[e!==void 0?"pipe":"inherit","inherit","inherit"]})}function mS(t){if(t.sudoers){let e=xt.default.join(Ii.default.tmpdir(),`allwright-sudoers-${process.pid}`);ye.default.writeFileSync(e,t.content,{mode:384});try{(0,Ut.execFileSync)("sudo",["visudo","-cf",e],{encoding:"utf8",timeout:3e4}),_e(["install","-m",t.mode,"-o","root","-g","root",e,t.path])}finally{ye.default.rmSync(e,{force:!0})}return}_e(["mkdir","-p",xt.default.dirname(t.path)]),_e(["tee",t.path],t.content),_e(["chmod",t.mode,t.path])}function gS(t){try{return ye.default.readFileSync(t,"utf8").includes(Ei)}catch{return!0}}async function yS(t){if(!ye.default.existsSync(t.dir))throw new Error(`${t.dir} does not exist - clone the repo there first`);if(!ye.default.existsSync(xt.default.join(t.dir,".git")))throw new Error(`${t.dir} is not a git checkout`);let e=$m(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=zm({flag:t.proxy,caddyActive:xi("caddy"),nginxActive:xi("nginx")});if("error"in n)throw new Error(n.error);let r=n.mode,s=Am(t.repoName,t.envName),i=t.publicUrl?bS(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 E=`
448
+ `}function Mm(t,e,n){return iu(t,e,n)}function Dm(t){return t.trim()===""||t.includes("# BEGIN allwright ")||t.includes(Ii)}function zm(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 Lm(t){let e=ye.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,Ut.execFileSync)("id",["-nu",String(e)],{encoding:"utf8",timeout:5e3}).trim()}catch{return Ei.default.userInfo().username}}function _e(t,e){(0,Ut.execFileSync)("sudo",t,{encoding:"utf8",timeout:6e4,...e!==void 0?{input:e}:{},stdio:[e!==void 0?"pipe":"inherit","inherit","inherit"]})}function _S(t){if(t.sudoers){let e=xt.default.join(Ei.default.tmpdir(),`allwright-sudoers-${process.pid}`);ye.default.writeFileSync(e,t.content,{mode:384});try{(0,Ut.execFileSync)("sudo",["visudo","-cf",e],{encoding:"utf8",timeout:3e4}),_e(["install","-m",t.mode,"-o","root","-g","root",e,t.path])}finally{ye.default.rmSync(e,{force:!0})}return}_e(["mkdir","-p",xt.default.dirname(t.path)]),_e(["tee",t.path],t.content),_e(["chmod",t.mode,t.path])}function SS(t){try{return ye.default.readFileSync(t,"utf8").includes(Ii)}catch{return!0}}async function TS(t){if(!ye.default.existsSync(t.dir))throw new Error(`${t.dir} does not exist - clone the repo there first`);if(!ye.default.existsSync(xt.default.join(t.dir,".git")))throw new Error(`${t.dir} is not a git checkout`);let e=$m(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=zm({flag:t.proxy,caddyActive:xi("caddy"),nginxActive:xi("nginx")});if("error"in n)throw new Error(n.error);let r=n.mode,s=Am(t.repoName,t.envName),i=t.publicUrl?xS(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 I=`
449
449
  ${i} {
450
450
  root * ${t.dir}/<your build output>
451
451
  file_server
452
452
  }
453
- `,C=`
453
+ `,$=`
454
454
  server {
455
455
  listen 80;
456
456
  server_name ${i};
@@ -459,27 +459,27 @@ server {
459
459
  try_files $uri $uri/ =404;
460
460
  }
461
461
  }
462
- `;r==="caddy"?(g.info("Add a site block for it to /etc/caddy/Caddyfile yourself, for example:"),g.info(E)):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(E),g.info(C));return}let o=Co(t.dir).filter(E=>!E.startsWith(s)),l=`/etc/systemd/system/${s}.service`;if(o.length&&!ye.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(!gS(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=Lm(t.dir),u=Cm(c);if(!u)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 Nm(t.port),f=[{path:l,content:jm({slug:s,repoName:t.repoName,envName:t.envName,dir:t.dir,user:c,port:p,nodeBin:u}),mode:"644"},{path:`/etc/sudoers.d/allwright-${s}`,content:Om({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 E of f)g.info(`
463
- --- ${E.path} (mode ${E.mode}) ---
464
- ${E.content}`);i&&r==="caddy"&&g.info(`--- appended to /etc/caddy/Caddyfile ---
462
+ `;r==="caddy"?(g.info("Add a site block for it to /etc/caddy/Caddyfile yourself, for example:"),g.info(I)):r==="nginx"?(g.info("Add a server block for it under /etc/nginx yourself, for example:"),g.info($),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(I),g.info($));return}let o=Co(t.dir).filter(I=>!I.startsWith(s)),l=`/etc/systemd/system/${s}.service`;if(o.length&&!ye.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(!SS(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=Lm(t.dir),d=Cm(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 Nm(t.port),f=[{path:l,content:Om({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:jm({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 I of f)g.info(`
463
+ --- ${I.path} (mode ${I.mode}) ---
464
+ ${I.content}`);i&&r==="caddy"&&g.info(`--- appended to /etc/caddy/Caddyfile ---
465
465
  ${Ls({slug:s,hostname:i,port:p})}`),i&&r==="nginx"&&g.info(`--- written to /etc/nginx/{sites-available,conf.d}/allwright-${s}.conf ---
466
466
  `+Ti({slug:s,hostname:i,port:p})),i&&r==="print-both"&&g.info(`--- no proxy is running; one of these, whichever you pick with --proxy ---
467
467
  ${Ls({slug:s,hostname:i,port:p})}
468
468
 
469
- ${Ti({slug:s,hostname:i,port:p})}`);return}for(let E of f)mS(E);let w=`/etc/allwright/env.d/${s}.env`;ye.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]),g.info(`created empty ${w} - add secrets with: sudoedit ${w}`));let v=ye.default.existsSync(xt.default.join(t.dir,".next"))||ye.default.existsSync(xt.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}`),_e(["systemctl","daemon-reload"]),_e(["systemctl","reset-failed",s]),_e(["systemctl","enable","--now",s]),i&&r!=="none"&&(r==="caddy"?vS({slug:s,hostname:i,port:p}):r==="nginx"?kS({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(`
469
+ ${Ti({slug:s,hostname:i,port:p})}`);return}for(let I of f)_S(I);let w=`/etc/allwright/env.d/${s}.env`;ye.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]),g.info(`created empty ${w} - add secrets with: sudoedit ${w}`));let v=ye.default.existsSync(xt.default.join(t.dir,".next"))||ye.default.existsSync(xt.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}`),_e(["systemctl","daemon-reload"]),_e(["systemctl","reset-failed",s]),_e(["systemctl","enable","--now",s]),i&&r!=="none"&&(r==="caddy"?IS({slug:s,hostname:i,port:p}):r==="nginx"?RS({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(`
470
470
  ${Ls({slug:s,hostname:i,port:p})}
471
471
  `),g.info(`
472
472
  ${Ti({slug:s,hostname:i,port:p})}
473
- `)));let k=v?await wS(p,3e4):!1,x=xi(s);g.info(""),g.info(`${x?"\u2713":"\u2717"} service ${s}: ${x?"active":"NOT active - journalctl -u "+s+" -n 40"}`),v&&g.info(`${k?"\u2713":"\u2717"} listening on 127.0.0.1:${p}${k?"":" - 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 bS(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 xi(t){try{return(0,Ut.execFileSync)("systemctl",["is-active",t],{encoding:"utf8",timeout:1e4}).trim()==="active"}catch{return!1}}async function wS(t,e){let n=Date.now()+e;for(;Date.now()<n;){if(await new Promise(s=>{let i=su.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 vS(t){let e="/etc/caddy/Caddyfile";if(!ye.default.existsSync(e)||!xi("caddy")){g.warn(`caddy is not running here (or ${e} does not exist) - add this to your web server yourself:
474
- ${Ls(t)}`);return}let n;try{n=ye.default.readFileSync(e,"utf8")}catch{n=(0,Ut.execFileSync)("sudo",["cat",e],{encoding:"utf8",timeout:1e4})}let r=Mm(n,t.slug,Ls(t));if(r===n){g.info(`caddy already routes ${t.hostname} - unchanged`);return}let s=xt.default.join(Ii.default.tmpdir(),`Caddyfile-allwright-${process.pid}`);ye.default.writeFileSync(s,r,{mode:420});try{(0,Ut.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"]),g.info(`\u2713 caddy: ${t.hostname} \u2192 127.0.0.1:${t.port} (validated, reloaded, backup kept)`)}finally{ye.default.rmSync(s,{force:!0})}}function kS(t){let e=Ti(t),n=`TLS stays yours: nginx does not fetch certificates (Caddy does) - run certbot for ${t.hostname} when DNS points here.`;if(!ye.default.existsSync("/etc/nginx")||!xi("nginx")){g.warn(`nginx is not running here (or /etc/nginx does not exist) - add this server block yourself:
475
- ${e}`),g.info(n);return}let r=ye.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(ye.default.existsSync(s)){try{o=ye.default.readFileSync(s,"utf8")}catch{o=(0,Ut.execFileSync)("sudo",["cat",s],{encoding:"utf8",timeout:1e4})}if(!Dm(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=iu(o??"",t.slug,e).replace(/^\n+/,"");if(o!==null&&l===o){g.info(`nginx already routes ${t.hostname} - unchanged`);return}let c=i?ye.default.existsSync(i):!1;_e(["mkdir","-p",xt.default.dirname(s)]),_e(["tee",s],l),_e(["chmod","644",s]),i&&!c&&_e(["ln","-s",s,i]);try{(0,Ut.execFileSync)("sudo",["nginx","-t"],{encoding:"utf8",timeout:3e4})}catch(u){o!==null?(_e(["tee",s],o),_e(["chmod","644",s])):(i&&!c&&_e(["rm","-f",i]),_e(["rm","-f",s]));let p=u&&typeof u=="object"&&"stderr"in u&&typeof u.stderr=="string"?u.stderr.trim():String(u);throw new Error(`nginx -t rejected the new config - ${s} was ${o!==null?"restored":"removed"} and nginx was NOT reloaded. nginx said:
476
- ${p}`)}_e(["systemctl","reload","nginx"]),g.info(`\u2713 nginx: ${t.hostname} \u2192 127.0.0.1:${t.port} (${s}, validated, reloaded)`),g.info(n)}var Ut,ye,su,Ii,xt,Ei,qm=we(()=>{"use strict";Ut=require("node:child_process"),ye=R(require("node:fs"),1),su=R(require("node:net"),1),Ii=R(require("node:os"),1),xt=R(require("node:path"),1);en();Po();Ei="# managed by allwright env prepare"});var Wm={};fn(Wm,{buildSetupReport:()=>SS,claudeLoggedIn:()=>Gm,repoCurrentBranch:()=>Hm,repoDefaultBranch:()=>Km});function Hm(t){try{let e=(0,Ai.execFileSync)("git",["-C",t,"rev-parse","--abbrev-ref","HEAD"],{encoding:"utf8",timeout:1e4}).trim();return e==="HEAD"?"":e}catch{return""}}function Km(t){let e=(...s)=>{try{return(0,Ai.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 Gm(t=Fm.default.homedir()){if(zn.default.existsSync(Zr.default.join(t,".claude",".credentials.json")))return!0;try{return!!JSON.parse(zn.default.readFileSync(Zr.default.join(t,".claude.json"),"utf8")).oauthAccount}catch{return!1}}async function SS(t,e,n){let r=!1,s="";if(Ri&&Date.now()-Ri.at<6e4)r=Ri.installed,s=Ri.version;else{try{let{stdout:l}=await _S(t.claudeBin,["--version"],{timeout:1e4});r=!0,s=l.trim().slice(0,60)}catch{r=!1}Ri={at:Date.now(),installed:r,version:s}}let i=e.map(l=>{let c=t.repos[l];if(!c)return{repoName:l,path:"",mapped:!1,liveMapped:!!n?.repos?.[l],pathExists:!1,isGit:!1,currentBranch:"",claudeMd:!1,deployMd:!1,testMd:!1,githubToken:!1,githubTokenOwn:!1,defaultBranch:""};let u=zn.default.existsSync(c.path);return{repoName:l,path:c.path,mapped:!0,liveMapped:n?!!n.repos?.[l]:!0,pathExists:u,isGit:u&&zn.default.existsSync(Zr.default.join(c.path,".git")),currentBranch:u?Hm(c.path):"",claudeMd:u&&zn.default.existsSync(Zr.default.join(c.path,"CLAUDE.md")),deployMd:u&&zn.default.existsSync(Zr.default.join(c.path,"DEPLOY.md")),testMd:u&&zn.default.existsSync(Zr.default.join(c.path,"TEST.md")),githubToken:!!ze(t,l),githubTokenOwn:!!c.github?.token,defaultBranch:u?Km(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:Gm()},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 Ai,zn,Fm,Zr,Bm,_S,Ri,Zm=we(()=>{"use strict";Ai=require("node:child_process"),zn=R(require("node:fs"),1),Fm=R(require("node:os"),1),Zr=R(require("node:path"),1),Bm=require("node:util");xr();_S=(0,Bm.promisify)(Ai.execFile);Ri=null});var rt=R(require("node:fs"),1),Ci=R(require("node:os"),1),un=R(require("node:path"),1),hn=require("node:child_process"),Ln=require("node:crypto"),Un=R(require("node:readline/promises"),1);var Su=R(_u(),1),{program:LS,createCommand:US,createArgument:qS,createOption:FS,CommanderError:BS,InvalidArgumentError:HS,InvalidOptionArgumentError:KS,Command:Tu,Argument:GS,Option:WS,Help:ZS}=Su.default;$e();var Ki=require("node:child_process"),Qe=R(require("node:fs"),1),Gi=R(require("node:path"),1);$e();var Cy=new Set(["runner.log","runner.pid"]);function $y(t){return Qe.default.readdirSync(t).filter(e=>!Cy.has(e)&&!/\.bak-\d+$/.test(e)).sort()}function Uu(t){let e=le();if(!Qe.default.existsSync(e))throw new Error(`nothing to export - ${e} does not exist`);let n=$y(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=Gi.default.resolve(t||`ticketpilot-backup-${r}.tgz`);return Qe.default.writeFileSync(s,"",{mode:384}),(0,Ki.execFileSync)("tar",["-czf",s,"-C",e,...n]),Qe.default.chmodSync(s,384),{file:s,entries:n}}function qu(t){let e=Gi.default.resolve(t);if(!Qe.default.existsSync(e))throw new Error(`backup file not found: ${e}`);let n=(0,Ki.execFileSync)("tar",["-tzf",e],{encoding:"utf8"}).split(`
477
- `).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=le(),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,Ki.execFileSync)("tar",["-xzf",e,"-C",r]);for(let i of Qe.default.readdirSync(r)){let o=Gi.default.join(r,i);Qe.default.statSync(o).isFile()&&Qe.default.chmodSync(o,384)}return{restored:n.map(i=>i.replace(/\/$/,"")).sort(),previousDir:s}}var ss=R(require("node:fs"),1),wn=R(require("node:path"),1),Wi=".ticketpilot-attachments",Py=15*1024*1024,Ny=50*1024*1024,Fu=20;function Bu(t,e){let n=wn.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 is(t,e,n,r){if(!e.length)return"";let s=wn.default.join(n,Wi);ss.default.mkdirSync(s,{recursive:!0});let i=new Set,o=[],l=0;for(let c of e){if(o.length>=Fu){r("warn",`attachment cap reached (${Fu} files) - skipping the rest`);break}if(c.size>Py){r("warn",`skipping attachment "${c.filename}" - ${My(c.size)} MB exceeds the 15 MB limit`);continue}if(l+c.size>Ny){r("warn",`attachment size budget reached - skipping "${c.filename}" and the rest`);break}try{let u=await t.downloadAttachment(c.contentUrl),p=Bu(c.filename,i);ss.default.writeFileSync(wn.default.join(s,p),u),l+=u.length,o.push(`- ${Wi}/${p} (${c.mimeType||"unknown type"}, ${Da(u.length)} KB)`),r("info",`Downloaded attachment "${c.filename}" (${Da(u.length)} KB)`)}catch(u){r("warn",`could not download attachment "${c.filename}": ${u instanceof Error?u.message:u}`)}}return o.length?`
473
+ `)));let k=v?await ES(p,3e4):!1,E=xi(s);g.info(""),g.info(`${E?"\u2713":"\u2717"} service ${s}: ${E?"active":"NOT active - journalctl -u "+s+" -n 40"}`),v&&g.info(`${k?"\u2713":"\u2717"} listening on 127.0.0.1:${p}${k?"":" - 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 xS(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 xi(t){try{return(0,Ut.execFileSync)("systemctl",["is-active",t],{encoding:"utf8",timeout:1e4}).trim()==="active"}catch{return!1}}async function ES(t,e){let n=Date.now()+e;for(;Date.now()<n;){if(await new Promise(s=>{let i=su.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 IS(t){let e="/etc/caddy/Caddyfile";if(!ye.default.existsSync(e)||!xi("caddy")){g.warn(`caddy is not running here (or ${e} does not exist) - add this to your web server yourself:
474
+ ${Ls(t)}`);return}let n;try{n=ye.default.readFileSync(e,"utf8")}catch{n=(0,Ut.execFileSync)("sudo",["cat",e],{encoding:"utf8",timeout:1e4})}let r=Mm(n,t.slug,Ls(t));if(r===n){g.info(`caddy already routes ${t.hostname} - unchanged`);return}let s=xt.default.join(Ei.default.tmpdir(),`Caddyfile-allwright-${process.pid}`);ye.default.writeFileSync(s,r,{mode:420});try{(0,Ut.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"]),g.info(`\u2713 caddy: ${t.hostname} \u2192 127.0.0.1:${t.port} (validated, reloaded, backup kept)`)}finally{ye.default.rmSync(s,{force:!0})}}function RS(t){let e=Ti(t),n=`TLS stays yours: nginx does not fetch certificates (Caddy does) - run certbot for ${t.hostname} when DNS points here.`;if(!ye.default.existsSync("/etc/nginx")||!xi("nginx")){g.warn(`nginx is not running here (or /etc/nginx does not exist) - add this server block yourself:
475
+ ${e}`),g.info(n);return}let r=ye.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(ye.default.existsSync(s)){try{o=ye.default.readFileSync(s,"utf8")}catch{o=(0,Ut.execFileSync)("sudo",["cat",s],{encoding:"utf8",timeout:1e4})}if(!Dm(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=iu(o??"",t.slug,e).replace(/^\n+/,"");if(o!==null&&l===o){g.info(`nginx already routes ${t.hostname} - unchanged`);return}let c=i?ye.default.existsSync(i):!1;_e(["mkdir","-p",xt.default.dirname(s)]),_e(["tee",s],l),_e(["chmod","644",s]),i&&!c&&_e(["ln","-s",s,i]);try{(0,Ut.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:
476
+ ${p}`)}_e(["systemctl","reload","nginx"]),g.info(`\u2713 nginx: ${t.hostname} \u2192 127.0.0.1:${t.port} (${s}, validated, reloaded)`),g.info(n)}var Ut,ye,su,Ei,xt,Ii,qm=we(()=>{"use strict";Ut=require("node:child_process"),ye=R(require("node:fs"),1),su=R(require("node:net"),1),Ei=R(require("node:os"),1),xt=R(require("node:path"),1);en();Po();Ii="# managed by allwright env prepare"});var Wm={};fn(Wm,{buildSetupReport:()=>CS,claudeLoggedIn:()=>Gm,repoCurrentBranch:()=>Hm,repoDefaultBranch:()=>Km});function Hm(t){try{let e=(0,Ai.execFileSync)("git",["-C",t,"rev-parse","--abbrev-ref","HEAD"],{encoding:"utf8",timeout:1e4}).trim();return e==="HEAD"?"":e}catch{return""}}function Km(t){let e=(...s)=>{try{return(0,Ai.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 Gm(t=Fm.default.homedir()){if(zn.default.existsSync(Zr.default.join(t,".claude",".credentials.json")))return!0;try{return!!JSON.parse(zn.default.readFileSync(Zr.default.join(t,".claude.json"),"utf8")).oauthAccount}catch{return!1}}async function CS(t,e,n){let r=!1,s="";if(Ri&&Date.now()-Ri.at<6e4)r=Ri.installed,s=Ri.version;else{try{let{stdout:l}=await AS(t.claudeBin,["--version"],{timeout:1e4});r=!0,s=l.trim().slice(0,60)}catch{r=!1}Ri={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=zn.default.existsSync(c.path);return{repoName:l,path:c.path,mapped:!0,liveMapped:n?!!n.repos?.[l]:!0,pathExists:d,isGit:d&&zn.default.existsSync(Zr.default.join(c.path,".git")),currentBranch:d?Hm(c.path):"",claudeMd:d&&zn.default.existsSync(Zr.default.join(c.path,"CLAUDE.md")),deployMd:d&&zn.default.existsSync(Zr.default.join(c.path,"DEPLOY.md")),testMd:d&&zn.default.existsSync(Zr.default.join(c.path,"TEST.md")),githubToken:!!ze(t,l),githubTokenOwn:!!c.github?.token,defaultBranch:d?Km(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:Gm()},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 Ai,zn,Fm,Zr,Bm,AS,Ri,Zm=we(()=>{"use strict";Ai=require("node:child_process"),zn=R(require("node:fs"),1),Fm=R(require("node:os"),1),Zr=R(require("node:path"),1),Bm=require("node:util");xr();AS=(0,Bm.promisify)(Ai.execFile);Ri=null});var rt=R(require("node:fs"),1),Ci=R(require("node:os"),1),un=R(require("node:path"),1),hn=require("node:child_process"),Ln=require("node:crypto"),Un=R(require("node:readline/promises"),1);var Su=R(_u(),1),{program:GS,createCommand:WS,createArgument:ZS,createOption:VS,CommanderError:YS,InvalidArgumentError:JS,InvalidOptionArgumentError:XS,Command:Tu,Argument:QS,Option:e0,Help:t0}=Su.default;$e();var Ki=require("node:child_process"),Qe=R(require("node:fs"),1),Gi=R(require("node:path"),1);$e();var Cy=new Set(["runner.log","runner.pid"]);function $y(t){return Qe.default.readdirSync(t).filter(e=>!Cy.has(e)&&!/\.bak-\d+$/.test(e)).sort()}function Uu(t){let e=le();if(!Qe.default.existsSync(e))throw new Error(`nothing to export - ${e} does not exist`);let n=$y(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=Gi.default.resolve(t||`ticketpilot-backup-${r}.tgz`);return Qe.default.writeFileSync(s,"",{mode:384}),(0,Ki.execFileSync)("tar",["-czf",s,"-C",e,...n]),Qe.default.chmodSync(s,384),{file:s,entries:n}}function qu(t){let e=Gi.default.resolve(t);if(!Qe.default.existsSync(e))throw new Error(`backup file not found: ${e}`);let n=(0,Ki.execFileSync)("tar",["-tzf",e],{encoding:"utf8"}).split(`
477
+ `).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=le(),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,Ki.execFileSync)("tar",["-xzf",e,"-C",r]);for(let i of Qe.default.readdirSync(r)){let o=Gi.default.join(r,i);Qe.default.statSync(o).isFile()&&Qe.default.chmodSync(o,384)}return{restored:n.map(i=>i.replace(/\/$/,"")).sort(),previousDir:s}}var ss=R(require("node:fs"),1),wn=R(require("node:path"),1),Wi=".ticketpilot-attachments",Py=15*1024*1024,Ny=50*1024*1024,Fu=20;function Bu(t,e){let n=wn.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 is(t,e,n,r){if(!e.length)return"";let s=wn.default.join(n,Wi);ss.default.mkdirSync(s,{recursive:!0});let i=new Set,o=[],l=0;for(let c of e){if(o.length>=Fu){r("warn",`attachment cap reached (${Fu} files) - skipping the rest`);break}if(c.size>Py){r("warn",`skipping attachment "${c.filename}" - ${My(c.size)} MB exceeds the 15 MB limit`);continue}if(l+c.size>Ny){r("warn",`attachment size budget reached - skipping "${c.filename}" and the rest`);break}try{let d=await t.downloadAttachment(c.contentUrl),p=Bu(c.filename,i);ss.default.writeFileSync(wn.default.join(s,p),d),l+=d.length,o.push(`- ${Wi}/${p} (${c.mimeType||"unknown type"}, ${Da(d.length)} KB)`),r("info",`Downloaded attachment "${c.filename}" (${Da(d.length)} KB)`)}catch(d){r("warn",`could not download attachment "${c.filename}": ${d instanceof Error?d.message:d}`)}}return o.length?`
478
478
 
479
479
  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:
480
480
  ${o.join(`
481
481
  `)}
482
- Read them with the Read tool when relevant; images (screenshots) can be viewed directly.`:(vn(n),"")}function vn(t){ss.default.rmSync(wn.default.join(t,Wi),{recursive:!0,force:!0})}var jy=4*1024*1024,Oy=16*1024*1024;function Hu(t,e,n){let r=wn.default.join(t,Wi,`chat-${e.replace(/[^\w-]/g,"")}`);if(!n.length)return{section:"",dir:r};ss.default.mkdirSync(r,{recursive:!0});let s=new Set,i=[],o=0,l=wn.default.relative(t,r);for(let u of n){let p=Buffer.from(u.contentBase64,"base64");if(p.length>jy||o+p.length>Oy){i.push(`- (skipped "${u.name}" - over the upload size budget)`);continue}let f=Bu(u.name,s);ss.default.writeFileSync(wn.default.join(r,f),p),o+=p.length,i.push(`- ${l}/${f} (${Da(p.length)} KB)`)}return{section:`
482
+ Read them with the Read tool when relevant; images (screenshots) can be viewed directly.`:(vn(n),"")}function vn(t){ss.default.rmSync(wn.default.join(t,Wi),{recursive:!0,force:!0})}var Oy=4*1024*1024,jy=16*1024*1024;function Hu(t,e,n){let r=wn.default.join(t,Wi,`chat-${e.replace(/[^\w-]/g,"")}`);if(!n.length)return{section:"",dir:r};ss.default.mkdirSync(r,{recursive:!0});let s=new Set,i=[],o=0,l=wn.default.relative(t,r);for(let d of n){let p=Buffer.from(d.contentBase64,"base64");if(p.length>Oy||o+p.length>jy){i.push(`- (skipped "${d.name}" - over the upload size budget)`);continue}let f=Bu(d.name,s);ss.default.writeFileSync(wn.default.join(r,f),p),o+=p.length,i.push(`- ${l}/${f} (${Da(p.length)} KB)`)}return{section:`
483
483
 
484
484
  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:
485
485
  ${i.join(`
@@ -495,12 +495,12 @@ _${$d} - never treated as a trigger._`;await this.request("POST",`/rest/api/3/is
495
495
 
496
496
  `).trim()}function ho(t){let e=t.replace(/\r\n/g,`
497
497
  `).split(`
498
- `),n=[],r=0,s=i=>{let o=[],l=/(\*\*[^*]+\*\*|`[^`]+`)/g,c=0,u;for(;(u=l.exec(i))!==null;){u.index>c&&o.push({type:"text",text:i.slice(c,u.index)});let p=u[0];p.startsWith("**")?o.push({type:"text",text:p.slice(2,-2),marks:[{type:"strong"}]}):o.push({type:"text",text:p.slice(1,-1),marks:[{type:"code"}]}),c=u.index+p.length}return c<i.length&&o.push({type:"text",text:i.slice(c)}),o.length?o:[{type:"text",text:" "}]};for(;r<e.length;){let i=e[r];if(i.trim()===""){r++;continue}let o=i.match(/^```(\w*)\s*$/);if(o){let f=[];for(r++;r<e.length&&!/^```\s*$/.test(e[r]);)f.push(e[r]),r++;r++,n.push({type:"codeBlock",attrs:o[1]?{language:o[1]}:{},content:[{type:"text",text:f.join(`
498
+ `),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(`
499
499
  `)||" "}]});continue}let l=i.match(/^(#{1,6})\s+(.*)$/);if(l){n.push({type:"heading",attrs:{level:l[1].length},content:s(l[2])}),r++;continue}if(i.match(/^\s*[-*]\s+(.*)$/)){let f=[];for(;r<e.length;){let w=e[r].match(/^\s*[-*]\s+(.*)$/);if(!w)break;f.push({type:"listItem",content:[{type:"paragraph",content:s(w[1])}]}),r++}n.push({type:"bulletList",content:f});continue}if(i.match(/^\s*\d+[.)]\s+(.*)$/)){let f=[];for(;r<e.length;){let w=e[r].match(/^\s*\d+[.)]\s+(.*)$/);if(!w)break;f.push({type:"listItem",content:[{type:"paragraph",content:s(w[1])}]}),r++}n.push({type:"orderedList",content:f});continue}let p=[i];for(r++;r<e.length&&e[r].trim()!==""&&!/^(#{1,6}\s|```|\s*[-*]\s|\s*\d+[.)]\s)/.test(e[r]);)p.push(e[r]),r++;n.push({type:"paragraph",content:s(p.join(" "))})}return{type:"doc",version:1,content:n}}function Pd(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:
500
500
 
501
501
  allwright jira user-add ${s}
502
502
 
503
- It prompts for your Atlassian email and an API token (create one at id.atlassian.com -> Security -> API tokens). Takes effect immediately - then just retry this action.`}}function Nd(t){let e=[t.jiraUrl,t.jiraEmail,t.jiraToken].filter(n=>!!n?.trim());if(t.jira===!1){if(e.length)throw new Error("--no-jira and --jira-url/--jira-email/--jira-token contradict each other - pass one or the other, never both.");return"skip"}return e.length===3?"flags":e.length?"prompt":"offer-skip"}function jd(t){return["s","skip","n","no","later"].includes(t.trim().toLowerCase())}xr();var yw=/\btickets?[ \t-]?#?(\d{1,2})\b/gi;function Md(t,e){let n=!1;return{text:t.replace(yw,(s,i)=>{let o=Number(i);return o<1||o>e.length?s:(n=!0,e[o-1])}),changed:n}}var $n=require("node:child_process"),Pn=R(require("node:fs"),1),fo=R(require("node:os"),1),bs=R(require("node:path"),1),zd=R(xe(),1);var ys="allwright",Dd=`/etc/systemd/system/${ys}.service`,mo="ticketpilot-runner";function ml(){let t=process.env.SUDO_USER&&process.env.SUDO_USER!=="root"?process.env.SUDO_USER:"",e=t||fo.default.userInfo().username,n=t?bs.default.join("/home",t):fo.default.homedir();return{nodePath:process.execPath,scriptPath:Pn.default.realpathSync(process.argv[1]),user:e,home:n}}function gl(t){let e=bs.default.dirname(t.nodePath);return`[Unit]
503
+ It prompts for your Atlassian email and an API token (create one at id.atlassian.com -> Security -> API tokens). Takes effect immediately - then just retry this action.`}}function Nd(t){let e=[t.jiraUrl,t.jiraEmail,t.jiraToken].filter(n=>!!n?.trim());if(t.jira===!1){if(e.length)throw new Error("--no-jira and --jira-url/--jira-email/--jira-token contradict each other - pass one or the other, never both.");return"skip"}return e.length===3?"flags":e.length?"prompt":"offer-skip"}function Od(t){return["s","skip","n","no","later"].includes(t.trim().toLowerCase())}xr();var yw=/\btickets?[ \t-]?#?(\d{1,2})\b/gi;function Md(t,e){let n=!1;return{text:t.replace(yw,(s,i)=>{let o=Number(i);return o<1||o>e.length?s:(n=!0,e[o-1])}),changed:n}}var $n=require("node:child_process"),Pn=R(require("node:fs"),1),fo=R(require("node:os"),1),bs=R(require("node:path"),1),zd=R(xe(),1);var ys="allwright",Dd=`/etc/systemd/system/${ys}.service`,mo="ticketpilot-runner";function ml(){let t=process.env.SUDO_USER&&process.env.SUDO_USER!=="root"?process.env.SUDO_USER:"",e=t||fo.default.userInfo().username,n=t?bs.default.join("/home",t):fo.default.homedir();return{nodePath:process.execPath,scriptPath:Pn.default.realpathSync(process.argv[1]),user:e,home:n}}function gl(t){let e=bs.default.dirname(t.nodePath);return`[Unit]
504
504
  Description=Allwright runner
505
505
  After=network-online.target
506
506
 
@@ -554,7 +554,7 @@ Fold what these results show - failures, flaky exits, suspiciously green suites
554
554
 
555
555
  ### ${r.crawlResults}
556
556
 
557
- This transcript is your PRIMARY evidence. A URL with issues becomes a finding; the repo is there to trace WHY. Do not invent problems the crawl does not show, and state plainly what a JS-free crawl cannot see.`:"",u=r.detailLevel==="simple"?`
557
+ This transcript is your PRIMARY evidence. A URL with issues becomes a finding; the repo is there to trace WHY. Do not invent problems the crawl does not show, and state plainly what a JS-free crawl cannot see.`:"",d=r.detailLevel==="simple"?`
558
558
 
559
559
  ### WRITING STYLE - plain language
560
560
 
@@ -573,8 +573,8 @@ Explore the repository first - entry points, routes, storage, tests - then audit
573
573
  "evidence": [{"file": "<repo-relative path>", "line": <number, omit if n/a>, "note": "<what is there>"}],
574
574
  "fix": "<2-4 sentences: concrete fix, specific to this code>"}]}
575
575
  \`\`\`
576
- Rules: every finding needs at least one evidence file you actually read - findings without real evidence will be DELETED from your report. Max 25 findings, worst first. An empty findings list with an honest summary is a valid, good answer.`+u}function Wd(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=Tw(l),u=c?yo.AuditFinding.safeParse(c):null;if(!u?.success){i++;continue}let p=u.data.id;for(;o.has(p);)p=`${p}-2`;o.add(p),s.push({...u.data,id:p})}return{summary:typeof r.summary=="string"?r.summary.trim().slice(0,2e3):"",findings:s,dropped:i}}function Tw(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:"",...Kd(i.line)?{line:Kd(i.line)}:{},note:typeof i.note=="string"?i.note:""})).filter(i=>i.file):[],s=typeof e.ruleId=="string"?e.ruleId.trim().toUpperCase():"";return{id:xw(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:yo.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 Kd(t){let e=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):NaN;return Number.isInteger(e)&&e>0?e:void 0}function xw(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"finding"}function Iw(t){try{let e=kl.default.readFileSync(t,"utf8");return e?e.split(`
577
- `).length:0}catch{return null}}function Zd(t,e){let n=go.default.resolve(t),r=[],s=[],i=0;for(let o of e){let l=[];for(let c of o.evidence){let u=c.file.trim().replace(/^\.\//,""),p=go.default.resolve(n,u);if(p!==n&&!p.startsWith(n+go.default.sep))continue;let f;try{f=kl.default.statSync(p)}catch{continue}if(f.isFile()){if(c.line!==void 0){let w=Iw(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 Qs=R(require("node:fs"),1),_l=R(require("node:path"),1),Vd=R(xe(),1);$e();var Ew=20;function Yd(){return _l.default.join(le(),"audits.json")}function ws(){try{return{byProject:JSON.parse(Qs.default.readFileSync(Yd(),"utf8")).byProject??{}}}catch{return{byProject:{}}}}function Jd(t){let e=Yd();Qs.default.mkdirSync(_l.default.dirname(e),{recursive:!0,mode:448});let n=e+".tmp";Qs.default.writeFileSync(n,JSON.stringify(t,null,2),{mode:384}),Qs.default.renameSync(n,e)}function Xd(t,e){let n=ws(),r=n.byProject[t]??[];r.unshift(Vd.AuditRecord.parse(e)),n.byProject[t]=r.slice(0,Ew),Jd(n)}function Qd(t){return(ws().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 eh(t,e){let n=ws(),r=e?Date.parse(e):NaN,s={};for(let i of t){let o=(n.byProject[i]??[]).filter(c=>!Number.isFinite(r)||Date.parse(c.createdAt)>=r);if(!o.length)continue;let l={audits:o.length,findings:0,valid:0,falsePositive:0,wontFix:0,unreviewed:0};for(let c of o){l.findings+=c.findings.length;for(let u of c.findings){let p=c.verdicts[u.id]?.verdict;p==="valid"?l.valid++:p==="false-positive"?l.falsePositive++:p==="wont-fix"?l.wontFix++:l.unreviewed++}}s[i]=l}return s}function Sl(t,e,n){let r=ws(),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 Jd(r),i}function th(t,e){return(ws().byProject[t]??[]).find(s=>s.role===e&&(s.scope?.kind??"repo")==="repo")?.createdAt??null}function Tl(t,e){return(ws().byProject[t]??[]).find(n=>n.id===e)??null}Nt();var Fe=R(require("node:fs"),1),jt=R(require("node:path"),1),oh=R(xe(),1);var Le=R(require("node:fs"),1),kt=R(require("node:path"),1),Rw=25e4,Aw=2e5,nh="/.ticketpilot/memory/";function Cw(t){let e=kt.default.join(t,".git"),n;try{n=Le.default.statSync(e)}catch{return null}if(n.isDirectory())return kt.default.join(e,"info");let r=/^gitdir:\s*(.+)$/m.exec(Le.default.readFileSync(e,"utf8"));if(!r?.[1])return null;let s=kt.default.resolve(t,r[1].trim());try{let i=Le.default.readFileSync(kt.default.join(s,"commondir"),"utf8").trim();return kt.default.join(kt.default.resolve(s,i),"info")}catch{return kt.default.join(s,"info")}}function $w(t){try{let e=Cw(t);if(!e)return;let n=kt.default.join(e,"exclude"),r="";try{r=Le.default.readFileSync(n,"utf8")}catch{}if(r.split(`
576
+ 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 Wd(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=Tw(l),d=c?yo.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 Tw(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:"",...Kd(i.line)?{line:Kd(i.line)}:{},note:typeof i.note=="string"?i.note:""})).filter(i=>i.file):[],s=typeof e.ruleId=="string"?e.ruleId.trim().toUpperCase():"";return{id:xw(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:yo.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 Kd(t){let e=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):NaN;return Number.isInteger(e)&&e>0?e:void 0}function xw(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"finding"}function Ew(t){try{let e=kl.default.readFileSync(t,"utf8");return e?e.split(`
577
+ `).length:0}catch{return null}}function Zd(t,e){let n=go.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=go.default.resolve(n,d);if(p!==n&&!p.startsWith(n+go.default.sep))continue;let f;try{f=kl.default.statSync(p)}catch{continue}if(f.isFile()){if(c.line!==void 0){let w=Ew(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 Qs=R(require("node:fs"),1),_l=R(require("node:path"),1),Vd=R(xe(),1);$e();var Iw=20;function Yd(){return _l.default.join(le(),"audits.json")}function ws(){try{return{byProject:JSON.parse(Qs.default.readFileSync(Yd(),"utf8")).byProject??{}}}catch{return{byProject:{}}}}function Jd(t){let e=Yd();Qs.default.mkdirSync(_l.default.dirname(e),{recursive:!0,mode:448});let n=e+".tmp";Qs.default.writeFileSync(n,JSON.stringify(t,null,2),{mode:384}),Qs.default.renameSync(n,e)}function Xd(t,e){let n=ws(),r=n.byProject[t]??[];r.unshift(Vd.AuditRecord.parse(e)),n.byProject[t]=r.slice(0,Iw),Jd(n)}function Qd(t){return(ws().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 eh(t,e){let n=ws(),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 Sl(t,e,n){let r=ws(),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 Jd(r),i}function th(t,e){return(ws().byProject[t]??[]).find(s=>s.role===e&&(s.scope?.kind??"repo")==="repo")?.createdAt??null}function Tl(t,e){return(ws().byProject[t]??[]).find(n=>n.id===e)??null}Nt();var Fe=R(require("node:fs"),1),Ot=R(require("node:path"),1),oh=R(xe(),1);var Le=R(require("node:fs"),1),kt=R(require("node:path"),1),Rw=25e4,Aw=2e5,nh="/.ticketpilot/memory/";function Cw(t){let e=kt.default.join(t,".git"),n;try{n=Le.default.statSync(e)}catch{return null}if(n.isDirectory())return kt.default.join(e,"info");let r=/^gitdir:\s*(.+)$/m.exec(Le.default.readFileSync(e,"utf8"));if(!r?.[1])return null;let s=kt.default.resolve(t,r[1].trim());try{let i=Le.default.readFileSync(kt.default.join(s,"commondir"),"utf8").trim();return kt.default.join(kt.default.resolve(s,i),"info")}catch{return kt.default.join(s,"info")}}function $w(t){try{let e=Cw(t);if(!e)return;let n=kt.default.join(e,"exclude"),r="";try{r=Le.default.readFileSync(n,"utf8")}catch{}if(r.split(`
578
578
  `).some(i=>i.trim()===nh))return;Le.default.mkdirSync(e,{recursive:!0});let s=r&&!r.endsWith(`
579
579
  `)?`
580
580
  `:"";Le.default.appendFileSync(n,`${s}# Allwright runner scratch - see .ticketpilot/memory/
@@ -634,7 +634,7 @@ Every rule has a stable id. Findings must cite the id they violate.
634
634
  - **SEC-042** TLS/redirect handling that downgrades to http.
635
635
 
636
636
  Prioritize by real exploitability in THIS codebase, not by rule order.
637
- `,jw=`# Test gaps - what to check in any repo
637
+ `,Ow=`# Test gaps - what to check in any repo
638
638
 
639
639
  Every rule has a stable id. Findings must cite the id they violate.
640
640
 
@@ -664,7 +664,7 @@ Every rule has a stable id. Findings must cite the id they violate.
664
664
  flaky suspects.
665
665
 
666
666
  Report the GAP and why it is risky here, not generic coverage philosophy.
667
- `,Ow=`# GDPR readiness - data-protection audit for repos with EU exposure
667
+ `,jw=`# GDPR readiness - data-protection audit for repos with EU exposure
668
668
 
669
669
  FIRST decide exposure: if this product clearly has no EU users, no personal
670
670
  data, or is a purely static/internal tool, say so in ONE summary sentence and
@@ -747,7 +747,7 @@ deviations.
747
747
 
748
748
  Summarize with an overall verdict: is this repository HEALTHY for its
749
749
  purpose, and what are the 2-3 structural moves with the best payoff?
750
- `,ih={security:[{name:"baseline.md",content:Nw},{name:"gdpr.md",content:Ow}],testing:[{name:"test-gaps.md",content:jw}],architecture:[{name:"architecture-health.md",content:Mw}],functional:[],implement:[],compose:[]},Dw=["You are auditing code you can READ but never run or change.","You are auditing test coverage by READING code and tests","\\`area\\`"];function Il(t){return jt.default.join(le(),"knowledge",t)}function ah(t,e){return jt.default.join(t,".ticketpilot","knowledge",`${e}.md`)}function El(t,e){return jt.default.join(t,".ticketpilot","lessons",`${e}.md`)}function lh(t,e){let n=[],r=Il(t),s=[];if(Fe.default.existsSync(r)){for(let c of Fe.default.readdirSync(r)){if(!c.endsWith(".md"))continue;let u=jt.default.join(r,c),p=Fe.default.readFileSync(u,"utf8");if(Dw.some(f=>p.includes(f))&&ih[t].map(w=>w.name).includes(c)&&!p.includes("SEC-0")&&!p.includes("TEST-0")&&!p.includes("GDPR-0")){Fe.default.rmSync(u);continue}s.push(c)}s.sort()}let i=new Set(s);for(let c of ih[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:Fe.default.readFileSync(jt.default.join(r,c),"utf8").slice(0,3e4),editable:!0});let o=ah(e,t);Fe.default.existsSync(o)&&n.push({level:"project",source:"pack",name:`${t}.md`,content:Fe.default.readFileSync(o,"utf8").slice(0,3e4),editable:!0});let l=El(e,t);return Fe.default.existsSync(l)&&n.push({level:"project",source:"lessons",name:`${t}.md`,content:Fe.default.readFileSync(l,"utf8").slice(0,2e4),editable:!0}),n}function vs(t,e){let n=lh(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 Rl(t,e,n,r="project"){let s=r==="org"?jt.default.join(Il(e),"org-lessons.md"):El(t,e);Fe.default.mkdirSync(jt.default.dirname(s),{recursive:!0});let i=Fe.default.existsSync(s)?"":`# ${e} lessons (${r} level)
750
+ `,ih={security:[{name:"baseline.md",content:Nw},{name:"gdpr.md",content:jw}],testing:[{name:"test-gaps.md",content:Ow}],architecture:[{name:"architecture-health.md",content:Mw}],functional:[],implement:[],compose:[]},Dw=["You are auditing code you can READ but never run or change.","You are auditing test coverage by READING code and tests","\\`area\\`"];function El(t){return Ot.default.join(le(),"knowledge",t)}function ah(t,e){return Ot.default.join(t,".ticketpilot","knowledge",`${e}.md`)}function Il(t,e){return Ot.default.join(t,".ticketpilot","lessons",`${e}.md`)}function lh(t,e){let n=[],r=El(t),s=[];if(Fe.default.existsSync(r)){for(let c of Fe.default.readdirSync(r)){if(!c.endsWith(".md"))continue;let d=Ot.default.join(r,c),p=Fe.default.readFileSync(d,"utf8");if(Dw.some(f=>p.includes(f))&&ih[t].map(w=>w.name).includes(c)&&!p.includes("SEC-0")&&!p.includes("TEST-0")&&!p.includes("GDPR-0")){Fe.default.rmSync(d);continue}s.push(c)}s.sort()}let i=new Set(s);for(let c of ih[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:Fe.default.readFileSync(Ot.default.join(r,c),"utf8").slice(0,3e4),editable:!0});let o=ah(e,t);Fe.default.existsSync(o)&&n.push({level:"project",source:"pack",name:`${t}.md`,content:Fe.default.readFileSync(o,"utf8").slice(0,3e4),editable:!0});let l=Il(e,t);return Fe.default.existsSync(l)&&n.push({level:"project",source:"lessons",name:`${t}.md`,content:Fe.default.readFileSync(l,"utf8").slice(0,2e4),editable:!0}),n}function vs(t,e){let n=lh(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 Rl(t,e,n,r="project"){let s=r==="org"?Ot.default.join(El(e),"org-lessons.md"):Il(t,e);Fe.default.mkdirSync(Ot.default.dirname(s),{recursive:!0});let i=Fe.default.existsSync(s)?"":`# ${e} lessons (${r} level)
751
751
 
752
752
  Human-confirmed corrections and rules. `+(e==="implement"?`Every implement run on this repo reads this BEFORE starting work.
753
753
 
@@ -758,45 +758,45 @@ Human-confirmed corrections and rules. `+(e==="implement"?`Every implement run o
758
758
  `)}function ch(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}
759
759
  Finding \`${t.id}\` [${t.severity}] was marked **${e}**`+(r?` by ${r}`:"")+`.${n?` Reason: ${n}`:""}
760
760
  `+(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 uh(t,e){return`## ${new Date().toISOString().slice(0,10)} \xB7 taught${e?` by ${e}`:""}
761
- ${t.trim()}`}function dh(t){let e=[];for(let r of oh.KnowledgeRole.options)for(let s of lh(r,t))e.push({role:r,...s});let n=sh(t);return n&&e.push({role:"implement",level:"project",source:"memory",name:"incidents.md",content:n.slice(-3e4),editable:!1}),e}function hh(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"?jt.default.join(Il(e),s):r==="lessons"?El(t,e):ah(t,e);Fe.default.mkdirSync(jt.default.dirname(o),{recursive:!0}),Fe.default.writeFileSync(o,i,{mode:n==="org"?384:420})}en();var ph=require("node:child_process"),fh=R(require("node:fs"),1),mh=R(require("node:path"),1);function ks(t){for(let e of["TEST.md","TESTING.md","docs/TEST.md"]){let n=mh.default.join(t,e);if(fh.default.existsSync(n))return n}return null}var zw=/(^|\n)\s*(if|for|while|case|until)\s|\{\s*$|\)\s*\{|<<[-~]?\s*['"]?\w+|\\\s*$/;function _s(t){let e=[];for(let n of t.matchAll(/```(?:bash|sh|shell)?\s*\n([\s\S]*?)```/g)){let r=n[1],s=r.split(`
762
- `).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#"));if(s.length){if(zw.test(r)){e.push(r.trim());continue}e.push(...s)}}return e.slice(0,10)}async function Ir(t,e,n={}){let r=[],s=n.perCommandTimeoutMs??6e5;for(let i of e){n.onProgress?.(`running: ${i}`);let o=Date.now(),l=await new Promise(c=>{let u=(0,ph.spawn)("bash",["-lc",i],{cwd:t,env:{...process.env,CI:"1",FORCE_COLOR:"0"}}),p="",f=v=>{p+=v.toString(),p.length>2e5&&(p=p.slice(-1e5))};u.stdout.on("data",f),u.stderr.on("data",f);let w=setTimeout(()=>{u.kill("SIGKILL"),p+=`
763
- [killed: timed out]`},s);u.on("close",v=>{clearTimeout(w),c({command:i,exitCode:v??-1,durationMs:Date.now()-o,tail:p.slice(-4e3)})}),u.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}async function Ss(t){let{packs:e,lessons:n}=vs(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:k}=await Promise.resolve().then(()=>(wh(),bh));try{r=k(await v(t.baseUrl.trim()))}catch(x){return{ok:!1,error:`could not crawl ${t.baseUrl}: ${x instanceof Error?x.message:"unreachable"}`}}}let s="";if(t.scope.kind==="ticket"&&t.scope.ref){let v=t.scope.ref,k="";try{let E=await t.jira.getIssue(v);k=`Ticket ${v}: ${E.summary}
761
+ ${t.trim()}`}function dh(t){let e=[];for(let r of oh.KnowledgeRole.options)for(let s of lh(r,t))e.push({role:r,...s});let n=sh(t);return n&&e.push({role:"implement",level:"project",source:"memory",name:"incidents.md",content:n.slice(-3e4),editable:!1}),e}function hh(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"?Ot.default.join(El(e),s):r==="lessons"?Il(t,e):ah(t,e);Fe.default.mkdirSync(Ot.default.dirname(o),{recursive:!0}),Fe.default.writeFileSync(o,i,{mode:n==="org"?384:420})}en();var ph=require("node:child_process"),fh=R(require("node:fs"),1),mh=R(require("node:path"),1);function ks(t){for(let e of["TEST.md","TESTING.md","docs/TEST.md"]){let n=mh.default.join(t,e);if(fh.default.existsSync(n))return n}return null}var zw=/(^|\n)\s*(if|for|while|case|until)\s|\{\s*$|\)\s*\{|<<[-~]?\s*['"]?\w+|\\\s*$/;function _s(t){let e=[];for(let n of t.matchAll(/```(?:bash|sh|shell)?\s*\n([\s\S]*?)```/g)){let r=n[1],s=r.split(`
762
+ `).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#"));if(s.length){if(zw.test(r)){e.push(r.trim());continue}e.push(...s)}}return e.slice(0,10)}async function Er(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,ph.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+=`
763
+ [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}async function Ss(t){let{packs:e,lessons:n}=vs(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:k}=await Promise.resolve().then(()=>(wh(),bh));try{r=k(await v(t.baseUrl.trim()))}catch(E){return{ok:!1,error:`could not crawl ${t.baseUrl}: ${E instanceof Error?E.message:"unreachable"}`}}}let s="";if(t.scope.kind==="ticket"&&t.scope.ref){let v=t.scope.ref,k="";try{let I=await t.jira.getIssue(v);k=`Ticket ${v}: ${I.summary}
764
764
 
765
- ${E.description}`.slice(0,4e3)}catch{k=`Ticket ${v} (could not fetch its text from Jira).`}let x=await rl(t.repoPath,v).catch(()=>null);if(x){let{base:E,stat:C,diff:V}=await co(t.repoPath,x).catch(()=>({base:"",stat:"",diff:""}));s=`${k}
765
+ ${I.description}`.slice(0,4e3)}catch{k=`Ticket ${v} (could not fetch its text from Jira).`}let E=await rl(t.repoPath,v).catch(()=>null);if(E){let{base:I,stat:$,diff:V}=await co(t.repoPath,E).catch(()=>({base:"",stat:"",diff:""}));s=`${k}
766
766
 
767
- Its implementation branch \`${x}\` vs \`${E}\`:
767
+ Its implementation branch \`${E}\` vs \`${I}\`:
768
768
  \`\`\`
769
- ${C}\`\`\`
769
+ ${$}\`\`\`
770
770
  \`\`\`diff
771
771
  ${V}
772
772
  \`\`\``}else s=`${k}
773
773
 
774
- 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:k,diff:x}=await co(t.repoPath,t.scope.ref);s=`The diff of \`${t.scope.ref}\` vs \`${v}\`:
774
+ 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:k,diff:E}=await co(t.repoPath,t.scope.ref);s=`The diff of \`${t.scope.ref}\` vs \`${v}\`:
775
775
  \`\`\`
776
776
  ${k}\`\`\`
777
777
  \`\`\`diff
778
- ${x}
779
- \`\`\``}let i,o;if(t.role==="testing"){let v=ks(t.repoPath),k=v?_s(vh.default.readFileSync(v,"utf8")):[];k.length&&(g.info(`Audit (testing): executing ${k.length} TEST.md command(s)`),o=await Ir(t.repoPath,k,{onProgress:x=>g.info(`[test-run] ${x}`)}),i=o.map(x=>`$ ${x.command}
780
- (exit ${x.exitCode}, ${Math.round(x.durationMs/1e3)}s)
781
- ${x.tail.slice(-2e3)}`).join(`
778
+ ${E}
779
+ \`\`\``}let i,o;if(t.role==="testing"){let v=ks(t.repoPath),k=v?_s(vh.default.readFileSync(v,"utf8")):[];k.length&&(g.info(`Audit (testing): executing ${k.length} TEST.md command(s)`),o=await Er(t.repoPath,k,{onProgress:E=>g.info(`[test-run] ${E}`)}),i=o.map(E=>`$ ${E.command}
780
+ (exit ${E.exitCode}, ${Math.round(E.durationMs/1e3)}s)
781
+ ${E.tail.slice(-2e3)}`).join(`
782
782
 
783
783
  ---
784
784
 
785
- `))}let l=t.model||t.agent.adapter.deepModel,c=t.detailLevel??"technical",u=await t.agent.adapter.run({repoPath:t.repoPath,prompt:Gd(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,Cl.randomUUID)(),model:l,onLog:(v,k)=>{v==="agent"&&g.info(`[audit:${t.role}] ${k.slice(0,160)}`)}}),p=Wd(u.resultText);if("error"in p)return{ok:!1,error:p.error};let f=Zd(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,Cl.randomUUID)(),role:t.role,createdAt:new Date().toISOString(),model:u.model||l,summary:p.summary,packNames:e.map(v=>v.name),findings:f.findings,costUsd:u.costUsd??0,ticketed:{},verdicts:{},lessonsWritten:[],scope:t.scope,detailLevel:c,...o?{testRun:o}:{}};return Xd(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 On=R(xe(),1);$e();var Hl=R(require("node:fs"),1),Ro=R(require("node:path"),1),Ao=require("node:crypto"),Se=R(xe(),1);$e();var Er=R(xe(),1);var $l=R(require("node:fs"),1),kh=R(require("node:os"),1),wo=R(require("node:path"),1),_h=require("node:child_process"),Sh=R(require("node:readline"),1),Th=R(xe(),1);function bo(t){return`
785
+ `))}let l=t.model||t.agent.adapter.deepModel,c=t.detailLevel??"technical",d=await t.agent.adapter.run({repoPath:t.repoPath,prompt:Gd(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,Cl.randomUUID)(),model:l,onLog:(v,k)=>{v==="agent"&&g.info(`[audit:${t.role}] ${k.slice(0,160)}`)}}),p=Wd(d.resultText);if("error"in p)return{ok:!1,error:p.error};let f=Zd(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,Cl.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 Xd(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 jn=R(xe(),1);$e();var Hl=R(require("node:fs"),1),Ro=R(require("node:path"),1),Ao=require("node:crypto"),Se=R(xe(),1);$e();var Ir=R(xe(),1);var $l=R(require("node:fs"),1),kh=R(require("node:os"),1),wo=R(require("node:path"),1),_h=require("node:child_process"),Sh=R(require("node:readline"),1),Th=R(xe(),1);function bo(t){return`
786
786
 
787
787
  YOUR CAPABILITIES IN THIS RUN - state them accurately, never guess:
788
788
  - 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.
789
789
  `+(t==="edit_no_shell"?`- You CAN read files and CREATE or EDIT files inside this working directory.
790
790
  `:`- You can ONLY read: Read, Glob and Grep inside this working directory. You cannot create or change a single file.
791
- `)+'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 qw=4e3,Fw={read_only:["Read(./**)","Glob(./**)","Grep(./**)"],edit_no_shell:["Read(./**)","Glob(./**)","Grep(./**)","Edit(./**)","Write(./**)"]};function Bw(t){if(process.env.ANTHROPIC_API_KEY)return"API key";let e=t??wo.default.join(kh.default.homedir(),".claude");try{if($l.default.existsSync(wo.default.join(e,".credentials.json"))||$l.default.existsSync(wo.default.join(e,"credentials.json")))return"subscription"}catch{}return"unknown"}function Hw(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 Kw(t){let e=["-p","--output-format","stream-json","--verbose","--allowedTools",Fw[t.mode].join(","),"--max-turns",String(t.maxTurns??60),...t.model?["--model",t.model]:[],...t.resume?["--resume",t.sessionId]:["--session-id",t.sessionId]],n=Bw(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,_h.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,u=0,p=0,f=0,w=()=>{if(!t.onUsage)return;let Y=Date.now();Y-f<qw||(f=Y,t.onUsage({inputTokens:c,outputTokens:u,cacheReadTokens:p,turns:o}))},v=!1,k=()=>{v||(v=!0,clearTimeout(E),t.signal?.removeEventListener("abort",x),r(i))},x=()=>{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",x,{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+bo(t.mode)),s.stdin.end(),Sh.default.createInterface({input:s.stdout}).on("line",Y=>{if(!Y.trim())return;let b;try{b=JSON.parse(Y)}catch{t.onLog("agent",Y.slice(0,1e3));return}if(b.type==="system"&&b.subtype==="init")i.model=typeof b.model=="string"?b.model:void 0,t.onLog("info",`Claude Code session started (model: ${b.model??"default"})`);else if(b.type==="assistant"){o+=1,l=b.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($){c+=Number($.input_tokens??0)+Number($.cache_creation_input_tokens??0);let D=JSON.stringify(b.message?.content??[]).length;u+=Math.max(Number($.output_tokens??0),Math.round(D/4)),p+=Number($.cache_read_input_tokens??0),w()}for(let D of b.message?.content??[])if(D.type==="text"&&D.text?.trim())t.onLog("agent",D.text.trim().slice(0,4e3));else if(D.type==="tool_use"){let j=D.input??{},B=["file_path","path","pattern","command","description","url"].map(m=>typeof j[m]=="string"?`${m}=${j[m]}`:null).filter(Boolean).join(" "),d=JSON.stringify(j).slice(0,400);if(t.onLog("info",`tool ${D.name} ${B?`${B} `:""}${d}`),t.onTool){let m=Hw(String(D.name??""),j,t.repoPath);t.onTool(m.verb,m.target.slice(0,200))}}}else b.type==="result"&&(i.costUsd=Number(b.total_cost_usd??0),i.inputTokens=Number(b.usage?.input_tokens??0)+Number(b.usage?.cache_creation_input_tokens??0),i.outputTokens=Number(b.usage?.output_tokens??0),c=Math.max(i.inputTokens,c),u=Math.max(i.outputTokens,u),i.inputTokens=c,i.outputTokens=u,p=Number(b.usage?.cache_read_input_tokens??p),i.cacheReadTokens=p,t.onUsage&&(t.onUsage({inputTokens:c,outputTokens:u,cacheReadTokens:p,costUsd:i.costUsd,turns:o}),f=Date.now()),b.subtype==="success"&&!b.is_error?(i.ok=!0,i.resultText=String(b.result??""),i.outputTruncated=l):b.subtype==="error_max_turns"?(i.turnLimitHit=!0,i.error=`hit the ${t.maxTurns??60}-turn limit before finishing`):i.error||(i.error=b.subtype==="error_during_execution"?"the agent stopped mid-work before it could finish - the session was interrupted or hit an internal limit":String(b.result??b.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",Y=>{V=(V+Y.toString()).slice(-2e3)}),s.on("error",Y=>{i.error=`failed to start ${t.bin}: ${Y.message}`,t.onLog("error",i.error),k()}),s.on("close",Y=>{!i.ok&&!i.error&&(i.error=i.timedOut?i.error:`claude exited with code ${Y}${V?`: ${V.slice(-500)}`:""}`),k()})})}var vo={id:"claude-code",displayName:"Claude Code",fastModel:"claude-sonnet-5",deepModel:"claude-fable-5",capabilities:Th.REGISTERED_AGENTS.find(t=>t.id==="claude-code").capabilities,run:Kw};var xh=require("node:child_process"),Ih=R(require("node:readline"),1),Eh=R(xe(),1);async function Gw(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,xh.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+bo(t.mode)),r.stdin.end(),Ih.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,k=v?.type??w.type,x=v?.text??v?.message??"";k==="agent_message"&&typeof x=="string"&&x.trim()?(i=x,t.onLog("agent",x.trim().slice(0,4e3))):k==="command_execution"||k==="exec_command_begin"?t.onLog("info",`tool ${String(v?.command??"").slice(0,300)}`):k==="error"&&typeof x=="string"&&x&&t.onLog("error",x.slice(0,1e3))});let p="";r.stderr.on("data",f=>{p=(p+f.toString()).slice(-2e3)}),r.on("error",f=>{s.error=`failed to start ${t.bin}: ${f.message} - is the Codex CLI installed and logged in?`,t.onLog("error",s.error),l()}),r.on("close",f=>{f===0&&i.trim()?(s.ok=!0,s.resultText=i):s.error||(s.error=`codex exited with code ${f}`+(i?"":" and produced no answer")+(p?`: ${p.slice(-500)}`:"")),l()})})}var Pl={id:"codex",fastModel:"",deepModel:"",displayName:"OpenAI Codex CLI (experimental)",capabilities:Eh.REGISTERED_AGENTS.find(t=>t.id==="codex").capabilities,run:Gw};var Ww={[vo.id]:vo,[Pl.id]:Pl};function Ye(t){return Ww[t||Er.DEFAULT_AGENT_ID]??null}function Je(t,e){return!e||e===vo.id?t.claudeBin:t.agents[e]?.bin??e}function Nn(t,e){let n=Ye(t);if(!n)return`no agent adapter named "${t}" on this runner - update the runner, or set the rule's agent to "${Er.DEFAULT_AGENT_ID}"`;let r=(0,Er.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 Ue(t,e,n){let r=e.defaultAgent||Er.DEFAULT_AGENT_ID,s=Ye(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,Er.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:Je(t,s.id)}}function tn(t,e){return t.replace(/\{\{(\w+)\}\}/g,(n,r)=>r in e?e[r]:n)}var jn=R(xe(),1);var Nl=R(require("node:fs"),1),ko=R(require("node:path"),1),Zw=24,Vw=120,Yw=30,Jw=6e3,Xw=new Set(["node_modules","dist","build","out","coverage","vendor","target"]);function Qw(t){let e=[],n=(r,s)=>{if(s>4||e.length>=200)return;let i;try{i=Nl.default.readdirSync(r,{withFileTypes:!0})}catch{return}for(let o of i){if(o.name.startsWith(".")||Xw.has(o.name))continue;let l=ko.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 _o(t){let e=[],n=0;for(let r of Qw(t)){if(n>=Zw||e.join(`
791
+ `)+'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 qw=4e3,Fw={read_only:["Read(./**)","Glob(./**)","Grep(./**)"],edit_no_shell:["Read(./**)","Glob(./**)","Grep(./**)","Edit(./**)","Write(./**)"]};function Bw(t){if(process.env.ANTHROPIC_API_KEY)return"API key";let e=t??wo.default.join(kh.default.homedir(),".claude");try{if($l.default.existsSync(wo.default.join(e,".credentials.json"))||$l.default.existsSync(wo.default.join(e,"credentials.json")))return"subscription"}catch{}return"unknown"}function Hw(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 Kw(t){let e=["-p","--output-format","stream-json","--verbose","--allowedTools",Fw[t.mode].join(","),"--max-turns",String(t.maxTurns??60),...t.model?["--model",t.model]:[],...t.resume?["--resume",t.sessionId]:["--session-id",t.sessionId]],n=Bw(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,_h.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 Y=Date.now();Y-f<qw||(f=Y,t.onUsage({inputTokens:c,outputTokens:d,cacheReadTokens:p,turns:o}))},v=!1,k=()=>{v||(v=!0,clearTimeout(I),t.signal?.removeEventListener("abort",E),r(i))},E=()=>{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",E,{once:!0});let I=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+bo(t.mode)),s.stdin.end(),Sh.default.createInterface({input:s.stdout}).on("line",Y=>{if(!Y.trim())return;let b;try{b=JSON.parse(Y)}catch{t.onLog("agent",Y.slice(0,1e3));return}if(b.type==="system"&&b.subtype==="init")i.model=typeof b.model=="string"?b.model:void 0,t.onLog("info",`Claude Code session started (model: ${b.model??"default"})`);else if(b.type==="assistant"){o+=1,l=b.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 P=b.message?.usage;if(P){c+=Number(P.input_tokens??0)+Number(P.cache_creation_input_tokens??0);let D=JSON.stringify(b.message?.content??[]).length;d+=Math.max(Number(P.output_tokens??0),Math.round(D/4)),p+=Number(P.cache_read_input_tokens??0),w()}for(let D of b.message?.content??[])if(D.type==="text"&&D.text?.trim())t.onLog("agent",D.text.trim().slice(0,4e3));else if(D.type==="tool_use"){let j=D.input??{},B=["file_path","path","pattern","command","description","url"].map(m=>typeof j[m]=="string"?`${m}=${j[m]}`:null).filter(Boolean).join(" "),u=JSON.stringify(j).slice(0,400);if(t.onLog("info",`tool ${D.name} ${B?`${B} `:""}${u}`),t.onTool){let m=Hw(String(D.name??""),j,t.repoPath);t.onTool(m.verb,m.target.slice(0,200))}}}else b.type==="result"&&(i.costUsd=Number(b.total_cost_usd??0),i.inputTokens=Number(b.usage?.input_tokens??0)+Number(b.usage?.cache_creation_input_tokens??0),i.outputTokens=Number(b.usage?.output_tokens??0),c=Math.max(i.inputTokens,c),d=Math.max(i.outputTokens,d),i.inputTokens=c,i.outputTokens=d,p=Number(b.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()),b.subtype==="success"&&!b.is_error?(i.ok=!0,i.resultText=String(b.result??""),i.outputTruncated=l):b.subtype==="error_max_turns"?(i.turnLimitHit=!0,i.error=`hit the ${t.maxTurns??60}-turn limit before finishing`):i.error||(i.error=b.subtype==="error_during_execution"?"the agent stopped mid-work before it could finish - the session was interrupted or hit an internal limit":String(b.result??b.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",Y=>{V=(V+Y.toString()).slice(-2e3)}),s.on("error",Y=>{i.error=`failed to start ${t.bin}: ${Y.message}`,t.onLog("error",i.error),k()}),s.on("close",Y=>{!i.ok&&!i.error&&(i.error=i.timedOut?i.error:`claude exited with code ${Y}${V?`: ${V.slice(-500)}`:""}`),k()})})}var vo={id:"claude-code",displayName:"Claude Code",fastModel:"claude-sonnet-5",deepModel:"claude-fable-5",capabilities:Th.REGISTERED_AGENTS.find(t=>t.id==="claude-code").capabilities,run:Kw};var xh=require("node:child_process"),Eh=R(require("node:readline"),1),Ih=R(xe(),1);async function Gw(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,xh.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+bo(t.mode)),r.stdin.end(),Eh.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,k=v?.type??w.type,E=v?.text??v?.message??"";k==="agent_message"&&typeof E=="string"&&E.trim()?(i=E,t.onLog("agent",E.trim().slice(0,4e3))):k==="command_execution"||k==="exec_command_begin"?t.onLog("info",`tool ${String(v?.command??"").slice(0,300)}`):k==="error"&&typeof E=="string"&&E&&t.onLog("error",E.slice(0,1e3))});let p="";r.stderr.on("data",f=>{p=(p+f.toString()).slice(-2e3)}),r.on("error",f=>{s.error=`failed to start ${t.bin}: ${f.message} - is the Codex CLI installed and logged in?`,t.onLog("error",s.error),l()}),r.on("close",f=>{f===0&&i.trim()?(s.ok=!0,s.resultText=i):s.error||(s.error=`codex exited with code ${f}`+(i?"":" and produced no answer")+(p?`: ${p.slice(-500)}`:"")),l()})})}var Pl={id:"codex",fastModel:"",deepModel:"",displayName:"OpenAI Codex CLI (experimental)",capabilities:Ih.REGISTERED_AGENTS.find(t=>t.id==="codex").capabilities,run:Gw};var Ww={[vo.id]:vo,[Pl.id]:Pl};function Ye(t){return Ww[t||Ir.DEFAULT_AGENT_ID]??null}function Je(t,e){return!e||e===vo.id?t.claudeBin:t.agents[e]?.bin??e}function Nn(t,e){let n=Ye(t);if(!n)return`no agent adapter named "${t}" on this runner - update the runner, or set the rule's agent to "${Ir.DEFAULT_AGENT_ID}"`;let r=(0,Ir.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 Ue(t,e,n){let r=e.defaultAgent||Ir.DEFAULT_AGENT_ID,s=Ye(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,Ir.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:Je(t,s.id)}}function tn(t,e){return t.replace(/\{\{(\w+)\}\}/g,(n,r)=>r in e?e[r]:n)}var On=R(xe(),1);var Nl=R(require("node:fs"),1),ko=R(require("node:path"),1),Zw=24,Vw=120,Yw=30,Jw=6e3,Xw=new Set(["node_modules","dist","build","out","coverage","vendor","target"]);function Qw(t){let e=[],n=(r,s)=>{if(s>4||e.length>=200)return;let i;try{i=Nl.default.readdirSync(r,{withFileTypes:!0})}catch{return}for(let o of i){if(o.name.startsWith(".")||Xw.has(o.name))continue;let l=ko.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 _o(t){let e=[],n=0;for(let r of Qw(t)){if(n>=Zw||e.join(`
792
792
  `).length>Jw)break;let s=ko.default.relative(t,r);if(ko.default.basename(r).toUpperCase()==="CLAUDE.MD")continue;let i;try{i=Nl.default.readFileSync(r,"utf8")}catch{continue}let o=i.split(`
793
- `);if(o.length<Vw)continue;let l=[],c=!1;for(let u=0;u<o.length;u++){let p=o[u];if(/^\s*(```|~~~)/.test(p)){c=!c;continue}if(!c&&/^#{1,3}\s+\S/.test(p)&&(l.push(` L${u+1} ${p.trim().slice(0,110)}`),l.length>=Yw)){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?`
793
+ `);if(o.length<Vw)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>=Yw)){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?`
794
794
 
795
795
  DOCUMENT INDEX - the repo's larger Markdown documents, with 1-based line numbers (generated; the files themselves are the truth):
796
796
  ${e.join(`
797
797
  `)}
798
- 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 ti=R(require("node:fs"),1),Rh=R(require("node:path"),1);$e();var jl=2,Ah=()=>Rh.default.join(le(),"timeout-sessions.json");function Ch(){try{return JSON.parse(ti.default.readFileSync(Ah(),"utf8"))}catch{return{}}}function $h(t){ti.default.mkdirSync(le(),{recursive:!0,mode:448}),ti.default.writeFileSync(Ah(),JSON.stringify(t,null,2),{mode:384})}var Ph=(t,e)=>`${t}:${e}`;function Nh(t,e,n){let r=Ch();r[Ph(t,e)]={...n,at:new Date().toISOString()},$h(r)}function jh(t,e,n){let r=Ch(),s=Ph(t,e),i=r[s];return!i||(delete r[s],$h(r),i.branch!==n)||!ti.default.existsSync(i.worktreePath)?null:i}_t();xr();Nt();var Be=R(require("node:fs"),1),Ts=R(require("node:path"),1);rs();$e();var tv=_.object({runId:_.string(),issueKey:_.string(),repoName:_.string(),owner:_.string(),repo:_.string(),prNumber:_.number().int(),prUrl:_.string(),branch:_.string(),headSha:_.string(),doneLabel:_.string(),failedLabel:_.string(),jiraTransition:_.string().optional(),mergeOnApprove:_.boolean().default(!1),mergeMethod:_.enum(["squash","merge","rebase"]).default("squash"),autoMerge:_.boolean().default(!1),nextDecisionSeq:_.number().int().default(1e5),changesRequestedNotified:_.boolean().optional(),conflictNotified:_.boolean().optional(),agentConfigDir:_.string().optional()}),nv=_.record(tv),rv=_.object({runId:_.string(),issueKey:_.string(),issueSummary:_.string().default(""),projectId:_.string(),repoName:_.string(),environmentName:_.string(),requestedBy:_.string().default(""),createdAt:_.string()}),sv=_.record(rv),iv=_.object({runId:_.string(),issueKey:_.string(),kind:_.enum(["plan","implement"]),repoPath:_.string(),sessionId:_.string(),doneLabel:_.string(),failedLabel:_.string(),timeoutSeconds:_.number(),createdAt:_.string(),questionsPostedAt:_.string(),rounds:_.number().int().default(1),nextLogSeq:_.number().int().nonnegative().default(0),baseRepoPath:_.string().optional(),repoName:_.string().optional(),branch:_.string().optional(),baseBranch:_.string().optional(),jiraTransition:_.string().optional(),jiraTransitionOnMerge:_.string().optional(),requireApproval:_.boolean().optional(),maxTurns:_.number().int().optional(),runTests:_.boolean().default(!0),mergeOnApprove:_.boolean().default(!1),mergeMethod:_.enum(["squash","merge","rebase"]).default("squash"),autoMerge:_.boolean().default(!1),issueSummary:_.string().default(""),claudeConfigDir:_.string().optional(),agent:_.string().optional(),model:_.string().optional(),actorEmail:_.string().optional(),preflight:_.enum(["epic-confirm"]).optional(),ruleId:_.string().optional()}),ov=_.object({runId:_.string(),issueKey:_.string(),issueSummary:_.string().default(""),repoName:_.string(),baseRepoPath:_.string(),branch:_.string(),baseBranch:_.string(),headSha:_.string(),requireApproval:_.boolean(),mergeOnApprove:_.boolean().default(!1),mergeMethod:_.enum(["squash","merge","rebase"]).default("squash"),autoMerge:_.boolean().default(!1),doneLabel:_.string(),failedLabel:_.string(),jiraTransition:_.string().optional(),jiraTransitionOnMerge:_.string().optional(),actorEmail:_.string().optional(),resultSummary:_.string().default(""),prSummary:_.string().default(""),costUsd:_.number().default(0),nextLogSeq:_.number().int().default(1e5),createdAt:_.string()}),av=_.record(ov),lv=_.object({runId:_.string(),issueKey:_.string(),repoName:_.string(),owner:_.string(),repo:_.string(),prNumber:_.number().int(),prUrl:_.string(),jiraTransitionOnMerge:_.string().default(""),createdAt:_.string()}),cv=_.record(lv),uv=_.record(iv);function Oh(){return Ts.default.join(le(),"pending-runs.json")}function Ol(){return Ts.default.join(le(),"pending-deploys.json")}function Ml(){return Ts.default.join(le(),"pending-inputs.json")}function Dl(){return Ts.default.join(le(),"merge-watch.json")}function zl(){return Ts.default.join(le(),"pending-pushes.json")}function Ll(){let t=zl();if(!Be.default.existsSync(t))return{};try{return av.parse(JSON.parse(Be.default.readFileSync(t,"utf8")))}catch{return{}}}function So(t){let e=Ll();e[t.runId]=t,nn(zl(),e)}function To(t){return Ll()[t]??null}function Ul(t){let e=Ll();t in e&&(delete e[t],nn(zl(),e))}function xo(){let t=Dl();if(!Be.default.existsSync(t))return{};try{return cv.parse(JSON.parse(Be.default.readFileSync(t,"utf8")))}catch{return{}}}function Mh(t){let e=xo();e[t.runId]=t,nn(Dl(),e)}function ni(t){let e=xo();t in e&&(delete e[t],nn(Dl(),e))}function ri(){let t=Oh();if(!Be.default.existsSync(t))return{};try{return nv.parse(JSON.parse(Be.default.readFileSync(t,"utf8")))}catch{return{}}}function nn(t,e){Be.default.mkdirSync(le(),{recursive:!0,mode:448});let n=t+".tmp";Be.default.writeFileSync(n,JSON.stringify(e,null,2)+`
799
- `,{mode:384}),Be.default.renameSync(n,t),Be.default.chmodSync(t,384)}function Dh(t){nn(Oh(),t)}function St(t){let e=ri();e[t.runId]=t,Dh(e)}function xs(t){return ri()[t]??null}function Ar(t){let e=ri();t in e&&(delete e[t],Dh(e))}function ql(){let t=Ol();if(!Be.default.existsSync(t))return{};try{return sv.parse(JSON.parse(Be.default.readFileSync(t,"utf8")))}catch{return{}}}function zh(t){let e=ql();e[t.runId]=t,nn(Ol(),e)}function Io(t){return ql()[t]??null}function Eo(t){let e=ql();t in e&&(delete e[t],nn(Ol(),e))}function Cr(){let t=Ml();if(!Be.default.existsSync(t))return{};try{return uv.parse(JSON.parse(Be.default.readFileSync(t,"utf8")))}catch{return{}}}function Lh(t){let e=Cr();e[t.runId]=t,nn(Ml(),e)}function Uh(t){return Cr()[t]??null}function Ot(t){let e=Cr();t in e&&(delete e[t],nn(Ml(),e))}en();var dv=`
798
+ 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 ti=R(require("node:fs"),1),Rh=R(require("node:path"),1);$e();var Ol=2,Ah=()=>Rh.default.join(le(),"timeout-sessions.json");function Ch(){try{return JSON.parse(ti.default.readFileSync(Ah(),"utf8"))}catch{return{}}}function $h(t){ti.default.mkdirSync(le(),{recursive:!0,mode:448}),ti.default.writeFileSync(Ah(),JSON.stringify(t,null,2),{mode:384})}var Ph=(t,e)=>`${t}:${e}`;function Nh(t,e,n){let r=Ch();r[Ph(t,e)]={...n,at:new Date().toISOString()},$h(r)}function Oh(t,e,n){let r=Ch(),s=Ph(t,e),i=r[s];return!i||(delete r[s],$h(r),i.branch!==n)||!ti.default.existsSync(i.worktreePath)?null:i}_t();xr();Nt();var Be=R(require("node:fs"),1),Ts=R(require("node:path"),1);rs();$e();var tv=_.object({runId:_.string(),issueKey:_.string(),repoName:_.string(),owner:_.string(),repo:_.string(),prNumber:_.number().int(),prUrl:_.string(),branch:_.string(),headSha:_.string(),doneLabel:_.string(),failedLabel:_.string(),jiraTransition:_.string().optional(),mergeOnApprove:_.boolean().default(!1),mergeMethod:_.enum(["squash","merge","rebase"]).default("squash"),autoMerge:_.boolean().default(!1),nextDecisionSeq:_.number().int().default(1e5),changesRequestedNotified:_.boolean().optional(),conflictNotified:_.boolean().optional(),agentConfigDir:_.string().optional()}),nv=_.record(tv),rv=_.object({runId:_.string(),issueKey:_.string(),issueSummary:_.string().default(""),projectId:_.string(),repoName:_.string(),environmentName:_.string(),requestedBy:_.string().default(""),createdAt:_.string()}),sv=_.record(rv),iv=_.object({runId:_.string(),issueKey:_.string(),kind:_.enum(["plan","implement"]),repoPath:_.string(),sessionId:_.string(),doneLabel:_.string(),failedLabel:_.string(),timeoutSeconds:_.number(),createdAt:_.string(),questionsPostedAt:_.string(),rounds:_.number().int().default(1),nextLogSeq:_.number().int().nonnegative().default(0),baseRepoPath:_.string().optional(),repoName:_.string().optional(),branch:_.string().optional(),baseBranch:_.string().optional(),jiraTransition:_.string().optional(),jiraTransitionOnMerge:_.string().optional(),requireApproval:_.boolean().optional(),maxTurns:_.number().int().optional(),runTests:_.boolean().default(!0),mergeOnApprove:_.boolean().default(!1),mergeMethod:_.enum(["squash","merge","rebase"]).default("squash"),autoMerge:_.boolean().default(!1),issueSummary:_.string().default(""),claudeConfigDir:_.string().optional(),agent:_.string().optional(),model:_.string().optional(),actorEmail:_.string().optional(),preflight:_.enum(["epic-confirm"]).optional(),ruleId:_.string().optional()}),ov=_.object({runId:_.string(),issueKey:_.string(),issueSummary:_.string().default(""),repoName:_.string(),baseRepoPath:_.string(),branch:_.string(),baseBranch:_.string(),headSha:_.string(),requireApproval:_.boolean(),mergeOnApprove:_.boolean().default(!1),mergeMethod:_.enum(["squash","merge","rebase"]).default("squash"),autoMerge:_.boolean().default(!1),doneLabel:_.string(),failedLabel:_.string(),jiraTransition:_.string().optional(),jiraTransitionOnMerge:_.string().optional(),actorEmail:_.string().optional(),resultSummary:_.string().default(""),prSummary:_.string().default(""),costUsd:_.number().default(0),nextLogSeq:_.number().int().default(1e5),createdAt:_.string()}),av=_.record(ov),lv=_.object({runId:_.string(),issueKey:_.string(),repoName:_.string(),owner:_.string(),repo:_.string(),prNumber:_.number().int(),prUrl:_.string(),jiraTransitionOnMerge:_.string().default(""),createdAt:_.string()}),cv=_.record(lv),uv=_.record(iv);function jh(){return Ts.default.join(le(),"pending-runs.json")}function jl(){return Ts.default.join(le(),"pending-deploys.json")}function Ml(){return Ts.default.join(le(),"pending-inputs.json")}function Dl(){return Ts.default.join(le(),"merge-watch.json")}function zl(){return Ts.default.join(le(),"pending-pushes.json")}function Ll(){let t=zl();if(!Be.default.existsSync(t))return{};try{return av.parse(JSON.parse(Be.default.readFileSync(t,"utf8")))}catch{return{}}}function So(t){let e=Ll();e[t.runId]=t,nn(zl(),e)}function To(t){return Ll()[t]??null}function Ul(t){let e=Ll();t in e&&(delete e[t],nn(zl(),e))}function xo(){let t=Dl();if(!Be.default.existsSync(t))return{};try{return cv.parse(JSON.parse(Be.default.readFileSync(t,"utf8")))}catch{return{}}}function Mh(t){let e=xo();e[t.runId]=t,nn(Dl(),e)}function ni(t){let e=xo();t in e&&(delete e[t],nn(Dl(),e))}function ri(){let t=jh();if(!Be.default.existsSync(t))return{};try{return nv.parse(JSON.parse(Be.default.readFileSync(t,"utf8")))}catch{return{}}}function nn(t,e){Be.default.mkdirSync(le(),{recursive:!0,mode:448});let n=t+".tmp";Be.default.writeFileSync(n,JSON.stringify(e,null,2)+`
799
+ `,{mode:384}),Be.default.renameSync(n,t),Be.default.chmodSync(t,384)}function Dh(t){nn(jh(),t)}function St(t){let e=ri();e[t.runId]=t,Dh(e)}function xs(t){return ri()[t]??null}function Ar(t){let e=ri();t in e&&(delete e[t],Dh(e))}function ql(){let t=jl();if(!Be.default.existsSync(t))return{};try{return sv.parse(JSON.parse(Be.default.readFileSync(t,"utf8")))}catch{return{}}}function zh(t){let e=ql();e[t.runId]=t,nn(jl(),e)}function Eo(t){return ql()[t]??null}function Io(t){let e=ql();t in e&&(delete e[t],nn(jl(),e))}function Cr(){let t=Ml();if(!Be.default.existsSync(t))return{};try{return uv.parse(JSON.parse(Be.default.readFileSync(t,"utf8")))}catch{return{}}}function Lh(t){let e=Cr();e[t.runId]=t,nn(Ml(),e)}function Uh(t){return Cr()[t]??null}function jt(t){let e=Cr();t in e&&(delete e[t],nn(Ml(),e))}en();var dv=`
800
800
 
801
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.`,hv=`
802
802
 
@@ -829,46 +829,46 @@ This repository has working rules taught to Allwright - follow them:
829
829
  Lessons from earlier runs on this repository (human-confirmed - follow them BEFORE writing code, they exist because a run got this wrong once):
830
830
  `+o}return r}catch{return""}}function Kl(t){return Hl.default.existsSync(Ro.default.join(t,"DESIGN.md"))?`
831
831
 
832
- This repository has a DESIGN.md at its root: read it before doing any user-facing work (UI, copy, styling) and follow it. Where the ticket and DESIGN.md conflict, say so instead of silently picking one.`:""}var Gh=5,Bh=2,gv=8,Hh=2,Fl="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.",yv="Proceed - this epic's own description is the spec for this run",bv="Stop this run - the work lives in the child tickets",wv="You stopped because the session hit its turn limit - nothing failed. Continue exactly where you left off. Do not re-read files you already know or redo completed work; be economical with tool calls and finish the remaining work. Then end with your final summary exactly as the original instructions asked.";async function oi(t,e,n,r){let s=Date.now(),i="";r&&(i=await r().catch(()=>""));let o=await t.run(e),l=0,c="",u=r?gv:Bh,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>=u){c=`resume cap (${u}) reached`;break}if(r&&l>=Bh){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*Hh*1e3){c=`wall-clock budget (${Hh}x the rule's timeout) exhausted`;break}}l++,n("info",`Turn limit hit mid-work - auto-resuming the same session (resume ${l}, cap ${u})`);let f=await t.run({...e,prompt:wv,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}var si=new Map;function Wh(t){let e=si.get(t);return e?(e.abort(),!0):!1}function Zh(t){let e=new AbortController;return si.set(t,e),e}function Vh(t){si.delete(t)}async function Es(t,e,n,r,s){let i=new AbortController;si.set(t,i);try{return await oi(e,{...n,signal:i.signal},r,s)}finally{si.delete(t)}}function $r(t,e,n=0){let r=n;return{emit:(l,c)=>{e.send({type:"run.log",runId:t,seq:r++,ts:new Date().toISOString(),level:l,message:c}),l!=="agent"&&g.info(`[run ${t}] ${c}`)},setStatus:(l,c={})=>{e.send({type:"run.status",runId:t,status:l,...c})},sendUsage:l=>{e.send({type:"run.usage",runId:t,inputTokens:Math.round(l.inputTokens),outputTokens:Math.round(l.outputTokens),cacheReadTokens:l.cacheReadTokens===void 0?void 0:Math.round(l.cacheReadTokens),costUsd:l.costUsd,turns:l.turns})},nextSeq:()=>r}}async function ai(t){return t.rule.action.type==="implement"?_v(t):t.rule.action.type==="respond"?kv(t):vv(t)}async function vv(t){let{emit:e,setStatus:n,sendUsage:r,nextSeq:s}=$r(t.runId,t.transport),{trigger:i}=t.rule,o=t.rule.action;if(o.type!=="plan_only")return;let l=Nn(o.agent,o.type);if(l){e("error",l),await Is(t,l),n("failed",{error:l});return}let c=(0,Ao.randomUUID)();try{n("running"),e("info",`Run started for ${t.issueKey} (rule "${t.rule.name}", plan-only)`),e("info",`Fetching ${t.issueKey} from Jira`);let u=await t.jira.getIssue(t.issueKey),p=tn(o.promptTemplate,{issueKey:u.key,summary:u.summary,description:u.description||"(no description)",comments:Pr(u.comments)})+await is(t.jira,u.attachments,t.repoPath,e)+Kl(t.repoPath)+_o(t.repoPath)+jn.FOCUSED_READING_PROMPT+Se.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 Es(t.runId,Ye(o.agent),{repoPath:t.repoPath,prompt:p,timeoutSeconds:o.timeoutSeconds,bin:Je(t.cfg,o.agent),configDir:t.claudeConfigDir,mode:"read_only",model:o.model||void 0,sessionId:c,onLog:(k,x)=>e(k,x),onUsage:r},e),w={costUsd:f.costUsd,inputTokens:f.inputTokens,outputTokens:f.outputTokens,billingMode:f.billingMode,model:f.model};if(!f.ok||!f.resultText.trim()){let k=f.error??"Claude Code produced no output";e("error",`Run failed: ${k}`),await Is(t,k),n(f.timedOut?"timed_out":"failed",{error:k,...f.cancelled?{errorKind:"guard"}:{},...w});return}let v=ci(f.resultText);if(v){await ii({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 Yh({runId:t.runId,issueKey:t.issueKey,doneLabel:i.doneLabel,jira:t.jira,resultText:f.resultText,costFields:w,emit:e,setStatus:n})}catch(u){let p=u instanceof Error?u.message:String(u);e("error",`Run failed: ${p}`),await Is(t,p),n("failed",{error:p})}finally{vn(t.repoPath)}}async function Gl(t,e,n,r){let{emit:s,setStatus:i,sendUsage:o,nextSeq:l}=$r(t.runId,r.transport,t.nextLogSeq);try{i("running"),s("info",`Reply received on ${t.issueKey} - continuing run \`${t.runId}\``);let c=op(e)+await is(r.jiraFor(t.repoName??""),n,t.repoPath,s),u=await Es(t.runId,Ye(t.agent),{repoPath:t.repoPath,prompt:c,timeoutSeconds:t.timeoutSeconds,bin:Je(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:u.costUsd,inputTokens:u.inputTokens,outputTokens:u.outputTokens,billingMode:u.billingMode,model:u.model};if(!u.ok||!u.resultText.trim()){let w=u.error??"Claude Code produced no output";s("error",`Run failed: ${w}`),await Mt(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,w),Ot(t.runId),i(u.timedOut?"timed_out":"failed",{error:w,...u.cancelled?{errorKind:"guard"}:{},...p});return}let f=ci(u.resultText);if(f){if(t.rounds>=Gh){await ap(r.jiraFor(t.repoName??""),t,s,i,p);return}await ii({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 Yh({runId:t.runId,issueKey:t.issueKey,doneLabel:t.doneLabel,jira:r.jiraFor(t.repoName??""),resultText:u.resultText,costFields:p,emit:s,setStatus:i}),Ot(t.runId)}catch(c){let u=c instanceof Error?c.message:String(c);s("error",`Run failed: ${u}`),await Mt(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,u),Ot(t.runId),i("failed",{error:u})}finally{vn(t.repoPath)}}async function Yh(t){let{runId:e,issueKey:n,doneLabel:r,jira:s,resultText:i,costFields:o,emit:l,setStatus:c}=t;c("posting",o),l("info",`Posting plan to ${n} (${i.length} chars)`);let u=`
832
+ This repository has a DESIGN.md at its root: read it before doing any user-facing work (UI, copy, styling) and follow it. Where the ticket and DESIGN.md conflict, say so instead of silently picking one.`:""}var Gh=5,Bh=2,gv=8,Hh=2,Fl="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.",yv="Proceed - this epic's own description is the spec for this run",bv="Stop this run - the work lives in the child tickets",wv="You stopped because the session hit its turn limit - nothing failed. Continue exactly where you left off. Do not re-read files you already know or redo completed work; be economical with tool calls and finish the remaining work. Then end with your final summary exactly as the original instructions asked.";async function oi(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?gv:Bh,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>=Bh){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*Hh*1e3){c=`wall-clock budget (${Hh}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:wv,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}var si=new Map;function Wh(t){let e=si.get(t);return e?(e.abort(),!0):!1}function Zh(t){let e=new AbortController;return si.set(t,e),e}function Vh(t){si.delete(t)}async function Is(t,e,n,r,s){let i=new AbortController;si.set(t,i);try{return await oi(e,{...n,signal:i.signal},r,s)}finally{si.delete(t)}}function $r(t,e,n=0){let r=n;return{emit:(l,c)=>{e.send({type:"run.log",runId:t,seq:r++,ts:new Date().toISOString(),level:l,message:c}),l!=="agent"&&g.info(`[run ${t}] ${c}`)},setStatus:(l,c={})=>{e.send({type:"run.status",runId:t,status:l,...c})},sendUsage:l=>{e.send({type:"run.usage",runId:t,inputTokens:Math.round(l.inputTokens),outputTokens:Math.round(l.outputTokens),cacheReadTokens:l.cacheReadTokens===void 0?void 0:Math.round(l.cacheReadTokens),costUsd:l.costUsd,turns:l.turns})},nextSeq:()=>r}}async function ai(t){return t.rule.action.type==="implement"?_v(t):t.rule.action.type==="respond"?kv(t):vv(t)}async function vv(t){let{emit:e,setStatus:n,sendUsage:r,nextSeq:s}=$r(t.runId,t.transport),{trigger:i}=t.rule,o=t.rule.action;if(o.type!=="plan_only")return;let l=Nn(o.agent,o.type);if(l){e("error",l),await Es(t,l),n("failed",{error:l});return}let c=(0,Ao.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=tn(o.promptTemplate,{issueKey:d.key,summary:d.summary,description:d.description||"(no description)",comments:Pr(d.comments)})+await is(t.jira,d.attachments,t.repoPath,e)+Kl(t.repoPath)+_o(t.repoPath)+On.FOCUSED_READING_PROMPT+Se.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 Is(t.runId,Ye(o.agent),{repoPath:t.repoPath,prompt:p,timeoutSeconds:o.timeoutSeconds,bin:Je(t.cfg,o.agent),configDir:t.claudeConfigDir,mode:"read_only",model:o.model||void 0,sessionId:c,onLog:(k,E)=>e(k,E),onUsage:r},e),w={costUsd:f.costUsd,inputTokens:f.inputTokens,outputTokens:f.outputTokens,billingMode:f.billingMode,model:f.model};if(!f.ok||!f.resultText.trim()){let k=f.error??"Claude Code produced no output";e("error",`Run failed: ${k}`),await Es(t,k),n(f.timedOut?"timed_out":"failed",{error:k,...f.cancelled?{errorKind:"guard"}:{},...w});return}let v=ci(f.resultText);if(v){await ii({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 Yh({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 Es(t,p),n("failed",{error:p})}finally{vn(t.repoPath)}}async function Gl(t,e,n,r){let{emit:s,setStatus:i,sendUsage:o,nextSeq:l}=$r(t.runId,r.transport,t.nextLogSeq);try{i("running"),s("info",`Reply received on ${t.issueKey} - continuing run \`${t.runId}\``);let c=op(e)+await is(r.jiraFor(t.repoName??""),n,t.repoPath,s),d=await Is(t.runId,Ye(t.agent),{repoPath:t.repoPath,prompt:c,timeoutSeconds:t.timeoutSeconds,bin:Je(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 Mt(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,w),jt(t.runId),i(d.timedOut?"timed_out":"failed",{error:w,...d.cancelled?{errorKind:"guard"}:{},...p});return}let f=ci(d.resultText);if(f){if(t.rounds>=Gh){await ap(r.jiraFor(t.repoName??""),t,s,i,p);return}await ii({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 Yh({runId:t.runId,issueKey:t.issueKey,doneLabel:t.doneLabel,jira:r.jiraFor(t.repoName??""),resultText:d.resultText,costFields:p,emit:s,setStatus:i}),jt(t.runId)}catch(c){let d=c instanceof Error?c.message:String(c);s("error",`Run failed: ${d}`),await Mt(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,d),jt(t.runId),i("failed",{error:d})}finally{vn(t.repoPath)}}async function Yh(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=`
833
833
 
834
834
  ---
835
- _Allwright plan-only run \`${e}\` \xB7 cost $${o.costUsd.toFixed(4)} \xB7 no code was written._`;await s.addComment(n,i+u),await s.editLabels(n,{add:[r],remove:[Se.NEEDS_INPUT_LABEL]}),l("info",`Labeled ${n} with "${r}"`),c("succeeded",{...o,resultSummary:Nr(i)}),l("info",`Run succeeded \xB7 $${o.costUsd.toFixed(4)}`)}async function kv(t){let{emit:e,setStatus:n,sendUsage:r}=$r(t.runId,t.transport),s=t.rule.action;if(s.type!=="respond")return;let i=Nn(s.agent,s.type);if(i){e("error",i),await t.jira.addComment(t.issueKey,`**Allwright could not answer this question.**
835
+ _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:[Se.NEEDS_INPUT_LABEL]}),l("info",`Labeled ${n} with "${r}"`),c("succeeded",{...o,resultSummary:Nr(i)}),l("info",`Run succeeded \xB7 $${o.costUsd.toFixed(4)}`)}async function kv(t){let{emit:e,setStatus:n,sendUsage:r}=$r(t.runId,t.transport),s=t.rule.action;if(s.type!=="respond")return;let i=Nn(s.agent,s.type);if(i){e("error",i),await t.jira.addComment(t.issueKey,`**Allwright could not answer this question.**
836
836
 
837
- ${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=tn(s.promptTemplate,{issueKey:o.key,summary:o.summary,description:o.description||"(no description)",comments:Pr(o.comments),question:t.question?.body??"(see the latest comment on the ticket)",questionAuthor:t.question?.author??"the commenter"})+await is(t.jira,o.attachments,t.repoPath,e)+Kl(t.repoPath)+_o(t.repoPath)+jn.FOCUSED_READING_PROMPT;e("info",`Starting Claude Code in ${t.repoPath} - read-only tools, path-jailed, timeout ${s.timeoutSeconds}s`);let c=await Es(t.runId,Ye(s.agent),{repoPath:t.repoPath,prompt:l,timeoutSeconds:s.timeoutSeconds,bin:Je(t.cfg,s.agent),configDir:t.claudeConfigDir,mode:"read_only",model:s.model||void 0,sessionId:(0,Ao.randomUUID)(),onLog:(p,f)=>e(p,f),onUsage:r},e),u={costUsd:c.costUsd,inputTokens:c.inputTokens,outputTokens:c.outputTokens,billingMode:c.billingMode,model:c.model};if(!c.ok||!c.resultText.trim()){let p=c.error??"Claude Code produced no answer";e("error",`Run failed: ${p}`),await t.jira.addComment(t.issueKey,`**Allwright could not answer this question.**
837
+ ${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=tn(s.promptTemplate,{issueKey:o.key,summary:o.summary,description:o.description||"(no description)",comments:Pr(o.comments),question:t.question?.body??"(see the latest comment on the ticket)",questionAuthor:t.question?.author??"the commenter"})+await is(t.jira,o.attachments,t.repoPath,e)+Kl(t.repoPath)+_o(t.repoPath)+On.FOCUSED_READING_PROMPT;e("info",`Starting Claude Code in ${t.repoPath} - read-only tools, path-jailed, timeout ${s.timeoutSeconds}s`);let c=await Is(t.runId,Ye(s.agent),{repoPath:t.repoPath,prompt:l,timeoutSeconds:s.timeoutSeconds,bin:Je(t.cfg,s.agent),configDir:t.claudeConfigDir,mode:"read_only",model:s.model||void 0,sessionId:(0,Ao.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.**
838
838
 
839
839
  Error: ${p.slice(0,800)}
840
840
 
841
- Ask again in a new comment to retry. (run \`${t.runId}\`)`).catch(f=>g.error(`could not post answer failure to ${t.issueKey}: ${f}`)),n(c.timedOut?"timed_out":"failed",{error:p,...c.cancelled?{errorKind:"guard"}:{},...u});return}n("posting",u),e("info",`Posting answer to ${t.issueKey} (${c.resultText.length} chars)`),await t.jira.addComment(t.issueKey,c.resultText),n("succeeded",{...u,resultSummary:Nr(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{vn(t.repoPath)}}async function Jh(t,e,n,r){let s=`${e}-wip`;try{return vn(t),await _r(t,`WIP: turn limit exhausted (Allwright run ${n})`),await Za(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 Xh(t){return`
841
+ 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:Nr(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{vn(t.repoPath)}}async function Jh(t,e,n,r){let s=`${e}-wip`;try{return vn(t),await _r(t,`WIP: turn limit exhausted (Allwright run ${n})`),await Za(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 Xh(t){return`
842
842
 
843
- 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 _v(t){let{emit:e,setStatus:n,sendUsage:r,nextSeq:s}=$r(t.runId,t.transport,t.startLogSeq??0),{trigger:i}=t.rule,o=t.rule.action;if(o.type!=="implement")return;let l=Nn(o.agent,o.type);if(l){e("error",l),await Is(t,l),n("failed",{error:l});return}let c=tn(o.branchTemplate,{issueKey:t.issueKey}),u=t.chain?null:jh(t.project.id,t.issueKey,c),p=t.chain?.worktreePath??u?.worktreePath??Ro.default.join(Qt(),t.runId),f=t.chain?.sessionId??u?.sessionId??(0,Ao.randomUUID)(),w=!1,v=!1,k=!1;try{if(!po(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(I){e("warn",`Jira start transition failed: ${I instanceof Error?I.message:I} - continuing anyway`)}let x=await Tr(t.repoPath);if(e("info",`Repo origin: ${x}`),!vt(x))throw new Error(`origin "${x}" 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&&!u&&!t.chain){k=!0;let I="```";await ii({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.
843
+ 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 _v(t){let{emit:e,setStatus:n,sendUsage:r,nextSeq:s}=$r(t.runId,t.transport,t.startLogSeq??0),{trigger:i}=t.rule,o=t.rule.action;if(o.type!=="implement")return;let l=Nn(o.agent,o.type);if(l){e("error",l),await Es(t,l),n("failed",{error:l});return}let c=tn(o.branchTemplate,{issueKey:t.issueKey}),d=t.chain?null:Oh(t.project.id,t.issueKey,c),p=t.chain?.worktreePath??d?.worktreePath??Ro.default.join(Qt(),t.runId),f=t.chain?.sessionId??d?.sessionId??(0,Ao.randomUUID)(),w=!1,v=!1,k=!1;try{if(!po(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(x){e("warn",`Jira start transition failed: ${x instanceof Error?x.message:x} - continuing anyway`)}let E=await Tr(t.repoPath);if(e("info",`Repo origin: ${E}`),!vt(E))throw new Error(`origin "${E}" is not a GitHub remote - implement mode supports GitHub only`);e("info",`Fetching ${t.issueKey} from Jira`);let I=await t.jira.getIssue(t.issueKey);if(/^epic$/i.test(I.issueType)&&!t.preflightAnswer&&!d&&!t.chain){k=!0;let x="```";await ii({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:I.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.
844
844
 
845
845
  Should this run implement the epic ticket itself?
846
846
 
847
- ${I}${Se.NEEDS_INPUT_ASK_FENCE}
847
+ ${x}${Se.NEEDS_INPUT_ASK_FENCE}
848
848
  {"options": ["${yv}", "${bv}"]}
849
- ${I}`,e,n,{costUsd:0,inputTokens:0,outputTokens:0});return}let C=t.continueBranch;C&&!u&&await Ja(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;u?e("info",`Resuming the session that timed out on this ticket (timeout resume ${u.resumes}/${jl}) - 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 Rn(t.repoPath,V),t.chain&&C||await Xa(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 sl(p,c,C?`origin/${c}`:`origin/${o.baseBranch}`)):await Qa(t.repoPath,p,c,V)),w=!0;let Y=tn(o.promptTemplate,{issueKey:E.key,summary:E.summary,description:E.description||"(no description)",comments:Pr(E.comments)});!u&&!Iv(`${E.summary}
850
- ${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 b=u?null:await Ya(p,o.baseBranch,E.key).catch(()=>null),$=[],D=(I,P)=>(P&&$.push({part:I,chars:P.length}),P),j=D("ticket: rule template + summary (rendered)",Y)+D("attachments listing",await is(t.jira,E.attachments,p,e))+D("design guideline pointer",Kl(p))+D("knowledge: packs + lessons",mv(t.repoPath))+D("doc index",_o(p))+D("revision: previous delivery + what is new",b?xv(b,E.comments,dt):"")+D("appendix: focused reading",jn.FOCUSED_READING_PROMPT)+D("appendix: protected paths",dv)+D("appendix: needs-input options",Se.NEEDS_INPUT_OPTIONS_PROMPT)+D("appendix: PR summary",hv)+D("appendix: go-live",t.project.goLiveIssueKey?pv:"")+D("appendix: write tests",o.writeTests?jn.WRITE_TESTS_PROMPT:"")+D("appendix: update memory",o.updateMemory?Se.MEMORY_UPDATE_PROMPT:"")+D("epic confirmation answer",t.preflightAnswer?`
849
+ ${x}`,e,n,{costUsd:0,inputTokens:0,outputTokens:0});return}let $=t.continueBranch;$&&!d&&await Ja(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}.`),$=!1);let V=$?c:o.baseBranch;d?e("info",`Resuming the session that timed out on this ticket (timeout resume ${d.resumes}/${Ol}) - same worktree, uncommitted work intact, repo context cached`):(e("info",$?`Continuing branch "${c}" from origin/${c} (autopilot batch)`:`Preparing worktree on branch "${c}" from origin/${o.baseBranch}`),await Rn(t.repoPath,V),t.chain&&$||await Xa(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 sl(p,c,$?`origin/${c}`:`origin/${o.baseBranch}`)):await Qa(t.repoPath,p,c,V)),w=!0;let Y=tn(o.promptTemplate,{issueKey:I.key,summary:I.summary,description:I.description||"(no description)",comments:Pr(I.comments)});!d&&!Ev(`${I.summary}
850
+ ${I.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 b=d?null:await Ya(p,o.baseBranch,I.key).catch(()=>null),P=[],D=(x,A)=>(A&&P.push({part:x,chars:A.length}),A),j=D("ticket: rule template + summary (rendered)",Y)+D("attachments listing",await is(t.jira,I.attachments,p,e))+D("design guideline pointer",Kl(p))+D("knowledge: packs + lessons",mv(t.repoPath))+D("doc index",_o(p))+D("revision: previous delivery + what is new",b?xv(b,I.comments,dt):"")+D("appendix: focused reading",On.FOCUSED_READING_PROMPT)+D("appendix: protected paths",dv)+D("appendix: needs-input options",Se.NEEDS_INPUT_OPTIONS_PROMPT)+D("appendix: PR summary",hv)+D("appendix: go-live",t.project.goLiveIssueKey?pv:"")+D("appendix: write tests",o.writeTests?On.WRITE_TESTS_PROMPT:"")+D("appendix: update memory",o.updateMemory?Se.MEMORY_UPDATE_PROMPT:"")+D("epic confirmation answer",t.preflightAnswer?`
851
851
 
852
852
  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:
853
- ${t.preflightAnswer.slice(0,4e3)}`:"");E.description&&$.push({part:"\u21B3 of which ticket description",chars:E.description.length});let B=Pr(E.comments).length;B&&$.push({part:"\u21B3 of which comment history",chars:B}),t.transport.sendRunContext({runId:t.runId,pieces:u?[{part:"continuation prompt (session resumed - original context already cached)",chars:Fl.length}]:$,totalChars:u?Fl.length:j.length,sessionMode:u?"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 d=await Es(t.runId,Ye(o.agent),{repoPath:p,prompt:u?Fl:j,timeoutSeconds:o.timeoutSeconds,bin:Je(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||!!u,onLog:(I,P)=>e(I,P),onUsage:r},e,()=>ao(p)),m={costUsd:d.costUsd,inputTokens:d.inputTokens,outputTokens:d.outputTokens,billingMode:d.billingMode,model:d.model};if(!d.ok){let I=d.error??"Claude Code failed";e("error",`Run failed: ${I}`);let P=I,K=(d.timedOut||d.costCapped)&&!d.cancelled&&Ye(o.agent)?.capabilities.sessionResume&&(u?.resumes??0)<jl;if(d.turnLimitHit&&!K){let U=await Jh(p,c,t.runId,e);U&&(P+=Xh(U))}K&&(Nh(t.project.id,t.issueKey,{sessionId:f,worktreePath:p,branch:c,resumes:(u?.resumes??0)+1}),v=!0,e("info","Worktree and session preserved - the next trigger on this ticket resumes here"),P+=" - 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"),ht(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:"implement failed",detail:I.slice(0,500)}),await Is(t,P),n(d.timedOut?"timed_out":"failed",{error:P,...d.cancelled||d.costCapped?{errorKind:"guard"}:{},...m});return}let y=ci(d.resultText);if(y){k=!0,await ii({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},y,e,n,m);return}vn(p),await Qh({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:d.resultText,costFields:m,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(x){let E=x instanceof Error?x.message:String(x);e("error",`Run failed: ${E}`),ht(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:"implement failed",detail:E.slice(0,500)}),await Is(t,E),n("failed",{error:E})}finally{w&&!k&&!t.keepWorktree&&!v&&await Pt(t.repoPath,p).catch(()=>{})}}async function Wl(t,e,n,r){let{emit:s,setStatus:i,sendUsage:o,nextSeq:l}=$r(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 ai({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,u=!1;try{if(!po(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=op(e)+await is(r.jiraFor(t.repoName??""),n,c,s),f=await Es(t.runId,Ye(t.agent),{repoPath:c,prompt:p,timeoutSeconds:t.timeoutSeconds,bin:Je(r.cfg,t.agent??""),configDir:t.claudeConfigDir,mode:"edit_no_shell",model:t.model||void 0,maxTurns:t.maxTurns??120,sessionId:t.sessionId,resume:!0,onLog:(k,x)=>s(k,x),onUsage:o},s,()=>ao(c)),w={costUsd:f.costUsd,inputTokens:f.inputTokens,outputTokens:f.outputTokens,billingMode:f.billingMode,model:f.model};if(!f.ok){let k=f.error??"Claude Code failed";s("error",`Run failed: ${k}`);let x=k;if(f.turnLimitHit&&t.branch){let E=await Jh(c,t.branch,t.runId,s);E&&(x+=Xh(E))}await Mt(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,x),Ot(t.runId),i(f.timedOut?"timed_out":"failed",{error:k,...f.cancelled?{errorKind:"guard"}:{},...w});return}let v=ci(f.resultText);if(v){if(t.rounds>=Gh){await ap(r.jiraFor(t.repoName??""),t,s,i,w);return}u=!0,await ii({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}vn(c),await Qh({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}),Ot(t.runId)}catch(p){let f=p instanceof Error?p.message:String(p);s("error",`Run failed: ${f}`),await Mt(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,f),Ot(t.runId),i("failed",{error:f})}finally{u||await Pt(t.baseRepoPath??c,c).catch(()=>{})}}async function Qh(t){let{runId:e,issueKey:n,issueSummary:r,worktreePath:s,baseRepoPath:i,branch:o,baseBranch:l,jiraTransition:c,jiraTransitionOnMerge:u,requireApproval:p,doneLabel:f,failedLabel:w,repoName:v,jira:k,cfg:x,actorEmail:E,runTests:C,mergeOnApprove:V,mergeMethod:Y,autoMerge:b,resultText:$,costFields:D,emit:j,setStatus:B}=t,d=await ms(s);d.deleted.length&&j("info",`Deleted ${d.deleted.length} file(s) listed in ${Xt}: `+d.deleted.slice(0,10).join(", ")+(d.deleted.length>10?", \u2026":""));for(let he of d.refused)j("warn",`${Xt} entry refused: ${he}`);j("info","Committing changes"),await _r(s,`${n}: ${r}
853
+ ${t.preflightAnswer.slice(0,4e3)}`:"");I.description&&P.push({part:"\u21B3 of which ticket description",chars:I.description.length});let B=Pr(I.comments).length;B&&P.push({part:"\u21B3 of which comment history",chars:B}),t.transport.sendRunContext({runId:t.runId,pieces:d?[{part:"continuation prompt (session resumed - original context already cached)",chars:Fl.length}]:P,totalChars:d?Fl.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 u=await Is(t.runId,Ye(o.agent),{repoPath:p,prompt:d?Fl:j,timeoutSeconds:o.timeoutSeconds,bin:Je(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:(x,A)=>e(x,A),onUsage:r},e,()=>ao(p)),m={costUsd:u.costUsd,inputTokens:u.inputTokens,outputTokens:u.outputTokens,billingMode:u.billingMode,model:u.model};if(!u.ok){let x=u.error??"Claude Code failed";e("error",`Run failed: ${x}`);let A=x,K=(u.timedOut||u.costCapped)&&!u.cancelled&&Ye(o.agent)?.capabilities.sessionResume&&(d?.resumes??0)<Ol;if(u.turnLimitHit&&!K){let U=await Jh(p,c,t.runId,e);U&&(A+=Xh(U))}K&&(Nh(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"),A+=" - 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"),ht(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:"implement failed",detail:x.slice(0,500)}),await Es(t,A),n(u.timedOut?"timed_out":"failed",{error:A,...u.cancelled||u.costCapped?{errorKind:"guard"}:{},...m});return}let y=ci(u.resultText);if(y){k=!0,await ii({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:I.summary},y,e,n,m);return}vn(p),await Qh({runId:t.runId,issueKey:t.issueKey,issueSummary:I.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:u.resultText,costFields:m,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(E){let I=E instanceof Error?E.message:String(E);e("error",`Run failed: ${I}`),ht(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:"implement failed",detail:I.slice(0,500)}),await Es(t,I),n("failed",{error:I})}finally{w&&!k&&!t.keepWorktree&&!v&&await Pt(t.repoPath,p).catch(()=>{})}}async function Wl(t,e,n,r){let{emit:s,setStatus:i,sendUsage:o,nextSeq:l}=$r(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 ai({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(!po(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=op(e)+await is(r.jiraFor(t.repoName??""),n,c,s),f=await Is(t.runId,Ye(t.agent),{repoPath:c,prompt:p,timeoutSeconds:t.timeoutSeconds,bin:Je(r.cfg,t.agent??""),configDir:t.claudeConfigDir,mode:"edit_no_shell",model:t.model||void 0,maxTurns:t.maxTurns??120,sessionId:t.sessionId,resume:!0,onLog:(k,E)=>s(k,E),onUsage:o},s,()=>ao(c)),w={costUsd:f.costUsd,inputTokens:f.inputTokens,outputTokens:f.outputTokens,billingMode:f.billingMode,model:f.model};if(!f.ok){let k=f.error??"Claude Code failed";s("error",`Run failed: ${k}`);let E=k;if(f.turnLimitHit&&t.branch){let I=await Jh(c,t.branch,t.runId,s);I&&(E+=Xh(I))}await Mt(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,E),jt(t.runId),i(f.timedOut?"timed_out":"failed",{error:k,...f.cancelled?{errorKind:"guard"}:{},...w});return}let v=ci(f.resultText);if(v){if(t.rounds>=Gh){await ap(r.jiraFor(t.repoName??""),t,s,i,w);return}d=!0,await ii({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}vn(c),await Qh({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}),jt(t.runId)}catch(p){let f=p instanceof Error?p.message:String(p);s("error",`Run failed: ${f}`),await Mt(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,f),jt(t.runId),i("failed",{error:f})}finally{d||await Pt(t.baseRepoPath??c,c).catch(()=>{})}}async function Qh(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:k,cfg:E,actorEmail:I,runTests:$,mergeOnApprove:V,mergeMethod:Y,autoMerge:b,resultText:P,costFields:D,emit:j,setStatus:B}=t,u=await ms(s);u.deleted.length&&j("info",`Deleted ${u.deleted.length} file(s) listed in ${Xt}: `+u.deleted.slice(0,10).join(", ")+(u.deleted.length>10?", \u2026":""));for(let he of u.refused)j("warn",`${Xt} entry refused: ${he}`);j("info","Committing changes"),await _r(s,`${n}: ${r}
854
854
 
855
- Allwright run ${e}`);let m=await An(s,l);if(!m.ok){let he=m.forbidden.length?`refusing to push: changes touch protected paths (${m.forbidden.slice(0,5).join(", ")}) - CI/workflow files can exfiltrate repo secrets and are never pushed by the agent. Apply those files' changes yourself, or re-run the ticket with them out of scope.`:`refusing to push: change is too large (${m.files} files, ${m.insertions+m.deletions} lines; limits ${In}/${En})`;j("error",he),await Mt(k,n,e,w,he),B("failed",{error:he,errorKind:"guard",...D});return}j("info",`Diff: ${m.files} file(s), +${m.insertions}/-${m.deletions}`);let y={...D},I="",P="",K,U,W;if(C){let he=ks(s);if(!he)j("info","No TEST.md in this repo - skipping the test run (nothing documented to run)");else{let He=_s(Hl.default.readFileSync(he,"utf8"));if(!He.length)j("info",`${Ro.default.basename(he)} lists no commands - nothing to run`);else{j("info",`Running ${He.length} documented test command(s) - no tokens, plain shell`);let Ne=await Ir(s,He,{perCommandTimeoutMs:15*6e4}),Ie=Ne.filter(ie=>ie.exitCode!==0),re=Ie.length;for(let ie of Ne)j(ie.exitCode===0?"info":"warn",Fh(ie));let pn="";if(Ie.length&&t.fixSession){let ie=await Tv({runId:e,issueKey:n,worktreePath:s,baseBranch:l,fixSession:t.fixSession,agentConfigDir:t.agentConfigDir,cfg:x,failed:Ie,emit:j,sendUsage:t.sendUsage,baseCost:y});if(y.costUsd+=ie.cost.costUsd,y.inputTokens+=ie.cost.inputTokens,y.outputTokens+=ie.cost.outputTokens,ie.outcome==="cancelled"){let je="stopped by a person during the automatic test-fix attempt - nothing was pushed";j("warn",je),So({runId:e,issueKey:n,issueSummary:r,mergeOnApprove:V,mergeMethod:Y,autoMerge:b,repoName:v,baseRepoPath:i,branch:o,baseBranch:l,headSha:await Ve(s),requireApproval:p,doneLabel:f,failedLabel:w,jiraTransition:c,jiraTransitionOnMerge:u,actorEmail:E,resultSummary:Kh($),prSummary:Bl($)??"",costUsd:y.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),await Mt(k,n,e,w,`${je}. The commit survived on the runner - "Retry push" on the run's dashboard page ships it without a new agent run.`),B("failed",{error:je,errorKind:"guard",retryAvailable:!0,...y});return}if(ie.outcome==="committed"){P=ie.resultText,j("info",`Re-running ${He.length} documented test command(s) after the fix`),Ne=await Ir(s,He,{perCommandTimeoutMs:15*6e4}),Ie=Ne.filter(je=>je.exitCode!==0);for(let je of Ne)j(je.exitCode===0?"info":"warn",Fh(je));pn=Ie.length?`One automatic same-session fix attempt ran; the results above are AFTER it. First pass: ${re} failure(s). ${ie.note}`:`The first pass had ${re} failure(s); one automatic same-session fix attempt resolved them. ${ie.note}`}else pn=ie.note}K=Ie.slice(0,20).map(ie=>({command:ie.command.slice(0,500),exitCode:ie.exitCode,tail:ie.tail.slice(-4e3)})),U=Ne.length-Ie.length,W=Ne.length,I=`
855
+ Allwright run ${e}`);let m=await An(s,l);if(!m.ok){let he=m.forbidden.length?`refusing to push: changes touch protected paths (${m.forbidden.slice(0,5).join(", ")}) - CI/workflow files can exfiltrate repo secrets and are never pushed by the agent. Apply those files' changes yourself, or re-run the ticket with them out of scope.`:`refusing to push: change is too large (${m.files} files, ${m.insertions+m.deletions} lines; limits ${En}/${In})`;j("error",he),await Mt(k,n,e,w,he),B("failed",{error:he,errorKind:"guard",...D});return}j("info",`Diff: ${m.files} file(s), +${m.insertions}/-${m.deletions}`);let y={...D},x="",A="",K,U,W;if($){let he=ks(s);if(!he)j("info","No TEST.md in this repo - skipping the test run (nothing documented to run)");else{let He=_s(Hl.default.readFileSync(he,"utf8"));if(!He.length)j("info",`${Ro.default.basename(he)} lists no commands - nothing to run`);else{j("info",`Running ${He.length} documented test command(s) - no tokens, plain shell`);let Ne=await Er(s,He,{perCommandTimeoutMs:15*6e4}),Ee=Ne.filter(ie=>ie.exitCode!==0),re=Ee.length;for(let ie of Ne)j(ie.exitCode===0?"info":"warn",Fh(ie));let pn="";if(Ee.length&&t.fixSession){let ie=await Tv({runId:e,issueKey:n,worktreePath:s,baseBranch:l,fixSession:t.fixSession,agentConfigDir:t.agentConfigDir,cfg:E,failed:Ee,emit:j,sendUsage:t.sendUsage,baseCost:y});if(y.costUsd+=ie.cost.costUsd,y.inputTokens+=ie.cost.inputTokens,y.outputTokens+=ie.cost.outputTokens,ie.outcome==="cancelled"){let Oe="stopped by a person during the automatic test-fix attempt - nothing was pushed";j("warn",Oe),So({runId:e,issueKey:n,issueSummary:r,mergeOnApprove:V,mergeMethod:Y,autoMerge:b,repoName:v,baseRepoPath:i,branch:o,baseBranch:l,headSha:await Ve(s),requireApproval:p,doneLabel:f,failedLabel:w,jiraTransition:c,jiraTransitionOnMerge:d,actorEmail:I,resultSummary:Kh(P),prSummary:Bl(P)??"",costUsd:y.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),await Mt(k,n,e,w,`${Oe}. The commit survived on the runner - "Retry push" on the run's dashboard page ships it without a new agent run.`),B("failed",{error:Oe,errorKind:"guard",retryAvailable:!0,...y});return}if(ie.outcome==="committed"){A=ie.resultText,j("info",`Re-running ${He.length} documented test command(s) after the fix`),Ne=await Er(s,He,{perCommandTimeoutMs:15*6e4}),Ee=Ne.filter(Oe=>Oe.exitCode!==0);for(let Oe of Ne)j(Oe.exitCode===0?"info":"warn",Fh(Oe));pn=Ee.length?`One automatic same-session fix attempt ran; the results above are AFTER it. First pass: ${re} failure(s). ${ie.note}`:`The first pass had ${re} failure(s); one automatic same-session fix attempt resolved them. ${ie.note}`}else pn=ie.note}K=Ee.slice(0,20).map(ie=>({command:ie.command.slice(0,500),exitCode:ie.exitCode,tail:ie.tail.slice(-4e3)})),U=Ne.length-Ee.length,W=Ne.length,x=`
856
856
 
857
857
  ### Tests
858
858
  `+Ne.map(ie=>`- ${ie.exitCode===0?"PASS":"FAIL"} \`${ie.command}\``).join(`
859
- `)+(Ie.length?`
859
+ `)+(Ee.length?`
860
860
 
861
- **${Ie.length} of ${Ne.length} failed.** Output is in the run log.`:`
861
+ **${Ee.length} of ${Ne.length} failed.** Output is in the run log.`:`
862
862
 
863
863
  All ${Ne.length} passed.`)+(pn?`
864
864
 
865
- ${pn}`:""),Ie.length&&j("warn",`${Ie.length} test command(s) failed - the PR will say so; review before merging`),re>0&&ht(i,{issueKey:n,runId:e,title:Ie.length?`TEST.md commands failing at PR (${Ie.length} of ${Ne.length})`:"TEST.md failures fixed by same-session retry",detail:Ne.map(ie=>`${ie.exitCode===0?"PASS":"FAIL"} ${ie.command}`).join(`
865
+ ${pn}`:""),Ee.length&&j("warn",`${Ee.length} test command(s) failed - the PR will say so; review before merging`),re>0&&ht(i,{issueKey:n,runId:e,title:Ee.length?`TEST.md commands failing at PR (${Ee.length} of ${Ne.length})`:"TEST.md failures fixed by same-session retry",detail:Ne.map(ie=>`${ie.exitCode===0?"PASS":"FAIL"} ${ie.command}`).join(`
866
866
  `)+(pn?`
867
- ${pn}`:"")})}}}let F=await Tr(s),z=vt(F);if(!z){let he=`origin "${F}" is not a GitHub remote - implement mode supports GitHub only`;j("error",he),await Mt(k,n,e,w,he),B("failed",{error:he,...D});return}let oe=await Ve(s),Z=Kh($),fe=(P?Bl(P):null)??Bl($);try{await ep({gitDir:s,ownerRepo:z,runId:e,issueKey:n,issueSummary:r,agentConfigDir:t.agentConfigDir,branch:o,baseBranch:l,jiraTransition:c,jiraTransitionOnMerge:u,requireApproval:p,doneLabel:f,failedLabel:w,repoName:v,jira:k,cfg:x,actorEmail:E,mergeOnApprove:V,mergeMethod:Y,autoMerge:b,summary:Z,prSummary:fe??void 0,cost:y,testReport:I,failedTests:K,testsPassed:U,testsTotal:W,goLiveDraft:(P?qh(P):null)??qh($)??void 0,emit:j,setStatus:B})}catch(he){let He=he instanceof Error?he.message:String(he);So({runId:e,issueKey:n,issueSummary:r,mergeOnApprove:V,mergeMethod:Y,autoMerge:b,repoName:v,baseRepoPath:i,branch:o,baseBranch:l,headSha:oe,requireApproval:p,doneLabel:f,failedLabel:w,jiraTransition:c,jiraTransitionOnMerge:u,actorEmail:E,resultSummary:Z,prSummary:fe??"",costUsd:y.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),j("error",`Run failed: ${He}`),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 Mt(k,n,e,w,`${He}
867
+ ${pn}`:"")})}}}let F=await Tr(s),z=vt(F);if(!z){let he=`origin "${F}" is not a GitHub remote - implement mode supports GitHub only`;j("error",he),await Mt(k,n,e,w,he),B("failed",{error:he,...D});return}let oe=await Ve(s),Z=Kh(P),fe=(A?Bl(A):null)??Bl(P);try{await ep({gitDir:s,ownerRepo:z,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:k,cfg:E,actorEmail:I,mergeOnApprove:V,mergeMethod:Y,autoMerge:b,summary:Z,prSummary:fe??void 0,cost:y,testReport:x,failedTests:K,testsPassed:U,testsTotal:W,goLiveDraft:(A?qh(A):null)??qh(P)??void 0,emit:j,setStatus:B})}catch(he){let He=he instanceof Error?he.message:String(he);So({runId:e,issueKey:n,issueSummary:r,mergeOnApprove:V,mergeMethod:Y,autoMerge:b,repoName:v,baseRepoPath:i,branch:o,baseBranch:l,headSha:oe,requireApproval:p,doneLabel:f,failedLabel:w,jiraTransition:c,jiraTransitionOnMerge:d,actorEmail:I,resultSummary:Z,prSummary:fe??"",costUsd:y.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),j("error",`Run failed: ${He}`),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 Mt(k,n,e,w,`${He}
868
868
 
869
- The agent's commit survived on the runner - "Retry push" on the dashboard's run page re-pushes it without a new agent run.`),B("failed",{error:He,retryAvailable:!0,...y})}}var Sv={costUsd:0,inputTokens:0,outputTokens:0};async function Tv(t){let{runId:e,issueKey:n,worktreePath:r,baseBranch:s,fixSession:i,cfg:o,failed:l,emit:c,sendUsage:u,baseCost:p}=t,f=Ye(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:Sv}}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 Ve(r),v=await Es(e,f,{repoPath:r,prompt:fv(l),timeoutSeconds:i.timeoutSeconds,bin:Je(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,V)=>c(C,V),onUsage:u?C=>u({...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),k={costUsd:v.costUsd,inputTokens:v.inputTokens,outputTokens:v.outputTokens};if(v.cancelled)return{outcome:"cancelled",cost:k};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:k}}if(ci(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:k}}let x=await ms(r);for(let C of x.refused)c("warn",`${Xt} entry refused: ${C}`);try{await _r(r,`${n}: fix failing TEST.md commands
869
+ The agent's commit survived on the runner - "Retry push" on the dashboard's run page re-pushes it without a new agent run.`),B("failed",{error:He,retryAvailable:!0,...y})}}var Sv={costUsd:0,inputTokens:0,outputTokens:0};async function Tv(t){let{runId:e,issueKey:n,worktreePath:r,baseBranch:s,fixSession:i,cfg:o,failed:l,emit:c,sendUsage:d,baseCost:p}=t,f=Ye(i.agent);if(!f?.capabilities.sessionResume){let $=`No automatic fix attempt: the ${i.agent||"configured"} adapter cannot resume sessions.`;return c("info",$),{outcome:"skipped",note:$,cost:Sv}}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 Ve(r),v=await Is(e,f,{repoPath:r,prompt:fv(l),timeoutSeconds:i.timeoutSeconds,bin:Je(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:($,V)=>c($,V),onUsage:d?$=>d({...$,inputTokens:p.inputTokens+$.inputTokens,outputTokens:p.outputTokens+$.outputTokens,costUsd:$.costUsd===void 0?void 0:p.costUsd+$.costUsd}):void 0},c),k={costUsd:v.costUsd,inputTokens:v.inputTokens,outputTokens:v.outputTokens};if(v.cancelled)return{outcome:"cancelled",cost:k};if(!v.ok){let $=`One automatic fix attempt did not complete (${v.error??"agent error"}) - the results above are from the original work.`;return c("warn",$),{outcome:"agent_failed",note:$,cost:k}}if(ci(v.resultText)){let $="One automatic fix attempt asked for human input instead of fixing - the original commit ships unchanged; answer on the PR instead.";return c("warn",$),{outcome:"agent_failed",note:$,cost:k}}let E=await ms(r);for(let $ of E.refused)c("warn",`${Xt} entry refused: ${$}`);try{await _r(r,`${n}: fix failing TEST.md commands
870
870
 
871
- Allwright run ${e} (automatic test-fix attempt)`)}catch{let C=`An automatic fix attempt concluded no code change was warranted: ${Nr(v.resultText)}`;return c("info",C),{outcome:"no_changes",note:C,cost:k}}let E=await An(r,s);if(!E.ok){await gs(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:k}}return{outcome:"committed",note:`Fix attempt: ${Nr(v.resultText)}`,resultText:v.resultText,cost:k}}async function ep(t){let{gitDir:e,ownerRepo:n,runId:r,issueKey:s,issueSummary:i,mergeOnApprove:o,mergeMethod:l,autoMerge:c,branch:u,baseBranch:p,jiraTransition:f,jiraTransitionOnMerge:w,requireApproval:v,doneLabel:k,failedLabel:x,repoName:E,jira:C,cfg:V,actorEmail:Y,summary:b,prSummary:$,cost:D,testReport:j,emit:B,setStatus:d}=t;B("info",`Pushing ${u} to origin`),await Sr(e,u);let m=await lo(e,u),I=`${$?.trim()?`${$.trim()}
871
+ Allwright run ${e} (automatic test-fix attempt)`)}catch{let $=`An automatic fix attempt concluded no code change was warranted: ${Nr(v.resultText)}`;return c("info",$),{outcome:"no_changes",note:$,cost:k}}let I=await An(r,s);if(!I.ok){await gs(r,w);let $=I.forbidden.length?`An automatic fix attempt touched protected paths (${I.forbidden.slice(0,3).join(", ")}) and was discarded - the results above are from the original work.`:"An automatic fix attempt pushed the diff past the safety limits and was discarded - the results above are from the original work.";return c("warn",$),{outcome:"reverted",note:$,cost:k}}return{outcome:"committed",note:`Fix attempt: ${Nr(v.resultText)}`,resultText:v.resultText,cost:k}}async function ep(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:k,failedLabel:E,repoName:I,jira:$,cfg:V,actorEmail:Y,summary:b,prSummary:P,cost:D,testReport:j,emit:B,setStatus:u}=t;B("info",`Pushing ${d} to origin`),await Sr(e,d);let m=await lo(e,d),x=`${P?.trim()?`${P.trim()}
872
872
 
873
873
  <details>
874
874
  <summary>Technical details</summary>
@@ -879,13 +879,13 @@ ${b}
879
879
 
880
880
  ---
881
881
  Jira: ${new URL(`/browse/${s}`,V.jira?.baseUrl??"").toString()}
882
- _Allwright implement run \`${r}\` \xB7 cost $${D.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._");B("info","Opening pull request");let P=po(ke()??V,E,Y);P.source==="user"&&B("info",`PR will be authored with ${Y}'s own GitHub token`);let U=await new qe(P.token).createPullRequest(n.owner,n.repo,{title:`${s}: ${i}`.slice(0,250),head:u,base:p,body:I});B("info",`PR ready: ${U.url}`),Mh({runId:r,issueKey:s,repoName:E,owner:n.owner,repo:n.repo,prNumber:U.number,prUrl:U.url,jiraTransitionOnMerge:w??"",createdAt:new Date().toISOString()}),d("posting",D);let W={nextDecisionSeq:1e5,runId:r,issueKey:s,repoName:E,owner:n.owner,repo:n.repo,prNumber:U.number,prUrl:U.url,branch:u,headSha:m,doneLabel:k,failedLabel:x,jiraTransition:f,mergeOnApprove:o,mergeMethod:l,autoMerge:c,agentConfigDir:t.agentConfigDir};if(v)St(W),await C.addComment(s,`**Allwright opened a pull request for review.**
882
+ _Allwright implement run \`${r}\` \xB7 cost $${D.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._");B("info","Opening pull request");let A=po(ke()??V,I,Y);A.source==="user"&&B("info",`PR will be authored with ${Y}'s own GitHub token`);let U=await new qe(A.token).createPullRequest(n.owner,n.repo,{title:`${s}: ${i}`.slice(0,250),head:d,base:p,body:x});B("info",`PR ready: ${U.url}`),Mh({runId:r,issueKey:s,repoName:I,owner:n.owner,repo:n.repo,prNumber:U.number,prUrl:U.url,jiraTransitionOnMerge:w??"",createdAt:new Date().toISOString()}),u("posting",D);let W={nextDecisionSeq:1e5,runId:r,issueKey:s,repoName:I,owner:n.owner,repo:n.repo,prNumber:U.number,prUrl:U.url,branch:d,headSha:m,doneLabel:k,failedLabel:E,jiraTransition:f,mergeOnApprove:o,mergeMethod:l,autoMerge:c,agentConfigDir:t.agentConfigDir};if(v)St(W),await $.addComment(s,`**Allwright opened a pull request for review.**
883
883
 
884
884
  PR: ${U.url}
885
885
 
886
- 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}\`)`),d("awaiting_approval",{...D,prUrl:U.url,headSha:m,resultSummary:Nr($?.trim()||b),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}:{}}),B("info",`Awaiting approval on the dashboard \xB7 $${D.costUsd.toFixed(4)}`);else{if(c){B("info",`Auto-merging PR #${U.number} (${l})`);let z=ze(V,E),oe=z?await new qe(z).mergePullRequest(n.owner,n.repo,U.number,l,{sha:m,title:`${s} (#${U.number})`}):{merged:!1,reason:"no GitHub token applies to this repo"};oe.merged?B("info",`PR #${U.number} merged`):(B("warn",`Auto-merge did not go through - ${oe.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 - ${oe.reason}
886
+ 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}\`)`),u("awaiting_approval",{...D,prUrl:U.url,headSha:m,resultSummary:Nr(P?.trim()||b),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}:{}}),B("info",`Awaiting approval on the dashboard \xB7 $${D.costUsd.toFixed(4)}`);else{if(c){B("info",`Auto-merging PR #${U.number} (${l})`);let z=ze(V,I),oe=z?await new qe(z).mergePullRequest(n.owner,n.repo,U.number,l,{sha:m,title:`${s} (#${U.number})`}):{merged:!1,reason:"no GitHub token applies to this repo"};oe.merged?B("info",`PR #${U.number} merged`):(B("warn",`Auto-merge did not go through - ${oe.reason}. The PR stays open.`),await $.addComment(s,`**Allwright:** the work is done and the PR is open, but auto-merge did not go through - ${oe.reason}
887
887
 
888
- PR: ${U.url}`))}let F=(ke()??V).repos[E]?.path;F&&ei(F,s)&&ht(F,{issueKey:s,runId:r,title:"shipped after earlier failure",detail:`PR ${U.url} merged/opened straight-through.`}),await tp({jira:C,issueKey:s},W,B),d("succeeded",{...D,prUrl:U.url,headSha:m,resultSummary:Nr($?.trim()||b),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}:{}}),B("info",`Run succeeded \xB7 ${U.url} \xB7 $${D.costUsd.toFixed(4)}`)}}async function tp(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.**
888
+ PR: ${U.url}`))}let F=(ke()??V).repos[I]?.path;F&&ei(F,s)&&ht(F,{issueKey:s,runId:r,title:"shipped after earlier failure",detail:`PR ${U.url} merged/opened straight-through.`}),await tp({jira:$,issueKey:s},W,B),u("succeeded",{...D,prUrl:U.url,headSha:m,resultSummary:Nr(P?.trim()||b),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}:{}}),B("info",`Run succeeded \xB7 ${U.url} \xB7 $${D.costUsd.toFixed(4)}`)}}async function tp(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.**
889
889
 
890
890
  PR: ${e.prUrl}`:`**Allwright: the change is approved, but NOT merged yet.**
891
891
 
@@ -895,18 +895,18 @@ This rule is set to "my team merges on GitHub", so Allwright deliberately did no
895
895
 
896
896
  Note: ${r}`:"")+`
897
897
 
898
- (run \`${e.runId}\`)`),await t.jira.editLabels(e.issueKey,{add:[e.doneLabel],remove:[Se.NEEDS_INPUT_LABEL]}),r}async function li(t,e,n){let r=xs(e);if(!r){g.warn(`run.approved for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:s,setStatus:i}=sp(t,e);try{let o=ze(ke()??t.cfg,r.repoName);if(!o)throw new Error("GitHub token missing on this runner");let l=new qe(o);s("info",`Approval received for ${r.issueKey} - verifying PR state`);let c=await l.getPullRequest(r.owner,r.repo,r.prNumber);if(!c)throw new Error(`PR #${r.prNumber} no longer exists on GitHub`);if(c.state==="closed"&&!c.merged)throw new Error(`PR #${r.prNumber} was closed on GitHub without merging`);let u=n??r.headSha;if(c.state==="open"&&c.headSha!==u){let p=`PR #${r.prNumber} changed since review started (${u.slice(0,7)} \u2192 ${c.headSha.slice(0,7)}) - approval not applied. Re-review the PR and approve again.`;s("warn",p),await t.jiraFor(r.repoName??"").addComment(r.issueKey,`**Allwright:** ${p}`),i("awaiting_approval",{prUrl:r.prUrl,headSha:c.headSha,resultSummary:p});return}if(r.mergeOnApprove&&c.state==="open"&&!c.merged){s("info",`Merging PR #${r.prNumber} (${r.mergeMethod})`);let p=await l.mergePullRequest(r.owner,r.repo,r.prNumber,r.mergeMethod,{sha:u,title:`${r.issueKey} (#${r.prNumber})`});if(!p.merged){let f=`Approved, but the merge did not go through - ${p.reason}`;s("warn",f),await t.jiraFor(r.repoName??"").addComment(r.issueKey,`**Allwright:** ${f}
898
+ (run \`${e.runId}\`)`),await t.jira.editLabels(e.issueKey,{add:[e.doneLabel],remove:[Se.NEEDS_INPUT_LABEL]}),r}async function li(t,e,n){let r=xs(e);if(!r){g.warn(`run.approved for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:s,setStatus:i}=sp(t,e);try{let o=ze(ke()??t.cfg,r.repoName);if(!o)throw new Error("GitHub token missing on this runner");let l=new qe(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}
899
899
 
900
900
  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&&ei(p,r.issueKey)&&ht(p,{issueKey:r.issueKey,runId:e,title:"shipped after earlier failure",detail:`PR ${r.prUrl} approved and completed.`})}await tp({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.'),Ar(e)}catch(o){let l=o instanceof Error?o.message:String(o);s("error",`Approval handling failed: ${l}`),await ip(t,r,l),i("failed",{error:l}),Ar(e)}}async function np(t,e){let n=xs(e);if(!n){g.warn(`run.rejected for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:r,setStatus:s}=sp(t,e);try{let i=ze(ke()??t.cfg,n.repoName);if(!i)throw new Error("GitHub token missing on this runner");let o=new qe(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.**
901
901
 
902
- 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"),Ar(e)}catch(i){let o=i instanceof Error?i.message:String(i);r("error",`Rejection handling failed: ${o}`),await ip(t,n,o),s("failed",{error:o}),Ar(e)}}async function rp(t,e){let n=To(e);if(!n){g.warn(`run.retryPush for ${e}: no retry record (already pushed, or invalidated?)`);let{emit:l,setStatus:c,sendUsage:u}=$r(e,t.transport,1e5);l("error","Retry push requested, but this runner holds no retry record for the run - it was already used or never saved. Re-run the ticket instead."),c("failed",{retryAvailable:!1});return}let{emit:r,setStatus:s,sendUsage:i,nextSeq:o}=$r(e,t.transport,n.nextLogSeq);try{let l=await lo(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.`),Ul(e),s("failed",{retryAvailable:!1});return}let c=await Tr(n.baseRepoPath),u=vt(c);if(!u)throw new Error(`origin "${c}" is not a GitHub remote`);r("info",`Retry push for ${n.issueKey}: branch ${n.branch} at ${n.headSha.slice(0,7)}`);let p=t.jiraFor(n.repoName);await ep({gitDir:n.baseRepoPath,ownerRepo:u,runId:n.runId,issueKey:n.issueKey,issueSummary:n.issueSummary,branch:n.branch,baseBranch:n.baseBranch,jiraTransition:n.jiraTransition,jiraTransitionOnMerge:n.jiraTransitionOnMerge,requireApproval:n.requireApproval,mergeOnApprove:n.mergeOnApprove??!1,mergeMethod:n.mergeMethod??"squash",autoMerge:n.autoMerge??!1,doneLabel:n.doneLabel,failedLabel:n.failedLabel,repoName:n.repoName,jira:p,cfg:ke()??t.cfg,actorEmail:n.actorEmail,summary:n.resultSummary,prSummary:n.prSummary||void 0,cost:{costUsd:n.costUsd},emit:r,setStatus:s}),Ul(e),await p.editLabels(n.issueKey,{remove:[n.failedLabel]}).catch(()=>{})}catch(l){let c=l instanceof Error?l.message:String(l);r("error",`Retry push failed: ${c}`),So({...n,nextLogSeq:o()}),s("failed",{error:c,retryAvailable:!0})}}function sp(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 ip(t,e,n){try{await t.jiraFor(e.repoName??"").addComment(e.issueKey,`**Allwright could not complete the approval decision.**
902
+ 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"),Ar(e)}catch(i){let o=i instanceof Error?i.message:String(i);r("error",`Rejection handling failed: ${o}`),await ip(t,n,o),s("failed",{error:o}),Ar(e)}}async function rp(t,e){let n=To(e);if(!n){g.warn(`run.retryPush for ${e}: no retry record (already pushed, or invalidated?)`);let{emit:l,setStatus:c,sendUsage:d}=$r(e,t.transport,1e5);l("error","Retry push requested, but this runner holds no retry record for the run - it was already used or never saved. Re-run the ticket instead."),c("failed",{retryAvailable:!1});return}let{emit:r,setStatus:s,sendUsage:i,nextSeq:o}=$r(e,t.transport,n.nextLogSeq);try{let l=await lo(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.`),Ul(e),s("failed",{retryAvailable:!1});return}let c=await Tr(n.baseRepoPath),d=vt(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 ep({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}),Ul(e),await p.editLabels(n.issueKey,{remove:[n.failedLabel]}).catch(()=>{})}catch(l){let c=l instanceof Error?l.message:String(l);r("error",`Retry push failed: ${c}`),So({...n,nextLogSeq:o()}),s("failed",{error:c,retryAvailable:!0})}}function sp(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 ip(t,e,n){try{await t.jiraFor(e.repoName??"").addComment(e.issueKey,`**Allwright could not complete the approval decision.**
903
903
 
904
904
  Error: ${n.slice(0,800)}
905
905
 
906
906
  PR: ${e.prUrl}
907
907
  (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 xv(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?Pr(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(`
908
908
  `)+(t.more?`
909
- - (\u2026 ${t.more} more file(s))`:""):"(the commit touched no files this checkout can list)";return jn.REVISION_PROMPT+`
909
+ - (\u2026 ${t.more} more file(s))`:""):"(the commit touched no files this checkout can list)";return On.REVISION_PROMPT+`
910
910
 
911
911
  ALREADY SHIPPED: commit ${t.sha.slice(0,10)} - ${t.subject}
912
912
  Files it touched, your reading list:
@@ -920,27 +920,27 @@ ${i.body}`),r=[],s=0;for(let i=n.length-1;i>=0;i--){if(s+=n[i].length+6,s>e){r.u
920
920
 
921
921
  ${t}
922
922
 
923
- 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 ${Se.NEEDS_INPUT_MARKER} marker).`}function Iv(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 Ev(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(Se.NEEDS_INPUT_MARKER)}function ci(t){let e=t.trim().split(`
924
- `);for(let n=0;n<e.length;n++){if(!Ev(e[n]))continue;let r=e.slice(n+1).join(`
923
+ 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 ${Se.NEEDS_INPUT_MARKER} marker).`}function Ev(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 Iv(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(Se.NEEDS_INPUT_MARKER)}function ci(t){let e=t.trim().split(`
924
+ `);for(let n=0;n<e.length;n++){if(!Iv(e[n]))continue;let r=e.slice(n+1).join(`
925
925
  `).trim();if(r)return r}return null}function Rv(t){let n=[...t.matchAll(new RegExp(`\`\`\`${Se.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(`\`\`\`${Se.NEEDS_INPUT_ASK_FENCE}\\s*\\n[\\s\\S]*?\`\`\``,"g"),"").trim()||t.trim(),options:r}}async function ii(t,e,n,r,s){let{questions:i,options:o}=Rv(e);n("info",`Claude needs more information - posting questions to ${t.issueKey}`),await t.jira.addComment(t.issueKey,`**${Se.NEEDS_INPUT_COMMENT_MARKER} before it can continue.**
926
926
 
927
927
  ${i}
928
928
 
929
- 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:[Se.NEEDS_INPUT_LABEL]}),Lh({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:Nr(i),inputQuestions:i.slice(0,4e3),inputOptions:o}),n("info",`Waiting for an answer on ${t.issueKey} (label "${Se.NEEDS_INPUT_LABEL}") or on this run page`+(o.length?` - ${o.length} suggested answer(s) offered`:""))}async function ap(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 Mt(t,e.issueKey,e.runId,e.failedLabel,i),Ot(e.runId),r("failed",{error:i,...s})}async function Is(t,e){await Mt(t.jira,t.issueKey,t.runId,t.rule.trigger.failedLabel,e)}async function Mt(t,e,n,r,s){try{await t.addComment(e,`**Allwright run failed.**
929
+ 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:[Se.NEEDS_INPUT_LABEL]}),Lh({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:Nr(i),inputQuestions:i.slice(0,4e3),inputOptions:o}),n("info",`Waiting for an answer on ${t.issueKey} (label "${Se.NEEDS_INPUT_LABEL}") or on this run page`+(o.length?` - ${o.length} suggested answer(s) offered`:""))}async function ap(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 Mt(t,e.issueKey,e.runId,e.failedLabel,i),jt(e.runId),r("failed",{error:i,...s})}async function Es(t,e){await Mt(t.jira,t.issueKey,t.runId,t.rule.trigger.failedLabel,e)}async function Mt(t,e,n,r,s){try{await t.addComment(e,`**Allwright run failed.**
930
930
 
931
931
  Error: ${s.slice(0,800)}
932
932
 
933
933
  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:[Se.NEEDS_INPUT_LABEL]})}catch(i){g.error(`could not post failure comment to ${e}: ${i}`)}}function Kh(t){let e=t.split(/\n##\s*(?:PR summary|Go-live draft)\s*\n/i)[0],n=/##\s*Summary of changes\s*\n([\s\S]*)$/i.exec(e);return(n?n[1]:e).trim().slice(0,8e3)||"(no summary provided)"}function Bl(t){let e=/##\s*PR summary\s*\n([\s\S]*?)(?=\n##\s|$)/i.exec(t),n=e?e[1].trim():"";return n?n.slice(0,2e3):null}function Nr(t){for(let e of t.split(`
934
- `)){let n=e.replace(/^#+\s*/,"").trim();if(n.length>10)return n.slice(0,200)}return t.slice(0,200)}var Rs=R(require("node:fs"),1);var jr=R(require("node:fs"),1),Zl=R(require("node:os"),1),Or=R(require("node:path"),1);function Av(){try{return Zl.default.userInfo().username}catch{return"the user the runner service runs as"}}function Cv(t,e){let n=Or.default.join(t,"apps","api","prisma","manual"),r=Or.default.join(t,"prisma","manual");for(let s of[n,r]){let i;try{i=jr.default.readdirSync(s).filter(o=>o.endsWith(".sql")).sort()}catch{continue}for(let o of i.reverse())try{let l=jr.default.readFileSync(Or.default.join(s,o),"utf8");if(new RegExp(`"${e}"`,"i").test(l))return o}catch{}}return null}function Vl(t,e){let n=t.slice(-4e3),r=Av(),s=e?.cwd?` -C ${e.cwd}`:"",i=/column "([^"]+)" of relation "([^"]+)" does not exist/i.exec(n)??/column ([\w.]+) does not exist/i.exec(n)??/The column `?([\w.]+)`? does not exist in the current database/i.exec(n)??/relation "([^"]+)" does not exist/i.exec(n);if(i){let u=(i[1]??"").split(".").pop()??"",p=e?.cwd?Cv(e.cwd,u):null;return{cause:`The code expects "${u}" in the database and the database does not have it. This is not a deploy-steps problem: a schema change shipped with the code, and the SQL that applies it is a HUMAN step by design`+(p?` - it is \`prisma/manual/${p}\`, checked in and not yet applied.`:"."),commands:p?[`cd apps/api && npx prisma db execute --file prisma/manual/${p} # dev/test database`,`cd apps/api && npx prisma db execute --url "$PROD_DATABASE_URL" --file prisma/manual/${p} # the live one`]:[`ls apps/api/prisma/manual/ # find the migration that adds "${u}"`,"cd apps/api && npx prisma db execute --file prisma/manual/<that file>"],note:"Apply it to EVERY database the code talks to - the test database and the live one are usually different, and applying only one turns a red build into a green build that breaks at runtime. Then re-run the deploy."}}let o=/\/usr\/bin\/env: ['\u2018]?(node|npm)['\u2019]?: No such file or directory/i.exec(n);if(o){let u="";try{let p=Or.default.join(Zl.default.homedir(),".nvm","versions","node"),f=jr.default.readdirSync(p).sort();f.length&&(u=Or.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'
934
+ `)){let n=e.replace(/^#+\s*/,"").trim();if(n.length>10)return n.slice(0,200)}return t.slice(0,200)}var Rs=R(require("node:fs"),1);var Or=R(require("node:fs"),1),Zl=R(require("node:os"),1),jr=R(require("node:path"),1);function Av(){try{return Zl.default.userInfo().username}catch{return"the user the runner service runs as"}}function Cv(t,e){let n=jr.default.join(t,"apps","api","prisma","manual"),r=jr.default.join(t,"prisma","manual");for(let s of[n,r]){let i;try{i=Or.default.readdirSync(s).filter(o=>o.endsWith(".sql")).sort()}catch{continue}for(let o of i.reverse())try{let l=Or.default.readFileSync(jr.default.join(s,o),"utf8");if(new RegExp(`"${e}"`,"i").test(l))return o}catch{}}return null}function Vl(t,e){let n=t.slice(-4e3),r=Av(),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?Cv(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=jr.default.join(Zl.default.homedir(),".nvm","versions","node"),f=Or.default.readdirSync(p).sort();f.length&&(d=jr.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'
935
935
  [Service]
936
- Environment=PATH=${u||"<the bin directory holding node>"}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
937
- EOF`,"sudo systemctl daemon-reload && sudo systemctl reset-failed <your-unit> && sudo systemctl restart <your-unit>"],note:"reset-failed because a crash loop leaves a restart counter behind. If you would rather not depend on a version-numbered nvm path, install Node system-wide instead - then /usr/bin/node exists and the bare PATH is enough."}}let l=/Failed to connect to ([\w.]+) port (\d+)|connect to ([\w.]+) port (\d+) failed|Connection refused/i.exec(n);if(l){let u=l[2]??l[4]??"",f=(jr.default.existsSync("/etc/systemd/system")?jr.default.readdirSync("/etc/systemd/system").filter(w=>w.endsWith(".service")).filter(w=>{try{let v=jr.default.readFileSync(Or.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"}${u?`:${u}`:""}. `+(f?`The service that runs this checkout is "${f}" - a restart moves its start timestamp even when it dies a second later, so "a restart really happened" does not mean it stayed up. Either it is crash-looping, or it bound a DIFFERENT port than this check expects.`:"No systemd unit on this machine references this checkout, so nothing here is keeping the app alive between deploys."),commands:f?[`systemctl status ${f} --no-pager -l # active (running), or restarting in a loop?`,`journalctl -u ${f} -n 40 --no-pager # the crash itself`,`systemctl show ${f} -p Environment --value # the PORT it was actually given`,"ss -ltnp | grep -E 'node|next' # what it really bound, if anything"]:["ss -ltnp | grep -E 'node|next' # is anything serving this app at all?"],note:f?"If the port differs, change either the unit's PORT or this check - they must be the same number. If it crash-loops, the journal's last lines are the reason; a wrong ExecStart path shows up as status=203/EXEC.":"Until something supervises this app, a deploy has nothing to restart and nothing survives a reboot."}}if(/could not read (Username|Password) for/i.test(n)||/Authentication failed for .*https/i.test(n)||/fatal: Authentication failed/i.test(n))return{cause:`git needs a GitHub credential for the account this deploy runs as (${r}) and has none. It tried to ask, found no terminal, and gave up. Allwright's own GitHub token is NOT used here: deploy steps are plain shell, so they see only this machine's git config - which is why the same repo can push fine from Allwright and still fail this step.`,commands:[`sudo -u ${r} git${s} ls-remote origin >/dev/null && echo "AUTH OK" || echo "AUTH FAIL"`,`sudo -u ${r} gh auth setup-git # if you signed in with the gh CLI - its login does not reach git by itself`,`sudo -u ${r} git config --global credential.helper store # then one manual 'git fetch' to save the token`],note:`Or switch the checkout to SSH and give ${r} a deploy key: git${s} remote set-url origin git@github.com:OWNER/REPO.git. Never paste a token into a deploy step - it ends up in run logs and screenshots.`};if(/Permission denied \(publickey/i.test(n))return{cause:`SSH could not authenticate to the git host as ${r}. The key either does not exist for that account, or is not the one registered with the repository.`,commands:[`sudo -u ${r} ssh -T git@github.com # expect "successfully authenticated"`,`sudo -u ${r} ls -l ~/.ssh/`],note:"Add that account's public key as a deploy key on the repository (read-only is enough to fetch)."};if(/Host key verification failed/i.test(n))return{cause:`The git host is not in ${r}'s known_hosts, and ssh will not accept it unattended.`,commands:[`sudo -u ${r} ssh-keyscan github.com >> ~/.ssh/known_hosts`],note:"Run it as that user - a known_hosts entry under your own account does nothing for the service."};let c=/(?:^|\n)(?:bash: )?([\w.-]+): command not found/i.exec(n);return c?{cause:`"${c[1]}" is not on the PATH of the account this deploy runs as (${r}). A tool installed through nvm, asdf or a shell profile usually is not: the service starts with a bare environment, not your login shell.`,commands:[`sudo -u ${r} which ${c[1]} || echo "not on this account's PATH"`,`command -v ${c[1]} # where YOUR shell finds it`],note:"Either install it system-wide, or use the absolute path in the step - the path your own shell resolves is not the one the deploy gets."}:/EACCES|Permission denied(?!\s*\(publickey)/i.test(n)?{cause:`A path in this step is not writable by the account the deploy runs as (${r}).`,commands:[`sudo -u ${r} test -w ${e?.cwd??"<the path>"} && echo writable || echo "NOT writable"`],note:"Fix the ownership of that path rather than running the deploy as root - a root-owned build directory breaks the next deploy the other way."}:null}function lp(t){return t?`
936
+ Environment=PATH=${d||"<the bin directory holding node>"}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
937
+ 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=(Or.default.existsSync("/etc/systemd/system")?Or.default.readdirSync("/etc/systemd/system").filter(w=>w.endsWith(".service")).filter(w=>{try{let v=Or.default.readFileSync(jr.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 lp(t){return t?`
938
938
 
939
939
  What this means: ${t.cause}
940
940
  Run these ON THE DEPLOY MACHINE:
941
941
  `+t.commands.map(e=>` ${e}`).join(`
942
942
  `)+`
943
- ${t.note}`:""}var Mr=R(require("node:path"),1),jo=require("node:child_process"),nc=R(require("node:readline"),1),rc=require("node:crypto"),Dr=R(xe(),1);rs();$e();var Oo=R(xe(),1);Nt();_t();xr();Po();var yp="";function bp(t){yp=(t??"").trim()}function wp(){return yp}ec();en();var xp=4e3,Bv=4e3;function Ip(t,e){t("warn",`${e.length} step(s) still need YOU - Allwright deliberately did not run these:
943
+ ${t.note}`:""}var Mr=R(require("node:path"),1),Oo=require("node:child_process"),nc=R(require("node:readline"),1),rc=require("node:crypto"),Dr=R(xe(),1);rs();$e();var jo=R(xe(),1);Nt();_t();xr();Po();var yp="";function bp(t){yp=(t??"").trim()}function wp(){return yp}ec();en();var xp=4e3,Bv=4e3;function Ep(t,e){t("warn",`${e.length} step(s) still need YOU - Allwright deliberately did not run these:
944
944
  `+e.map(n=>` ${n.command}${n.why?` # ${n.why}`:""}`).join(`
945
945
  `))}function sc(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,Bv)}),s!=="agent"&&g.info(`[deploy ${t.runId}] ${i}`)},setStatus:(s,i={})=>{t.transport.send({type:"run.status",runId:t.runId,status:s,...i})}}}var Hv=/^\s*(?:ALLWRIGHT|TICKETPILOT)[-\s]MANUAL:\s*(.+)$/i;function Kv(t){let e=Hv.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 Mo(t){let{emit:e,setStatus:n}=sc(t),r=t.environment;try{let s=Gv(t);if(s){e("error",s),await pt(t,`**Allwright could not deploy to \`${r.name}\`.**
946
946
 
@@ -950,30 +950,40 @@ ${t.requestedBy?`Requested by ${t.requestedBy}. `:""}Nothing has been executed y
950
950
 
951
951
  ${i.slice(0,800)}
952
952
 
953
- (run \`${t.runId}\`)`),n("failed",{error:i})}}function Gv(t){let e=t.environment;if(!t.cfg.deploy.enabled)return"deployments are turned off on this runner. Deploy steps are shell commands, so they stay disabled until someone with access to this machine runs `allwright deploy enable`.";if(!e.steps.length)return`environment "${e.name}" has no deploy steps configured - add them in the dashboard first`;if(e.promotionMode==="merge_and_deploy"&&!e.branch)return`environment "${e.name}" is set to merge-and-deploy but has no branch configured`;if(e.useDedicatedCheckout&&!e.branch)return`environment "${e.name}" wants a dedicated checkout but has no branch configured`;let n=Zt(t.cfg,t.project.repoName,e.name),r=new Set,s=new Set;for(let l of e.steps){for(let c of l.run.matchAll(/(?:^|[\s;&|(])([A-Za-z_][A-Za-z0-9_]*)=/g))r.add(c[1]);for(let c of l.run.matchAll(/\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/g))s.add(c[1])}let i=e.requiredSecrets.filter(l=>!s.has(l));i.length&&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 Cp(t,e,n){let r=t.environment,s=Zt(t.cfg,t.project.repoName,r.name),i=ic(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 b=Ue(t.cfg,t.project,"assist"),$="error"in b?{ok:!1,error:b.error}:await Ss({projectId:t.project.id,repoPath:t.repoPath,role:r.auditBeforeDeploy,scope:{kind:"repo",ref:""},model:"",agent:b,jira:t.jira});if(!$.ok)e("warn",`Pre-deploy audit could not run: ${$.error} - deploying anyway (advisory)`);else if(!$.audit.findings.length)e("info","Pre-deploy audit: no findings \u2713");else{let D={};for(let j of $.audit.findings)D[j.severity]=(D[j.severity]??0)+1;e("warn",`Pre-deploy audit: ${$.audit.findings.length} finding(s) (`+Object.entries(D).map(([j,B])=>`${B} ${j}`).join(", ")+") - full report on the Audits page. Deploying anyway (advisory).");for(let j of $.audit.findings.slice(0,5))e("warn",` [${j.severity}] ${j.title} - ${j.evidence[0]?.file??""}`)}}catch(b){e("warn",`Pre-deploy audit crashed: ${b instanceof Error?b.message:String(b)} - deploying anyway`)}}if(r.requireSyncCheck){if(!r.previousEnvBranch||!r.branch){let $=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",$),await pt(t,`**Allwright refused to deploy to \`${r.name}\`.**
953
+ (run \`${t.runId}\`)`),n("failed",{error:i})}}function Gv(t){let e=t.environment;if(!t.cfg.deploy.enabled)return"deployments are turned off on this runner. Deploy steps are shell commands, so they stay disabled until someone with access to this machine runs `allwright deploy enable`.";if(!e.steps.length)return`environment "${e.name}" has no deploy steps configured - add them in the dashboard first`;if(e.promotionMode==="merge_and_deploy"&&!e.branch)return`environment "${e.name}" is set to merge-and-deploy but has no branch configured`;if(e.useDedicatedCheckout&&!e.branch)return`environment "${e.name}" wants a dedicated checkout but has no branch configured`;let n=Zt(t.cfg,t.project.repoName,e.name),r=new Set,s=new Set;for(let l of e.steps){for(let c of l.run.matchAll(/(?:^|[\s;&|(])([A-Za-z_][A-Za-z0-9_]*)=/g))r.add(c[1]);for(let c of l.run.matchAll(/\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/g))s.add(c[1])}let i=e.requiredSecrets.filter(l=>!s.has(l));i.length&&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 Cp(t,e,n){let r=t.environment,s=Zt(t.cfg,t.project.repoName,r.name),i=ic(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 b=Ue(t.cfg,t.project,"assist"),P="error"in b?{ok:!1,error:b.error}:await Ss({projectId:t.project.id,repoPath:t.repoPath,role:r.auditBeforeDeploy,scope:{kind:"repo",ref:""},model:"",agent:b,jira:t.jira});if(!P.ok)e("warn",`Pre-deploy audit could not run: ${P.error} - deploying anyway (advisory)`);else if(!P.audit.findings.length)e("info","Pre-deploy audit: no findings \u2713");else{let D={};for(let j of P.audit.findings)D[j.severity]=(D[j.severity]??0)+1;e("warn",`Pre-deploy audit: ${P.audit.findings.length} finding(s) (`+Object.entries(D).map(([j,B])=>`${B} ${j}`).join(", ")+") - full report on the Audits page. Deploying anyway (advisory).");for(let j of P.audit.findings.slice(0,5))e("warn",` [${j.severity}] ${j.title} - ${j.evidence[0]?.file??""}`)}}catch(b){e("warn",`Pre-deploy audit crashed: ${b instanceof Error?b.message:String(b)} - deploying anyway`)}}if(r.requireSyncCheck){if(!r.previousEnvBranch||!r.branch){let P=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",P),await pt(t,`**Allwright refused to deploy to \`${r.name}\`.**
954
954
 
955
- ${$}
955
+ ${P}
956
956
 
957
- (run \`${t.runId}\`)`),n("failed",{error:$,errorKind:"guard"});return}let b=await Zv(t,e);if(b){await pt(t,b.comment),n("failed",{error:b.error,...b.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 il({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 b=tn(r.ticketBranchTemplate,{issueKey:t.issueKey});e("info",`Merging "${b}" into "${r.branch}"`);let $=await ol(c,b,`Deploy ${t.issueKey} to ${r.name}
957
+ (run \`${t.runId}\`)`),n("failed",{error:P,errorKind:"guard"});return}let b=await Zv(t,e);if(b){await pt(t,b.comment),n("failed",{error:b.error,...b.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 il({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 b=tn(r.ticketBranchTemplate,{issueKey:t.issueKey});e("info",`Merging "${b}" into "${r.branch}"`);let P=await ol(c,b,`Deploy ${t.issueKey} to ${r.name}
958
958
 
959
- Allwright run ${t.runId}`);if(!$.ok){e("error",$.reason??"merge failed"),await pt(t,`**Allwright deploy to \`${r.name}\` failed before running anything.**
959
+ Allwright run ${t.runId}`);if(!P.ok){e("error",P.reason??"merge failed"),await pt(t,`**Allwright deploy to \`${r.name}\` failed before running anything.**
960
960
 
961
- ${$.reason}`),n("failed",{error:$.reason});return}$.alreadyMerged?e("info",`"${b}" is already in "${r.branch}" - nothing to merge`):(e("info",`Pushing "${r.branch}" to origin`),await ul(c,r.branch))}let p=await Ve(c).catch(()=>"");p&&e("info",`Deploying commit ${p.slice(0,10)}`);let f=Vv(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,k=r.timeoutSeconds*1e3,x=Zh(t.runId),E=()=>x.signal.aborted;try{for(let[b,$]of r.steps.entries()){if(E()){let B=`stopped from the dashboard during step ${b+1} - nothing further ran`;e("error",B),n("failed",{error:B,errorKind:"guard",deployedRef:p});return}let D=k-(Date.now()-o);if(D<=0){let B=`deploy exceeded its ${r.timeoutSeconds}s budget before step ${b+1}`;e("error",B),await pt(t,`**Allwright deploy to \`${r.name}\` timed out.**
961
+ ${P.reason}`),n("failed",{error:P.reason});return}P.alreadyMerged?e("info",`"${b}" is already in "${r.branch}" - nothing to merge`):(e("info",`Pushing "${r.branch}" to origin`),await ul(c,r.branch))}let p=await Ve(c).catch(()=>"");p&&e("info",`Deploying commit ${p.slice(0,10)}`);let f=Vv(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,k=r.timeoutSeconds*1e3,E=Zh(t.runId),I=()=>E.signal.aborted;try{for(let[b,P]of r.steps.entries()){if(I()){let B=`stopped from the dashboard during step ${b+1} - nothing further ran`;e("error",B),n("failed",{error:B,errorKind:"guard",deployedRef:p});return}let D=k-(Date.now()-o);if(D<=0){let B=`deploy exceeded its ${r.timeoutSeconds}s budget before step ${b+1}`;e("error",B),await pt(t,`**Allwright deploy to \`${r.name}\` timed out.**
962
962
 
963
- ${B}`),n("timed_out",{error:B,deployedRef:p});return}e("info",`\u25B6 step ${b+1}/${r.steps.length}: ${$.name}`);let j=await Yv({command:$.run,cwd:f,env:w,timeoutMs:D,signal:x.signal,onLine:(B,d)=>{v++;let m=Kv(d);m&&l.length<20&&l.push(m),v===xp&&e("warn","(output truncated - deploy log limit reached)"),!(v>=xp)&&e(B,i(d))}});if(j.timedOut){let B=`step "${$.name}" hit the ${r.timeoutSeconds}s deploy budget and was killed`;e("error",B),await pt(t,`**Allwright deploy to \`${r.name}\` timed out.**
963
+ ${B}`),n("timed_out",{error:B,deployedRef:p});return}e("info",`\u25B6 step ${b+1}/${r.steps.length}: ${P.name}`);let j=await rk({command:P.run,cwd:f,env:w,timeoutMs:D,signal:E.signal,onLine:(B,u)=>{v++;let m=Kv(u);m&&l.length<20&&l.push(m),v===xp&&e("warn","(output truncated - deploy log limit reached)"),!(v>=xp)&&e(B,i(u))}});if(j.timedOut){let B=`step "${P.name}" hit the ${r.timeoutSeconds}s deploy budget and was killed`;e("error",B),await pt(t,`**Allwright deploy to \`${r.name}\` timed out.**
964
964
 
965
- ${B}`),n("timed_out",{error:B,deployedRef:p});return}if(j.code!==0){if($.continueOnError){e("warn",`step "${$.name}" exited ${j.code} - continuing (marked continue-on-error)`);continue}let B="";try{B=i(await Va(c))}catch{}let d=lp(Vl(j.tail??"",{cwd:c})),m=`step ${b+1} "${$.name}" failed with exit code ${j.code}`+(j.tail?`: ${i(j.tail)}`:"")+d+(B?`
965
+ ${B}`),n("timed_out",{error:B,deployedRef:p});return}if(j.code!==0){if(P.continueOnError){e("warn",`step "${P.name}" exited ${j.code} - continuing (marked continue-on-error)`);continue}let B="";try{B=i(await Va(c))}catch{}let u=j.failures?i(j.failures):"",m=j.tail?i(j.tail):"",y=lp(Vl(`${u}
966
+ ${m}`.trim(),{cwd:c})),x=`step ${b+1} "${P.name}" failed with exit code ${j.code}`+(u?`:
967
+ ${u}`:"")+(m?`${u?`
968
+
969
+ how the output ended:
970
+ `:": "}${m}`:"")+y+(B?`
966
971
 
967
972
  Checkout at failure:
968
- ${B}`:"");e("error",m),await pt(t,`**Allwright deploy to \`${r.name}\` failed.**
973
+ ${B}`:"");e("error",x),await pt(t,`**Allwright deploy to \`${r.name}\` failed.**
974
+
975
+ Step ${b+1} \`${P.name}\` exited ${j.code}.
969
976
 
970
- Step ${b+1} \`${$.name}\` exited ${j.code}.
977
+ `+(u?`\`\`\`
978
+ ${u}
979
+ \`\`\`
971
980
 
972
- `+(j.tail?`\`\`\`
973
- ${i(j.tail).slice(0,1200)}
981
+ `:"")+(m?`${u?`How the output ended:
982
+ `:""}\`\`\`
983
+ ${m.slice(0,1200)}
974
984
  \`\`\`
975
985
 
976
- `:"")+(d?`${d.trim()}
986
+ `:"")+(y?`${y.trim()}
977
987
 
978
988
  `:"")+(B?`Checkout at failure:
979
989
  \`\`\`
@@ -981,13 +991,13 @@ ${B.slice(0,800)}
981
991
  \`\`\`
982
992
 
983
993
  `:"")+(l.length?`**Before retrying, these still need a person:**
984
- `+l.map(y=>`- \`${y.command}\`${y.why?` - ${y.why}`:""}`).join(`
994
+ `+l.map(A=>`- \`${A.command}\`${A.why?` - ${A.why}`:""}`).join(`
985
995
  `)+`
986
996
 
987
- `:"")+`Nothing after it ran. Full log is on the Allwright dashboard. (run \`${t.runId}\`)`),ht(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.name} failed`,detail:`step ${b+1} "${$.name}" exit ${j.code}`+(j.tail?`
988
- ${i(j.tail).slice(0,500)}`:"")}),l.length&&Ip(e,l),n("failed",{error:m.slice(0,1600),deployedRef:p,...l.length?{manualSteps:l}:{}});return}e("info",`\u2713 step ${b+1}/${r.steps.length}: ${$.name}`)}}finally{Vh(t.runId)}if(p=await Ve(c).catch(()=>"")||p,r.servePath?.trim()){let b=r.servePath.trim(),$=r.branch.trim(),D=await Ve(b).catch(()=>"");if(!D)e("warn",`serving check: cannot read a git HEAD at ${b} - the deploy is done, but whether that checkout serves THIS build could not be verified`);else{p=D;let j=$?await el(b,$):"";if(!j)e("warn",`serving check: ${b} is at ${D.slice(0,10)}, but `+($?`origin/${$} could not be resolved there`:"this environment tracks no branch")+` - whether that is the latest ${$||"commit"} could not be verified`);else if(D!==j){let B=await tl(b,D,j),d=`The steps all succeeded, but the live checkout at ${b} is at ${D.slice(0,10)} while origin/${$} is at ${j.slice(0,10)}`+(B?` - ${B} commit(s) behind`:"")+`. Users are NOT getting the latest ${$}. 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: ${d}`),await pt(t,`**Allwright deployed to \`${r.name}\`, but it did not take.**
997
+ `:"")+`Nothing after it ran. Full log is on the Allwright dashboard. (run \`${t.runId}\`)`),ht(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.name} failed`,detail:`step ${b+1} "${P.name}" exit ${j.code}`+(u||m?`
998
+ ${(u||m).slice(0,500)}`:"")}),l.length&&Ep(e,l),n("failed",{error:x.slice(0,1600),deployedRef:p,...l.length?{manualSteps:l}:{}});return}e("info",`\u2713 step ${b+1}/${r.steps.length}: ${P.name}`)}}finally{Vh(t.runId)}if(p=await Ve(c).catch(()=>"")||p,r.servePath?.trim()){let b=r.servePath.trim(),P=r.branch.trim(),D=await Ve(b).catch(()=>"");if(!D)e("warn",`serving check: cannot read a git HEAD at ${b} - the deploy is done, but whether that checkout serves THIS build could not be verified`);else{p=D;let j=P?await el(b,P):"";if(!j)e("warn",`serving check: ${b} is at ${D.slice(0,10)}, but `+(P?`origin/${P} could not be resolved there`:"this environment tracks no branch")+` - whether that is the latest ${P||"commit"} could not be verified`);else if(D!==j){let B=await tl(b,D,j),u=`The steps all succeeded, but the live checkout at ${b} is at ${D.slice(0,10)} while origin/${P} is at ${j.slice(0,10)}`+(B?` - ${B} commit(s) behind`:"")+`. Users are NOT getting the latest ${P}. 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: ${u}`),await pt(t,`**Allwright deployed to \`${r.name}\`, but it did not take.**
989
999
 
990
- ${d}`),ht(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.name} did not take effect`,detail:`serving ${D.slice(0,10)}, origin/${$} at ${j.slice(0,10)} (${b})`}),n("failed",{error:d,deployedRef:p});return}else e("info",`serving check: ${b} is at ${D.slice(0,10)} = origin/${$} - users get this build`)}}n("posting");let C=Math.round((Date.now()-o)/1e3),V=null;r.publicUrl?.trim()&&(V=await Qv(r.publicUrl.trim()),e(V?"warn":"info",V??`${r.publicUrl.trim()} points at this machine - the deploy is live there`)),t.issueKey!==Dr.BRANCH_DEPLOY_ISSUE_KEY&&await pt(t,`**Allwright deployed \`${t.issueKey}\` to \`${r.name}\`.**
1000
+ ${u}`),ht(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.name} did not take effect`,detail:`serving ${D.slice(0,10)}, origin/${P} at ${j.slice(0,10)} (${b})`}),n("failed",{error:u,deployedRef:p});return}else e("info",`serving check: ${b} is at ${D.slice(0,10)} = origin/${P} - users get this build`)}}n("posting");let $=Math.round((Date.now()-o)/1e3),V=null;r.publicUrl?.trim()&&(V=await ok(r.publicUrl.trim()),e(V?"warn":"info",V??`${r.publicUrl.trim()} points at this machine - the deploy is live there`)),t.issueKey!==Dr.BRANCH_DEPLOY_ISSUE_KEY&&await pt(t,`**Allwright deployed \`${t.issueKey}\` to \`${r.name}\`.**
991
1001
 
992
1002
  `+(V?`> **Live where?** ${V}
993
1003
 
@@ -996,9 +1006,9 @@ ${d}`),ht(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.nam
996
1006
  `)+`
997
1007
 
998
1008
  `:"")+(p?`Commit: \`${p.slice(0,10)}\`${r.branch?` on \`${r.branch}\``:""}
999
- `:"")+`${r.steps.length} step(s) in ${C}s.`+(t.requestedBy?` Requested by ${t.requestedBy}.`:"")+`
1009
+ `:"")+`${r.steps.length} step(s) in ${$}s.`+(t.requestedBy?` Requested by ${t.requestedBy}.`:"")+`
1000
1010
 
1001
- (run \`${t.runId}\`)`);let Y=await Wv(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`),ei(t.repoPath,t.issueKey)&&ht(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&&Ip(e,l),n("succeeded",{resultSummary:`Deployed to ${r.name}${p?` at ${p.slice(0,10)}`:""} in ${C}s`+(Y!==null?` \xB7 ${Y} 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 Wv(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}.**
1011
+ (run \`${t.runId}\`)`);let Y=await Wv(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`),ei(t.repoPath,t.issueKey)&&ht(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&&Ep(e,l),n("succeeded",{resultSummary:`Deployed to ${r.name}${p?` at ${p.slice(0,10)}`:""} in ${$}s`+(Y!==null?` \xB7 ${Y} 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 ${$}s`)}async function Wv(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}.**
1002
1012
 
1003
1013
  `+(n?`Commit: \`${n.slice(0,10)}\`${r.branch?` on \`${r.branch}\``:""}
1004
1014
  `:"")+(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 Zv(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}\`.**
@@ -1007,20 +1017,21 @@ ${l}
1007
1017
 
1008
1018
  (run \`${t.runId}\`)`});e("info",`Checking "${n.branch}" is in sync with "${r}" before deploying`);try{await Rn(t.repoPath,r),await Rn(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 dl(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=ze(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 Tr(t.repoPath),c=vt(l);if(!c)throw new Error(`could not parse a GitHub owner/repo from origin "${l}"`);let p=await new qe(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.
1009
1019
 
1010
- (run \`${t.runId}\`)`});return s(`"${n.branch}" is not in sync with "${r}" - opened ${p.url} to catch it up. Merge that, then retry the deploy.`,!0)}catch(l){return s(`could not open a sync PR: ${l instanceof Error?l.message:String(l)}`)}}function Vv(t,e){if(!e.trim())return t;let n=Mr.default.resolve(t,e),r=Mr.default.relative(t,n);if(r.startsWith("..")||Mr.default.isAbsolute(r))throw new Error(`working directory "${e}" is outside the repository checkout`);return n}function Yv(t){return new Promise(e=>{let n=(0,jo.spawn)("bash",["-lc",t.command],{cwd:t.cwd,env:t.env,detached:!0,stdio:["ignore","pipe","pipe"]}),r=[],s=p=>{r.push(p),r.length>20&&r.shift()},i=!1,o=!1,l=p=>{i||(i=!0,clearTimeout(c),t.signal?.removeEventListener("abort",u),e({code:p,timedOut:o,tail:r.join(`
1011
- `)}))},c=setTimeout(()=>{o=!0,No(n.pid,"SIGTERM"),setTimeout(()=>No(n.pid,"SIGKILL"),1e4).unref()},t.timeoutMs),u=()=>{t.onLine("warn","stop requested - killing this step"),No(n.pid,"SIGTERM"),setTimeout(()=>No(n.pid,"SIGKILL"),5e3).unref()};t.signal&&(t.signal.aborted?u():t.signal.addEventListener("abort",u,{once:!0})),nc.default.createInterface({input:n.stdout}).on("line",p=>{s(p),t.onLine("info",p)}),nc.default.createInterface({input:n.stderr}).on("line",p=>{s(p),t.onLine("warn",p)}),n.on("error",p=>{s(`failed to start: ${p.message}`),l(127)}),n.on("close",p=>l(p??1))})}function No(t,e){if(t)try{process.kill(-t,e)}catch{try{process.kill(t,e)}catch{}}}function ic(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 pt(t,e){if(t.issueKey!==Dr.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 oc(t){return Io(t)!==null}async function $p(t,e){let n=Io(e);if(!n)return;let{emit:r,setStatus:s}=sc({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}),Eo(e);return}Eo(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 Cp(o,r,s)}catch(l){let c=l instanceof Error?l.message:String(l);r("error",`Deploy failed: ${c}`),await pt(o,`**Allwright deploy failed.**
1020
+ (run \`${t.runId}\`)`});return s(`"${n.branch}" is not in sync with "${r}" - opened ${p.url} to catch it up. Merge that, then retry the deploy.`,!0)}catch(l){return s(`could not open a sync PR: ${l instanceof Error?l.message:String(l)}`)}}function Vv(t,e){if(!e.trim())return t;let n=Mr.default.resolve(t,e),r=Mr.default.relative(t,n);if(r.startsWith("..")||Mr.default.isAbsolute(r))throw new Error(`working directory "${e}" is outside the repository checkout`);return n}var Yv=/^\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/,Xv=/^\s*(ok \d|# (pass|fail|tests|suites|skipped|todo|cancelled|duration)|\.\.\.\s*$)/,Qv=6,ek=40,tk=1200;function nk(){let t=[],e=0;return{push(n){if(!(t.length>=ek)){if(Yv.test(n)||Jv.test(n))t.push(n),e=Qv;else if(e>0){if(Xv.test(n)){e=0;return}t.push(n),e--}}},text(){return t.join(`
1021
+ `).slice(0,tk)}}}function rk(t){return new Promise(e=>{let n=(0,Oo.spawn)("bash",["-lc",t.command],{cwd:t.cwd,env:t.env,detached:!0,stdio:["ignore","pipe","pipe"]}),r=[],s=nk(),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(`
1022
+ `),failures:s.text()}))},d=setTimeout(()=>{l=!0,No(n.pid,"SIGTERM"),setTimeout(()=>No(n.pid,"SIGKILL"),1e4).unref()},t.timeoutMs),p=()=>{t.onLine("warn","stop requested - killing this step"),No(n.pid,"SIGTERM"),setTimeout(()=>No(n.pid,"SIGKILL"),5e3).unref()};t.signal&&(t.signal.aborted?p():t.signal.addEventListener("abort",p,{once:!0})),nc.default.createInterface({input:n.stdout}).on("line",f=>{i(f),t.onLine("info",f)}),nc.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 No(t,e){if(t)try{process.kill(-t,e)}catch{try{process.kill(t,e)}catch{}}}function ic(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 pt(t,e){if(t.issueKey!==Dr.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 oc(t){return Eo(t)!==null}async function $p(t,e){let n=Eo(e);if(!n)return;let{emit:r,setStatus:s}=sc({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}),Io(e);return}Io(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 Cp(o,r,s)}catch(l){let c=l instanceof Error?l.message:String(l);r("error",`Deploy failed: ${c}`),await pt(o,`**Allwright deploy failed.**
1012
1023
 
1013
- ${c.slice(0,800)}`),s("failed",{error:c})}}async function Pp(t,e){let n=Io(e);if(!n)return;let{emit:r,setStatus:s}=sc({runId:e,transport:t.transport});Eo(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.**
1024
+ ${c.slice(0,800)}`),s("failed",{error:c})}}async function Pp(t,e){let n=Eo(e);if(!n)return;let{emit:r,setStatus:s}=sc({runId:e,transport:t.transport});Io(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.**
1014
1025
 
1015
- No deploy step was executed. (run \`${e}\`)`)}catch(o){g.error(`could not post rejection comment to ${n.issueKey}: ${o}`)}s("failed",{error:"deploy rejected by a reviewer"})}var Jv=_.object({steps:_.array(Dr.DeployStep).max(50).default([]),requiredSecrets:_.array(_.string()).max(50).default([]),notes:_.string().default("")}),Ep=24e3;function Do(t){for(let e of Oo.DEPLOY_DOC_CANDIDATES){let n=Mr.default.join(t,e);try{if(!Rs.default.existsSync(n))continue;let r=Rs.default.readFileSync(n,"utf8");if(!r.trim())continue;return{path:e,content:r.length>Ep?r.slice(0,Ep)+`
1026
+ No deploy step was executed. (run \`${e}\`)`)}catch(o){g.error(`could not post rejection comment to ${n.issueKey}: ${o}`)}s("failed",{error:"deploy rejected by a reviewer"})}var sk=_.object({steps:_.array(Dr.DeployStep).max(50).default([]),requiredSecrets:_.array(_.string()).max(50).default([]),notes:_.string().default("")}),Ip=24e3;function Do(t){for(let e of jo.DEPLOY_DOC_CANDIDATES){let n=Mr.default.join(t,e);try{if(!Rs.default.existsSync(n))continue;let r=Rs.default.readFileSync(n,"utf8");if(!r.trim())continue;return{path:e,content:r.length>Ip?r.slice(0,Ip)+`
1016
1027
 
1017
- [\u2026document truncated\u2026]`:r}}catch{continue}}return null}var Rp=["docker","docker-compose","pm2","systemctl","node","pnpm","npm","yarn","make","python3","pip","rsync","ssh","caddy","nginx"];function Np(t){return Xv("bash",["-lc",`command -v ${JSON.stringify(t)}`]).trim().length>0}function Xv(t,e){try{let n=(0,jo.spawnSync)(t,e,{encoding:"utf8",timeout:5e3});return n.status===0?n.stdout??"":""}catch{return""}}async function Qv(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,u]=await Promise.all([o(e.hostname).catch(()=>[]),l(e.hostname).catch(()=>[])]);n=[...c,...u]}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=wp();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 ek(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 tk(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?`
1028
+ [\u2026document truncated\u2026]`:r}}catch{continue}}return null}var Rp=["docker","docker-compose","pm2","systemctl","node","pnpm","npm","yarn","make","python3","pip","rsync","ssh","caddy","nginx"];function Np(t){return ik("bash",["-lc",`command -v ${JSON.stringify(t)}`]).trim().length>0}function ik(t,e){try{let n=(0,Oo.spawnSync)(t,e,{encoding:"utf8",timeout:5e3});return n.status===0?n.stdout??"":""}catch{return""}}async function ok(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=wp();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 ak(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 lk(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?`
1018
1029
  - absolute paths the document mentions, checked on THIS machine:
1019
1030
  ${n.map(s=>` - ${s}: ${Rs.default.existsSync(s)?"EXISTS on this machine":"not found on this machine"}`).join(`
1020
- `)}`:""}function jp(t,e,n,r="",s="."){let i=Rp.filter(c=>Np(c)),o=Rp.filter(c=>!i.includes(c)),l=Object.keys(Zt(t,e,n));return`About the machine these steps will run on (gathered by the runner, trust it):
1031
+ `)}`:""}function Op(t,e,n,r="",s="."){let i=Rp.filter(c=>Np(c)),o=Rp.filter(c=>!i.includes(c)),l=Object.keys(Zt(t,e,n));return`About the machine these steps will run on (gathered by the runner, trust it):
1021
1032
  - available tools: ${i.join(", ")||"(none of the common ones)"}
1022
1033
  - NOT installed: ${o.join(", ")||"(none missing)"}
1023
- - secrets already stored for this environment (names only): ${l.join(", ")||"(none yet)"}`+Yl()+tk(r)+di(s)}async function Op(t){let e=[];if(t.publicUrl?.trim()&&await ek(t.publicUrl.trim(),e),e.push(Rs.default.existsSync(t.repoPath)?{name:"repo-path",ok:!0,detail:t.repoPath}:{name:"repo-path",ok:!1,detail:`checkout missing: ${t.repoPath}`}),e.push({name:"deploys-enabled",ok:t.cfg.deploy.enabled,detail:t.cfg.deploy.enabled?"enabled on this runner":"disabled - run: allwright deploy enable (then restart the runner)"}),t.workdir){let l=Mr.default.isAbsolute(t.workdir)?t.workdir:Mr.default.join(t.repoPath,t.workdir);e.push(Rs.default.existsSync(l)?{name:"workdir",ok:!0,detail:l}:{name:"workdir",ok:!1,detail:`does not exist: ${l}`})}if(t.branch){let l=$o(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=Zt(t.cfg,t.repoName,t.environmentName),r=new Set(t.requiredSecrets);for(let l of t.steps)for(let c of l.run.matchAll(/\$\{?([A-Z][A-Z0-9_]{2,})\}?/g))r.add(c[1]);let s=[...r].filter(l=>!n[l]&&!process.env[l]);e.push({name:"secrets",ok:s.length===0,detail:s.length?`missing: ${s.join(", ")} - set with: allwright env set "${t.repoName}" "${t.environmentName}" ${s[0]}=...`:`${r.size} present`});let i=new Set;for(let l of t.steps)for(let c of l.run.split(/&&|\|\||;|\|/)){let u=c.trim().split(/\s+/),p=u.shift();for(;p&&(/^[A-Za-z_][A-Za-z0-9_]*=/.test(p)||p==="sudo"||p==="env"||p==="nohup");)p=u.shift();!p||p.startsWith("$")||p.startsWith("#")||p.startsWith("(")||i.add(p)}let o=[...i].filter(l=>!Np(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 nk(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 Mp(t){let e=jp(t.cfg,t.repoName,t.environmentName,"",t.repoPath),n=tn(Oo.DEPLOY_FIX_PROMPT_TEMPLATE,{envName:t.environmentName,steps:t.steps.map((f,w)=>`${w+1}. [${f.name}]${f.continueOnError?" (continues on error)":""}
1034
+ - secrets already stored for this environment (names only): ${l.join(", ")||"(none yet)"}`+Yl()+lk(r)+di(s)}async function jp(t){let e=[];if(t.publicUrl?.trim()&&await ak(t.publicUrl.trim(),e),e.push(Rs.default.existsSync(t.repoPath)?{name:"repo-path",ok:!0,detail:t.repoPath}:{name:"repo-path",ok:!1,detail:`checkout missing: ${t.repoPath}`}),e.push({name:"deploys-enabled",ok:t.cfg.deploy.enabled,detail:t.cfg.deploy.enabled?"enabled on this runner":"disabled - run: allwright deploy enable (then restart the runner)"}),t.workdir){let l=Mr.default.isAbsolute(t.workdir)?t.workdir:Mr.default.join(t.repoPath,t.workdir);e.push(Rs.default.existsSync(l)?{name:"workdir",ok:!0,detail:l}:{name:"workdir",ok:!1,detail:`does not exist: ${l}`})}if(t.branch){let l=$o(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=Zt(t.cfg,t.repoName,t.environmentName),r=new Set(t.requiredSecrets);for(let l of t.steps)for(let c of l.run.matchAll(/\$\{?([A-Z][A-Z0-9_]{2,})\}?/g))r.add(c[1]);let s=[...r].filter(l=>!n[l]&&!process.env[l]);e.push({name:"secrets",ok:s.length===0,detail:s.length?`missing: ${s.join(", ")} - set with: allwright env set "${t.repoName}" "${t.environmentName}" ${s[0]}=...`:`${r.size} present`});let i=new Set;for(let l of t.steps)for(let c of l.run.split(/&&|\|\||;|\|/)){let 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=>!Np(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 ck(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 Mp(t){let e=Op(t.cfg,t.repoName,t.environmentName,"",t.repoPath),n=tn(jo.DEPLOY_FIX_PROMPT_TEMPLATE,{envName:t.environmentName,steps:t.steps.map((f,w)=>`${w+1}. [${f.name}]${f.continueOnError?" (continues on error)":""}
1024
1035
  ${f.run}`).join(`
1025
1036
  `),failedStep:t.failedStep||"(unknown)",errorText:t.errorText||"(no error text recorded)",knownCause:(()=>{let f=Vl(t.errorText,{cwd:t.repoPath});return f?`
1026
1037
 
@@ -1028,21 +1039,21 @@ THE RUNNER ALREADY RECOGNISES THIS FAILURE, and told the operator so:
1028
1039
  - what it means: ${f.cause}
1029
1040
  - what closes it: ${f.commands.join(" ; ")}
1030
1041
  - ${f.note}
1031
- 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:Tp(Sp({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,rc.randomUUID)(),onLog:()=>{}});if(!r.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:r.error??"the agent produced no output"};let s=zp(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=nk(r.resultText),u=l?Do(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:u?.path??(l?"DEPLOY.md":""),docContent:l}}async function Dp(t){let e=Do(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=jp(t.cfg,t.repoName,t.environmentName,e.content,t.repoPath),r=tn(Dr.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,rc.randomUUID)(),onLog:()=>{}});if(!s.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:s.error??"Claude Code produced no output"};let i=zp(s.resultText);return i?{ok:!0,...i}:(g.warn(`deploy step suggestion could not be parsed. Claude's raw answer follows:
1032
- `+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 zp(t){for(let e of rk(t)){let n;try{n=JSON.parse(e)}catch{continue}let r=Jv.safeParse(sk(n));if(r.success&&r.data.steps.length||r.success&&r.data.notes.trim())return r.data}return null}function rk(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 sk(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:Ap(o,l),run:o.trim()}:null;if(!o||typeof o!="object")return null;let c=o,u=tc(c.run,c.command,c.cmd,c.script,c.shell);return u?{name:(tc(c.name,c.title,c.description)??Ap(u,l)).slice(0,120),run:u,continueOnError:c.continueOnError===!0||c.continue_on_error===!0}:null}).filter(Boolean),s=e.requiredSecrets??e.required_secrets??e.secrets,i=Array.isArray(s)?s.filter(o=>typeof o=="string"):s&&typeof s=="object"?Object.keys(s):[];return{steps:r.slice(0,50),requiredSecrets:i.slice(0,50),notes:tc(e.notes,e.note,e.explanation)??""}}function tc(...t){for(let e of t)if(typeof e=="string"&&e.trim())return e.trim()}function Ap(t,e){return(t.split(`
1033
- `)[0].trim()||`Step ${e+1}`).slice(0,120)}Nt();_t();xr();function zo(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}}}en();Fo();var Up=24*3600*1e3,Bo=14,ok=Bo*24*3600*1e3,ak=new Set(["to","on","this","the","a","an","env","environment","please","now","it"]),Ho=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!!Bi(this.cfg,e)}get jiraless(){return Hi(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=th(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=Ue(this.cfg,n,"assist");if("error"in s){g.warn(`Scheduled audit skipped: ${s.error}`);continue}let i=await Ss({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 $=Date.parse(e.pausedUntil);Number.isFinite($)&&(this.autopilotPausedUntil=$);return}let n=e.item;if(!n)return;let r=this.rules.find($=>$.id===n.ruleId&&$.enabled),s=this.projects.find($=>$.id===n.projectId);if(!r||!s){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:"the rule or project this item was queued against no longer exists"});return}let i=zo(s,[]),o="project"in i?i.project:s,l=this.cfg.repos[o.repoName];if(!l){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:`no local checkout mapped for "${o.repoName}" on this machine`});return}if(!this.hasJira(o.repoName)){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:`no Jira credential for "${o.repoName}" on this machine - run \`allwright jira set-default\` there (or \`allwright jira set "${o.repoName}"\`)`});return}let c=n.baseOverride||n.branchOverride||n.autoMerge?{...r,action:r.action.type==="implement"?{...r.action,...n.baseOverride?{baseBranch:n.baseOverride}:{},...n.branchOverride?{branchTemplate:n.branchOverride}:{},...n.autoMerge?{requireApproval:!1,autoMerge:!0}:{}}:r.action}:r;g.info(`autopilot: taking ${n.issueKey} (${r.name})`+(n.branchOverride?` -> shared branch ${n.branchOverride}`:"")+(n.baseOverride?` -> stacked on ${n.baseOverride}`:""));let u=this.jiraOf(o),p="";try{p=(await u.getIssue(n.issueKey))?.summary??""}catch($){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:`could not read ${n.issueKey} from Jira: ${$ instanceof Error?$.message:String($)}`});return}let f=await this.transport.claimRun({ruleId:r.id,issueKey:n.issueKey,issueSummary:p,triggerFingerprint:`autopilot:${n.id}`,dedupKey:`autopilot:${n.id}`});if(!f.accepted||!f.runId){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:f.reason??"the control plane refused the run"});return}this.transport.sendAutopilotReport({itemId:n.id,outcome:"claimed",runId:f.runId});let w=`${r.id}:${n.issueKey}`;this.inFlight.add(w);let v=this.resolveClaudeProfile(f.runId,f.claudeProfile),k=!!(n.batchId&&n.branchOverride),x=n.batchId?cc(n.batchId):null,E=!n.continueBranch&&!k?uc(x,n.issueKey):null,C=E?qo(n.batchId,E,n.issueKey):null,V=k&&n.continueBranch?pc(n.batchId):null,Y=C??V,b=yc(E,n.issueKey)||k&&n.remainingInBatch>0;this.enqueueForRepo(l.path,async()=>{try{await ai({runId:f.runId,rule:c,project:o,issueKey:n.issueKey,repoPath:l.path,cfg:this.cfg,jira:u,transport:this.transport,claudeConfigDir:v,actorEmail:f.actorEmail,continueBranch:n.continueBranch,...Y?{chain:{sessionId:Y.sessionId,worktreePath:Y.worktreePath}}:{},keepWorktree:b,onChainSession:E?$=>dc(n.batchId,E,n.issueKey,$):k&&b?$=>fc(n.batchId,n.issueKey,$,!!V):void 0}),E&&!qo(n.batchId,E,E[E.indexOf(n.issueKey)+1]??"")&&E.indexOf(n.issueKey)<E.length-1&&hc(n.batchId,E),k&&!mc(n.batchId,n.issueKey)&&gc(n.batchId)}finally{this.inFlight.delete(w)}})}async sweepGitHubApprovals(){let e=Object.values(ri());if(!e.length)return;let n=ke()??this.cfg,r=new Map,s=i=>{let o=ze(n,i);if(!o)return null;let l=r.get(o);return l||r.set(o,l=new qe(o)),l};for(let i of e.slice(0,10)){let o=s(i.repoName);if(!o)continue;if(!this.hasJira(i.repoName)){this.warnNoJiraForRepo(i.repoName);continue}let l=`gh-approve:${i.runId}`;if(this.inFlight.has(l))continue;let c,u;try{[c,u]=await Promise.all([o.getReviews(i.owner,i.repo,i.prNumber),o.getPullRequest(i.owner,i.repo,i.prNumber)])}catch(v){g.warn(`review check failed for ${i.owner}/${i.repo}#${i.prNumber}: ${v instanceof Error?v.message:v}`);continue}if(!u)continue;let p={cfg:this.cfg,jiraFor:this.jiraFor,transport:this.transport};if(u.merged){g.info(`PR #${i.prNumber} for ${i.issueKey} was merged on GitHub - completing the run`),this.inFlight.add(l);try{await li(p,i.runId,u.headSha)}finally{this.inFlight.delete(l)}continue}if(u.state==="closed"){g.info(`PR #${i.prNumber} for ${i.issueKey} was closed unmerged on GitHub - failing the run`);let v=this.jiraFor(i.repoName),k=`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.**
1042
+ 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:Tp(Sp({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,rc.randomUUID)(),onLog:()=>{}});if(!r.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:r.error??"the agent produced no output"};let s=zp(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=ck(r.resultText),d=l?Do(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 Dp(t){let e=Do(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=Op(t.cfg,t.repoName,t.environmentName,e.content,t.repoPath),r=tn(Dr.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,rc.randomUUID)(),onLog:()=>{}});if(!s.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:s.error??"Claude Code produced no output"};let i=zp(s.resultText);return i?{ok:!0,...i}:(g.warn(`deploy step suggestion could not be parsed. Claude's raw answer follows:
1043
+ `+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 zp(t){for(let e of uk(t)){let n;try{n=JSON.parse(e)}catch{continue}let r=sk.safeParse(dk(n));if(r.success&&r.data.steps.length||r.success&&r.data.notes.trim())return r.data}return null}function uk(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 dk(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:Ap(o,l),run:o.trim()}:null;if(!o||typeof o!="object")return null;let c=o,d=tc(c.run,c.command,c.cmd,c.script,c.shell);return d?{name:(tc(c.name,c.title,c.description)??Ap(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:tc(e.notes,e.note,e.explanation)??""}}function tc(...t){for(let e of t)if(typeof e=="string"&&e.trim())return e.trim()}function Ap(t,e){return(t.split(`
1044
+ `)[0].trim()||`Step ${e+1}`).slice(0,120)}Nt();_t();xr();function zo(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}}}en();Fo();var Up=24*3600*1e3,Bo=14,pk=Bo*24*3600*1e3,fk=new Set(["to","on","this","the","a","an","env","environment","please","now","it"]),Ho=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!!Bi(this.cfg,e)}get jiraless(){return Hi(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=th(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=Ue(this.cfg,n,"assist");if("error"in s){g.warn(`Scheduled audit skipped: ${s.error}`);continue}let i=await Ss({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 P=Date.parse(e.pausedUntil);Number.isFinite(P)&&(this.autopilotPausedUntil=P);return}let n=e.item;if(!n)return;let r=this.rules.find(P=>P.id===n.ruleId&&P.enabled),s=this.projects.find(P=>P.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=zo(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(P){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:`could not read ${n.issueKey} from Jira: ${P instanceof Error?P.message:String(P)}`});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),k=!!(n.batchId&&n.branchOverride),E=n.batchId?cc(n.batchId):null,I=!n.continueBranch&&!k?uc(E,n.issueKey):null,$=I?qo(n.batchId,I,n.issueKey):null,V=k&&n.continueBranch?pc(n.batchId):null,Y=$??V,b=yc(I,n.issueKey)||k&&n.remainingInBatch>0;this.enqueueForRepo(l.path,async()=>{try{await ai({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,...Y?{chain:{sessionId:Y.sessionId,worktreePath:Y.worktreePath}}:{},keepWorktree:b,onChainSession:I?P=>dc(n.batchId,I,n.issueKey,P):k&&b?P=>fc(n.batchId,n.issueKey,P,!!V):void 0}),I&&!qo(n.batchId,I,I[I.indexOf(n.issueKey)+1]??"")&&I.indexOf(n.issueKey)<I.length-1&&hc(n.batchId,I),k&&!mc(n.batchId,n.issueKey)&&gc(n.batchId)}finally{this.inFlight.delete(w)}})}async sweepGitHubApprovals(){let e=Object.values(ri());if(!e.length)return;let n=ke()??this.cfg,r=new Map,s=i=>{let o=ze(n,i);if(!o)return null;let l=r.get(o);return l||r.set(o,l=new qe(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 li(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),k=`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.**
1034
1045
 
1035
1046
  PR: ${i.prUrl}
1036
1047
 
1037
- 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:k}),Ar(i.runId);continue}u.mergeableState==="dirty"?(this.transport.send({type:"run.pr.conflict",runId:i.runId,conflicted:!0}),i.conflictNotified||(await this.jiraFor(i.repoName).addComment(i.issueKey,`**Allwright: the pull request for this ticket has merge conflicts.** The base branch moved after this change was built, so GitHub cannot merge it as-is.
1048
+ 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:k}),Ar(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.
1038
1049
 
1039
1050
  PR: ${i.prUrl}
1040
1051
 
1041
- 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,St(i),g.info(`merge conflicts on PR #${i.prNumber} for ${i.issueKey} - ticket notified`))):u.mergeableState!==null&&u.mergeableState!=="unknown"&&(this.transport.send({type:"run.pr.conflict",runId:i.runId,conflicted:!1}),i.conflictNotified&&(i.conflictNotified=!1,St(i)));let f=c.filter(v=>v.state==="APPROVED"||v.state==="CHANGES_REQUESTED").sort((v,k)=>v.submittedAt.localeCompare(k.submittedAt)),w=f[f.length-1];if(w){if(w.state==="CHANGES_REQUESTED"){i.changesRequestedNotified||(await this.jiraFor(i.repoName).addComment(i.issueKey,`**Allwright: changes were requested on the pull request** (by ${w.user}).
1052
+ 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,St(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,St(i)));let f=c.filter(v=>v.state==="APPROVED"||v.state==="CHANGES_REQUESTED").sort((v,k)=>v.submittedAt.localeCompare(k.submittedAt)),w=f[f.length-1];if(w){if(w.state==="CHANGES_REQUESTED"){i.changesRequestedNotified||(await this.jiraFor(i.repoName).addComment(i.issueKey,`**Allwright: changes were requested on the pull request** (by ${w.user}).
1042
1053
 
1043
1054
  PR: ${i.prUrl}
1044
1055
 
1045
- Reply to the review on GitHub, or reject the run on the Allwright dashboard and re-trigger with new instructions. (run \`${i.runId}\`)`).catch(()=>{}),St({...i,changesRequestedNotified:!0}),g.info(`changes requested on PR #${i.prNumber} for ${i.issueKey} - ticket notified`));continue}if(w.commitId===u.headSha){g.info(`PR #${i.prNumber} for ${i.issueKey} approved on GitHub by ${w.user} - completing the run`),this.inFlight.add(l);try{await li(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(xo());if(!e.length)return;let n=ke()??this.cfg,r=new Map,s=l=>{let c=ze(n,l);if(!c)return null;let u=r.get(c);return u||r.set(c,u=new qe(c)),u},i=20,o=720*3600*1e3;for(let l of e.slice(0,i)){let c=s(l.repoName);if(!c)continue;if(!this.hasJira(l.repoName)){this.warnNoJiraForRepo(l.repoName);continue}if(Date.now()-new Date(l.createdAt).getTime()>o){g.warn(`merge watch for ${l.issueKey} PR #${l.prNumber} is over 30 days old - dropping`),ni(l.runId);continue}let u;try{u=await c.getPullRequest(l.owner,l.repo,l.prNumber)}catch(w){g.warn(`merge check failed for ${l.owner}/${l.repo}#${l.prNumber}: ${w instanceof Error?w.message:w}`);continue}if(!u){ni(l.runId);continue}if(u.state==="open")continue;if(!u.merged){ni(l.runId);continue}let p=this.jiraFor(l.repoName),f="";if(l.jiraTransitionOnMerge)try{f=await p.transitionByName(l.issueKey,l.jiraTransitionOnMerge)?`
1056
+ Reply to the review on GitHub, or reject the run on the Allwright dashboard and re-trigger with new instructions. (run \`${i.runId}\`)`).catch(()=>{}),St({...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 li(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(xo());if(!e.length)return;let n=ke()??this.cfg,r=new Map,s=l=>{let c=ze(n,l);if(!c)return null;let d=r.get(c);return d||r.set(c,d=new qe(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`),ni(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){ni(l.runId);continue}if(d.state==="open")continue;if(!d.merged){ni(l.runId);continue}let p=this.jiraFor(l.repoName),f="";if(l.jiraTransitionOnMerge)try{f=await p.transitionByName(l.issueKey,l.jiraTransitionOnMerge)?`
1046
1057
 
1047
1058
  Ticket moved to **${l.jiraTransitionOnMerge}**.`:`
1048
1059
 
@@ -1050,21 +1061,21 @@ Note: no transition named "${l.jiraTransitionOnMerge}" is available from this ti
1050
1061
 
1051
1062
  Note: the "${l.jiraTransitionOnMerge}" transition failed: ${w instanceof Error?w.message:w}`}try{await p.addComment(l.issueKey,`**Allwright: the pull request for this ticket was merged.**
1052
1063
 
1053
- PR: ${l.prUrl} (merged at \`${u.headSha.slice(0,10)}\`)${f}
1064
+ PR: ${l.prUrl} (merged at \`${d.headSha.slice(0,10)}\`)${f}
1054
1065
 
1055
- (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`),ni(l.runId)}}async sweepNeedsInput(e){let n;try{n=await this.jiraOf(e).search(`project = "${e.jiraProjectKey}" AND labels = "${On.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=Cr();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:[On.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()>ok){this.inFlight.add(c),this.abandonStaleInput(l,e).finally(()=>this.inFlight.delete(c));continue}try{o=o??await this.jiraOf(e).getIssue(s.key)}catch(k){g.warn(`needs-input check failed for ${s.key}: ${k instanceof Error?k.message:k}`);continue}let u=new Date(l.questionsPostedAt).getTime(),p=o.comments.filter(k=>!dt(k.body)&&new Date(k.created).getTime()>u);if(!p.length)continue;let f=Pr(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:[On.NEEDS_INPUT_LABEL]}).catch(k=>{g.warn(`could not remove needs-input label on ${s.key}: ${k}`)});let v={jiraFor:this.jiraFor,transport:this.transport,cfg:this.cfg,findRule:k=>this.findRuleForResume(k)};l.kind==="implement"?this.enqueueForRepo(l.baseRepoPath??l.repoPath,async()=>{try{await Wl(l,f,w,v)}finally{this.inFlight.delete(c)}}):this.enqueueForRepo(l.repoPath,async()=>{try{await Gl(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=Uh(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}`:""}.**
1066
+ (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`),ni(l.runId)}}async sweepNeedsInput(e){let n;try{n=await this.jiraOf(e).search(`project = "${e.jiraProjectKey}" AND labels = "${jn.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=Cr();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:[jn.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()>pk){this.inFlight.add(c),this.abandonStaleInput(l,e).finally(()=>this.inFlight.delete(c));continue}try{o=o??await this.jiraOf(e).getIssue(s.key)}catch(k){g.warn(`needs-input check failed for ${s.key}: ${k instanceof Error?k.message:k}`);continue}let d=new Date(l.questionsPostedAt).getTime(),p=o.comments.filter(k=>!dt(k.body)&&new Date(k.created).getTime()>d);if(!p.length)continue;let f=Pr(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:[jn.NEEDS_INPUT_LABEL]}).catch(k=>{g.warn(`could not remove needs-input label on ${s.key}: ${k}`)});let v={jiraFor:this.jiraFor,transport:this.transport,cfg:this.cfg,findRule:k=>this.findRuleForResume(k)};l.kind==="implement"?this.enqueueForRepo(l.baseRepoPath??l.repoPath,async()=>{try{await Wl(l,f,w,v)}finally{this.inFlight.delete(c)}}):this.enqueueForRepo(l.repoPath,async()=>{try{await Gl(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=Uh(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}`:""}.**
1056
1067
 
1057
1068
  ${n}
1058
1069
 
1059
- This run is continuing from where it left off. (run \`${e}\`)`),await o.editLabels(s.issueKey,{remove:[On.NEEDS_INPUT_LABEL]})}catch(f){this.inFlight.delete(i);let w=f instanceof Error?f.message:String(f);return{ok:!1,note:"",error:`could not write the answer to ${s.issueKey}: ${w}`}}g.info(`answer received from the dashboard for ${s.issueKey} - resuming run ${e}`);let c=r?`${r}: ${n}`:n,u={jiraFor:this.jiraFor,transport:this.transport,cfg:this.cfg,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 Wl(s,c,l,u):await Gl(s,c,l,u)}finally{this.inFlight.delete(i)}}),{ok:!0,note:`Answer sent - the run is continuing, and it was posted to ${s.issueKey} too.`}}async abandonStaleInput(e,n){g.warn(`${e.issueKey}: needs-input unanswered for over ${Bo}d - abandoning run ${e.runId}`);try{await this.jiraOf(n).addComment(e.issueKey,`**Allwright gave up waiting for an answer.**
1070
+ This run is continuing from where it left off. (run \`${e}\`)`),await o.editLabels(s.issueKey,{remove:[jn.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 Wl(s,c,l,d):await Gl(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 ${Bo}d - abandoning run ${e.runId}`);try{await this.jiraOf(n).addComment(e.issueKey,`**Allwright gave up waiting for an answer.**
1060
1071
 
1061
- No reply arrived within ${Bo} 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:[On.NEEDS_INPUT_LABEL]})}catch(r){g.warn(`could not post staleness notice for ${e.issueKey}: ${r}`)}e.kind==="implement"&&await Pt(e.baseRepoPath??e.repoPath,e.repoPath).catch(()=>{}),Ot(e.runId),this.transport.send({type:"run.status",runId:e.runId,status:"failed",error:`no reply within ${Bo} 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=zo(n,i.components??[]);if("error"in l){this.warnRoutingOnce(`${e.id}:${i.issueKey}`,`${i.issueKey}: ${l.error}`);continue}let c=l.project,u=c.repoName===n.repoName?r:this.cfg.repos[c.repoName]?.path;if(!u){this.warnRoutingOnce(`${e.id}:${i.issueKey}:path`,`${i.issueKey}: routed to repo "${c.repoName}" but it has no local checkout - run: allwright repo add "${c.repoName}" /path/to/checkout`);continue}let p=await this.transport.claimRun({ruleId:e.id,issueKey:i.issueKey,issueSummary:i.summary,triggerFingerprint:i.fingerprint,triggeredByAccountId:i.triggeredByAccountId});if(!p.accepted||!p.runId){p.reason!=="duplicate"&&g.warn(`claim rejected for ${i.issueKey}: ${p.reason??"unknown"}`);continue}this.inFlight.add(o),g.info(`claimed run ${p.runId} for ${i.issueKey}`+(c.repoName!==n.repoName?` (routed \u2192 ${c.repoName})`:"")+(p.claudeProfile?` (claude profile "${p.claudeProfile}")`:""));let f=this.resolveClaudeProfile(p.runId,p.claudeProfile);this.enqueueForRepo(u,async()=>{try{await ai({runId:p.runId,rule:e,project:c,issueKey:i.issueKey,repoPath:u,cfg:this.cfg,jira:this.jiraOf(c),transport:this.transport,claudeConfigDir:f,actorEmail:p.actorEmail})}finally{this.inFlight.delete(o)}})}}async pollRespondRule(e,n,r){let s=e.trigger;if(s.type!=="comment_keyword"||e.action.type!=="respond")return;let i=await this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=s.keyword.toLowerCase(),l=Date.now()-Up;for(let c of i){let u=await this.jiraOf(n).getIssue(c.key);for(let p of u.comments){if(!p.body.toLowerCase().includes(o)||dt(p.body)||new Date(p.created).getTime()<l||!p.id)continue;let f=`respond:${p.id}`;if(this.inFlight.has(f))continue;let w=zo(n,c.components??[]);if("error"in w){this.warnRoutingOnce(`${e.id}:${c.key}`,`${c.key}: ${w.error}`);continue}let v=w.project,k=v.repoName===n.repoName?r:this.cfg.repos[v.repoName]?.path;if(!k){this.warnRoutingOnce(`${e.id}:${c.key}:path`,`${c.key}: routed to repo "${v.repoName}" but it has no local checkout - run: allwright repo add "${v.repoName}" /path/to/checkout`);continue}let x=await this.transport.claimRun({ruleId:e.id,issueKey:c.key,issueSummary:c.summary,triggerFingerprint:`question by ${p.author} at ${p.created}`,dedupKey:`respond:comment:${p.id}`,triggeredByAccountId:p.authorAccountId??void 0});if(!x.accepted||!x.runId){x.reason!=="duplicate"&&g.warn(`respond claim rejected for ${c.key}: ${x.reason??"unknown"}`);continue}this.inFlight.add(f),g.info(`claimed respond run ${x.runId}: ${c.key} (comment ${p.id})`+(v.repoName!==n.repoName?` (routed \u2192 ${v.repoName})`:"")+(x.claudeProfile?` (claude profile "${x.claudeProfile}")`:""));let E={author:p.author,body:p.body},C=this.resolveClaudeProfile(x.runId,x.claudeProfile);this.enqueueForRepo(k,async()=>{try{await ai({runId:x.runId,rule:e,project:v,issueKey:c.key,repoPath:k,cfg:this.cfg,jira:this.jiraOf(v),transport:this.transport,question:E,claudeConfigDir:C,actorEmail:x.actorEmail})}finally{this.inFlight.delete(f)}})}}}async sweepRevisions(e,n){let r=e.trigger;if(r.type!=="comment_keyword")return;let s;try{s=await this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND labels = "${r.doneLabel}" AND updated >= "-2d"`,10)}catch(o){g.warn(`revision sweep failed for ${n.jiraProjectKey}: ${o instanceof Error?o.message:o}`);return}let i=r.keyword.toLowerCase();for(let o of s)try{let l=await this.jiraOf(n).getIssue(o.key),c=null;for(let p of l.comments)dt(p.body)&&(c=Math.max(c??0,new Date(p.created).getTime()));if(c===null||!l.comments.some(p=>!dt(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.**
1072
+ No reply arrived within ${Bo} 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:[jn.NEEDS_INPUT_LABEL]})}catch(r){g.warn(`could not post staleness notice for ${e.issueKey}: ${r}`)}e.kind==="implement"&&await Pt(e.baseRepoPath??e.repoPath,e.repoPath).catch(()=>{}),jt(e.runId),this.transport.send({type:"run.status",runId:e.runId,status:"failed",error:`no reply within ${Bo} 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=zo(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 ai({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()-Up;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)||dt(p.body)||new Date(p.created).getTime()<l||!p.id)continue;let f=`respond:${p.id}`;if(this.inFlight.has(f))continue;let w=zo(n,c.components??[]);if("error"in w){this.warnRoutingOnce(`${e.id}:${c.key}`,`${c.key}: ${w.error}`);continue}let v=w.project,k=v.repoName===n.repoName?r:this.cfg.repos[v.repoName]?.path;if(!k){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 E=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(!E.accepted||!E.runId){E.reason!=="duplicate"&&g.warn(`respond claim rejected for ${c.key}: ${E.reason??"unknown"}`);continue}this.inFlight.add(f),g.info(`claimed respond run ${E.runId}: ${c.key} (comment ${p.id})`+(v.repoName!==n.repoName?` (routed \u2192 ${v.repoName})`:"")+(E.claudeProfile?` (claude profile "${E.claudeProfile}")`:""));let I={author:p.author,body:p.body},$=this.resolveClaudeProfile(E.runId,E.claudeProfile);this.enqueueForRepo(k,async()=>{try{await ai({runId:E.runId,rule:e,project:v,issueKey:c.key,repoPath:k,cfg:this.cfg,jira:this.jiraOf(v),transport:this.transport,question:I,claudeConfigDir:$,actorEmail:E.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)dt(p.body)&&(c=Math.max(c??0,new Date(p.created).getTime()));if(c===null||!l.comments.some(p=>!dt(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.**
1062
1073
 
1063
1074
  ${l.reason}`+(i.requestedByAccountId?`
1064
1075
 
1065
1076
  Jira account id: \`${i.requestedByAccountId}\``:"")+`
1066
1077
 
1067
- (run \`${l.runId}\`)`).catch(u=>g.warn(`could not post refusal to ${i.issueKey}: ${u}`)),g.warn(`deploy refused for ${i.issueKey}: ${l.reason}`)):l.reason&&g.warn(`deploy claim rejected for ${i.issueKey}: ${l.reason}`);continue}let c=l.environment;this.inFlight.add(o),g.info(`claimed deploy ${l.runId}: ${i.issueKey} \u2192 ${c.name}`),this.enqueue(this.envQueues,c.id,async()=>{try{await Mo({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()-Up,c=this.environments.filter(f=>f.projectId===n.id).map(f=>f.name),u=this.fixedEnvironmentName(s.environmentId),p=[];for(let f of i){let w=await this.jiraOf(n).getIssue(f.key);if(!(s.requireStatus&&w.status.toLowerCase()!==s.requireStatus.toLowerCase()))for(let v of w.comments){if(!v.body.toLowerCase().includes(o)||dt(v.body)||new Date(v.created).getTime()<l||!v.id)continue;let k=s.envSelection==="fixed"?u:lk(v.body,r.keyword,c);p.push({issueKey:f.key,summary:f.summary,environmentName:k,requestedByAccountId:v.authorAccountId??void 0,requestedByDisplayName:v.author,dedupKey:`deploy:comment:${v.id}`,fingerprint:`comment "${r.keyword}" by ${v.author} at ${v.created}`+(k?` \u2192 ${k}`:"")})}}return p}async matchStatusDeploys(e,n){let r=e.trigger,s=e.action;if(r.type!=="status_changed"||s.type!=="deploy")return[];let i=await this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND status = "${r.status}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=this.fixedEnvironmentName(s.environmentId),l=[];for(let c of i){let u=await this.jiraOf(n).lastEnteredStatus(c.key,r.status);u&&l.push({issueKey:c.key,summary:c.summary,environmentName:o,requestedByAccountId:u.authorAccountId??void 0,requestedByDisplayName:u.author,dedupKey:`deploy:status:${e.id}:${c.key}:${u.at}`,fingerprint:`moved to "${r.status}" by ${u.author} at ${u.at}`})}return l}fixedEnvironmentName(e){return e?this.environments.find(n=>n.id===e)?.name??"":""}async matchLabelTrigger(e,n){let r=e.trigger;if(r.type!=="label_added")return[];let s=`project = "${n.jiraProjectKey}" AND labels = "${r.label}" AND labels not in ("${r.doneLabel}", "${r.failedLabel}", "${On.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}", "${On.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)&&!dt(f.body));p&&l.push({issueKey:c.key,components:c.components,summary:c.summary,fingerprint:`comment keyword "${r.keyword}" by ${p.author} at ${p.created}`,triggeredByAccountId:p.authorAccountId??void 0})}return l}async diagnoseRule(e,n){let r=e.trigger;if(e.action.type==="deploy"){let c=r.type==="status_changed"?await this.matchStatusDeploys(e,n):await this.matchCommentDeploys(e,n),u=c.filter(p=>p.environmentName);return{matchedCount:u.length,excludedCount:c.length-u.length,excludedSample:c.filter(p=>!p.environmentName).slice(0,5).map(p=>p.issueKey)}}if(r.type==="status_changed")return{matchedCount:(await this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND status = "${r.status}"`,50)).length,excludedCount:0,excludedSample:[]};if(r.type==="label_added"){let[c,u]=await Promise.all([this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND labels = "${r.label}" AND labels not in ("${r.doneLabel}", "${r.failedLabel}")`,50),this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND labels = "${r.label}" AND labels in ("${r.doneLabel}", "${r.failedLabel}")`,50)]);return{matchedCount:c.length,excludedCount:u.length,excludedSample:u.slice(0,5).map(p=>p.key)}}let s=r.keyword.toLowerCase(),[i,o]=await Promise.all([this.matchCommentTrigger(e,n),this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND updated >= "-2d" AND labels in ("${r.doneLabel}", "${r.failedLabel}")`,50)]),l=[];for(let c of o)(await this.jiraOf(n).getIssue(c.key)).comments.some(p=>p.body.toLowerCase().includes(s))&&l.push(c.key);return{matchedCount:i.length,excludedCount:l.length,excludedSample:l.slice(0,5)}}enqueueForRepo(e,n){this.enqueue(this.repoQueues,e,n)}runOnRepoQueue(e,n){this.enqueue(this.repoQueues,e,n)}runOnEnvironmentQueue(e,n){this.enqueue(this.envQueues,e,n)}enqueue(e,n,r){let i=(e.get(n)??Promise.resolve()).then(async()=>{this.activeWork++;try{await r()}finally{this.activeWork--}}).catch(o=>{g.error(`run crashed: ${o instanceof Error?o.stack:o}`)});e.set(n,i)}};function lk(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(!ak.has(o.toLowerCase()))return o;return""}var qp=R(require("node:fs"),1),Fp=R(require("node:path"),1),wc=require("node:crypto");Nt();var ck=`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.
1078
+ (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 Mo({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()-Up,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)||dt(v.body)||new Date(v.created).getTime()<l||!v.id)continue;let k=s.envSelection==="fixed"?d:mk(v.body,r.keyword,c);p.push({issueKey:f.key,summary:f.summary,environmentName:k,requestedByAccountId:v.authorAccountId??void 0,requestedByDisplayName:v.author,dedupKey:`deploy:comment:${v.id}`,fingerprint:`comment "${r.keyword}" by ${v.author} at ${v.created}`+(k?` \u2192 ${k}`:"")})}}return p}async matchStatusDeploys(e,n){let r=e.trigger,s=e.action;if(r.type!=="status_changed"||s.type!=="deploy")return[];let i=await this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND status = "${r.status}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=this.fixedEnvironmentName(s.environmentId),l=[];for(let c of i){let 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}", "${jn.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}", "${jn.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)&&!dt(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 mk(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(!fk.has(o.toLowerCase()))return o;return""}var qp=R(require("node:fs"),1),Fp=R(require("node:path"),1),wc=require("node:crypto");Nt();var gk=`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.
1068
1079
 
1069
1080
  Rules:
1070
1081
  - Edit ONLY the conflicted files listed below. Do not touch anything else, do not refactor, do not "improve" surrounding code.
@@ -1073,10 +1084,10 @@ Rules:
1073
1084
  - When you are done, every listed file must contain no conflict markers and must be syntactically valid.
1074
1085
 
1075
1086
  Conflicted files:
1076
- `;async function Bp(t){let{cfg:e,repoPath:n,branch:r,baseBranch:s,issueKey:i,onLog:o}=t,l=Fp.default.join(Qt(),`conflict-${(0,wc.randomUUID)().slice(0,8)}`),c=!1;try{o("info",`Preparing a worktree for ${r} to merge ${s} into it`),await Xs(n,l,r),c=!0;let u=await al(l,s);if(u.ok&&u.alreadyUpToDate)return o("info",`${r} already contains ${s} - nothing to merge`),{ok:!0,freeOfCharge:!0,note:`This branch already contains ${s}, so there was nothing to merge - GitHub's conflict flag was out of date. Refresh the PR.`};if(!u.ok&&u.conflicts===null)return{ok:!1,note:`The merge could not even be started: ${u.reason}`};let p={},f=!1;if(!u.ok){let k=u.conflicts;o("info",`git merged everything except ${k.length} file(s): ${k.slice(0,20).join(", ")}`+(k.length>20?", \u2026":""));let x=Ye(t.agentId);if(!x)return await Cn(l),{ok:!1,note:`no adapter for agent "${t.agentId}" on this runner`};let E=Nn(t.agentId,"edit_no_shell");if(E)return await Cn(l),{ok:!1,note:`${E} Resolve the conflicts yourself on branch ${r}, or use Rebuild on current base.`};o("info",`Asking ${x.displayName} to resolve only those files`);let C=-1,V=setInterval(()=>{cl(l,k).then($=>{let D=k.filter(j=>!$.includes(j));D.length!==C&&(C=D.length,o("info",`Conflict progress: ${D.length}/${k.length} resolved`+(D.length?` \xB7 clean: ${D.join(", ")}`:"")+($.length?` \xB7 still conflicted: ${$.join(", ")}`:"")))}).catch(()=>{})},12e3),Y=await oi(x,{repoPath:l,prompt:ck+k.map($=>`- ${$}`).join(`
1077
- `),timeoutSeconds:t.timeoutSeconds,bin:Je(e,t.agentId),configDir:t.configDir,mode:"edit_no_shell",sessionId:(0,wc.randomUUID)(),onLog:($,D)=>o($,D)},($,D)=>o($==="warn"?"warn":$,D));if(clearInterval(V),p={costUsd:Y.costUsd,inputTokens:Y.inputTokens,outputTokens:Y.outputTokens},!Y.ok)return await Cn(l),{ok:!1,...p,note:`The agent could not do the resolution: ${Y.error??"it produced no output"}. Nothing was changed - the merge was rolled back. Fix that first, then Resolve again.`};f=!0;let b=await uo(l);if(b.length)return await Cn(l),{ok:!1,...p,note:`The agent left conflict markers in ${b.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 ll(l,`${i}: merge ${s}, conflicts resolved by the agent
1087
+ `;async function Bp(t){let{cfg:e,repoPath:n,branch:r,baseBranch:s,issueKey:i,onLog:o}=t,l=Fp.default.join(Qt(),`conflict-${(0,wc.randomUUID)().slice(0,8)}`),c=!1;try{o("info",`Preparing a worktree for ${r} to merge ${s} into it`),await Xs(n,l,r),c=!0;let d=await al(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 k=d.conflicts;o("info",`git merged everything except ${k.length} file(s): ${k.slice(0,20).join(", ")}`+(k.length>20?", \u2026":""));let E=Ye(t.agentId);if(!E)return await Cn(l),{ok:!1,note:`no adapter for agent "${t.agentId}" on this runner`};let I=Nn(t.agentId,"edit_no_shell");if(I)return await Cn(l),{ok:!1,note:`${I} Resolve the conflicts yourself on branch ${r}, or use Rebuild on current base.`};o("info",`Asking ${E.displayName} to resolve only those files`);let $=-1,V=setInterval(()=>{cl(l,k).then(P=>{let D=k.filter(j=>!P.includes(j));D.length!==$&&($=D.length,o("info",`Conflict progress: ${D.length}/${k.length} resolved`+(D.length?` \xB7 clean: ${D.join(", ")}`:"")+(P.length?` \xB7 still conflicted: ${P.join(", ")}`:"")))}).catch(()=>{})},12e3),Y=await oi(E,{repoPath:l,prompt:gk+k.map(P=>`- ${P}`).join(`
1088
+ `),timeoutSeconds:t.timeoutSeconds,bin:Je(e,t.agentId),configDir:t.configDir,mode:"edit_no_shell",sessionId:(0,wc.randomUUID)(),onLog:(P,D)=>o(P,D)},(P,D)=>o(P==="warn"?"warn":P,D));if(clearInterval(V),p={costUsd:Y.costUsd,inputTokens:Y.inputTokens,outputTokens:Y.outputTokens},!Y.ok)return await Cn(l),{ok:!1,...p,note:`The agent could not do the resolution: ${Y.error??"it produced no output"}. Nothing was changed - the merge was rolled back. Fix that first, then Resolve again.`};f=!0;let b=await uo(l);if(b.length)return await Cn(l),{ok:!1,...p,note:`The agent left conflict markers in ${b.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 ll(l,`${i}: merge ${s}, conflicts resolved by the agent
1078
1089
 
1079
- Resolved via Allwright`)}let w=await An(l,s);if(!w.ok){let k=w.forbidden.length?`the merged result touches protected paths (${w.forbidden.slice(0,5).join(", ")})`:`the merged result is too large (${w.files} files, ${w.insertions+w.deletions} lines; limits ${In}/${En})`;return await Cn(l),{ok:!1,...p,note:`Nothing was pushed: ${k}. The merge was rolled back.`}}await Sr(l,r);let v=await Ve(l);return o("info",`Pushed the merge to ${r} (${v.slice(0,7)})`),{ok:!0,...p,freeOfCharge:!f,headSha:v,note:f?`Merged ${s} into ${r}; the agent resolved the overlapping files. The PR is the same one - review the merge commit, then approve.`:`Merged ${s} into ${r} cleanly - no agent was needed, so this cost nothing. The PR is the same one; review and approve.`}}catch(u){return await Cn(l).catch(()=>{}),{ok:!1,note:`Could not resolve the conflict: ${u instanceof Error?u.message.slice(0,300):String(u)}`}}finally{c&&(await Pt(n,l).catch(()=>{}),qp.default.rmSync(l,{recursive:!0,force:!0}))}}var vc=R(require("node:fs"),1),Hp=R(require("node:path"),1),kc=require("node:crypto");Nt();function uk(t,e){let n=e.map(r=>`$ ${r.command} (exit ${r.exitCode})
1090
+ Resolved via Allwright`)}let w=await An(l,s);if(!w.ok){let k=w.forbidden.length?`the merged result touches protected paths (${w.forbidden.slice(0,5).join(", ")})`:`the merged result is too large (${w.files} files, ${w.insertions+w.deletions} lines; limits ${En}/${In})`;return await Cn(l),{ok:!1,...p,note:`Nothing was pushed: ${k}. The merge was rolled back.`}}await Sr(l,r);let v=await Ve(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 Cn(l).catch(()=>{}),{ok:!1,note:`Could not resolve the conflict: ${d instanceof Error?d.message.slice(0,300):String(d)}`}}finally{c&&(await Pt(n,l).catch(()=>{}),qp.default.rmSync(l,{recursive:!0,force:!0}))}}var vc=R(require("node:fs"),1),Hp=R(require("node:path"),1),kc=require("node:crypto");Nt();function yk(t,e){let n=e.map(r=>`$ ${r.command} (exit ${r.exitCode})
1080
1091
  ${r.tail.slice(-2e3)}`).join(`
1081
1092
 
1082
1093
  `);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:
@@ -1089,17 +1100,17 @@ Your ONLY job is to make these commands pass, with the smallest change possible.
1089
1100
  - 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.
1090
1101
  - Do not ask questions; if you cannot fix something safely, say what you found and stop.
1091
1102
  - You have no shell; the runner re-runs every documented command after you finish.
1092
- End with one short paragraph stating exactly what you changed, or why you changed nothing.`}async function Kp(t){let{cfg:e,repoPath:n,branch:r,baseBranch:s,issueKey:i,failedTests:o,onLog:l}=t,c=Hp.default.join(Qt(),`testfix-${(0,kc.randomUUID)().slice(0,8)}`),u=!1;try{let p=Ye(t.agentId);if(!p)return{ok:!1,note:`no adapter for agent "${t.agentId}" on this runner`};let f=Nn(t.agentId,"edit_no_shell");if(f)return{ok:!1,note:f};l("info",`Preparing a worktree on ${r} for the test fix`),await Rn(n,r),await Xs(n,c,r),u=!0,await gs(c,`origin/${r}`);let w=await Ve(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 oi(p,{repoPath:c,prompt:uk(i,o),timeoutSeconds:t.timeoutSeconds,bin:Je(e,t.agentId),configDir:t.configDir,mode:"edit_no_shell",maxTurns:60,sessionId:(0,kc.randomUUID)(),onLog:(j,B)=>l(j,B)},(j,B)=>l(j==="warn"?"warn":j,B)),k={costUsd:v.costUsd,inputTokens:v.inputTokens,outputTokens:v.outputTokens};if(!v.ok)return{ok:!1,...k,note:`The fix agent could not run: ${v.error??"it produced no output"}. Nothing was changed or pushed.`};let x=await ms(c);for(let j of x.refused)l("warn",`${Xt} entry refused: ${j}`);let E=!0;try{await _r(c,`${i}: fix failing TEST.md commands
1103
+ End with one short paragraph stating exactly what you changed, or why you changed nothing.`}async function Kp(t){let{cfg:e,repoPath:n,branch:r,baseBranch:s,issueKey:i,failedTests:o,onLog:l}=t,c=Hp.default.join(Qt(),`testfix-${(0,kc.randomUUID)().slice(0,8)}`),d=!1;try{let p=Ye(t.agentId);if(!p)return{ok:!1,note:`no adapter for agent "${t.agentId}" on this runner`};let f=Nn(t.agentId,"edit_no_shell");if(f)return{ok:!1,note:f};l("info",`Preparing a worktree on ${r} for the test fix`),await Rn(n,r),await Xs(n,c,r),d=!0,await gs(c,`origin/${r}`);let w=await Ve(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 oi(p,{repoPath:c,prompt:yk(i,o),timeoutSeconds:t.timeoutSeconds,bin:Je(e,t.agentId),configDir:t.configDir,mode:"edit_no_shell",maxTurns:60,sessionId:(0,kc.randomUUID)(),onLog:(j,B)=>l(j,B)},(j,B)=>l(j==="warn"?"warn":j,B)),k={costUsd:v.costUsd,inputTokens:v.inputTokens,outputTokens:v.outputTokens};if(!v.ok)return{ok:!1,...k,note:`The fix agent could not run: ${v.error??"it produced no output"}. Nothing was changed or pushed.`};let E=await ms(c);for(let j of E.refused)l("warn",`${Xt} entry refused: ${j}`);let I=!0;try{await _r(c,`${i}: fix failing TEST.md commands
1093
1104
 
1094
- 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,...k,remaining:o,note:j}}let C=await An(c,s);if(!C.ok){await gs(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 ${In}/${En})`;return{ok:!1,...k,note:`Nothing was pushed: ${j}. The fix commit was discarded; the PR is unchanged.`}}let V=o,Y,b,$=ks(c);if($){let j=_s(vc.default.readFileSync($,"utf8"));if(j.length){l("info",`Re-running ${j.length} documented test command(s)`);let B=await Ir(c,j,{perCommandTimeoutMs:15*6e4});for(let d of B)l(d.exitCode===0?"info":"warn",`${d.exitCode===0?"PASS":"FAIL"} ${d.command} (exit ${d.exitCode})`+(d.exitCode===0?"":`
1095
- ${d.tail.slice(-1500)}`));V=B.filter(d=>d.exitCode!==0).slice(0,20).map(d=>({command:d.command.slice(0,500),exitCode:d.exitCode,tail:d.tail.slice(-4e3)})),b=B.length,Y=B.length-V.length}}await Sr(c,r);let D=await Ve(c);return l("info",`Pushed the fix to ${r} (${D.slice(0,7)})`),{ok:!0,...k,headSha:D,remaining:V,testsPassed:Y,testsTotal:b,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{u&&(await Pt(n,c).catch(()=>{}),vc.default.rmSync(c,{recursive:!0,force:!0}))}}_t();var zr=R(require("node:fs"),1),Gp=R(require("node:path"),1);rs();$e();var dk=_.object({role:_.enum(["user","agent"]),text:_.string(),steps:_.array(_.string()).default([]),files:_.array(_.string()).default([]),at:_.string().default(""),ms:_.number().int().nonnegative().default(0)}),hk=_.object({sessionId:_.string(),projectId:_.string(),title:_.string().default(""),updatedAt:_.string(),messages:_.array(dk).default([])}),pk=_.record(hk),fk=10,mk=200,_c=2e4,gk=30,yk=2e3,Wp=8,Zp=255;function Vp(){return Gp.default.join(le(),"chat-sessions.json")}function pi(){let t=Vp();if(!zr.default.existsSync(t))return{};try{return pk.parse(JSON.parse(zr.default.readFileSync(t,"utf8")))}catch{return{}}}function Yp(t){zr.default.mkdirSync(le(),{recursive:!0,mode:448});let e=Vp(),n=e+".tmp";zr.default.writeFileSync(n,JSON.stringify(t,null,2)+`
1096
- `,{mode:384}),zr.default.renameSync(n,e),zr.default.chmodSync(e,384)}function Sc(t){t.messages[t.messages.length-1]?.role==="user"&&t.messages.pop()}function Jp(t,e){e.messages=e.messages.slice(-mk),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(fk))delete t[r.sessionId];Yp(t)}function Xp(t,e,n,r=[],s=new Date().toISOString()){let i=pi(),o=i[e]??{sessionId:e,projectId:t,title:n.slice(0,80),updatedAt:s,messages:[]};Sc(o),o.messages.push({role:"user",text:n.slice(0,_c),steps:[],files:r.slice(0,Wp).map(l=>l.slice(0,Zp)),at:s,ms:0}),Jp(i,o)}function Ko(t){let e=pi(),n=e[t];if(!n)return;let r=n.messages.length;Sc(n),n.messages.length!==r&&(n.messages.length===0?delete e[t]:e[t]=n,Yp(e))}function Qp(t,e,n,r,s=[],i=[],o={}){let l=pi(),u=l[e]??{sessionId:e,projectId:t,title:n.slice(0,80),updatedAt:new Date().toISOString(),messages:[]};Sc(u),u.messages.push({role:"user",text:n.slice(0,_c),steps:[],files:i.slice(0,Wp).map(p=>p.slice(0,Zp)),at:o.askedAt||new Date().toISOString(),ms:0},{role:"agent",text:r.slice(0,_c),steps:s.slice(0,gk).map(p=>p.slice(0,yk)),files:[],at:new Date().toISOString(),ms:Math.max(0,Math.round(o.ms??0))}),Jp(l,u)}function ef(t){return Object.values(pi()).filter(e=>e.projectId===t).sort((e,n)=>n.updatedAt.localeCompare(e.updatedAt)).map(e=>({sessionId:e.sessionId,title:e.title,updatedAt:e.updatedAt,messageCount:e.messages.length}))}function fi(t){return pi()[t]??null}en();var tf=36,nf=60;function rf(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 bk=`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:
1105
+ Allwright test-fix run`)}catch{I=!1}if(!I){let j=`The agent changed nothing - its own conclusion: ${v.resultText.trim().slice(0,400)||"(no explanation given)"}`;return l("info",j),{ok:!0,...k,remaining:o,note:j}}let $=await An(c,s);if(!$.ok){await gs(c,w);let j=$.forbidden.length?`the fixed result touches protected paths (${$.forbidden.slice(0,5).join(", ")})`:`the fixed result is too large (${$.files} files, ${$.insertions+$.deletions} lines; limits ${En}/${In})`;return{ok:!1,...k,note:`Nothing was pushed: ${j}. The fix commit was discarded; the PR is unchanged.`}}let V=o,Y,b,P=ks(c);if(P){let j=_s(vc.default.readFileSync(P,"utf8"));if(j.length){l("info",`Re-running ${j.length} documented test command(s)`);let B=await Er(c,j,{perCommandTimeoutMs:15*6e4});for(let u of B)l(u.exitCode===0?"info":"warn",`${u.exitCode===0?"PASS":"FAIL"} ${u.command} (exit ${u.exitCode})`+(u.exitCode===0?"":`
1106
+ ${u.tail.slice(-1500)}`));V=B.filter(u=>u.exitCode!==0).slice(0,20).map(u=>({command:u.command.slice(0,500),exitCode:u.exitCode,tail:u.tail.slice(-4e3)})),b=B.length,Y=B.length-V.length}}await Sr(c,r);let D=await Ve(c);return l("info",`Pushed the fix to ${r} (${D.slice(0,7)})`),{ok:!0,...k,headSha:D,remaining:V,testsPassed:Y,testsTotal:b,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 Pt(n,c).catch(()=>{}),vc.default.rmSync(c,{recursive:!0,force:!0}))}}_t();var zr=R(require("node:fs"),1),Gp=R(require("node:path"),1);rs();$e();var bk=_.object({role:_.enum(["user","agent"]),text:_.string(),steps:_.array(_.string()).default([]),files:_.array(_.string()).default([]),at:_.string().default(""),ms:_.number().int().nonnegative().default(0)}),wk=_.object({sessionId:_.string(),projectId:_.string(),title:_.string().default(""),updatedAt:_.string(),messages:_.array(bk).default([])}),vk=_.record(wk),kk=10,_k=200,_c=2e4,Sk=30,Tk=2e3,Wp=8,Zp=255;function Vp(){return Gp.default.join(le(),"chat-sessions.json")}function pi(){let t=Vp();if(!zr.default.existsSync(t))return{};try{return vk.parse(JSON.parse(zr.default.readFileSync(t,"utf8")))}catch{return{}}}function Yp(t){zr.default.mkdirSync(le(),{recursive:!0,mode:448});let e=Vp(),n=e+".tmp";zr.default.writeFileSync(n,JSON.stringify(t,null,2)+`
1107
+ `,{mode:384}),zr.default.renameSync(n,e),zr.default.chmodSync(e,384)}function Sc(t){t.messages[t.messages.length-1]?.role==="user"&&t.messages.pop()}function Jp(t,e){e.messages=e.messages.slice(-_k),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(kk))delete t[r.sessionId];Yp(t)}function Xp(t,e,n,r=[],s=new Date().toISOString()){let i=pi(),o=i[e]??{sessionId:e,projectId:t,title:n.slice(0,80),updatedAt:s,messages:[]};Sc(o),o.messages.push({role:"user",text:n.slice(0,_c),steps:[],files:r.slice(0,Wp).map(l=>l.slice(0,Zp)),at:s,ms:0}),Jp(i,o)}function Ko(t){let e=pi(),n=e[t];if(!n)return;let r=n.messages.length;Sc(n),n.messages.length!==r&&(n.messages.length===0?delete e[t]:e[t]=n,Yp(e))}function Qp(t,e,n,r,s=[],i=[],o={}){let l=pi(),d=l[e]??{sessionId:e,projectId:t,title:n.slice(0,80),updatedAt:new Date().toISOString(),messages:[]};Sc(d),d.messages.push({role:"user",text:n.slice(0,_c),steps:[],files:i.slice(0,Wp).map(p=>p.slice(0,Zp)),at:o.askedAt||new Date().toISOString(),ms:0},{role:"agent",text:r.slice(0,_c),steps:s.slice(0,Sk).map(p=>p.slice(0,Tk)),files:[],at:new Date().toISOString(),ms:Math.max(0,Math.round(o.ms??0))}),Jp(l,d)}function ef(t){return Object.values(pi()).filter(e=>e.projectId===t).sort((e,n)=>n.updatedAt.localeCompare(e.updatedAt)).map(e=>({sessionId:e.sessionId,title:e.title,updatedAt:e.updatedAt,messageCount:e.messages.length}))}function fi(t){return pi()[t]??null}en();var tf=36,nf=60;function rf(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 xk=`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:
1097
1108
  Goal: what the user is trying to achieve.
1098
1109
  Decided: choices already made, including ones you talked them out of - each as one line.
1099
1110
  Constraints: rules, preferences and corrections the user gave you.
1100
1111
  Repo facts: what you learned about this codebase that is worth not re-reading.
1101
1112
  Open: what is still unresolved right now.
1102
- Write plain statements, no preamble, no closing offer of help. Do NOT emit a ticket block.`;async function sf(t,e,n){if(!fi(e))return null;let s=Ue(n,t.project,"chat");if("error"in s)return null;try{let i=await s.adapter.run({repoPath:t.repoPath,prompt:bk,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 of=`
1113
+ Write plain statements, no preamble, no closing offer of help. Do NOT emit a ticket block.`;async function sf(t,e,n){if(!fi(e))return null;let s=Ue(n,t.project,"chat");if("error"in s)return null;try{let i=await s.adapter.run({repoPath:t.repoPath,prompt:xk,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 of=`
1103
1114
 
1104
1115
  TWO OPTIONAL BLOCKS, for the dashboard's benefit. Never mention them in your prose.
1105
1116
  1. When you ASK the user something and the sensible answers are countable, end with:
@@ -1112,10 +1123,10 @@ TWO OPTIONAL BLOCKS, for the dashboard's benefit. Never mention them in your pro
1112
1123
  ["\u2026", "\u2026"]
1113
1124
  \`\`\`
1114
1125
  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.
1115
- Never emit both blocks in one reply, and never let either replace the actual answer.`;var Lr=R(require("node:fs"),1),ft=R(require("node:path"),1),Tc=300,wk=4,af=512*1024,vk=new Set([".git","node_modules","dist","build","out",".next","vendor","coverage",".venv","venv","__pycache__",".turbo",".cache"]),lf=/\.mdx?$/i;function cf(t){let e=ft.default.resolve(t),n=[],r=(s,i)=>{if(i>wk||n.length>=Tc)return;let o;try{o=Lr.default.readdirSync(s,{withFileTypes:!0})}catch{return}for(let l of o){if(n.length>=Tc)return;if(!l.isFile()||!lf.test(l.name))continue;let c=ft.default.join(s,l.name);try{let u=Lr.default.statSync(c);n.push({path:ft.default.relative(e,c).split(ft.default.sep).join("/"),sizeBytes:u.size,updatedAt:u.mtime.toISOString()})}catch{}}for(let l of o){if(n.length>=Tc)return;!l.isDirectory()||l.isSymbolicLink()||vk.has(l.name)||l.name.startsWith(".")||r(ft.default.join(s,l.name),i+1)}};return r(e,0),n}function uf(t,e){let n=ft.default.resolve(t);if(!lf.test(e))return{ok:!1,error:"only markdown files can be opened here"};let r=ft.default.resolve(n,e);if(r!==n&&!r.startsWith(n+ft.default.sep))return{ok:!1,error:"that path is outside the project checkout"};let s;try{s=Lr.default.realpathSync(r)}catch{return{ok:!1,error:"file not found in this checkout"}}let i=(()=>{try{return Lr.default.realpathSync(n)}catch{return n}})();if(s!==i&&!s.startsWith(i+ft.default.sep))return{ok:!1,error:"that path links outside the project checkout"};let o;try{o=Lr.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=Lr.default.readFileSync(s,"utf8"),c=Buffer.byteLength(l,"utf8")>af;return{ok:!0,path:ft.default.relative(i,s).split(ft.default.sep).join("/"),content:c?l.slice(0,af):l,truncated:c}}catch(l){return{ok:!1,error:l instanceof Error?l.message:"could not read the file"}}}var Te=R(xe(),1);var Go=R(require("node:fs"),1),df=R(require("node:path"),1);rs();$e();var kk=_.object({id:_.string(),name:_.string().default(""),jiraProjectKey:_.string().default(""),repoName:_.string().default(""),jiraSiteUrl:_.string().default("")}),_k=_.array(kk);function hf(){return df.default.join(le(),"synced-projects.json")}function pf(t){try{let e=t.map(n=>({id:n.id,name:n.name,jiraProjectKey:n.jiraProjectKey,repoName:n.repoName,jiraSiteUrl:n.jiraSiteUrl??""}));Go.default.mkdirSync(le(),{recursive:!0}),Go.default.writeFileSync(hf(),JSON.stringify(e,null,2),{mode:384})}catch{}}function Sk(){try{let t=_k.safeParse(JSON.parse(Go.default.readFileSync(hf(),"utf8")));return t.success?t.data:[]}catch{return[]}}function ff(t){return Sk().find(e=>e.repoName===t)??null}var Ic=R(require("node:fs"),1),Ur=R(require("node:path"),1),mf=require("node:child_process"),qr=R(xe(),1);$e();var Tk=15e4,xc=(t,e,n,r="")=>({ok:!1,file:t,checks:[e],output:r,error:n});function xk(t){let e=Ur.default.join(t,"node_modules",".bin","prisma");return Ic.default.existsSync(e)?{bin:e,prefix:[]}:{bin:"npx",prefix:["--yes","prisma"]}}function Ik(t,e){if(!(0,qr.isSelfMigrationFilename)(e))return null;let n=Ur.default.join(t,qr.SELF_MIGRATION_DIR),r=Ur.default.resolve(n,e),s=Ur.default.relative(n,r);return s!==e||s.startsWith("..")||Ur.default.isAbsolute(s)?null:r}async function gf(t){let{file:e}=t,n=Ik(t.repoPath,e);if(!n)return xc(e,{name:"file",ok:!1,detail:`"${e}" is not a migration filename`,fix:[]},`"${e}" is not a migration filename`);if(!Ic.default.existsSync(n))return xc(e,{name:"file",ok:!1,detail:`${qr.SELF_MIGRATION_DIR}/${e} does not exist in this checkout`,fix:[`cd ${t.repoPath} && git pull`]},`${qr.SELF_MIGRATION_DIR}/${e} is not in this checkout - it may be newer than the code here`);let s=Zt(t.cfg,t.repoName,t.environmentName)[t.urlSecret]?.trim();if(!s)return xc(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=Ur.default.join(t.repoPath,"apps","api"),{bin:o,prefix:l}=xk(i),c=ic([s]),u=await Ek(o,[...l,"db","execute","--url",s,"--file",n],i),p=c(u.output).slice(-8e3);return u.code!==0?{ok:!1,file:e,checks:[{name:"apply",ok:!1,detail:`prisma db execute exited ${u.code}`,fix:[`cd apps/api && npx prisma db execute --url "$DATABASE_URL" --file prisma/manual/${e}`]}],output:p,error:`applying ${e} failed (exit ${u.code})`}:{ok:!0,file:e,checks:[{name:"apply",ok:!0,detail:`${qr.SELF_MIGRATION_DIR}/${e} applied`,fix:[]}],output:p,error:""}}function Ek(t,e,n){return new Promise(r=>{(0,mf.execFile)(t,e,{cwd:n,timeout:Tk,maxBuffer:4*1024*1024,encoding:"utf8"},(s,i,o)=>{let l=[i,o].filter(Boolean).join(`
1116
- `).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 Z_=R(dm(),1),V_=R(ta(),1),Y_=R(Ps(),1),J_=R(Dc(),1),X_=R(Uc(),1),Q_=R(Gc(),1),vm=R(ia(),1),eS=R(wm(),1);var Zc=vm.default;var _i=R(require("node:crypto"),1),Lt=R(xe(),1);en();function tS(t){let e=t&&typeof t=="object"&&"name"in t?String(t.name):null;return e?`"${e}"`:"(unnamed)"}function Vc(t,e,n,r){t.push(`dropped ${e} ${n} - this runner is out of date and does not understand it yet (${r}). Update the runner (npm install -g @ticketpilot/runner) to pick it up.`)}function nS(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=Lt.ProjectConfig.safeParse(l);c.success?r.push(c.data):Vc(n,"project","",c.error.issues[0]?.message??"invalid shape")}let s=[];for(let l of Array.isArray(e.rules)?e.rules:[]){let c=Lt.RuleConfig.safeParse(l);c.success?s.push(c.data):Vc(n,"rule",tS(l),c.error.issues[0]?.message??"invalid shape")}let i=[];for(let l of Array.isArray(e.environments)?e.environments:[]){let c=Lt.EnvironmentConfig.safeParse(l);c.success?i.push(c.data):Vc(n,"environment","",c.error.issues[0]?.message??"invalid shape")}return{msg:{type:"config",projects:r,rules:s,environments:i,pollingPaused:typeof e.pollingPaused=="boolean"?e.pollingPaused:!1,publicIp:typeof e.publicIp=="string"?e.publicIp:""},warnings:n}}var rS=2e4,sS=6e4,iS=5e3,aa=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===Zc.OPEN}connect(){if(this.closed)return;g.info(`connecting to control plane at ${this.wsUrl}`);let e=new Zc(this.wsUrl,{headers:{authorization:`Bearer ${this.runnerToken}`}});this.ws=e,e.on("open",()=>{this.backoffMs=1e3,this.sendNow({type:"hello",protocolVersion:Lt.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()})},rS)}),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,Lt.parseServerMsg)(r)}catch(i){let o=nS(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,sS)}),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==="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>=iS){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=_i.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=_i.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:_i.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=_i.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,messages:n.messages.map(r=>({...r,steps:r.steps??[],files:r.files??[],at:r.at??"",ms:r.ms??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"}))})}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 la=R(require("node:fs"),1),zs=R(require("node:path"),1),Yc=require("node:child_process"),oS=/\.mdx?$/i,km=6,aS=/^[\w.\- ()]+$/;function lS(t,e){let n=e.trim().replace(/\\/g,"/").replace(/^\.\//,"");if(!n)return{ok:!1,error:"empty path"};if(zs.default.isAbsolute(n))return{ok:!1,error:"path must be repo-relative"};if(!oS.test(n))return{ok:!1,error:"only markdown files (.md) can be saved"};let r=n.split("/");if(r.length>km)return{ok:!1,error:`path deeper than ${km} levels`};for(let o of r)if(o==="."||o===".."||!aS.test(o))return{ok:!1,error:`invalid path segment "${o}"`};if(r[0]===".git")return{ok:!1,error:"cannot write under .git"};let s=zs.default.resolve(t),i=zs.default.resolve(s,n);return i!==s&&!i.startsWith(s+zs.default.sep)?{ok:!1,error:"path escapes the checkout"}:{ok:!0,abs:i,rel:n}}async function Jc(t){let e=lS(t.repoPath,t.relPath);if(!e.ok)return{ok:!1,error:e.error};if(la.default.existsSync(e.abs)&&!t.overwrite)return{ok:!1,error:`${e.rel} already exists in this checkout`};la.default.mkdirSync(zs.default.dirname(e.abs),{recursive:!0}),la.default.writeFileSync(e.abs,t.content.endsWith(`
1126
+ Never emit both blocks in one reply, and never let either replace the actual answer.`;var Lr=R(require("node:fs"),1),ft=R(require("node:path"),1),Tc=300,Ek=4,af=512*1024,Ik=new Set([".git","node_modules","dist","build","out",".next","vendor","coverage",".venv","venv","__pycache__",".turbo",".cache"]),lf=/\.mdx?$/i;function cf(t){let e=ft.default.resolve(t),n=[],r=(s,i)=>{if(i>Ek||n.length>=Tc)return;let o;try{o=Lr.default.readdirSync(s,{withFileTypes:!0})}catch{return}for(let l of o){if(n.length>=Tc)return;if(!l.isFile()||!lf.test(l.name))continue;let c=ft.default.join(s,l.name);try{let d=Lr.default.statSync(c);n.push({path:ft.default.relative(e,c).split(ft.default.sep).join("/"),sizeBytes:d.size,updatedAt:d.mtime.toISOString()})}catch{}}for(let l of o){if(n.length>=Tc)return;!l.isDirectory()||l.isSymbolicLink()||Ik.has(l.name)||l.name.startsWith(".")||r(ft.default.join(s,l.name),i+1)}};return r(e,0),n}function uf(t,e){let n=ft.default.resolve(t);if(!lf.test(e))return{ok:!1,error:"only markdown files can be opened here"};let r=ft.default.resolve(n,e);if(r!==n&&!r.startsWith(n+ft.default.sep))return{ok:!1,error:"that path is outside the project checkout"};let s;try{s=Lr.default.realpathSync(r)}catch{return{ok:!1,error:"file not found in this checkout"}}let i=(()=>{try{return Lr.default.realpathSync(n)}catch{return n}})();if(s!==i&&!s.startsWith(i+ft.default.sep))return{ok:!1,error:"that path links outside the project checkout"};let o;try{o=Lr.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=Lr.default.readFileSync(s,"utf8"),c=Buffer.byteLength(l,"utf8")>af;return{ok:!0,path:ft.default.relative(i,s).split(ft.default.sep).join("/"),content:c?l.slice(0,af):l,truncated:c}}catch(l){return{ok:!1,error:l instanceof Error?l.message:"could not read the file"}}}var Te=R(xe(),1);var Go=R(require("node:fs"),1),df=R(require("node:path"),1);rs();$e();var Rk=_.object({id:_.string(),name:_.string().default(""),jiraProjectKey:_.string().default(""),repoName:_.string().default(""),jiraSiteUrl:_.string().default("")}),Ak=_.array(Rk);function hf(){return df.default.join(le(),"synced-projects.json")}function pf(t){try{let e=t.map(n=>({id:n.id,name:n.name,jiraProjectKey:n.jiraProjectKey,repoName:n.repoName,jiraSiteUrl:n.jiraSiteUrl??""}));Go.default.mkdirSync(le(),{recursive:!0}),Go.default.writeFileSync(hf(),JSON.stringify(e,null,2),{mode:384})}catch{}}function Ck(){try{let t=Ak.safeParse(JSON.parse(Go.default.readFileSync(hf(),"utf8")));return t.success?t.data:[]}catch{return[]}}function ff(t){return Ck().find(e=>e.repoName===t)??null}var Ec=R(require("node:fs"),1),Ur=R(require("node:path"),1),mf=require("node:child_process"),qr=R(xe(),1);$e();var $k=15e4,xc=(t,e,n,r="")=>({ok:!1,file:t,checks:[e],output:r,error:n});function Pk(t){let e=Ur.default.join(t,"node_modules",".bin","prisma");return Ec.default.existsSync(e)?{bin:e,prefix:[]}:{bin:"npx",prefix:["--yes","prisma"]}}function Nk(t,e){if(!(0,qr.isSelfMigrationFilename)(e))return null;let n=Ur.default.join(t,qr.SELF_MIGRATION_DIR),r=Ur.default.resolve(n,e),s=Ur.default.relative(n,r);return s!==e||s.startsWith("..")||Ur.default.isAbsolute(s)?null:r}async function gf(t){let{file:e}=t,n=Nk(t.repoPath,e);if(!n)return xc(e,{name:"file",ok:!1,detail:`"${e}" is not a migration filename`,fix:[]},`"${e}" is not a migration filename`);if(!Ec.default.existsSync(n))return xc(e,{name:"file",ok:!1,detail:`${qr.SELF_MIGRATION_DIR}/${e} does not exist in this checkout`,fix:[`cd ${t.repoPath} && git pull`]},`${qr.SELF_MIGRATION_DIR}/${e} is not in this checkout - it may be newer than the code here`);let s=Zt(t.cfg,t.repoName,t.environmentName)[t.urlSecret]?.trim();if(!s)return xc(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=Ur.default.join(t.repoPath,"apps","api"),{bin:o,prefix:l}=Pk(i),c=ic([s]),d=await Ok(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:`${qr.SELF_MIGRATION_DIR}/${e} applied`,fix:[]}],output:p,error:""}}function Ok(t,e,n){return new Promise(r=>{(0,mf.execFile)(t,e,{cwd:n,timeout:$k,maxBuffer:4*1024*1024,encoding:"utf8"},(s,i,o)=>{let l=[i,o].filter(Boolean).join(`
1127
+ `).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 tS=R(dm(),1),nS=R(ta(),1),rS=R(Ps(),1),sS=R(Dc(),1),iS=R(Uc(),1),oS=R(Gc(),1),vm=R(ia(),1),aS=R(wm(),1);var Zc=vm.default;var _i=R(require("node:crypto"),1),Lt=R(xe(),1);en();function lS(t){let e=t&&typeof t=="object"&&"name"in t?String(t.name):null;return e?`"${e}"`:"(unnamed)"}function Vc(t,e,n,r){t.push(`dropped ${e} ${n} - this runner is out of date and does not understand it yet (${r}). Update the runner (npm install -g @ticketpilot/runner) to pick it up.`)}function cS(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=Lt.ProjectConfig.safeParse(l);c.success?r.push(c.data):Vc(n,"project","",c.error.issues[0]?.message??"invalid shape")}let s=[];for(let l of Array.isArray(e.rules)?e.rules:[]){let c=Lt.RuleConfig.safeParse(l);c.success?s.push(c.data):Vc(n,"rule",lS(l),c.error.issues[0]?.message??"invalid shape")}let i=[];for(let l of Array.isArray(e.environments)?e.environments:[]){let c=Lt.EnvironmentConfig.safeParse(l);c.success?i.push(c.data):Vc(n,"environment","",c.error.issues[0]?.message??"invalid shape")}return{msg:{type:"config",projects:r,rules:s,environments:i,pollingPaused:typeof e.pollingPaused=="boolean"?e.pollingPaused:!1,publicIp:typeof e.publicIp=="string"?e.publicIp:""},warnings:n}}var uS=2e4,dS=6e4,hS=5e3,aa=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===Zc.OPEN}connect(){if(this.closed)return;g.info(`connecting to control plane at ${this.wsUrl}`);let e=new Zc(this.wsUrl,{headers:{authorization:`Bearer ${this.runnerToken}`}});this.ws=e,e.on("open",()=>{this.backoffMs=1e3,this.sendNow({type:"hello",protocolVersion:Lt.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()})},uS)}),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,Lt.parseServerMsg)(r)}catch(i){let o=cS(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,dS)}),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==="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>=hS){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=_i.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=_i.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:_i.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=_i.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,messages:n.messages.map(r=>({...r,steps:r.steps??[],files:r.files??[],at:r.at??"",ms:r.ms??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"}))})}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 la=R(require("node:fs"),1),zs=R(require("node:path"),1),Yc=require("node:child_process"),pS=/\.mdx?$/i,km=6,fS=/^[\w.\- ()]+$/;function mS(t,e){let n=e.trim().replace(/\\/g,"/").replace(/^\.\//,"");if(!n)return{ok:!1,error:"empty path"};if(zs.default.isAbsolute(n))return{ok:!1,error:"path must be repo-relative"};if(!pS.test(n))return{ok:!1,error:"only markdown files (.md) can be saved"};let r=n.split("/");if(r.length>km)return{ok:!1,error:`path deeper than ${km} levels`};for(let o of r)if(o==="."||o===".."||!fS.test(o))return{ok:!1,error:`invalid path segment "${o}"`};if(r[0]===".git")return{ok:!1,error:"cannot write under .git"};let s=zs.default.resolve(t),i=zs.default.resolve(s,n);return i!==s&&!i.startsWith(s+zs.default.sep)?{ok:!1,error:"path escapes the checkout"}:{ok:!0,abs:i,rel:n}}async function Jc(t){let e=mS(t.repoPath,t.relPath);if(!e.ok)return{ok:!1,error:e.error};if(la.default.existsSync(e.abs)&&!t.overwrite)return{ok:!1,error:`${e.rel} already exists in this checkout`};la.default.mkdirSync(zs.default.dirname(e.abs),{recursive:!0}),la.default.writeFileSync(e.abs,t.content.endsWith(`
1117
1128
  `)?t.content:t.content+`
1118
- `);let n=i=>new Promise((o,l)=>{(0,Yc.execFile)("git",["-C",t.repoPath,...i],{timeout:12e4},(c,u,p)=>c?l(new Error(p||c.message)):o())}),r="";try{r=await new Promise((i,o)=>(0,Yc.execFile)("git",["-C",t.repoPath,"rev-parse","--abbrev-ref","HEAD"],{timeout:2e4},(l,c,u)=>l?o(new Error(u||l.message)):i(c.trim())))}catch{}let s="";try{await n(["add",e.rel]),await n(["-c","user.name=Allwright","-c","user.email=runner@allwright.local","commit","-m",t.commitMessage]);try{await n(["push"]),s=`committed and pushed to ${r||"the current branch"}`}catch(i){s=`committed locally to ${r||"the current branch"}, but push failed: `+(i instanceof Error?i.message.slice(0,200):"unknown")+" - push it from the server when convenient"}}catch(i){s="file written, but commit failed: "+(i instanceof Error?i.message.slice(0,200):"unknown")+" - commit it from the server when convenient"}return{ok:!0,note:s}}var Wr=R(require("node:fs"),1),Xc=R(require("node:path"),1),ca=require("node:child_process"),Sm=require("node:util");$e();xr();Nt();var Tm=R(xe(),1),_m=(0,Sm.promisify)(ca.execFile);function cS(t){try{return new URL(t).host}catch{return t}}function uS(t){try{return(0,ca.execFileSync)("git",["-C",t,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim()}catch{return null}}async function ua(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=cS(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 De(o);try{let k=await v.myself();s.push({name:"jira-auth",ok:!0,detail:`authenticated as ${k.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(x){s.push({name:"jira-project",ok:!1,detail:`cannot read project ${e.jiraProjectKey} on ${f}: ${Si(x)}`})}}catch(k){s.push({name:"jira-auth",ok:!1,detail:`Jira auth failed on ${f}: ${Si(k)}`})}}}let c=t.repos[e.repoName];if(c&&Wr.default.existsSync(c.path)){let f=Xc.default.join(c.path,"CLAUDE.md"),w=Wr.default.existsSync(f)&&Wr.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=Do(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(!Wr.default.existsSync(c.path))s.push({name:"repo-path",ok:!1,detail:`path does not exist: ${c.path}`});else{let f=Wr.default.existsSync(Xc.default.join(c.path,".git"));s.push({name:"repo-path",ok:!0,detail:`${c.path}${f?" (git checkout)":" (warning: not a git checkout)"}`})}let u=[...new Set([e.defaultAgent||"claude-code",...r??[]])];for(let f of u){let w=Je(t,f),v=f==="claude-code"?"claude-code":`agent:${f}`;try{let{stdout:k}=await _m(w,["--version"],{timeout:15e3});s.push({name:v,ok:!0,detail:k.trim().slice(0,100)})}catch(k){s.push({name:v,ok:!1,detail:`cannot run "${w}" for agent "${f}": ${Si(k)}`,fixNote:f==="claude-code"?"Install Claude Code on this server (npm install -g @anthropic-ai/claude-code) and log it in.":`Install the "${f}" CLI on this server, or point the runner at its binary in the config's agents section.`})}}try{let{stdout:f}=await _m("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: ${Si(f)}`})}let p=ze(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 ${Tm.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(()=>(_t(),Rr)),w=new f(p),v=await w.whoami(),k=c&&Wr.default.existsSync(c.path)?uS(c.path):null,x=k?vt(k):null;if(!x)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(x.owner,x.repo);s.push({name:"github-token",ok:E.ok&&E.canPush,detail:E.ok?E.canPush?`${v} has push access to ${x.owner}/${x.repo}`:`${v} can read ${x.owner}/${x.repo} but NOT push to it - implement rules will fail at the push`:`${v} cannot see ${x.owner}/${x.repo}: ${E.error}`,...E.ok&&E.canPush?{}:{fix:[`allwright github set "${e.repoName}"`],fixNote:`Two ways: edit the existing PAT on GitHub and add ${x.owner}/${x.repo} to it with contents:write and pull_requests:write - or give this repo its own token with the command above. A fine-grained PAT only ever covers ONE organisation, so a repo in a different org than your other projects always needs its own.`}})}}catch(f){s.push({name:"github-token",ok:!1,detail:Si(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=Zt(t,e.repoName,f.name),v=f.requiredSecrets.filter(k=>!w[k]&&!process.env[k]);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 Si(t){return(t instanceof Error?t.message:String(t)).slice(0,300)}en();Po();Fo();ru();var TS=180,xS=26e4,IS=45e3,Vm=2,ES="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.";function RS(t){try{let{packs:e,lessons:n}=vs("compose",t),r=[e.map(s=>`### ${s.name}
1129
+ `);let n=i=>new Promise((o,l)=>{(0,Yc.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,Yc.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 Wr=R(require("node:fs"),1),Xc=R(require("node:path"),1),ca=require("node:child_process"),Sm=require("node:util");$e();xr();Nt();var Tm=R(xe(),1),_m=(0,Sm.promisify)(ca.execFile);function gS(t){try{return new URL(t).host}catch{return t}}function yS(t){try{return(0,ca.execFileSync)("git",["-C",t,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim()}catch{return null}}async function ua(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=gS(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 De(o);try{let k=await v.myself();s.push({name:"jira-auth",ok:!0,detail:`authenticated as ${k.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(E){s.push({name:"jira-project",ok:!1,detail:`cannot read project ${e.jiraProjectKey} on ${f}: ${Si(E)}`})}}catch(k){s.push({name:"jira-auth",ok:!1,detail:`Jira auth failed on ${f}: ${Si(k)}`})}}}let c=t.repos[e.repoName];if(c&&Wr.default.existsSync(c.path)){let f=Xc.default.join(c.path,"CLAUDE.md"),w=Wr.default.existsSync(f)&&Wr.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=Do(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(!Wr.default.existsSync(c.path))s.push({name:"repo-path",ok:!1,detail:`path does not exist: ${c.path}`});else{let f=Wr.default.existsSync(Xc.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=Je(t,f),v=f==="claude-code"?"claude-code":`agent:${f}`;try{let{stdout:k}=await _m(w,["--version"],{timeout:15e3});s.push({name:v,ok:!0,detail:k.trim().slice(0,100)})}catch(k){s.push({name:v,ok:!1,detail:`cannot run "${w}" for agent "${f}": ${Si(k)}`,fixNote:f==="claude-code"?"Install Claude Code on this server (npm install -g @anthropic-ai/claude-code) and log it in.":`Install the "${f}" CLI on this server, or point the runner at its binary in the config's agents section.`})}}try{let{stdout:f}=await _m("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: ${Si(f)}`})}let p=ze(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 ${Tm.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(()=>(_t(),Rr)),w=new f(p),v=await w.whoami(),k=c&&Wr.default.existsSync(c.path)?yS(c.path):null,E=k?vt(k):null;if(!E)s.push({name:"github-token",ok:!0,detail:`authenticated as ${v} - repo access not checked (no local checkout yet)`});else{let I=await w.repoAccess(E.owner,E.repo);s.push({name:"github-token",ok:I.ok&&I.canPush,detail:I.ok?I.canPush?`${v} has push access to ${E.owner}/${E.repo}`:`${v} can read ${E.owner}/${E.repo} but NOT push to it - implement rules will fail at the push`:`${v} cannot see ${E.owner}/${E.repo}: ${I.error}`,...I.ok&&I.canPush?{}:{fix:[`allwright github set "${e.repoName}"`],fixNote:`Two ways: edit the existing PAT on GitHub and add ${E.owner}/${E.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:Si(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=Zt(t,e.repoName,f.name),v=f.requiredSecrets.filter(k=>!w[k]&&!process.env[k]);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 Si(t){return(t instanceof Error?t.message:String(t)).slice(0,300)}en();Po();Fo();ru();var $S=180,PS=26e4,NS=45e3,Vm=2,OS="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.";function jS(t){try{let{packs:e,lessons:n}=vs("compose",t),r=[e.map(s=>`### ${s.name}
1119
1130
  ${s.content}`).join(`
1120
1131
 
1121
1132
  `).slice(0,4e3),n.trim().slice(-4e3)].filter(Boolean).join(`
@@ -1123,17 +1134,17 @@ ${s.content}`).join(`
1123
1134
  `).trim();return r?`
1124
1135
  HOUSE RULES FOR TICKETS here - taught by this team, follow them over the generic guidance above when they conflict:
1125
1136
  ${r}
1126
- `:""}catch{return""}}function AS(t){let e=t.map(r=>r.trim()).filter(Boolean).join(`
1137
+ `:""}catch{return""}}function MS(t){let e=t.map(r=>r.trim()).filter(Boolean).join(`
1127
1138
 
1128
1139
  `);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.
1129
1140
 
1130
1141
  ${e.length>8e3?`\u2026
1131
1142
 
1132
- ${e.slice(-8e3)}`:e}`}var Ae=new Tu;Ae.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 Ym(t){g.info(`Create the token at ${Te.GITHUB_TOKEN_PERMISSIONS.where}`);for(let e of Te.GITHUB_TOKEN_PERMISSIONS.steps)g.info(` - ${e}`);g.info(Te.GITHUB_TOKEN_PERMISSIONS.note),g.info(`Then paste it below for ${t}.`)}Ae.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",Ci.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=Un.default.createInterface({input:process.stdin,output:process.stdout}),n=async(r,s,i=!1)=>{if(s)return s;let o=await e.question(`${r}: `);if(!o.trim())throw new Error(`${r} is required`);return o.trim()};try{let r=await n("Control plane URL",t.cpUrl),s=await n("Enrolment token (from the web UI)",t.enrollToken),i=Nd(t),o=i==="skip";i==="offer-skip"&&(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=jd(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=Ma.parse({controlPlaneUrl:r,runnerName:t.name,jira:l});if(c.jira){let u=await new De(c.jira).myself();g.info(`Jira credential OK - authenticated as ${u.displayName}`)}c=await kd(c,s),g.info(`Enrolled as runner "${c.runnerName}" (${c.runnerId})`),g.info(`Credentials saved to ${Wt()} (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 ou=Ae.command("repo").description("Map control-plane repo names to local checkouts");ou.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=ue(),s=un.default.resolve(e.replace(/^~(?=\/|$)/,Ci.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(un.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},be(r),g.info(`mapped repo "${t}" -> ${s}`);try{let{originUrl:i}=await Promise.resolve().then(()=>(Nt(),Ad));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?`)}dn()||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.`)});ou.command("list").description("Show configured repo mappings").action(()=>{let t=ue(),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 Jm=Ae.command("claude").description("Per-user Claude login profiles - each teammate's runs bill their OWN Claude account");Jm.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=ue(),n=e.claudeProfiles[t]?.configDir??`${Wt().replace(/runner\.json$/,"")}claude-profiles/${t}`;rt.default.mkdirSync(n,{recursive:!0,mode:448}),e.claudeProfiles[t]={configDir:n},be(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,hn.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}".`),dn()});Jm.command("list").description("Show configured Claude profiles and whether each looks logged in").action(()=>{let t=ue(),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=rt.default.existsSync(r.configDir)&&rt.default.readdirSync(r.configDir).length>0;g.info(`${n} -> ${r.configDir} ${s?"(logged in)":"(NOT logged in yet)"}`)}});ou.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=ue();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),be(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 au=Ae.command("service").description("Run the runner as a system service (starts on boot, restarts on crash)");au.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(`
1133
- `+gl(ml()));return}Ld(g)});au.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(()=>Ud(g));au.command("status").description("systemctl status for the runner service").action(()=>{(0,hn.spawn)("systemctl",["status","allwright","--no-pager"],{stdio:"inherit"}).on("exit",e=>process.exit(e??0))});Ae.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,hn.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 Us=Ae.command("jira").description("Per-repo Jira site overrides - for projects living on a different Atlassian site");Us.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=ue();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=ff(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 De(l).myself();if(e.repos[t].jira=l,be(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 De(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.`)}dn();return}catch{g.info(`The token already on this server does not work on ${r} - asking for one that does.`)}}let o=Un.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 De(w).myself();g.info(`Jira credential OK - authenticated as ${v.displayName} on ${c}`),e.repos[t].jira=w,be(e),g.info(`Saved: repo "${t}" now polls ${c} (other repos keep the runner-wide credential)`),dn()}finally{o.close()}});Us.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=ue(),e=Un.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 De(l).myself();t.jira=l,be(t),g.info(`Jira credential OK - authenticated as ${c.displayName} on ${s}`),g.info(`Saved to ${Wt()} (mode 600, this machine only). Repo overrides are untouched.`),dn()}finally{e.close()}});Us.command("show").description("Show which Jira site each repo uses (never prints tokens)").action(()=>{let t=ue();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)"}`)});Us.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=ue(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=Un.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await r.question(`Their ATLASSIAN account email [${n}]: `)).trim()||n,i=(await r.question("Their Jira API token (they create it at id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!i)throw new Error("API token is required");let o=[e.jira,...Object.values(e.repos).map(u=>u.jira)].filter(u=>!!u),l=new Set,c=!1;for(let u of o)if(!l.has(u.baseUrl)){l.add(u.baseUrl);try{let p=await new De({baseUrl:u.baseUrl,email:s,apiToken:i}).myself();g.info(`${u.baseUrl}: OK - authenticated as ${p.displayName}`),c=!0}catch{g.warn(`${u.baseUrl}: this credential does NOT work there (fine if they don't use that site)`)}}if(!c)throw new Error("credential failed on every configured Jira site - nothing saved");e.jiraUsers[n]={email:s,apiToken:i},be(e),g.info(`Saved. Dashboard actions by ${n} now post to Jira as ${s}. No restart needed.`)}finally{r.close()}});Us.command("user-list").description("Show which Allwright users have their own Jira credential here (never prints tokens)").action(()=>{let t=ue(),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}`)});Us.command("user-remove <ticketpilotEmail>").description("Delete a person's stored Jira credential").action(t=>{let e=ue(),n=t.trim().toLowerCase();if(!e.jiraUsers[n])throw new Error(`no credential stored for ${n}`);delete e.jiraUsers[n],be(e),g.info(`Removed. Dashboard actions by ${n} will now be refused until a new credential is added.`)});var qs=Ae.command("github").description("GitHub credential for implement-mode rules");qs.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=Un.default.createInterface({input:process.stdin,output:process.stdout});try{let n=t.token??void Ym("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(()=>(_t(),Rr)),s=await new r(n).whoami(),i=ue();i.github={token:n,login:s},be(i),g.info(`GitHub token OK - authenticated as ${s}`),g.info(`Saved to ${Wt()} (mode 600, this machine only)`)}finally{e.close()}});qs.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=ue();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,hn.execFileSync)("git",["-C",r,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim(),o=vt(i);if(o){let{GitHubClient:l}=await Promise.resolve().then(()=>(_t(),Rr)),c=new l(n),u=await c.repoAccess(o.owner,o.repo);if(u.ok&&u.canPush){let p=await c.whoami();g.info(`The shared token on this server already has push access to ${o.owner}/${o.repo} as ${p} - "${t}" needs nothing of its own. Storing a second token here would only give you two to rotate.`),g.info("Want a separately revocable one anyway? Paste it at the prompt below; press Enter to leave things as they are.")}}}catch{}let s=Un.default.createInterface({input:process.stdin,output:process.stdout});try{Ym(`"${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(()=>(_t(),Rr)),l=await new o(i).whoami();e.repos[t].github={token:i,login:l},be(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()}});qs.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=ue(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=Un.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(()=>(_t(),Rr)),o=await new i(s).whoami();e.githubUsers[n]={token:s,login:o},be(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()}});qs.command("user-list").description("Show which Allwright users have their own GitHub token here (never prints tokens)").action(()=>{let t=ue(),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`)});qs.command("user-remove <ticketpilotEmail>").description("Delete a person's stored GitHub token (their runs fall back to the shared token)").action(t=>{let e=ue(),n=t.trim().toLowerCase();if(!e.githubUsers[n])throw new Error(`no GitHub token stored for ${n}`);delete e.githubUsers[n],be(e),g.info(`Removed. ${n}'s runs use the repo/runner-wide token again.`)});qs.command("show").description("Show which GitHub token each repo and person would use (never prints tokens)").action(()=>{let t=ue();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 lu=Ae.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=ue();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}],be(r),g.info(`Scheduled: ${e} audit of "${t}" every ${s}h. Restart the runner to apply.`)});lu.command("schedules").description("List scheduled audits").action(()=>{let t=ue();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`)});lu.command("unschedule <repoName> <role>").description("Remove a scheduled audit").action((t,e)=>{let n=ue(),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");be(n),g.info("Removed. Restart the runner to apply.")});var cu=Ae.command("deploy").description("Deployment settings for this machine");cu.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=ue();t.deploy={enabled:!0},be(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."),dn()});cu.command("disable").description("Stop this runner from executing any deploy steps").action(()=>{let t=ue();t.deploy={enabled:!1},be(t),g.info("deployments DISABLED on this runner"),dn()});cu.command("status").description("Show whether deployments are enabled here, and which env secrets are stored").action(()=>{let t=ue();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 ha=Ae.command("env").description("Per-environment deploy secrets. Values stay on this machine, like your Jira token.");ha.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=ue(),s=Fi(t,e),i=r.environments[s]??{secrets:{}},o=[];for(let l of n){let c=l.indexOf("=");if(c<=0)throw new Error(`expected KEY=VALUE, got "${l}"`);let u=l.slice(0,c).trim();i.secrets[u]=l.slice(c+1),o.push(u)}r.environments[s]=i,be(r),g.info(`stored ${o.length} secret(s) for ${s}: ${o.join(", ")}`),g.info(`Saved to ${Wt()} (mode 600, this machine only)`),dn()});ha.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=ue().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(()=>(qm(),Um));await o({repoName:t,envName:e,dir:un.default.resolve(i.replace(/^~(?=\/|$)/,Ci.default.homedir())),port:n.port?Number(n.port):void 0,publicUrl:n.url,proxy:n.proxy,dryRun:!!n.dryRun})});ha.command("unset <repoName> <envName> <names...>").description("Remove stored secrets for an environment").action((t,e,n)=>{let r=ue(),s=Fi(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,be(r),g.info(`removed ${n.join(", ")} from ${s}`)});ha.command("list").description("Show which environments have secrets stored here (names only, never values)").action(()=>{let t=ue(),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)"}`)});Ae.command("export [file]").description("Back up ALL runner state (config+secrets, knowledge, audits, chats) to one tarball").action(t=>{try{let e=Uu(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 ${un.default.basename(e.file)}`)}catch(e){g.error(e instanceof Error?e.message:String(e)),process.exitCode=1}});Ae.command("import <file>").description("Restore runner state from an `export` tarball (existing config is kept as a .bak dir)").action(t=>{let e=rr();if(e&&sr(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=qu(t);g.info(`Restored ${n.restored.length} entries into ${le()}`),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}});Ae.command("test").alias("doctor").description("Check local setup: Jira auth, repo mappings, Claude Code binary").action(async()=>{let t=ue(),e=Object.keys(t.repos),n=Hi(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 ua(t,i),l=!Bi(t,i.repoName);for(let c of o){if(i.jiraProjectKey==="*"&&c.name==="jira-project")continue;if(l&&c.name==="jira-credentials"){n||g.warn(`[WARN] jira-credentials: nothing covers "${i.repoName}" - add a runner-wide credential with \`allwright jira set-default\`, or one for this repo with \`allwright jira set "${i.repoName}"\`.`);continue}let u=c.ok?"PASS":"FAIL";(c.ok?g.info:g.error)(`[${u}] ${c.name}: ${c.detail}`),s&&=c.ok}}s||(process.exitCode=1)});function dn(){let t=rr()??as();if(t&&sr(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?Vu(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 CS(t){if(!t.runnerToken)throw new Error("runner not enrolled - run `allwright init`");let e=Zu();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",La);let n=t.jira?new De(t.jira):pl(),r=new Map,s=d=>{let m=t.repos[d]?.jira;if(!m)return n;let y=r.get(d);return y||(y=new De(m),r.set(d,y)),y},i=new Map,o=(d,m)=>{let y=Pd(ke()??t,d,m);switch(y.kind){case"legacy":return{jira:s(d),authored:!1};case"self":return{jira:s(d),authored:!0};case"missing":return{error:y.error};case"user":{let I=`${y.creds.baseUrl}:${y.creds.email}:${y.creds.apiToken.slice(-6)}`,P=i.get(I);return P||(P=new De(y.creds),i.set(I,P)),{jira:P,authored:!0}}}},l=new URL("/api/runner/ws",t.controlPlaneUrl);l.protocol=l.protocol==="https:"?"wss:":"ws:";let c=[],u=[],p=[],f,w=null,v={cfg:t,jiraFor:s,transport:null},k=new Set,x=async(d,m,y)=>{if(!(m.length<2))for(let I=0;I<m.length;I++){let{text:P,changed:K}=Md(y[I]??"",m);K&&await d.updateDescription(m[I],P).then(()=>g.info(`Compose: rewrote sibling ticket refs in ${m[I]} to real keys`)).catch(U=>g.warn(`Compose: could not rewrite refs in ${m[I]}: ${U instanceof Error?U.message:U}`))}},E=d=>{let m=c.find(I=>I.id===d),y=m&&t.repos[m.repoName];return m&&y?{project:m,repoPath:y.path}:null},C=d=>{let m=c.find(P=>P.id===d),y=t.runnerName?`This runner ("${t.runnerName}")`:"This runner";if(!m)return`${y} does not know that project at all - it may have been deleted, or this runner has not synced yet.`;let I=Object.keys(t.repos).join(", ")||"(none)";return`${y} has no local checkout for "${m.name}" (repo "${m.repoName}"). Repos mapped here: ${I}. 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:(d,m)=>{let y=E(d),I=p.find(P=>P.projectId===d&&P.name===m);return y&&I?{...y,environment:I}:null}},Y=new Map,b=new aa(l.toString(),t.runnerToken,{runnerVersion:so},{onConfig:d=>{c=d.projects,pf(d.projects),u=d.rules,p=d.environments,bp(d.publicIp),f.setConfig(d.projects,d.rules,d.pollingPaused,d.environments)},onDeployFix:async d=>{let m=E(d.projectId);if(!m){b.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:C(d.projectId)});return}let y=Ue(t,m.project,"assist");if("error"in y){b.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:y.error});return}g.info(`investigating failed deploy of "${d.environmentName}" (step: ${d.failedStep||"?"})`);let I=await Mp({agent:y,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,steps:d.steps,failedStep:d.failedStep,errorText:d.errorText,cfg:t});b.sendDeploySuggestResult(d.requestId,I)},onProjectTest:async d=>{let m=c.find(I=>I.id===d.projectId);if(!m){b.sendProjectTestResult(d.requestId,!1,[{name:"config",ok:!1,detail:"project not in this runner's synced config yet"}]);return}g.info(`running connection test for project "${m.name}"`);let y=await ua(ke()??t,m,p.filter(I=>I.projectId===m.id),u.filter(I=>I.projectId===m.id).map(I=>"agent"in I.action?I.action.agent:"").filter(Boolean));b.sendProjectTestResult(d.requestId,y.every(I=>I.ok),y)},onRuleDiagnose:async d=>{let m=u.find(F=>F.id===d.ruleId),y=m&&c.find(F=>F.id===m.projectId);if(!m||!y){b.sendRuleDiagnoseResult(d.requestId,{checks:[{name:"config",ok:!1,detail:"rule not in this runner's synced config yet"}],matchedCount:0,excludedCount:0,excludedSample:[]});return}g.info(`diagnosing rule "${m.name}"`);let I=await ua(ke()??t,y,m.action.type==="deploy"?p.filter(F=>F.projectId===y.id):[]),P=m.action.type==="implement"?I:I.filter(F=>F.name!=="github-token"),{matchedCount:K,excludedCount:U,excludedSample:W}=await f.diagnoseRule(m,y);b.sendRuleDiagnoseResult(d.requestId,{checks:P,matchedCount:K,excludedCount:U,excludedSample:W})},onCancel:d=>{Wh(d)?g.info(`run ${d} stopped from the dashboard`):g.warn(`cancel requested for run ${d}, but nothing is running under that id here - it likely finished already`)},onApproved:(d,m)=>{if(oc(d)){$p(V,d).catch(y=>g.error(`deploy approval crashed for ${d}: ${y instanceof Error?y.stack:y}`));return}li(v,d,m).catch(y=>g.error(`approval handling crashed for ${d}: ${y instanceof Error?y.stack:y}`))},onRetryPush:d=>{let m=To(d),y=()=>rp(v,d).catch(I=>g.error(`retry push crashed for ${d}: ${I instanceof Error?I.stack:I}`));m?f.runOnRepoQueue(m.baseRepoPath,y):y()},onRejected:d=>{if(oc(d)){Pp(V,d).catch(m=>g.error(`deploy rejection crashed for ${d}: ${m instanceof Error?m.stack:m}`));return}np(v,d).catch(m=>g.error(`rejection handling crashed for ${d}: ${m instanceof Error?m.stack:m}`))},onDeployStart:d=>{let m=`${d.runId}#${d.attempt}`;if(k.has(m))return;k.add(m);let y=E(d.projectId);if(!y){let I=C(d.projectId);g.error(`deploy ${d.runId}: ${I}`),b.send({type:"run.status",runId:d.runId,status:"failed",error:I});return}g.info(`deploy ${d.runId} requested from the dashboard: ${d.issueKey} \u2192 ${d.environment.name}`),f.runOnEnvironmentQueue(d.environment.id,()=>Mo({runId:d.runId,project:y.project,environment:d.environment,issueKey:d.issueKey,issueSummary:d.issueSummary,repoPath:y.repoPath,cfg:t,jira:s(y.project.repoName),transport:b,requestedBy:d.requestedBy}).catch(I=>g.error(`deploy crashed for ${d.runId}: ${I instanceof Error?I.stack:I}`)))},onDeploySuggest:async d=>{let m=E(d.projectId);if(!m){b.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:C(d.projectId)});return}let y=Ue(t,m.project,"assist");if("error"in y){b.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:y.error});return}g.info(`asking ${y.adapter.displayName} for "${d.environmentName}" deploy steps in ${m.repoPath}`);let I=await Dp({agent:y,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,notes:d.notes,timeoutSeconds:d.timeoutSeconds,cfg:t});b.sendDeploySuggestResult(d.requestId,I)},onEnvPreflight:async d=>{let m=E(d.projectId);if(!m){b.sendEnvPreflightResult(d.requestId,{ok:!1,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project"}]});return}let y=await Op({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,steps:d.steps,requiredSecrets:d.requiredSecrets,workdir:d.workdir,branch:d.branch,publicUrl:d.publicUrl,cfg:t});b.sendEnvPreflightResult(d.requestId,y)},onSelfMigrationApply:async d=>{let m=E(d.projectId);if(!m){b.sendSelfMigrationApplyResult(d.requestId,{ok:!1,file:d.file,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project",fix:[]}],output:"",error:C(d.projectId)});return}g.info(`applying migration ${d.file} for "${d.environmentName}"`);let y=await gf({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,file:d.file,urlSecret:d.urlSecret,cfg:t});g.info(y.ok?`migration ${d.file} applied`:`migration ${d.file} failed: ${y.error}`),b.sendSelfMigrationApplyResult(d.requestId,y)},onAutopilotPlan:async d=>{try{let m=E(d.projectId);if(!m){b.sendAutopilotPlanResult(d.requestId,{ok:!1,error:C(d.projectId)});return}let y=s(m.project.repoName),I=[];for(let z of d.issueKeys)try{let oe=await y.getIssue(z);I.push(`${z}: ${oe.summary}
1134
- ${(oe.description||"").slice(0,500)}`)}catch{I.push(`${z}: (could not read from Jira)`)}let P=Ue(t,m.project,"assist");if("error"in P){b.sendAutopilotPlanResult(d.requestId,{ok:!1,error:P.error});return}let K=`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.
1143
+ ${e.slice(-8e3)}`:e}`}var Ae=new Tu;Ae.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 Ym(t){g.info(`Create the token at ${Te.GITHUB_TOKEN_PERMISSIONS.where}`);for(let e of Te.GITHUB_TOKEN_PERMISSIONS.steps)g.info(` - ${e}`);g.info(Te.GITHUB_TOKEN_PERMISSIONS.note),g.info(`Then paste it below for ${t}.`)}Ae.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",Ci.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=Un.default.createInterface({input:process.stdin,output:process.stdout}),n=async(r,s,i=!1)=>{if(s)return s;let o=await e.question(`${r}: `);if(!o.trim())throw new Error(`${r} is required`);return o.trim()};try{let r=await n("Control plane URL",t.cpUrl),s=await n("Enrolment token (from the web UI)",t.enrollToken),i=Nd(t),o=i==="skip";i==="offer-skip"&&(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=Od(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=Ma.parse({controlPlaneUrl:r,runnerName:t.name,jira:l});if(c.jira){let d=await new De(c.jira).myself();g.info(`Jira credential OK - authenticated as ${d.displayName}`)}c=await kd(c,s),g.info(`Enrolled as runner "${c.runnerName}" (${c.runnerId})`),g.info(`Credentials saved to ${Wt()} (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 ou=Ae.command("repo").description("Map control-plane repo names to local checkouts");ou.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=ue(),s=un.default.resolve(e.replace(/^~(?=\/|$)/,Ci.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(un.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},be(r),g.info(`mapped repo "${t}" -> ${s}`);try{let{originUrl:i}=await Promise.resolve().then(()=>(Nt(),Ad));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?`)}dn()||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.`)});ou.command("list").description("Show configured repo mappings").action(()=>{let t=ue(),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 Jm=Ae.command("claude").description("Per-user Claude login profiles - each teammate's runs bill their OWN Claude account");Jm.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=ue(),n=e.claudeProfiles[t]?.configDir??`${Wt().replace(/runner\.json$/,"")}claude-profiles/${t}`;rt.default.mkdirSync(n,{recursive:!0,mode:448}),e.claudeProfiles[t]={configDir:n},be(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,hn.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}".`),dn()});Jm.command("list").description("Show configured Claude profiles and whether each looks logged in").action(()=>{let t=ue(),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=rt.default.existsSync(r.configDir)&&rt.default.readdirSync(r.configDir).length>0;g.info(`${n} -> ${r.configDir} ${s?"(logged in)":"(NOT logged in yet)"}`)}});ou.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=ue();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),be(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 au=Ae.command("service").description("Run the runner as a system service (starts on boot, restarts on crash)");au.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(`
1144
+ `+gl(ml()));return}Ld(g)});au.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(()=>Ud(g));au.command("status").description("systemctl status for the runner service").action(()=>{(0,hn.spawn)("systemctl",["status","allwright","--no-pager"],{stdio:"inherit"}).on("exit",e=>process.exit(e??0))});Ae.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,hn.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 Us=Ae.command("jira").description("Per-repo Jira site overrides - for projects living on a different Atlassian site");Us.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=ue();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=ff(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 De(l).myself();if(e.repos[t].jira=l,be(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 De(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.`)}dn();return}catch{g.info(`The token already on this server does not work on ${r} - asking for one that does.`)}}let o=Un.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 De(w).myself();g.info(`Jira credential OK - authenticated as ${v.displayName} on ${c}`),e.repos[t].jira=w,be(e),g.info(`Saved: repo "${t}" now polls ${c} (other repos keep the runner-wide credential)`),dn()}finally{o.close()}});Us.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=ue(),e=Un.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 De(l).myself();t.jira=l,be(t),g.info(`Jira credential OK - authenticated as ${c.displayName} on ${s}`),g.info(`Saved to ${Wt()} (mode 600, this machine only). Repo overrides are untouched.`),dn()}finally{e.close()}});Us.command("show").description("Show which Jira site each repo uses (never prints tokens)").action(()=>{let t=ue();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)"}`)});Us.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=ue(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=Un.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 De({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},be(e),g.info(`Saved. Dashboard actions by ${n} now post to Jira as ${s}. No restart needed.`)}finally{r.close()}});Us.command("user-list").description("Show which Allwright users have their own Jira credential here (never prints tokens)").action(()=>{let t=ue(),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}`)});Us.command("user-remove <ticketpilotEmail>").description("Delete a person's stored Jira credential").action(t=>{let e=ue(),n=t.trim().toLowerCase();if(!e.jiraUsers[n])throw new Error(`no credential stored for ${n}`);delete e.jiraUsers[n],be(e),g.info(`Removed. Dashboard actions by ${n} will now be refused until a new credential is added.`)});var qs=Ae.command("github").description("GitHub credential for implement-mode rules");qs.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=Un.default.createInterface({input:process.stdin,output:process.stdout});try{let n=t.token??void Ym("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(()=>(_t(),Rr)),s=await new r(n).whoami(),i=ue();i.github={token:n,login:s},be(i),g.info(`GitHub token OK - authenticated as ${s}`),g.info(`Saved to ${Wt()} (mode 600, this machine only)`)}finally{e.close()}});qs.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=ue();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,hn.execFileSync)("git",["-C",r,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim(),o=vt(i);if(o){let{GitHubClient:l}=await Promise.resolve().then(()=>(_t(),Rr)),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=Un.default.createInterface({input:process.stdin,output:process.stdout});try{Ym(`"${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(()=>(_t(),Rr)),l=await new o(i).whoami();e.repos[t].github={token:i,login:l},be(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()}});qs.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=ue(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=Un.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(()=>(_t(),Rr)),o=await new i(s).whoami();e.githubUsers[n]={token:s,login:o},be(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()}});qs.command("user-list").description("Show which Allwright users have their own GitHub token here (never prints tokens)").action(()=>{let t=ue(),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`)});qs.command("user-remove <ticketpilotEmail>").description("Delete a person's stored GitHub token (their runs fall back to the shared token)").action(t=>{let e=ue(),n=t.trim().toLowerCase();if(!e.githubUsers[n])throw new Error(`no GitHub token stored for ${n}`);delete e.githubUsers[n],be(e),g.info(`Removed. ${n}'s runs use the repo/runner-wide token again.`)});qs.command("show").description("Show which GitHub token each repo and person would use (never prints tokens)").action(()=>{let t=ue();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 lu=Ae.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=ue();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}],be(r),g.info(`Scheduled: ${e} audit of "${t}" every ${s}h. Restart the runner to apply.`)});lu.command("schedules").description("List scheduled audits").action(()=>{let t=ue();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`)});lu.command("unschedule <repoName> <role>").description("Remove a scheduled audit").action((t,e)=>{let n=ue(),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");be(n),g.info("Removed. Restart the runner to apply.")});var cu=Ae.command("deploy").description("Deployment settings for this machine");cu.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=ue();t.deploy={enabled:!0},be(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."),dn()});cu.command("disable").description("Stop this runner from executing any deploy steps").action(()=>{let t=ue();t.deploy={enabled:!1},be(t),g.info("deployments DISABLED on this runner"),dn()});cu.command("status").description("Show whether deployments are enabled here, and which env secrets are stored").action(()=>{let t=ue();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 ha=Ae.command("env").description("Per-environment deploy secrets. Values stay on this machine, like your Jira token.");ha.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=ue(),s=Fi(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,be(r),g.info(`stored ${o.length} secret(s) for ${s}: ${o.join(", ")}`),g.info(`Saved to ${Wt()} (mode 600, this machine only)`),dn()});ha.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=ue().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(()=>(qm(),Um));await o({repoName:t,envName:e,dir:un.default.resolve(i.replace(/^~(?=\/|$)/,Ci.default.homedir())),port:n.port?Number(n.port):void 0,publicUrl:n.url,proxy:n.proxy,dryRun:!!n.dryRun})});ha.command("unset <repoName> <envName> <names...>").description("Remove stored secrets for an environment").action((t,e,n)=>{let r=ue(),s=Fi(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,be(r),g.info(`removed ${n.join(", ")} from ${s}`)});ha.command("list").description("Show which environments have secrets stored here (names only, never values)").action(()=>{let t=ue(),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)"}`)});Ae.command("export [file]").description("Back up ALL runner state (config+secrets, knowledge, audits, chats) to one tarball").action(t=>{try{let e=Uu(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 ${un.default.basename(e.file)}`)}catch(e){g.error(e instanceof Error?e.message:String(e)),process.exitCode=1}});Ae.command("import <file>").description("Restore runner state from an `export` tarball (existing config is kept as a .bak dir)").action(t=>{let e=rr();if(e&&sr(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=qu(t);g.info(`Restored ${n.restored.length} entries into ${le()}`),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}});Ae.command("test").alias("doctor").description("Check local setup: Jira auth, repo mappings, Claude Code binary").action(async()=>{let t=ue(),e=Object.keys(t.repos),n=Hi(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 ua(t,i),l=!Bi(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 dn(){let t=rr()??as();if(t&&sr(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?Vu(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 DS(t){if(!t.runnerToken)throw new Error("runner not enrolled - run `allwright init`");let e=Zu();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",La);let n=t.jira?new De(t.jira):pl(),r=new Map,s=u=>{let m=t.repos[u]?.jira;if(!m)return n;let y=r.get(u);return y||(y=new De(m),r.set(u,y)),y},i=new Map,o=(u,m)=>{let y=Pd(ke()??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)}`,A=i.get(x);return A||(A=new De(y.creds),i.set(x,A)),{jira:A,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},k=new Set,E=async(u,m,y)=>{if(!(m.length<2))for(let x=0;x<m.length;x++){let{text:A,changed:K}=Md(y[x]??"",m);K&&await u.updateDescription(m[x],A).then(()=>g.info(`Compose: rewrote sibling ticket refs in ${m[x]} to real keys`)).catch(U=>g.warn(`Compose: could not rewrite refs in ${m[x]}: ${U instanceof Error?U.message:U}`))}},I=u=>{let m=c.find(x=>x.id===u),y=m&&t.repos[m.repoName];return m&&y?{project:m,repoPath:y.path}:null},$=u=>{let m=c.find(A=>A.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=I(u),x=p.find(A=>A.projectId===u&&A.name===m);return y&&x?{...y,environment:x}:null}},Y=new Map,b=new aa(l.toString(),t.runnerToken,{runnerVersion:so},{onConfig:u=>{c=u.projects,pf(u.projects),d=u.rules,p=u.environments,bp(u.publicIp),f.setConfig(u.projects,u.rules,u.pollingPaused,u.environments)},onDeployFix:async u=>{let m=I(u.projectId);if(!m){b.sendDeploySuggestResult(u.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:$(u.projectId)});return}let y=Ue(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 Mp({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 ua(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,y.every(x=>x.ok),y)},onRuleDiagnose:async u=>{let m=d.find(F=>F.id===u.ruleId),y=m&&c.find(F=>F.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 ua(ke()??t,y,m.action.type==="deploy"?p.filter(F=>F.projectId===y.id):[]),A=m.action.type==="implement"?x:x.filter(F=>F.name!=="github-token"),{matchedCount:K,excludedCount:U,excludedSample:W}=await f.diagnoseRule(m,y);b.sendRuleDiagnoseResult(u.requestId,{checks:A,matchedCount:K,excludedCount:U,excludedSample:W})},onCancel:u=>{Wh(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(oc(u)){$p(V,u).catch(y=>g.error(`deploy approval crashed for ${u}: ${y instanceof Error?y.stack:y}`));return}li(v,u,m).catch(y=>g.error(`approval handling crashed for ${u}: ${y instanceof Error?y.stack:y}`))},onRetryPush:u=>{let m=To(u),y=()=>rp(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(oc(u)){Pp(V,u).catch(m=>g.error(`deploy rejection crashed for ${u}: ${m instanceof Error?m.stack:m}`));return}np(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(k.has(m))return;k.add(m);let y=I(u.projectId);if(!y){let x=$(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,()=>Mo({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=I(u.projectId);if(!m){b.sendDeploySuggestResult(u.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:$(u.projectId)});return}let y=Ue(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 Dp({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=I(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 jp({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=I(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:$(u.projectId)});return}g.info(`applying migration ${u.file} for "${u.environmentName}"`);let y=await gf({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=I(u.projectId);if(!m){b.sendAutopilotPlanResult(u.requestId,{ok:!1,error:$(u.projectId)});return}let y=s(m.project.repoName),x=[];for(let z of u.issueKeys)try{let oe=await y.getIssue(z);x.push(`${z}: ${oe.summary}
1145
+ ${(oe.description||"").slice(0,500)}`)}catch{x.push(`${z}: (could not read from Jira)`)}let A=Ue(t,m.project,"assist");if("error"in A){b.sendAutopilotPlanResult(u.requestId,{ok:!1,error:A.error});return}let K=`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.
1135
1146
 
1136
- `+I.join(`
1147
+ `+x.join(`
1137
1148
 
1138
1149
  `)+`
1139
1150
 
@@ -1144,7 +1155,7 @@ Rules:
1144
1155
  - "order": every key exactly once. Prerequisites before the work that needs them.
1145
1156
  - "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.
1146
1157
  - "dependencies": ONLY hard prerequisites, where the blocked ticket CANNOT pass if the other failed. An empty list is the normal answer.
1147
- - "reasoning": 2-3 short lines a person can check your plan against.`,U=await P.adapter.run({repoPath:m.repoPath,prompt:K,timeoutSeconds:90,bin:P.bin,mode:"read_only",maxTurns:3,model:P.adapter.fastModel,sessionId:(0,Ln.randomUUID)(),onLog:()=>{}}),W=bc(U.resultText,d.issueKeys);if(!W){b.sendAutopilotPlanResult(d.requestId,{ok:!1,error:"the planner's answer could not be parsed - the queue keeps its given order"});return}let{saveBatchPlan:F}=await Promise.resolve().then(()=>(Fo(),Lp));F({batchId:d.batchId,projectId:d.projectId,order:W.order,chains:W.chains,dependencies:W.dependencies,reasoning:W.reasoning}),b.sendAutopilotPlanResult(d.requestId,{ok:!0,...W})}catch(m){b.sendAutopilotPlanResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onChatDiagnostic:async d=>{try{let{runDiagnostic:m}=await Promise.resolve().then(()=>(ru(),Rm)),y=await m({command:d.command,args:d.args});g.info(`chat diagnostic (user-approved): ${y.commandLine}`),b.sendChatDiagnosticResult(d.requestId,y)}catch(m){b.sendChatDiagnosticResult(d.requestId,{ok:!1,output:m instanceof Error?m.message:String(m)})}},onChatCancel:d=>{let m=Y.get(d.turnId);m&&(m.abort(),g.info(`chat turn ${d.turnId} stopped from the dashboard`))},onChatTurn:async d=>{let m=E(d.projectId);if(!m){b.sendChatTurnResult(d.requestId,{ok:!1,sessionId:d.sessionId??"",reply:"",error:C(d.projectId)});return}let y=d.sessionId||(0,Ln.randomUUID)(),I=!d.sessionId,P=I?0:fi(y)?.messages.length??0,K=!1,U=0,W="";if(!I&&P>=tf){let ie=await sf(m,y,t);if(ie)K=!0,U=P,W=ie,y=(0,Ln.randomUUID)(),I=!0,g.info(`chat compacted: ${P} message(s) summarized into a fresh session`);else if(P>=nf){b.sendChatTurnResult(d.requestId,{ok:!1,sessionId:y,reply:"",error:"this chat is very long and could not be compacted automatically - start a new chat (it keeps the repo knowledge; only the conversation resets)."});return}}let F=d.files.length?Hu(m.repoPath,d.requestId,d.files):null,z=(0,Te.replyPreferenceAppendix)({language:d.replyLanguage,languageInstruction:d.replyLanguageInstruction,style:d.replyStyle})+(0,Te.pendingMigrationsAppendix)(d.pendingMigrations)+(0,Te.deployTargetsAppendix)(d.environments)+(0,Te.composeCommandAppendix)(d.command),oe=RS(m.repoPath),Z="```",fe=I?`You are the project assistant for "${m.project.name}" - this working directory is its repository, and you have read-only access.
1158
+ - "reasoning": 2-3 short lines a person can check your plan against.`,U=await A.adapter.run({repoPath:m.repoPath,prompt:K,timeoutSeconds:90,bin:A.bin,mode:"read_only",maxTurns:3,model:A.adapter.fastModel,sessionId:(0,Ln.randomUUID)(),onLog:()=>{}}),W=bc(U.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:F}=await Promise.resolve().then(()=>(Fo(),Lp));F({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(()=>(ru(),Rm)),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)})}},onChatCancel:u=>{let m=Y.get(u.turnId);m&&(m.abort(),g.info(`chat turn ${u.turnId} stopped from the dashboard`))},onChatTurn:async u=>{let m=I(u.projectId);if(!m){b.sendChatTurnResult(u.requestId,{ok:!1,sessionId:u.sessionId??"",reply:"",error:$(u.projectId)});return}let y=u.sessionId||(0,Ln.randomUUID)(),x=!u.sessionId,A=x?0:fi(y)?.messages.length??0,K=!1,U=0,W="";if(!x&&A>=tf){let ie=await sf(m,y,t);if(ie)K=!0,U=A,W=ie,y=(0,Ln.randomUUID)(),x=!0,g.info(`chat compacted: ${A} message(s) summarized into a fresh session`);else if(A>=nf){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 F=u.files.length?Hu(m.repoPath,u.requestId,u.files):null,z=(0,Te.replyPreferenceAppendix)({language:u.replyLanguage,languageInstruction:u.replyLanguageInstruction,style:u.replyStyle})+(0,Te.pendingMigrationsAppendix)(u.pendingMigrations)+(0,Te.deployTargetsAppendix)(u.environments)+(0,Te.composeCommandAppendix)(u.command),oe=jS(m.repoPath),Z="```",fe=x?`You are the project assistant for "${m.project.name}" - this working directory is its repository, and you have read-only access.
1148
1159
 
1149
1160
  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.
1150
1161
  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.
@@ -1162,17 +1173,17 @@ The user approves or denies each request - never assume the answer; wait for the
1162
1173
  This conversation was already running and has been compacted. Everything agreed so far, in summary form - treat it as established, do not re-ask:
1163
1174
  ${W}
1164
1175
  `:"")+z+`
1165
- ${d.userName||"The user"} says: ${d.message}`+(F?.section??""):z+Te.TICKET_RULES_APPENDIX+`
1176
+ ${u.userName||"The user"} says: ${u.message}`+(F?.section??""):z+Te.TICKET_RULES_APPENDIX+`
1166
1177
 
1167
1178
  `+oe+`
1168
- ${d.userName||"The user"} says: ${d.message}`+(F?.section??""),he=0,He=0,Ne=new Date;Xp(d.projectId,y,d.message,d.files.map(ie=>ie.name),Ne.toISOString()),b.send({type:"chat.session",requestId:d.requestId,sessionId:y});let Ie=[],re;try{let ie=Ue(t,m.project,"chat");if("error"in ie){Ko(y),b.sendChatTurnResult(d.requestId,{ok:!1,sessionId:y,reply:"",error:ie.error});return}let je=new AbortController;Y.set(d.requestId,je);let Xm=Date.now(),uu={repoPath:m.repoPath,prompt:fe,signal:je.signal,timeoutSeconds:TS,bin:ie.bin,mode:"read_only",maxTurns:25,model:d.model||ie.adapter.fastModel,sessionId:y,resume:!I,onLog:(Xe,It)=>{Xe==="agent"&&(Ie.push(It.slice(0,4e3)),b.send({type:"chat.stream",requestId:d.requestId,seq:he++,text:It.slice(0,8e3)}))},onTool:(Xe,It)=>{b.send({type:"chat.activity",requestId:d.requestId,seq:He++,verb:Xe,target:It})},onUsage:Xe=>{b.send({type:"chat.usage",requestId:d.requestId,inputTokens:Math.round(Xe.inputTokens),outputTokens:Math.round(Xe.outputTokens),cacheReadTokens:Xe.cacheReadTokens===void 0?void 0:Math.round(Xe.cacheReadTokens),turns:Xe.turns})}};re=await ie.adapter.run(uu);let pa=0;for(;!re.ok&&re.turnLimitHit&&!re.cancelled&&ie.adapter.capabilities.sessionResume&&pa<Vm;){let Xe=xS-(Date.now()-Xm);if(Xe<IS)break;pa++,g.info(`chat turn ${d.requestId}: turn limit hit - resuming the same session (resume ${pa}/${Vm}, ${Math.round(Xe/1e3)}s left)`);let It=await ie.adapter.run({...uu,prompt:ES,resume:!0,timeoutSeconds:Math.floor(Xe/1e3)});It.costUsd+=re.costUsd,It.inputTokens+=re.inputTokens,It.outputTokens+=re.outputTokens,It.cacheReadTokens+=re.cacheReadTokens,re=It}!re.ok&&re.turnLimitHit&&!re.resultText.trim()&&Ie.length&&(re.resultText=AS(Ie))}finally{Y.delete(d.requestId),F&&rt.default.rmSync(F.dir,{recursive:!0,force:!0})}if(re.cancelled){Ko(y),b.sendChatTurnResult(d.requestId,{ok:!1,sessionId:y,reply:"",error:"stopped by you - the reply was cut off and nothing was saved to this chat",inputTokens:re.inputTokens,outputTokens:re.outputTokens,cacheReadTokens:re.cacheReadTokens});return}if(!re.ok&&re.timedOut&&(re.error="this question needs more room than a chat turn has - ask something narrower, or make it a ticket so a full run (with more time and the ability to execute) can take it"),re.ok){let ie=Ie.filter(je=>je.trim()&&!re.resultText.trim().startsWith(je.trim()));Qp(d.projectId,y,d.message,re.resultText,ie,d.files.map(je=>je.name),{askedAt:Ne.toISOString(),ms:Date.now()-Ne.getTime()})}else Ko(y);let pn=(re.inputTokens??0)+(re.cacheReadTokens??0);b.sendChatTurnResult(d.requestId,{contextTokens:pn,contextLimit:rf(re.model||d.model||""),compacted:K,compactedMessages:U,ok:re.ok,sessionId:y,reply:re.resultText,outputTruncated:!!re.outputTruncated,error:re.ok?void 0:re.error??"the agent produced no reply",inputTokens:re.inputTokens,outputTokens:re.outputTokens,cacheReadTokens:re.cacheReadTokens,costUsd:re.costUsd,model:re.model??""})},onChatList:d=>{b.sendChatListResult(d.requestId,ef(d.projectId))},onRepoDocs:d=>{let m=E(d.projectId);if(!m){b.sendRepoDocsResult(d.requestId,{ok:!1,docs:[],error:C(d.projectId)});return}b.sendRepoDocsResult(d.requestId,{ok:!0,docs:cf(m.repoPath)})},onRepoDocRead:d=>{let m=E(d.projectId);if(!m){b.sendRepoDocReadResult(d.requestId,{ok:!1,path:d.path,content:"",truncated:!1,error:C(d.projectId)});return}let y=uf(m.repoPath,d.path);b.sendRepoDocReadResult(d.requestId,{ok:y.ok,path:y.ok?y.path:d.path,content:y.ok?y.content:"",truncated:y.ok?y.truncated:!1,error:y.ok?void 0:y.error})},onChatLoad:d=>{let m=fi(d.sessionId);b.sendChatLoadResult(d.requestId,{ok:m!==null,projectId:m?.projectId??"",messages:m?.messages??[],error:m?void 0:"chat not found on this runner (pruned or never existed)"})},onBoardFetch:async d=>{let m=E(d.projectId);if(!m){b.sendBoardFetchResult(d.requestId,{ok:!1,columns:[],error:C(d.projectId)});return}try{let y=s(m.project.repoName),I;try{I=await y.searchBoard(`project = "${m.project.jiraProjectKey}" ORDER BY Rank ASC`,100)}catch{I=await y.searchBoard(`project = "${m.project.jiraProjectKey}" ORDER BY updated DESC`,100)}let P=await y.boardColumns(m.project.jiraProjectKey),K;if(P){K=P.map(F=>({name:F.name,issues:[]}));let W=new Map;for(let F of I){let z=P.findIndex(Z=>Z.statusIds.includes(F.statusId)),oe={key:F.key,summary:F.summary,labels:F.labels};if(z>=0)K[z].issues.push(oe);else{let Z=W.get(F.status)??[];Z.push(oe),W.set(F.status,Z)}}for(let[F,z]of W)K.push({name:F,issues:z})}else{let W=fe=>fe.trim().toLowerCase(),F=new Map,z=new Map;for(let fe of I){let he=W(fe.status);F.has(he)||F.set(he,fe.status.trim());let He=z.get(he)??[];He.push({key:fe.key,summary:fe.summary,labels:fe.labels}),z.set(he,He)}let oe=[];try{oe=await y.projectStatuses(m.project.jiraProjectKey)}catch{}let Z=[];for(let fe of oe){let he=W(fe);!Z.includes(he)&&z.has(he)&&Z.push(he)}for(let fe of z.keys())Z.includes(fe)||Z.push(fe);K=Z.map(fe=>({name:F.get(fe)??fe,issues:z.get(fe)??[]}))}let U=t.repos[m.project.repoName]?.jira??t.jira;b.sendBoardFetchResult(d.requestId,{ok:!0,browseBaseUrl:(U?.baseUrl??"").replace(/\/+$/,""),columns:K})}catch(y){b.sendBoardFetchResult(d.requestId,{ok:!1,columns:[],error:y instanceof Error?y.message:String(y)})}},onBoardTrigger:async d=>{let m=E(d.projectId);if(!m){b.sendBoardTriggerResult(d.requestId,{ok:!1,error:C(d.projectId)});return}try{let y=s(m.project.repoName),I=d.comment.trim()?o(m.project.repoName,d.requestedByEmail):{jira:y,authored:!1};if(I.error!==void 0){b.sendBoardTriggerResult(d.requestId,{ok:!1,error:I.error});return}if(d.reimplement){let P=await y.getIssue(d.issueKey),K=P.comments.filter(F=>dt(F.body)),U=K.length?Math.max(...K.map(F=>new Date(F.created).getTime())):0;if(!P.comments.some(F=>!dt(F.body)&&new Date(F.created).getTime()>U)){b.sendBoardTriggerResult(d.requestId,{ok:!1,error:`${d.issueKey} has nothing new since the last implementation - add a comment describing what should change, then hit Implement again. Re-running with the same ticket would just rebuild the same thing.`});return}await y.editLabels(d.issueKey,{remove:["agent-implemented"]})}d.removeLabel.trim()&&await y.editLabels(d.issueKey,{remove:[d.removeLabel.trim()]}),d.comment.trim()&&await I.jira.addTriggerComment(d.issueKey,`${d.comment.trim()}`+(!I.authored&&d.requestedBy?`
1179
+ ${u.userName||"The user"} says: ${u.message}`+(F?.section??""),he=0,He=0,Ne=new Date;Xp(u.projectId,y,u.message,u.files.map(ie=>ie.name),Ne.toISOString()),b.send({type:"chat.session",requestId:u.requestId,sessionId:y});let Ee=[],re;try{let ie=Ue(t,m.project,"chat");if("error"in ie){Ko(y),b.sendChatTurnResult(u.requestId,{ok:!1,sessionId:y,reply:"",error:ie.error});return}let Oe=new AbortController;Y.set(u.requestId,Oe);let Xm=Date.now(),uu={repoPath:m.repoPath,prompt:fe,signal:Oe.signal,timeoutSeconds:$S,bin:ie.bin,mode:"read_only",maxTurns:25,model:u.model||ie.adapter.fastModel,sessionId:y,resume:!x,onLog:(Xe,Et)=>{Xe==="agent"&&(Ee.push(Et.slice(0,4e3)),b.send({type:"chat.stream",requestId:u.requestId,seq:he++,text:Et.slice(0,8e3)}))},onTool:(Xe,Et)=>{b.send({type:"chat.activity",requestId:u.requestId,seq:He++,verb:Xe,target:Et})},onUsage:Xe=>{b.send({type:"chat.usage",requestId:u.requestId,inputTokens:Math.round(Xe.inputTokens),outputTokens:Math.round(Xe.outputTokens),cacheReadTokens:Xe.cacheReadTokens===void 0?void 0:Math.round(Xe.cacheReadTokens),turns:Xe.turns})}};re=await ie.adapter.run(uu);let pa=0;for(;!re.ok&&re.turnLimitHit&&!re.cancelled&&ie.adapter.capabilities.sessionResume&&pa<Vm;){let Xe=PS-(Date.now()-Xm);if(Xe<NS)break;pa++,g.info(`chat turn ${u.requestId}: turn limit hit - resuming the same session (resume ${pa}/${Vm}, ${Math.round(Xe/1e3)}s left)`);let Et=await ie.adapter.run({...uu,prompt:OS,resume:!0,timeoutSeconds:Math.floor(Xe/1e3)});Et.costUsd+=re.costUsd,Et.inputTokens+=re.inputTokens,Et.outputTokens+=re.outputTokens,Et.cacheReadTokens+=re.cacheReadTokens,re=Et}!re.ok&&re.turnLimitHit&&!re.resultText.trim()&&Ee.length&&(re.resultText=MS(Ee))}finally{Y.delete(u.requestId),F&&rt.default.rmSync(F.dir,{recursive:!0,force:!0})}if(re.cancelled){Ko(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:re.inputTokens,outputTokens:re.outputTokens,cacheReadTokens:re.cacheReadTokens});return}if(!re.ok&&re.timedOut&&(re.error="this question needs more room than a chat turn has - ask something narrower, or make it a ticket so a full run (with more time and the ability to execute) can take it"),re.ok){let ie=Ee.filter(Oe=>Oe.trim()&&!re.resultText.trim().startsWith(Oe.trim()));Qp(u.projectId,y,u.message,re.resultText,ie,u.files.map(Oe=>Oe.name),{askedAt:Ne.toISOString(),ms:Date.now()-Ne.getTime()})}else Ko(y);let pn=(re.inputTokens??0)+(re.cacheReadTokens??0);b.sendChatTurnResult(u.requestId,{contextTokens:pn,contextLimit:rf(re.model||u.model||""),compacted:K,compactedMessages:U,ok:re.ok,sessionId:y,reply:re.resultText,outputTruncated:!!re.outputTruncated,error:re.ok?void 0:re.error??"the agent produced no reply",inputTokens:re.inputTokens,outputTokens:re.outputTokens,cacheReadTokens:re.cacheReadTokens,costUsd:re.costUsd,model:re.model??""})},onChatList:u=>{b.sendChatListResult(u.requestId,ef(u.projectId))},onRepoDocs:u=>{let m=I(u.projectId);if(!m){b.sendRepoDocsResult(u.requestId,{ok:!1,docs:[],error:$(u.projectId)});return}b.sendRepoDocsResult(u.requestId,{ok:!0,docs:cf(m.repoPath)})},onRepoDocRead:u=>{let m=I(u.projectId);if(!m){b.sendRepoDocReadResult(u.requestId,{ok:!1,path:u.path,content:"",truncated:!1,error:$(u.projectId)});return}let y=uf(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=fi(u.sessionId);b.sendChatLoadResult(u.requestId,{ok:m!==null,projectId:m?.projectId??"",messages:m?.messages??[],error:m?void 0:"chat not found on this runner (pruned or never existed)"})},onBoardFetch:async u=>{let m=I(u.projectId);if(!m){b.sendBoardFetchResult(u.requestId,{ok:!1,columns:[],error:$(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 A=await y.boardColumns(m.project.jiraProjectKey),K;if(A){K=A.map(F=>({name:F.name,issues:[]}));let W=new Map;for(let F of x){let z=A.findIndex(Z=>Z.statusIds.includes(F.statusId)),oe={key:F.key,summary:F.summary,labels:F.labels};if(z>=0)K[z].issues.push(oe);else{let Z=W.get(F.status)??[];Z.push(oe),W.set(F.status,Z)}}for(let[F,z]of W)K.push({name:F,issues:z})}else{let W=fe=>fe.trim().toLowerCase(),F=new Map,z=new Map;for(let fe of x){let he=W(fe.status);F.has(he)||F.set(he,fe.status.trim());let He=z.get(he)??[];He.push({key:fe.key,summary:fe.summary,labels:fe.labels}),z.set(he,He)}let oe=[];try{oe=await y.projectStatuses(m.project.jiraProjectKey)}catch{}let Z=[];for(let fe of oe){let he=W(fe);!Z.includes(he)&&z.has(he)&&Z.push(he)}for(let fe of z.keys())Z.includes(fe)||Z.push(fe);K=Z.map(fe=>({name:F.get(fe)??fe,issues:z.get(fe)??[]}))}let U=t.repos[m.project.repoName]?.jira??t.jira;b.sendBoardFetchResult(u.requestId,{ok:!0,browseBaseUrl:(U?.baseUrl??"").replace(/\/+$/,""),columns:K})}catch(y){b.sendBoardFetchResult(u.requestId,{ok:!1,columns:[],error:y instanceof Error?y.message:String(y)})}},onBoardTrigger:async u=>{let m=I(u.projectId);if(!m){b.sendBoardTriggerResult(u.requestId,{ok:!1,error:$(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 A=await y.getIssue(u.issueKey),K=A.comments.filter(F=>dt(F.body)),U=K.length?Math.max(...K.map(F=>new Date(F.created).getTime())):0;if(!A.comments.some(F=>!dt(F.body)&&new Date(F.created).getTime()>U)){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?`
1169
1180
 
1170
- _(requested by ${d.requestedBy} via Allwright)_`:"")),g.info(`Board action on ${d.issueKey}`+(d.comment?` comment "${d.comment.trim()}"`:"")+(d.removeLabel?` -label ${d.removeLabel}`:"")+(d.requestedBy?` by ${d.requestedBy}`:"")),b.sendBoardTriggerResult(d.requestId,{ok:!0})}catch(y){b.sendBoardTriggerResult(d.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onChatCreateTicket:async d=>{let m=E(d.projectId);if(!m){b.sendChatCreateTicketResult(d.requestId,{ok:!1,issueKey:"",error:C(d.projectId)});return}try{let y=o(m.project.repoName,d.requestedByEmail);if(y.error!==void 0){b.sendChatCreateTicketResult(d.requestId,{ok:!1,issueKey:"",error:y.error});return}let I=`
1181
+ _(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=I(u.projectId);if(!m){b.sendChatCreateTicketResult(u.requestId,{ok:!1,issueKey:"",error:$(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=`
1171
1182
 
1172
1183
  ---
1173
- _Created via Allwright Compose`+(!y.authored&&d.requestedBy?` by ${d.requestedBy}`:"")+", drafted with the project agent._";if(d.asEpic&&d.createAs!=="epic_with_children"&&d.children.length){let U=d.createAs==="separate_epics"?"Epic":"Task",W=[],F=[];for(let z of d.children){let oe=(z.description||"(no description)")+I,Z=await y.jira.createIssue(m.project.jiraProjectKey,z.summary,oe,U);W.push(Z.key),F.push(oe)}await x(y.jira,W,F),g.info(`Compose created ${W.length} standalone ${U.toLowerCase()}(s)`),b.sendChatCreateTicketResult(d.requestId,{ok:!0,issueKey:W[0]??"",childKeys:W});return}let{key:P}=await y.jira.createIssue(m.project.jiraProjectKey,d.summary,(d.description||"(no description)")+I,d.asEpic?"Epic":"Task");d.files.length&&await y.jira.addAttachments(P,d.files.map(U=>({name:U.name,content:Buffer.from(U.contentBase64,"base64")}))).then(()=>g.info(`Compose attached ${d.files.length} file(s) to ${P}`)).catch(U=>g.warn(`Compose could not attach files to ${P}: ${U instanceof Error?U.message:U}`));let K=[];if(d.asEpic){let U=[];for(let W of d.children){let F=(W.description||"(no description)")+I,z=await y.jira.createIssue(m.project.jiraProjectKey,W.summary,F,"Task",P);K.push(z.key),U.push(F)}await x(y.jira,K,U),g.info(`Compose created epic ${P} with ${K.length} child ticket(s)`),b.sendChatCreateTicketResult(d.requestId,{ok:!0,issueKey:P,childKeys:K});return}d.triggerComment.trim()&&await y.jira.addTriggerComment(P,`${d.triggerComment.trim()}`+(!y.authored&&d.requestedBy?`
1184
+ _Created via Allwright Compose`+(!y.authored&&u.requestedBy?` by ${u.requestedBy}`:"")+", drafted with the project agent._";if(u.asEpic&&u.createAs!=="epic_with_children"&&u.children.length){let U=u.createAs==="separate_epics"?"Epic":"Task",W=[],F=[];for(let z of u.children){let oe=(z.description||"(no description)")+x,Z=await y.jira.createIssue(m.project.jiraProjectKey,z.summary,oe,U);W.push(Z.key),F.push(oe)}await E(y.jira,W,F),g.info(`Compose created ${W.length} standalone ${U.toLowerCase()}(s)`),b.sendChatCreateTicketResult(u.requestId,{ok:!0,issueKey:W[0]??"",childKeys:W});return}let{key:A}=await y.jira.createIssue(m.project.jiraProjectKey,u.summary,(u.description||"(no description)")+x,u.asEpic?"Epic":"Task");u.files.length&&await y.jira.addAttachments(A,u.files.map(U=>({name:U.name,content:Buffer.from(U.contentBase64,"base64")}))).then(()=>g.info(`Compose attached ${u.files.length} file(s) to ${A}`)).catch(U=>g.warn(`Compose could not attach files to ${A}: ${U instanceof Error?U.message:U}`));let K=[];if(u.asEpic){let U=[];for(let W of u.children){let F=(W.description||"(no description)")+x,z=await y.jira.createIssue(m.project.jiraProjectKey,W.summary,F,"Task",A);K.push(z.key),U.push(F)}await E(y.jira,K,U),g.info(`Compose created epic ${A} with ${K.length} child ticket(s)`),b.sendChatCreateTicketResult(u.requestId,{ok:!0,issueKey:A,childKeys:K});return}u.triggerComment.trim()&&await y.jira.addTriggerComment(A,`${u.triggerComment.trim()}`+(!y.authored&&u.requestedBy?`
1174
1185
 
1175
- _(requested by ${d.requestedBy} via Allwright)_`:"")),g.info(`Compose created ${P}`+(d.requestedBy?` for ${d.requestedBy}`:"")+(d.triggerComment?` with trigger "${d.triggerComment.trim()}"`:"")),b.sendChatCreateTicketResult(d.requestId,{ok:!0,issueKey:P})}catch(y){b.sendChatCreateTicketResult(d.requestId,{ok:!1,issueKey:"",error:y instanceof Error?y.message:String(y)})}},onAuditStart:async d=>{let m=E(d.projectId);if(!m){b.sendAuditStartResult(d.requestId,{ok:!1,error:C(d.projectId)});return}try{g.info(`Audit (${d.role}) starting on ${m.project.repoName}`+(d.scope.kind!=="repo"?` scoped to ${d.scope.kind}:${d.scope.ref}`:""));let y=Ue(t,m.project,"assist");if("error"in y){b.sendAuditStartResult(d.requestId,{ok:!1,error:y.error});return}let I=await Ss({projectId:d.projectId,repoPath:m.repoPath,role:d.role,scope:d.scope,detailLevel:d.detailLevel,model:d.model,agent:y,jira:s(m.project.repoName),baseUrl:d.baseUrl});if(!I.ok){b.sendAuditStartResult(d.requestId,{ok:!1,error:I.error});return}b.sendAuditStartResult(d.requestId,{ok:!0,audit:I.audit})}catch(y){b.sendAuditStartResult(d.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onAuditList:async d=>{try{b.sendAuditListResult(d.requestId,{ok:!0,audits:Qd(d.projectId)})}catch(m){b.sendAuditListResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditExplain:async d=>{try{let m=Tl(d.projectId,d.auditId),y=m?.findings.find(F=>F.id===d.findingId);if(!m||!y){b.sendAuditExplainResult(d.requestId,{ok:!1,error:"that finding is not on this runner any more"});return}let I=E(d.projectId);if(!I){b.sendAuditExplainResult(d.requestId,{ok:!1,error:C(d.projectId)});return}let P=Ue(t,I.project,"assist");if("error"in P){b.sendAuditExplainResult(d.requestId,{ok:!1,error:P.error});return}let K=`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.
1186
+ _(requested by ${u.requestedBy} via Allwright)_`:"")),g.info(`Compose created ${A}`+(u.requestedBy?` for ${u.requestedBy}`:"")+(u.triggerComment?` with trigger "${u.triggerComment.trim()}"`:"")),b.sendChatCreateTicketResult(u.requestId,{ok:!0,issueKey:A})}catch(y){b.sendChatCreateTicketResult(u.requestId,{ok:!1,issueKey:"",error:y instanceof Error?y.message:String(y)})}},onAuditStart:async u=>{let m=I(u.projectId);if(!m){b.sendAuditStartResult(u.requestId,{ok:!1,error:$(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=Ue(t,m.project,"assist");if("error"in y){b.sendAuditStartResult(u.requestId,{ok:!1,error:y.error});return}let x=await Ss({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:Qd(u.projectId)})}catch(m){b.sendAuditListResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditExplain:async u=>{try{let m=Tl(u.projectId,u.auditId),y=m?.findings.find(F=>F.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=I(u.projectId);if(!x){b.sendAuditExplainResult(u.requestId,{ok:!1,error:$(u.projectId)});return}let A=Ue(t,x.project,"assist");if("error"in A){b.sendAuditExplainResult(u.requestId,{ok:!1,error:A.error});return}let K=`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.
1176
1187
 
1177
1188
  FINDING (${y.severity}${y.ruleId?`, rule ${y.ruleId}`:""}):
1178
1189
  ${y.title}
@@ -1187,7 +1198,7 @@ Answer in EXACTLY these four short sections, plain words, no jargon without an i
1187
1198
  **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.
1188
1199
  **How urgent:** now / before the next release / when convenient - and why.
1189
1200
  **What fixing it takes:** rough size (an hour, a day, a project) and whether anything visible to users changes.
1190
- Nothing else - no preamble, no code.`,U=await P.adapter.run({repoPath:I.repoPath,prompt:K,timeoutSeconds:120,bin:P.bin,mode:"read_only",maxTurns:8,sessionId:(0,Ln.randomUUID)(),onLog:()=>{}}),W=U.resultText.trim();if(!U.ok||!W){b.sendAuditExplainResult(d.requestId,{ok:!1,error:U.error??"the agent returned nothing - try again"});return}b.sendAuditExplainResult(d.requestId,{ok:!0,explanation:W})}catch(m){b.sendAuditExplainResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditGet:async d=>{try{let m=Tl(d.projectId,d.auditId);if(!m){b.sendAuditGetResult(d.requestId,{ok:!1,error:"audit not found on this runner"});return}b.sendAuditGetResult(d.requestId,{ok:!0,audit:m})}catch(m){b.sendAuditGetResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditReview:async d=>{try{let m=Sl(d.projectId,d.auditId,{selected:d.selected,ticketed:d.ticketed,verdicts:d.verdicts,verdictBy:d.verdictBy});if(!m){b.sendAuditReviewResult(d.requestId,{ok:!1,error:"audit not found on this runner"});return}let y=E(d.projectId);if(y&&d.verdicts.length){let I=[];for(let P of d.verdicts){if(P.verdict==="valid"||m.lessonsWritten.includes(P.findingId))continue;let K=m.findings.find(U=>U.id===P.findingId);K&&(Rl(y.repoPath,m.role,ch(K,P.verdict,P.note,d.verdictBy)),I.push(P.findingId),g.info(`Lesson written (${m.role}): ${P.verdict} - ${K.title.slice(0,60)}`))}I.length&&(m=Sl(d.projectId,d.auditId,{markLessonsWritten:I})??m)}b.sendAuditReviewResult(d.requestId,{ok:!0,audit:m})}catch(m){b.sendAuditReviewResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onKnowledgeList:async d=>{let m=E(d.projectId);if(!m){b.sendKnowledgeListResult(d.requestId,{ok:!1,error:C(d.projectId)});return}try{b.sendKnowledgeListResult(d.requestId,{ok:!0,files:dh(m.repoPath)})}catch(y){b.sendKnowledgeListResult(d.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onKnowledgeSave:async d=>{let m=E(d.projectId);if(!m){b.sendKnowledgeSaveResult(d.requestId,{ok:!1,error:C(d.projectId)});return}try{d.append?Rl(m.repoPath,d.role,uh(d.content,d.by),d.level):hh(m.repoPath,d.role,d.level,d.source,d.name,d.content),g.info(`Knowledge ${d.append?"taught":"saved"}: ${d.role}/${d.level}/${d.name}`),b.sendKnowledgeSaveResult(d.requestId,{ok:!0})}catch(y){b.sendKnowledgeSaveResult(d.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onEpicList:async d=>{let m=E(d.projectId);if(!m){b.sendEpicListResult(d.requestId,{ok:!1,error:C(d.projectId)});return}try{let y=s(m.project.repoName);if(d.epicKey){let I=await y.epicChildren(d.epicKey);b.sendEpicListResult(d.requestId,{ok:!0,children:I})}else{let I=await y.searchEpics(m.project.jiraProjectKey);b.sendEpicListResult(d.requestId,{ok:!0,epics:I})}}catch(y){b.sendEpicListResult(d.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onEpicSuggest:async d=>{let m=E(d.projectId);if(!m){b.sendEpicSuggestResult(d.requestId,{ok:!1,error:C(d.projectId)});return}try{let y=s(m.project.repoName),I=await y.epicChildren(d.epicKey),P=Fd(I);if(!P.length){b.sendEpicSuggestResult(d.requestId,{ok:!1,error:`every child of ${d.epicKey} is already done or in an agent's hands - nothing to sequence`});return}if(P.length===1){b.sendEpicSuggestResult(d.requestId,{ok:!0,issueKey:P[0].key,reason:"It's the only pending ticket left in this epic.",considered:1});return}let K=await Promise.all(P.slice(0,12).map(async oe=>{try{let Z=await y.getIssue(oe.key);return{...oe,description:Z.description}}catch{return{...oe,description:""}}})),U=(await y.getIssue(d.epicKey).catch(()=>null))?.summary??"";g.info(`Epic suggest: weighing ${K.length} pending children of ${d.epicKey}`);let W=Ue(t,m.project,"assist");if("error"in W){b.sendEpicSuggestResult(d.requestId,{ok:!1,error:W.error});return}let F=await W.adapter.run({repoPath:m.repoPath,prompt:Bd(d.epicKey,U,K),timeoutSeconds:150,bin:W.bin,mode:"read_only",maxTurns:20,sessionId:(0,Ln.randomUUID)(),model:d.model||"claude-sonnet-5",onLog:()=>{}}),z=Hd(F.resultText,K.map(oe=>oe.key));if("error"in z){b.sendEpicSuggestResult(d.requestId,{ok:!1,error:z.error});return}g.info(`Epic suggest: ${d.epicKey} -> do ${z.issueKey} first`),b.sendEpicSuggestResult(d.requestId,{ok:!0,issueKey:z.issueKey,reason:z.reason,considered:K.length})}catch(y){b.sendEpicSuggestResult(d.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onTeamCreds:async d=>{try{let m=ke()??t;if(m.github?.token&&!m.github.login)try{let{GitHubClient:I}=await Promise.resolve().then(()=>(_t(),Rr));m.github.login=await new I(m.github.token).whoami(),be(m)}catch{}let y=Od(m,d.emails);b.sendTeamCredsResult(d.requestId,{ok:!0,...y})}catch(m){b.sendTeamCredsResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRepoUnmap:d=>{try{let m=ke();if(!m){b.sendRepoUnmapResult(d.requestId,{ok:!1,error:"this runner has no config file"});return}let y=m.repos[d.repoName];if(!y){b.sendRepoUnmapResult(d.requestId,{ok:!0,removedPath:""});return}let I=y.path;delete m.repos[d.repoName];for(let P of Object.keys(m.environments).filter(K=>K.startsWith(`${d.repoName}:`)))delete m.environments[P];m.auditSchedules=m.auditSchedules.filter(P=>P.repoName!==d.repoName),be(m),dn(),g.info(`Unmapped "${d.repoName}" (was ${I}) - its project was deleted on the dashboard. The checkout on disk was NOT touched.`),b.sendRepoUnmapResult(d.requestId,{ok:!0,removedPath:I})}catch(m){b.sendRepoUnmapResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupRecheck:d=>{try{let m=E(d.projectId);if(!m){b.sendSetupRecheckResult(d.requestId,{ok:!1,error:C(d.projectId)});return}b.sendSetupRecheckResult(d.requestId,{ok:!0,checks:gp({repoPath:m.repoPath,environments:d.environments})})}catch(m){b.sendSetupRecheckResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupStatus:async d=>{try{let m=ke()??t,{buildSetupReport:y}=await Promise.resolve().then(()=>(Zm(),Wm)),I=await y(m,d.repoNames,t);b.sendSetupStatusResult(d.requestId,{ok:!0,...I})}catch(m){b.sendSetupStatusResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdGenerate:async d=>{try{let m=E(d.projectId);if(!m){b.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let y=d.kind==="deploy"?"DEPLOY.md":d.kind==="design"?"DESIGN.md":"CLAUDE.md";g.info(`Setup: drafting ${y} for ${m.project.repoName}`);let I="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.
1201
+ Nothing else - no preamble, no code.`,U=await A.adapter.run({repoPath:x.repoPath,prompt:K,timeoutSeconds:120,bin:A.bin,mode:"read_only",maxTurns:8,sessionId:(0,Ln.randomUUID)(),onLog:()=>{}}),W=U.resultText.trim();if(!U.ok||!W){b.sendAuditExplainResult(u.requestId,{ok:!1,error:U.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=Tl(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=Sl(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=I(u.projectId);if(y&&u.verdicts.length){let x=[];for(let A of u.verdicts){if(A.verdict==="valid"||m.lessonsWritten.includes(A.findingId))continue;let K=m.findings.find(U=>U.id===A.findingId);K&&(Rl(y.repoPath,m.role,ch(K,A.verdict,A.note,u.verdictBy)),x.push(A.findingId),g.info(`Lesson written (${m.role}): ${A.verdict} - ${K.title.slice(0,60)}`))}x.length&&(m=Sl(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=I(u.projectId);if(!m){b.sendKnowledgeListResult(u.requestId,{ok:!1,error:$(u.projectId)});return}try{b.sendKnowledgeListResult(u.requestId,{ok:!0,files:dh(m.repoPath)})}catch(y){b.sendKnowledgeListResult(u.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onKnowledgeSave:async u=>{let m=I(u.projectId);if(!m){b.sendKnowledgeSaveResult(u.requestId,{ok:!1,error:$(u.projectId)});return}try{u.append?Rl(m.repoPath,u.role,uh(u.content,u.by),u.level):hh(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=I(u.projectId);if(!m){b.sendEpicListResult(u.requestId,{ok:!1,error:$(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=I(u.projectId);if(!m){b.sendEpicSuggestResult(u.requestId,{ok:!1,error:$(u.projectId)});return}try{let y=s(m.project.repoName),x=await y.epicChildren(u.epicKey),A=Fd(x);if(!A.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(A.length===1){b.sendEpicSuggestResult(u.requestId,{ok:!0,issueKey:A[0].key,reason:"It's the only pending ticket left in this epic.",considered:1});return}let K=await Promise.all(A.slice(0,12).map(async oe=>{try{let Z=await y.getIssue(oe.key);return{...oe,description:Z.description}}catch{return{...oe,description:""}}})),U=(await y.getIssue(u.epicKey).catch(()=>null))?.summary??"";g.info(`Epic suggest: weighing ${K.length} pending children of ${u.epicKey}`);let W=Ue(t,m.project,"assist");if("error"in W){b.sendEpicSuggestResult(u.requestId,{ok:!1,error:W.error});return}let F=await W.adapter.run({repoPath:m.repoPath,prompt:Bd(u.epicKey,U,K),timeoutSeconds:150,bin:W.bin,mode:"read_only",maxTurns:20,sessionId:(0,Ln.randomUUID)(),model:u.model||"claude-sonnet-5",onLog:()=>{}}),z=Hd(F.resultText,K.map(oe=>oe.key));if("error"in z){b.sendEpicSuggestResult(u.requestId,{ok:!1,error:z.error});return}g.info(`Epic suggest: ${u.epicKey} -> do ${z.issueKey} first`),b.sendEpicSuggestResult(u.requestId,{ok:!0,issueKey:z.issueKey,reason:z.reason,considered:K.length})}catch(y){b.sendEpicSuggestResult(u.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onTeamCreds:async u=>{try{let m=ke()??t;if(m.github?.token&&!m.github.login)try{let{GitHubClient:x}=await Promise.resolve().then(()=>(_t(),Rr));m.github.login=await new x(m.github.token).whoami(),be(m)}catch{}let y=jd(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=ke();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 A of Object.keys(m.environments).filter(K=>K.startsWith(`${u.repoName}:`)))delete m.environments[A];m.auditSchedules=m.auditSchedules.filter(A=>A.repoName!==u.repoName),be(m),dn(),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=I(u.projectId);if(!m){b.sendSetupRecheckResult(u.requestId,{ok:!1,error:$(u.projectId)});return}b.sendSetupRecheckResult(u.requestId,{ok:!0,checks:gp({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:y}=await Promise.resolve().then(()=>(Zm(),Wm)),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=I(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.",A=`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.
1191
1202
 
1192
1203
  Ten things decide whether this document can actually be run:
1193
1204
  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.
@@ -1201,19 +1212,19 @@ Ten things decide whether this document can actually be run:
1201
1212
  9. Health checks must fail CLOSED. A check that only fails when it matches one exact error string passes for every other failure - a different error, a timeout, an empty body. Assert the GOOD state and fail on anything else, rather than hunting for one known bad message.
1202
1213
  10. Anchor checks to something stable - a health or version endpoint, an id, a data- attribute. Marketing copy is the worst possible anchor: an editor changing a headline turns a healthy deploy red. If only copy is available, use it AND say in the document that this check must be updated when the page text changes.
1203
1214
 
1204
- Reply with ONLY the file content - no preamble, no fences around the whole thing.`+(d.environments.length?`
1215
+ Reply with ONLY the file content - no preamble, no fences around the whole thing.`+(u.environments.length?`
1205
1216
 
1206
1217
  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:
1207
- `+d.environments.map(Z=>`- ${Z.name}`+(Z.branch?` (branch ${Z.branch})`:"")+(Z.publicUrl?` serves ${Z.publicUrl}`:" - no URL given")+(Z.onThisRunner?", its deploy commands run ON THIS MACHINE, in "+(Z.workdir?`${Z.workdir}`:Z.dedicatedCheckout?"a checkout of its own, managed by the runner":"THE MAPPED CHECKOUT - the same directory as every other environment"):", deployed by a DIFFERENT machine - this runner cannot see it")).join(`
1218
+ `+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(`
1208
1219
  `)+`
1209
- If the repo shows no evidence of how one of them deploys, still write its section with VERIFY: markers rather than dropping it.`:"")+(d.kind==="deploy"?Jl({repoPath:m.repoPath,urls:d.environments.map(Z=>Z.publicUrl).filter(Boolean)})+di(m.repoPath):""),K=`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.`,U=`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.
1220
+ 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"?Jl({repoPath:m.repoPath,urls:u.environments.map(Z=>Z.publicUrl).filter(Boolean)})+di(m.repoPath):""),K=`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.`,U=`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.
1210
1221
 
1211
1222
  BLOCKERS AS REPORTED:
1212
- `+d.blockers.map((Z,fe)=>`${fe+1}. ${Z}`).join(`
1213
- `)+(d.machineState.length?`
1223
+ `+u.blockers.map((Z,fe)=>`${fe+1}. ${Z}`).join(`
1224
+ `)+(u.machineState.length?`
1214
1225
 
1215
1226
  WHAT THE MACHINE SAYS RIGHT NOW - checked seconds ago, and NEWER than the list above, which came from a document written earlier:
1216
- `+d.machineState.map(Z=>`- ${Z}`).join(`
1227
+ `+u.machineState.map(Z=>`- ${Z}`).join(`
1217
1228
  `)+`
1218
1229
  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.`:"")+`
1219
1230
 
@@ -1242,30 +1253,30 @@ Rules, and they matter more than completeness:
1242
1253
  - A blocker you cannot close from here (a decision only the owner can make, a change that belongs in the code) gets one honest line saying so and what the decision is. Do not invent a command for it.
1243
1254
  - Order them so the ones that unblock the most come first.
1244
1255
  - If a fix moves or adds a checkout, changes a port, or renames a service, the matching Allwright setting has to change too - the environment's Working directory, or the deploy steps that name the service. Say which setting and what to put in it, as its own step. A fix that lands only on the machine leaves the deploy pointing at the old one.
1245
- Reply with ONLY the guide - no preamble.`+(d.environments.length?`
1256
+ Reply with ONLY the guide - no preamble.`+(u.environments.length?`
1246
1257
 
1247
1258
  THE ENVIRONMENTS AS ALLWRIGHT HAS THEM TODAY - your instructions have to end with these matching reality:
1248
- `+d.environments.map(Z=>`- ${Z.name}`+(Z.branch?` (branch ${Z.branch})`:"")+(Z.publicUrl?` serves ${Z.publicUrl}`:"")+(Z.onThisRunner?", deploy commands run ON THIS MACHINE, in "+(Z.workdir?Z.workdir:Z.dedicatedCheckout?"a checkout of its own":"the MAPPED CHECKOUT, shared with every other environment"):", deployed by a DIFFERENT machine - none of the commands below can set it up, and the facts below say nothing about it")).join(`
1249
- `):"")+Jl({repoPath:m.repoPath,urls:d.environments.map(Z=>Z.publicUrl).filter(Boolean)})+di(m.repoPath),W=Ue(t,m.project,"assist");if("error"in W){b.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,content:"",error:W.error});return}let F=0,z=await W.adapter.run({repoPath:m.repoPath,prompt:d.kind==="deploy"?P:d.kind==="design"?K:d.kind==="unblock"?U:I,timeoutSeconds:600,bin:W.bin,mode:"read_only",maxTurns:40,sessionId:(0,Ln.randomUUID)(),onLog:(Z,fe)=>{Z==="agent"&&d.streamId&&b.send({type:"chat.stream",requestId:d.streamId,seq:F++,text:fe.slice(0,8e3)})}}),oe=z.resultText.trim();if(!oe){b.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:"the agent returned no content - try again"});return}z.outputTruncated&&g.warn(`Setup: the ${y} draft was cut off at the agent's output limit - ${oe.length} chars, incomplete`),b.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!0,content:oe,truncated:!!z.outputTruncated})}catch(m){b.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupAsk:async d=>{try{let m=E(d.projectId);if(!m){b.sendSetupAskResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let y=Ue(t,m.project,"assist");if("error"in y){b.sendSetupAskResult(d.requestId,{ok:!1,error:y.error});return}g.info(`Setup: question about "${d.subject.slice(0,60)}" (${m.project.repoName})`);let I="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."+(d.subject?`
1259
+ `+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(`
1260
+ `):"")+Jl({repoPath:m.repoPath,urls:u.environments.map(Z=>Z.publicUrl).filter(Boolean)})+di(m.repoPath),W=Ue(t,m.project,"assist");if("error"in W){b.sendSetupClaudeMdGenerateResult(u.requestId,{ok:!1,content:"",error:W.error});return}let F=0,z=await W.adapter.run({repoPath:m.repoPath,prompt:u.kind==="deploy"?A:u.kind==="design"?K:u.kind==="unblock"?U:x,timeoutSeconds:600,bin:W.bin,mode:"read_only",maxTurns:40,sessionId:(0,Ln.randomUUID)(),onLog:(Z,fe)=>{Z==="agent"&&u.streamId&&b.send({type:"chat.stream",requestId:u.streamId,seq:F++,text:fe.slice(0,8e3)})}}),oe=z.resultText.trim();if(!oe){b.sendSetupClaudeMdGenerateResult(u.requestId,{ok:!1,error:"the agent returned no content - try again"});return}z.outputTruncated&&g.warn(`Setup: the ${y} draft was cut off at the agent's output limit - ${oe.length} chars, incomplete`),b.sendSetupClaudeMdGenerateResult(u.requestId,{ok:!0,content:oe,truncated:!!z.outputTruncated})}catch(m){b.sendSetupClaudeMdGenerateResult(u.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupAsk:async u=>{try{let m=I(u.projectId);if(!m){b.sendSetupAskResult(u.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let y=Ue(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?`
1250
1261
 
1251
1262
  WHAT THEY ARE WORKING ON:
1252
- ${d.subject}`:"")+(d.command?`
1263
+ ${u.subject}`:"")+(u.command?`
1253
1264
 
1254
1265
  THE COMMAND THE SCREEN GAVE THEM:
1255
- ${d.command}`:"")+(d.machineState.length?`
1266
+ ${u.command}`:"")+(u.machineState.length?`
1256
1267
 
1257
1268
  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:
1258
- `+d.machineState.map(U=>`- ${U}`).join(`
1259
- `):"")+(d.history.length?`
1269
+ `+u.machineState.map(U=>`- ${U}`).join(`
1270
+ `):"")+(u.history.length?`
1260
1271
 
1261
1272
  EARLIER IN THIS SAME BOX:
1262
- `+d.history.map(U=>`${U.role==="user"?"THEM":"YOU"}: ${U.text}`).join(`
1273
+ `+u.history.map(U=>`${U.role==="user"?"THEM":"YOU"}: ${U.text}`).join(`
1263
1274
 
1264
1275
  `):"")+`
1265
1276
 
1266
1277
  THEIR QUESTION - usually an error they just pasted:
1267
- ${d.question}
1278
+ ${u.question}
1268
1279
 
1269
1280
  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.
1270
1281
 
1271
- 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.`,K=(await y.adapter.run({repoPath:m.repoPath,prompt:I,timeoutSeconds:120,bin:y.bin,mode:"read_only",maxTurns:6,sessionId:(0,Ln.randomUUID)(),onLog:()=>{}})).resultText.trim();b.sendSetupAskResult(d.requestId,K?{ok:!0,answer:K}:{ok:!1,error:"the agent returned nothing - ask again, or rephrase"})}catch(m){b.sendSetupAskResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdSave:async d=>{try{let m=E(d.projectId);if(!m){b.sendSetupClaudeMdSaveResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let y=d.kind==="deploy"?"DEPLOY.md":d.kind==="design"?"DESIGN.md":"CLAUDE.md",I=await Jc({repoPath:m.repoPath,relPath:y,content:d.content,overwrite:d.overwrite,commitMessage:`Add ${y} (agent-drafted, human-approved via Allwright)`});I.ok&&g.info(`Setup: wrote human-approved ${y} to ${m.repoPath} - ${I.note}`),b.sendSetupClaudeMdSaveResult(d.requestId,I)}catch(m){b.sendSetupClaudeMdSaveResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRepoDocSave:async d=>{try{let m=E(d.projectId);if(!m){b.sendRepoDocSaveResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let y=await Jc({repoPath:m.repoPath,relPath:d.relPath,content:d.content,overwrite:d.overwrite,commitMessage:`Add ${d.relPath.trim()} (written in Allwright Compose, human-approved)`});y.ok&&g.info(`Saved approved doc ${d.relPath} into ${m.repoPath}`),b.sendRepoDocSaveResult(d.requestId,y)}catch(m){b.sendRepoDocSaveResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditStats:d=>{try{b.sendAuditStatsResult(d.requestId,{ok:!0,byProject:eh(d.projectIds,d.since)})}catch(m){b.sendAuditStatsResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRunnerUpdate:async d=>{if(!process.env.INVOCATION_ID){b.sendRunnerUpdateResult(d.requestId,{ok:!1,error:"this runner is not running as a systemd service, so it cannot restart itself after updating. On the machine run: allwright update && allwright stop && allwright start"});return}let m=()=>{g.info("Installing allwright@latest");let I=un.default.dirname(process.execPath),P=rt.default.existsSync(un.default.join(I,"npm"))?un.default.join(I,"npm"):"npm";(0,hn.execFile)(P,["install","-g","allwright@latest"],{timeout:18e4,env:{...process.env,PATH:`${I}:${process.env.PATH??""}`}},(K,U,W)=>{if(K){b.sendRunnerUpdateResult(d.requestId,{ok:!1,error:`npm install failed: ${(W||K.message).slice(0,300)} - on the machine run: allwright update && sudo systemctl restart allwright`});return}b.sendRunnerUpdateResult(d.requestId,{ok:!0,note:"updated - restarting now, back in a few seconds"}),g.info("Update installed; exiting so systemd restarts on the new version"),setTimeout(()=>process.exit(0),1500)})};if(f.idle){m();return}if(w){b.sendRunnerUpdateResult(d.requestId,{ok:!0,scheduled:!0,note:"an update is already scheduled and will install once the current work finishes"});return}let y=f.busyCount;b.sendRunnerUpdateResult(d.requestId,{ok:!0,scheduled:!0,note:`scheduled - ${y} run(s)/deploy(s) active right now. Nothing is refused meanwhile; the install runs automatically as soon as this machine goes idle.`}),g.info(`Update scheduled: waiting for ${y} active run(s)/deploy(s)/chat turn(s) to finish`),w=setInterval(()=>{f.idle&&(clearInterval(w),w=null,m())},5e3)},onRunnerUninstall:d=>{if(!f.idle){b.sendRunnerUninstallResult(d.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=vl()}catch(I){b.sendRunnerUninstallResult(d.requestId,{ok:!1,error:I instanceof Error?I.message:String(I)});return}let y=m.problems.length===0;if(b.sendRunnerUninstallResult(d.requestId,{ok:y,error:y?void 0:m.problems.join("; "),note:y?[m.serviceRemoved?"service stopped and removed":"no systemd service was installed here",m.configRemoved?`config deleted (${m.removedPaths.join(", ")}) - the Jira and GitHub tokens went with it`:"no runner config was left to delete","checkouts untouched"].join("; "):"",serviceRemoved:m.serviceRemoved||m.serviceAbsent,configRemoved:m.configRemoved}),!y){g.info("Uninstall requested from the dashboard, but it could not complete here");return}g.info("Uninstalled from the dashboard - stopping now. Checkouts were not touched."),setTimeout(()=>{wl(),process.exit(0)},1500)},onTestFix:async d=>{let m=y=>b.sendTestFixResult(d.requestId,{ok:!1,note:y});try{let y=xs(d.runId);if(!y){m("this runner no longer has that PR on file - it may have been decided already");return}let I=t.repos[y.repoName];if(!I){m(`no local checkout mapped for "${y.repoName}" on this machine`);return}let P=ze(t,y.repoName);if(!P){m("no GitHub token on this runner for that repo");return}let K=await new qe(P).getPullRequest(y.owner,y.repo,y.prNumber);if(!K){m("that pull request no longer exists on GitHub");return}if(K.merged||K.state==="closed"){m("that pull request is already merged or closed - there is nothing left to fix");return}let U=c.find(oe=>oe.repoName===y.repoName),W=y.nextDecisionSeq??1e5,F=(oe,Z)=>{b.send({type:"run.log",runId:d.runId,seq:W++,ts:new Date().toISOString(),level:oe,message:Z}),y.nextDecisionSeq=W,St(y)},z=await Kp({cfg:t,repoPath:I.path,branch:y.branch,baseBranch:K.baseRef||"main",issueKey:y.issueKey,agentId:U?.defaultAgent||Te.DEFAULT_AGENT_ID,configDir:y.agentConfigDir,failedTests:d.failedTests,timeoutSeconds:900,onLog:F});z.ok&&z.headSha&&(y.headSha=z.headSha,St(y),b.send({type:"run.status",runId:d.runId,status:"awaiting_approval",headSha:z.headSha,failedTests:z.remaining??[],...z.testsPassed!==void 0?{testsPassed:z.testsPassed}:{},...z.testsTotal!==void 0?{testsTotal:z.testsTotal}:{},...z.costUsd!==void 0?{costUsd:z.costUsd}:{},...z.inputTokens!==void 0?{inputTokens:z.inputTokens}:{},...z.outputTokens!==void 0?{outputTokens:z.outputTokens}:{}})),ht(I.path,{issueKey:y.issueKey,runId:d.runId,title:z.ok?z.headSha?(z.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:z.note.slice(0,500)}),b.sendTestFixResult(d.requestId,z)}catch(y){m(y instanceof Error?y.message.slice(0,300):String(y))}},onRunAnswer:async d=>{try{let m=await f.answerPendingInput(d.runId,d.text,d.answeredBy);b.sendRunAnswerResult(d.requestId,m)}catch(m){b.sendRunAnswerResult(d.requestId,{ok:!1,error:m instanceof Error?m.message.slice(0,300):String(m)})}},onResolveConflict:async d=>{let m=y=>b.sendResolveConflictResult(d.requestId,{ok:!1,note:y});try{let y=xs(d.runId);if(!y){m("this runner no longer has that PR on file - it may have been decided already");return}let I=t.repos[y.repoName];if(!I){m(`no local checkout mapped for "${y.repoName}" on this machine`);return}let P=ze(t,y.repoName);if(!P){m("no GitHub token on this runner for that repo");return}let K=await new qe(P).getPullRequest(y.owner,y.repo,y.prNumber);if(!K){m("that pull request no longer exists on GitHub");return}if(!K.baseRef){m("GitHub did not report the PR's base branch, so there is nothing to merge in");return}let U=c.find(oe=>oe.repoName===y.repoName),W=y.nextDecisionSeq??1e5,F=(oe,Z)=>{b.send({type:"run.log",runId:d.runId,seq:W++,ts:new Date().toISOString(),level:oe,message:Z}),y.nextDecisionSeq=W,St(y)},z=await Bp({cfg:t,repoPath:I.path,branch:y.branch,baseBranch:K.baseRef,issueKey:y.issueKey,agentId:U?.defaultAgent||Te.DEFAULT_AGENT_ID,configDir:y.agentConfigDir,timeoutSeconds:900,onLog:F});z.ok&&z.headSha&&(y.headSha=z.headSha,y.conflictNotified=!1,St(y),b.send({type:"run.pr.conflict",runId:d.runId,conflicted:!1}),b.send({type:"run.status",runId:d.runId,status:"awaiting_approval",headSha:z.headSha,...z.costUsd!==void 0?{costUsd:z.costUsd}:{},...z.inputTokens!==void 0?{inputTokens:z.inputTokens}:{},...z.outputTokens!==void 0?{outputTokens:z.outputTokens}:{}})),b.sendResolveConflictResult(d.requestId,z)}catch(y){m(y instanceof Error?y.message.slice(0,300):String(y))}},onAgentProfiles:d=>{try{let m=I=>{try{return rt.default.existsSync(I)&&rt.default.readdirSync(I).length>0}catch{return!1}},y=Object.entries(t.claudeProfiles).map(([I,P])=>({agent:"claude-code",name:I,loggedIn:m(P.configDir)}));b.sendAgentProfilesResult(d.requestId,{ok:!0,profiles:y,defaultLoggedIn:m(un.default.join(Ci.default.homedir(),".claude")),agentsWithoutProfiles:Te.REGISTERED_AGENTS.filter(I=>!I.capabilities.loginProfiles).map(I=>I.id)})}catch(m){b.sendAgentProfilesResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onJiraUsers:async d=>{try{let m=await n.searchUsers(d.query);b.sendJiraUsersResult(d.requestId,{ok:!0,users:m})}catch(m){b.sendJiraUsersResult(d.requestId,{ok:!1,users:[],error:m instanceof Error?m.message:String(m)})}}});v.transport=b,f=new Ho(t,s,b),f.setExternalBusy(()=>Y.size);let $=Object.values(Cr()).filter(d=>d.kind==="implement").map(d=>d.repoPath);nl(Object.values(t.repos).map(d=>d.path),$).catch(()=>{}),b.start(),f.start();let D=()=>{g.info("shutting down"),w&&clearInterval(w),b.stop(),Wu(process.pid),La(),process.exit(0)},j=!1,B=()=>{if(j){g.warn("second stop signal - exiting NOW; the interrupted run will be marked failed"),D();return}if(j=!0,f.stop(),f.idle){D();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 d=setInterval(()=>{f.idle&&(clearInterval(d),D())},3e3)};process.on("SIGINT",B),process.on("SIGTERM",B),process.on("SIGHUP",()=>{try{let d=ue();for(let m of Object.keys(t))delete t[m];Object.assign(t,d),n=d.jira?new De(d.jira):pl(),r.clear(),g.info("config reloaded live - new Jira tokens/repos/rules apply from the next poll. (Poll interval and control-plane URL still need a restart.)")}catch(d){g.error(`config reload failed - keeping the running config: ${d instanceof Error?d.message:String(d)}`)}})}Ae.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=ue();if(t.foreground){CS(e);return}let n=rr();if(n&&sr(n)){g.info(`already running in the background (pid ${n}). Use \`allwright status\` or \`stop\`.`);return}let r=as();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=Ku(),i=(0,hn.spawn)(process.execPath,[process.argv[1],"start","--foreground"],{detached:!0,stdio:["ignore",s,s]});i.unref(),Gu(i.pid),g.info(`Runner started in the background (pid ${i.pid}).`),g.info(`Logs: ${Zi()}`),g.info("It will keep polling Jira until you run `allwright stop` - closing this terminal is fine.")});Ae.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=rr();if(!e||!sr(e)){g.info("no background runner is running"),e&&rt.default.rmSync(os(),{force:!0});return}if(t.force){process.kill(e,"SIGKILL"),rt.default.rmSync(os(),{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.`)});Ae.command("status").description("Check whether the background runner is running").action(()=>{let t=rr();t&&sr(t)?g.info(`running in the background (pid ${t})`):g.info("not running")});Ae.parseAsync().catch(t=>{g.error(t instanceof Error?t.message:String(t)),process.exit(1)});
1282
+ 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.`,K=(await y.adapter.run({repoPath:m.repoPath,prompt:x,timeoutSeconds:120,bin:y.bin,mode:"read_only",maxTurns:6,sessionId:(0,Ln.randomUUID)(),onLog:()=>{}})).resultText.trim();b.sendSetupAskResult(u.requestId,K?{ok:!0,answer:K}:{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=I(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 Jc({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=I(u.projectId);if(!m){b.sendRepoDocSaveResult(u.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let y=await Jc({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:eh(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=un.default.dirname(process.execPath),A=rt.default.existsSync(un.default.join(x,"npm"))?un.default.join(x,"npm"):"npm";(0,hn.execFile)(A,["install","-g","allwright@latest"],{timeout:18e4,env:{...process.env,PATH:`${x}:${process.env.PATH??""}`}},(K,U,W)=>{if(K){b.sendRunnerUpdateResult(u.requestId,{ok:!1,error:`npm install failed: ${(W||K.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=vl()}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(()=>{wl(),process.exit(0)},1500)},onTestFix:async u=>{let m=y=>b.sendTestFixResult(u.requestId,{ok:!1,note:y});try{let y=xs(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 A=ze(t,y.repoName);if(!A){m("no GitHub token on this runner for that repo");return}let K=await new qe(A).getPullRequest(y.owner,y.repo,y.prNumber);if(!K){m("that pull request no longer exists on GitHub");return}if(K.merged||K.state==="closed"){m("that pull request is already merged or closed - there is nothing left to fix");return}let U=c.find(oe=>oe.repoName===y.repoName),W=y.nextDecisionSeq??1e5,F=(oe,Z)=>{b.send({type:"run.log",runId:u.runId,seq:W++,ts:new Date().toISOString(),level:oe,message:Z}),y.nextDecisionSeq=W,St(y)},z=await Kp({cfg:t,repoPath:x.path,branch:y.branch,baseBranch:K.baseRef||"main",issueKey:y.issueKey,agentId:U?.defaultAgent||Te.DEFAULT_AGENT_ID,configDir:y.agentConfigDir,failedTests:u.failedTests,timeoutSeconds:900,onLog:F});z.ok&&z.headSha&&(y.headSha=z.headSha,St(y),b.send({type:"run.status",runId:u.runId,status:"awaiting_approval",headSha:z.headSha,failedTests:z.remaining??[],...z.testsPassed!==void 0?{testsPassed:z.testsPassed}:{},...z.testsTotal!==void 0?{testsTotal:z.testsTotal}:{},...z.costUsd!==void 0?{costUsd:z.costUsd}:{},...z.inputTokens!==void 0?{inputTokens:z.inputTokens}:{},...z.outputTokens!==void 0?{outputTokens:z.outputTokens}:{}})),ht(x.path,{issueKey:y.issueKey,runId:u.runId,title:z.ok?z.headSha?(z.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:z.note.slice(0,500)}),b.sendTestFixResult(u.requestId,z)}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=xs(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 A=ze(t,y.repoName);if(!A){m("no GitHub token on this runner for that repo");return}let K=await new qe(A).getPullRequest(y.owner,y.repo,y.prNumber);if(!K){m("that pull request no longer exists on GitHub");return}if(!K.baseRef){m("GitHub did not report the PR's base branch, so there is nothing to merge in");return}let U=c.find(oe=>oe.repoName===y.repoName),W=y.nextDecisionSeq??1e5,F=(oe,Z)=>{b.send({type:"run.log",runId:u.runId,seq:W++,ts:new Date().toISOString(),level:oe,message:Z}),y.nextDecisionSeq=W,St(y)},z=await Bp({cfg:t,repoPath:x.path,branch:y.branch,baseBranch:K.baseRef,issueKey:y.issueKey,agentId:U?.defaultAgent||Te.DEFAULT_AGENT_ID,configDir:y.agentConfigDir,timeoutSeconds:900,onLog:F});z.ok&&z.headSha&&(y.headSha=z.headSha,y.conflictNotified=!1,St(y),b.send({type:"run.pr.conflict",runId:u.runId,conflicted:!1}),b.send({type:"run.status",runId:u.runId,status:"awaiting_approval",headSha:z.headSha,...z.costUsd!==void 0?{costUsd:z.costUsd}:{},...z.inputTokens!==void 0?{inputTokens:z.inputTokens}:{},...z.outputTokens!==void 0?{outputTokens:z.outputTokens}:{}})),b.sendResolveConflictResult(u.requestId,z)}catch(y){m(y instanceof Error?y.message.slice(0,300):String(y))}},onAgentProfiles:u=>{try{let m=x=>{try{return rt.default.existsSync(x)&&rt.default.readdirSync(x).length>0}catch{return!1}},y=Object.entries(t.claudeProfiles).map(([x,A])=>({agent:"claude-code",name:x,loggedIn:m(A.configDir)}));b.sendAgentProfilesResult(u.requestId,{ok:!0,profiles:y,defaultLoggedIn:m(un.default.join(Ci.default.homedir(),".claude")),agentsWithoutProfiles:Te.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 Ho(t,s,b),f.setExternalBusy(()=>Y.size);let P=Object.values(Cr()).filter(u=>u.kind==="implement").map(u=>u.repoPath);nl(Object.values(t.repos).map(u=>u.path),P).catch(()=>{}),b.start(),f.start();let D=()=>{g.info("shutting down"),w&&clearInterval(w),b.stop(),Wu(process.pid),La(),process.exit(0)},j=!1,B=()=>{if(j){g.warn("second stop signal - exiting NOW; the interrupted run will be marked failed"),D();return}if(j=!0,f.stop(),f.idle){D();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),D())},3e3)};process.on("SIGINT",B),process.on("SIGTERM",B),process.on("SIGHUP",()=>{try{let u=ue();for(let m of Object.keys(t))delete t[m];Object.assign(t,u),n=u.jira?new De(u.jira):pl(),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)}`)}})}Ae.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=ue();if(t.foreground){DS(e);return}let n=rr();if(n&&sr(n)){g.info(`already running in the background (pid ${n}). Use \`allwright status\` or \`stop\`.`);return}let r=as();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=Ku(),i=(0,hn.spawn)(process.execPath,[process.argv[1],"start","--foreground"],{detached:!0,stdio:["ignore",s,s]});i.unref(),Gu(i.pid),g.info(`Runner started in the background (pid ${i.pid}).`),g.info(`Logs: ${Zi()}`),g.info("It will keep polling Jira until you run `allwright stop` - closing this terminal is fine.")});Ae.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=rr();if(!e||!sr(e)){g.info("no background runner is running"),e&&rt.default.rmSync(os(),{force:!0});return}if(t.force){process.kill(e,"SIGKILL"),rt.default.rmSync(os(),{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.`)});Ae.command("status").description("Check whether the background runner is running").action(()=>{let t=rr();t&&sr(t)?g.info(`running in the background (pid ${t})`):g.info("not running")});Ae.parseAsync().catch(t=>{g.error(t instanceof Error?t.message:String(t)),process.exit(1)});