allwright 1.3.2 → 1.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/allwright.js +175 -174
- package/package.json +1 -1
package/bin/allwright.js
CHANGED
|
@@ -1,26 +1,26 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var
|
|
3
|
-
`).replace(/^/gm," ".repeat(i))}let c=[`Usage: ${t.commandUsage(e)}`,""],
|
|
2
|
+
"use strict";var Ad=Object.create;var gi=Object.defineProperty;var Rd=Object.getOwnPropertyDescriptor;var $d=Object.getOwnPropertyNames;var Pd=Object.getPrototypeOf,jd=Object.prototype.hasOwnProperty;var yi=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=[n],n}};var Y=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},ss=(r,e)=>{for(var t in e)gi(r,t,{get:e[t],enumerable:!0})},Od=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of $d(e))!jd.call(r,s)&&s!==t&&gi(r,s,{get:()=>e[s],enumerable:!(n=Rd(e,s))||n.enumerable});return r};var $=(r,e,t)=>(t=r!=null?Ad(Pd(r)):{},Od(e||!r||!r.__esModule?gi(t,"default",{value:r,enumerable:!0}):t,r));var Tn=Y(_i=>{var is=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},vi=class extends is{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};_i.CommanderError=is;_i.InvalidArgumentError=vi});var os=Y(wi=>{var{InvalidArgumentError:Nd}=Tn(),bi=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new Nd(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Md(r){let e=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+e+">":"["+e+"]"}wi.Argument=bi;wi.humanReadableArgName=Md});var Si=Y(ga=>{var{humanReadableArgName:zd}=os(),ki=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let t=e.commands.filter(s=>!s._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((s,i)=>s.name().localeCompare(i.name())),t}compareOptions(e,t){let n=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(s=>!s.hidden),n=e._getHelpOption();if(n&&!n.hidden){let s=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!s&&!i?t.push(n):n.long&&!i?t.push(e.createOption(n.long,n.description)):n.short&&!s&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let s=n.options.filter(i=>!i.hidden);t.push(...s)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(n=>zd(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((n,s)=>Math.max(n,t.subcommandTerm(s).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((n,s)=>Math.max(n,t.optionTerm(s).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((n,s)=>Math.max(n,t.optionTerm(s).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((n,s)=>Math.max(n,t.argumentTerm(s).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let n="";for(let s=e.parent;s;s=s.parent)n=s.name()+" "+n;return n+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,t){let n=t.padWidth(e,t),s=t.helpWidth||80,i=2,o=2;function a(x,C){if(C){let S=`${x.padEnd(n+o)}${C}`;return t.wrap(S,s-i,n+o)}return x}function l(x){return x.join(`
|
|
3
|
+
`).replace(/^/gm," ".repeat(i))}let c=[`Usage: ${t.commandUsage(e)}`,""],h=t.commandDescription(e);h.length>0&&(c=c.concat([t.wrap(h,s,0),""]));let p=t.visibleArguments(e).map(x=>a(t.argumentTerm(x),t.argumentDescription(x)));p.length>0&&(c=c.concat(["Arguments:",l(p),""]));let _=t.visibleOptions(e).map(x=>a(t.optionTerm(x),t.optionDescription(x)));if(_.length>0&&(c=c.concat(["Options:",l(_),""])),this.showGlobalOptions){let x=t.visibleGlobalOptions(e).map(C=>a(t.optionTerm(C),t.optionDescription(C)));x.length>0&&(c=c.concat(["Global Options:",l(x),""]))}let b=t.visibleCommands(e).map(x=>a(t.subcommandTerm(x),t.subcommandDescription(x)));return b.length>0&&(c=c.concat(["Commands:",l(b),""])),c.join(`
|
|
4
4
|
`)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,n,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 a=t-n;if(a<s)return e;let l=e.slice(0,n),c=e.slice(n).replace(`\r
|
|
5
5
|
`,`
|
|
6
|
-
`),
|
|
7
|
-
|.{1,${a-1}}([${_}]|$)|[^${_}]+?([${_}]|$)`,"g"),
|
|
8
|
-
`?"":(
|
|
9
|
-
`)}};
|
|
6
|
+
`),h=" ".repeat(n),_="\\s\u200B",b=new RegExp(`
|
|
7
|
+
|.{1,${a-1}}([${_}]|$)|[^${_}]+?([${_}]|$)`,"g"),x=c.match(b)||[];return l+x.map((C,S)=>C===`
|
|
8
|
+
`?"":(S>0?h:"")+C.trimEnd()).join(`
|
|
9
|
+
`)}};ga.Help=ki});var Ei=Y(Ci=>{var{InvalidArgumentError:Ld}=Tn(),xi=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=Ud(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new Ld(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return Dd(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Ti=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let s=this.negativeOptions.get(n).presetArg,i=s!==void 0?s:!1;return t.negate===(i===e)}};function Dd(r){return r.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Ud(r){let e,t,n=r.split(/[ |,]+/);return n.length>1&&!/^[[<]/.test(n[1])&&(e=n.shift()),t=n.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}Ci.Option=xi;Ci.DualOptions=Ti});var va=Y(ya=>{function qd(r,e){if(Math.abs(r.length-e.length)>3)return Math.max(r.length,e.length);let t=[];for(let n=0;n<=r.length;n++)t[n]=[n];for(let n=0;n<=e.length;n++)t[0][n]=n;for(let n=1;n<=e.length;n++)for(let s=1;s<=r.length;s++){let i=1;r[s-1]===e[n-1]?i=0:i=1,t[s][n]=Math.min(t[s-1][n]+1,t[s][n-1]+1,t[s-1][n-1]+i),s>1&&n>1&&r[s-1]===e[n-2]&&r[s-2]===e[n-1]&&(t[s][n]=Math.min(t[s][n],t[s-2][n-2]+1))}return t[r.length][e.length]}function Fd(r,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=r.startsWith("--");t&&(r=r.slice(2),e=e.map(o=>o.slice(2)));let n=[],s=3,i=.4;return e.forEach(o=>{if(o.length<=1)return;let a=qd(r,o),l=Math.max(r.length,o.length);(l-a)/l>i&&(a<s?(s=a,n=[o]):a===s&&n.push(o))}),n.sort((o,a)=>o.localeCompare(a)),t&&(n=n.map(o=>`--${o}`)),n.length>1?`
|
|
10
10
|
(Did you mean one of ${n.join(", ")}?)`:n.length===1?`
|
|
11
|
-
(Did you mean ${n[0]}?)`:""}
|
|
12
|
-
- specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new
|
|
13
|
-
Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new
|
|
14
|
-
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=s=>[s.name()].concat(s.aliases()),n=t(e).find(s=>this._findCommand(s));if(n){let s=t(this._findCommand(n)).join("|"),i=t(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let s=(i,o,a)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let l=this.getOptionValue(n);i!==null&&e.parseArg?i=this._callParseArg(e,i,l,o):i!==null&&e.variadic&&(i=e._concatValue(i,l)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(n,i,a)};return this.on("option:"+t,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;s(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+t,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;s(i,o,"env")}),this}_optionEx(e,t,n,s,i){if(typeof t=="object"&&t instanceof
|
|
11
|
+
(Did you mean ${n[0]}?)`:""}ya.suggestSimilar=Fd});var Sa=Y(ka=>{var Bd=require("node:events").EventEmitter,Ii=require("node:child_process"),tt=require("node:path"),Ai=require("node:fs"),ie=require("node:process"),{Argument:Zd,humanReadableArgName:Kd}=os(),{CommanderError:Ri}=Tn(),{Help:Vd}=Si(),{Option:_a,DualOptions:Gd}=Ei(),{suggestSimilar:ba}=va(),$i=class r extends Bd{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:t=>ie.stdout.write(t),writeErr:t=>ie.stderr.write(t),getOutHelpWidth:()=>ie.stdout.isTTY?ie.stdout.columns:void 0,getErrHelpWidth:()=>ie.stderr.isTTY?ie.stderr.columns:void 0,outputError:(t,n)=>n(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let s=t,i=n;typeof s=="object"&&s!==null&&(i=s,s=null),i=i||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(o);return s&&(l.description(s),l._executableHandler=!0),i.isDefault&&(this._defaultCommandName=l._name),l._hidden=!!(i.noHelp||i.hidden),l._executableFile=i.executableFile||null,a&&l.arguments(a),this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),s?this:l}createCommand(e){return new r(e)}createHelp(){return Object.assign(new Vd,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
12
|
+
- specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new Zd(e,t)}argument(e,t,n,s){let i=this.createArgument(e,t);return typeof n=="function"?i.default(s).argParser(n):i.default(n),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,n,s]=e.match(/([^ ]+) *(.*)/),i=t??"display help for command",o=this.createCommand(n);return o.helpOption(!1),s&&o.arguments(s),i&&o.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
13
|
+
Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new Ri(e,t,n)),ie.exit(e)}action(e){let t=n=>{let s=this.registeredArguments.length,i=n.slice(0,s);return this._storeOptionsAsProperties?i[s]=this:i[s]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=t,this}createOption(e,t){return new _a(e,t)}_callParseArg(e,t,n,s){try{return e.parseArg(t,n)}catch(i){if(i.code==="commander.invalidArgument"){let o=`${s} ${i.message}`;this.error(o,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=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 '${n}'
|
|
14
|
+
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=s=>[s.name()].concat(s.aliases()),n=t(e).find(s=>this._findCommand(s));if(n){let s=t(this._findCommand(n)).join("|"),i=t(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let s=(i,o,a)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let l=this.getOptionValue(n);i!==null&&e.parseArg?i=this._callParseArg(e,i,l,o):i!==null&&e.variadic&&(i=e._concatValue(i,l)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(n,i,a)};return this.on("option:"+t,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;s(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+t,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;s(i,o,"env")}),this}_optionEx(e,t,n,s,i){if(typeof t=="object"&&t instanceof _a)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(t,n);if(o.makeOptionMandatory(!!e.mandatory),typeof s=="function")o.default(i).argParser(s);else if(s instanceof RegExp){let a=s;s=(l,c)=>{let h=a.exec(l);return h?h[0]:c},o.default(i).argParser(s)}else o.default(s);return this.addOption(o)}option(e,t,n,s){return this._optionEx({},e,t,n,s)}requiredOption(e,t,n,s){return this._optionEx({mandatory:!0},e,t,n,s)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){ie.versions?.electron&&(t.from="electron");let s=ie.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(t.from="eval")}e===void 0&&(e=ie.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":ie.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,t){let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_executeSubCommand(e,t){t=t.slice();let n=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function i(h,p){let _=tt.resolve(h,p);if(Ai.existsSync(_))return _;if(s.includes(tt.extname(p)))return;let b=s.find(x=>Ai.existsSync(`${_}${x}`));if(b)return`${_}${b}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let h;try{h=Ai.realpathSync(this._scriptPath)}catch{h=this._scriptPath}a=tt.resolve(tt.dirname(h),a)}if(a){let h=i(a,o);if(!h&&!e._executableFile&&this._scriptPath){let p=tt.basename(this._scriptPath,tt.extname(this._scriptPath));p!==this._name&&(h=i(a,`${p}-${e._name}`))}o=h||o}n=s.includes(tt.extname(o));let l;ie.platform!=="win32"?n?(t.unshift(o),t=wa(ie.execArgv).concat(t),l=Ii.spawn(ie.argv[0],t,{stdio:"inherit"})):l=Ii.spawn(o,t,{stdio:"inherit"}):(t.unshift(o),t=wa(ie.execArgv).concat(t),l=Ii.spawn(ie.execPath,t,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(p=>{ie.on(p,()=>{l.killed===!1&&l.exitCode===null&&l.kill(p)})});let c=this._exitCallback;l.on("close",h=>{h=h??1,c?c(new Ri(h,"commander.executeSubCommandAsync","(close)")):ie.exit(h)}),l.on("error",h=>{if(h.code==="ENOENT"){let p=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",_=`'${o}' does not exist
|
|
15
15
|
- if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
16
16
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
17
|
-
- ${p}`;throw new Error(_)}else if(
|
|
17
|
+
- ${p}`;throw new Error(_)}else if(h.code==="EACCES")throw new Error(`'${o}' not executable`);if(!c)ie.exit(1);else{let p=new Ri(1,"commander.executeSubCommandAsync","(error)");p.nestedError=h,c(p)}}),this.runningCommand=l}_dispatchSubcommand(e,t,n){let s=this._findCommand(e);s||this.help({error:!0});let i;return i=this._chainOrCallSubCommandHook(i,s,"preSubcommand"),i=this._chainOrCall(i,()=>{if(s._executableHandler)this._executeSubCommand(s,t.concat(n));else return s._parseCommand(t,n)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(n,s,i)=>{let o=s;if(s!==null&&n.parseArg){let a=`error: command-argument value '${s}' is invalid for argument '${n.name()}'.`;o=this._callParseArg(n,s,i,a)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,s)=>{let i=n.defaultValue;n.variadic?s<this.args.length?(i=this.args.slice(s),n.parseArg&&(i=i.reduce((o,a)=>e(n,a,o),n.defaultValue))):i===void 0&&(i=[]):s<this.args.length&&(i=this.args[s],n.parseArg&&(i=e(n,i,n.defaultValue))),t[s]=i}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,s=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[t]!==void 0).forEach(i=>{i._lifeCycleHooks[t].forEach(o=>{s.push({hookedCommand:i,callback:o})})}),t==="postAction"&&s.reverse(),s.forEach(i=>{n=this._chainOrCall(n,()=>i.callback(i.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let s=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(i=>{s=this._chainOrCall(s,()=>i(this,t))}),s}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){s(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(i,e,t)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(i))s(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(n=>{let s=n.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let s=e.find(i=>n.conflictsWith.includes(i.attributeName()));s&&this._conflictingOption(n,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],s=t,i=e.slice();function o(l){return l.length>1&&l[0]==="-"}let a=null;for(;i.length;){let l=i.shift();if(l==="--"){s===n&&s.push(l),s.push(...i);break}if(a&&!o(l)){this.emit(`option:${a.name()}`,l);continue}if(a=null,o(l)){let c=this._findOption(l);if(c){if(c.required){let h=i.shift();h===void 0&&this.optionMissingArgument(c),this.emit(`option:${c.name()}`,h)}else if(c.optional){let h=null;i.length>0&&!o(i[0])&&(h=i.shift()),this.emit(`option:${c.name()}`,h)}else this.emit(`option:${c.name()}`);a=c.variadic?c:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let c=this._findOption(`-${l[1]}`);if(c){c.required||c.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${c.name()}`,l.slice(2)):(this.emit(`option:${c.name()}`),i.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let c=l.indexOf("="),h=this._findOption(l.slice(0,c));if(h&&(h.required||h.optional)){this.emit(`option:${h.name()}`,l.slice(c+1));continue}}if(o(l)&&(s=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(l)){t.push(l),i.length>0&&n.push(...i);break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l),i.length>0&&t.push(...i);break}else if(this._defaultCommandName){n.push(l),i.length>0&&n.push(...i);break}}if(this._passThroughOptions){s.push(l),i.length>0&&s.push(...i);break}s.push(l)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let s=this.options[n].attributeName();e[s]=s===this._versionOptionName?this._version:this[s]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
|
|
18
18
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
19
19
|
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
20
|
-
`),this.outputHelp({error:!0}));let n=t||{},s=n.exitCode||1,i=n.code||"commander.error";this._exit(s,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in ie.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,ie.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new
|
|
21
|
-
`),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let s=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(n=>
|
|
20
|
+
`),this.outputHelp({error:!0}));let n=t||{},s=n.exitCode||1,i=n.code||"commander.error";this._exit(s,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in ie.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,ie.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Gd(this.options),t=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(s=>!t(s)).forEach(s=>{this.setOptionValueWithSource(s,n.implied[s],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let n=o=>{let a=o.attributeName(),l=this.getOptionValue(a),c=this.options.find(p=>p.negate&&a===p.attributeName()),h=this.options.find(p=>!p.negate&&a===p.attributeName());return c&&(c.presetArg===void 0&&l===!1||c.presetArg!==void 0&&l===c.presetArg)?c:h||o},s=o=>{let a=n(o),l=a.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},i=`error: ${s(e)} cannot be used with ${s(t)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],i=this;do{let o=i.createHelp().visibleOptions(i).filter(a=>a.long).map(a=>a.long);s=s.concat(o),i=i.parent}while(i&&!i._enablePositionalOptions);t=ba(e,s)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(i=>{s.push(i.name()),i.alias()&&s.push(i.alias())}),t=ba(e,s)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:"commander.unknownCommand"})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",n=n||"output the version number";let s=this.createOption(t,n);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
21
|
+
`),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let s=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(n=>Kd(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=tt.basename(e,tt.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};let t={error:!!e.error},n;return t.error?n=s=>this._outputConfiguration.writeErr(s):n=s=>this._outputConfiguration.writeOut(s),t.write=e.write||n,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let n=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let s=this.helpInformation(n);if(t&&(s=t(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",n))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=ie.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
22
22
|
Expecting one of '${n.join("', '")}'`);let s=`${e}Help`;return this.on(s,i=>{let o;typeof t=="function"?o=t({error:i.error,command:i.command}):o=t,o&&i.write(`${o}
|
|
23
|
-
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(s=>t.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function _a(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",s="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?t=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=i[1],/^\d+$/.test(i[3])?s=i[3]:n=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],s=i[4]),t&&s!=="0"?`${t}=${n}:${parseInt(s)+1}`:e})}ba.Command=Ei});var xa=Y(Ie=>{var{Argument:ka}=is(),{Command:Ii}=wa(),{CommanderError:Zd,InvalidArgumentError:Sa}=Tn(),{Help:Kd}=_i(),{Option:Ta}=Si();Ie.program=new Ii;Ie.createCommand=r=>new Ii(r);Ie.createOption=(r,e)=>new Ta(r,e);Ie.createArgument=(r,e)=>new ka(r,e);Ie.Command=Ii;Ie.Option=Ta;Ie.Argument=ka;Ie.Help=Kd;Ie.CommanderError=Zd;Ie.InvalidArgumentError=Sa;Ie.InvalidOptionArgumentError=Sa});var Rn=Y(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.getParsedType=te.ZodParsedType=te.objectUtil=te.util=void 0;var Mi;(function(r){r.assertEqual=s=>{};function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},r.getValidEnumValues=s=>{let i=r.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),o={};for(let a of i)o[a]=s[a];return r.objectValues(o)},r.objectValues=s=>r.objectKeys(s).map(function(i){return s[i]}),r.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},r.find=(s,i)=>{for(let o of s)if(i(o))return o},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}r.joinValues=n,r.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(Mi||(te.util=Mi={}));var Wa;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(Wa||(te.objectUtil=Wa={}));te.ZodParsedType=Mi.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var cf=r=>{switch(typeof r){case"undefined":return te.ZodParsedType.undefined;case"string":return te.ZodParsedType.string;case"number":return Number.isNaN(r)?te.ZodParsedType.nan:te.ZodParsedType.number;case"boolean":return te.ZodParsedType.boolean;case"function":return te.ZodParsedType.function;case"bigint":return te.ZodParsedType.bigint;case"symbol":return te.ZodParsedType.symbol;case"object":return Array.isArray(r)?te.ZodParsedType.array:r===null?te.ZodParsedType.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?te.ZodParsedType.promise:typeof Map<"u"&&r instanceof Map?te.ZodParsedType.map:typeof Set<"u"&&r instanceof Set?te.ZodParsedType.set:typeof Date<"u"&&r instanceof Date?te.ZodParsedType.date:te.ZodParsedType.object;default:return te.ZodParsedType.unknown}};te.getParsedType=cf});var _s=Y(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.ZodError=Ct.quotelessJson=Ct.ZodIssueCode=void 0;var Ja=Rn();Ct.ZodIssueCode=Ja.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 df=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:");Ct.quotelessJson=df;var $n=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},n={_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)n._errors.push(t(o));else{let a=n,l=0;for(;l<o.path.length;){let c=o.path[l];l===o.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(t(o))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return s(this),n}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ja.util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},n=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];t[i]=t[i]||[],t[i].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};Ct.ZodError=$n;$n.create=r=>new $n(r)});var Di=Y(Li=>{"use strict";Object.defineProperty(Li,"__esModule",{value:!0});var me=_s(),er=Rn(),hf=(r,e)=>{let t;switch(r.code){case me.ZodIssueCode.invalid_type:r.received===er.ZodParsedType.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case me.ZodIssueCode.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,er.util.jsonStringifyReplacer)}`;break;case me.ZodIssueCode.unrecognized_keys:t=`Unrecognized key(s) in object: ${er.util.joinValues(r.keys,", ")}`;break;case me.ZodIssueCode.invalid_union:t="Invalid input";break;case me.ZodIssueCode.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${er.util.joinValues(r.options)}`;break;case me.ZodIssueCode.invalid_enum_value:t=`Invalid enum value. Expected ${er.util.joinValues(r.options)}, received '${r.received}'`;break;case me.ZodIssueCode.invalid_arguments:t="Invalid function arguments";break;case me.ZodIssueCode.invalid_return_type:t="Invalid function return type";break;case me.ZodIssueCode.invalid_date:t="Invalid date";break;case me.ZodIssueCode.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:er.util.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case me.ZodIssueCode.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case me.ZodIssueCode.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case me.ZodIssueCode.custom:t="Invalid input";break;case me.ZodIssueCode.invalid_intersection_types:t="Intersection results could not be merged";break;case me.ZodIssueCode.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case me.ZodIssueCode.not_finite:t="Number must be finite";break;default:t=e.defaultError,er.util.assertNever(r)}return{message:t}};Li.default=hf});var bs=Y(Et=>{"use strict";var ff=Et&&Et.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Et,"__esModule",{value:!0});Et.defaultErrorMap=void 0;Et.setErrorMap=pf;Et.getErrorMap=mf;var Ya=ff(Di());Et.defaultErrorMap=Ya.default;var Xa=Ya.default;function pf(r){Xa=r}function mf(){return Xa}});var Ui=Y(X=>{"use strict";var gf=X&&X.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(X,"__esModule",{value:!0});X.isAsync=X.isValid=X.isDirty=X.isAborted=X.OK=X.DIRTY=X.INVALID=X.ParseStatus=X.EMPTY_PATH=X.makeIssue=void 0;X.addIssueToContext=_f;var yf=bs(),Qa=gf(Di()),vf=r=>{let{data:e,path:t,errorMaps:n,issueData:s}=r,i=[...t,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let a="",l=n.filter(c=>!!c).slice().reverse();for(let c of l)a=c(o,{data:e,defaultError:a}).message;return{...s,path:i,message:a}};X.makeIssue=vf;X.EMPTY_PATH=[];function _f(r,e){let t=(0,yf.getErrorMap)(),n=(0,X.makeIssue)({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===Qa.default?void 0:Qa.default].filter(s=>!!s)});r.common.issues.push(n)}var zi=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let s of t){if(s.status==="aborted")return X.INVALID;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let s of t){let i=await s.key,o=await s.value;n.push({key:i,value:o})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let s of t){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return X.INVALID;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(n[i.value]=o.value)}return{status:e.value,value:n}}};X.ParseStatus=zi;X.INVALID=Object.freeze({status:"aborted"});var bf=r=>({status:"dirty",value:r});X.DIRTY=bf;var wf=r=>({status:"valid",value:r});X.OK=wf;var kf=r=>r.status==="aborted";X.isAborted=kf;var Sf=r=>r.status==="dirty";X.isDirty=Sf;var Tf=r=>r.status==="valid";X.isValid=Tf;var xf=r=>typeof Promise<"u"&&r instanceof Promise;X.isAsync=xf});var tu=Y(eu=>{"use strict";Object.defineProperty(eu,"__esModule",{value:!0})});var nu=Y(ws=>{"use strict";Object.defineProperty(ws,"__esModule",{value:!0});ws.errorUtil=void 0;var ru;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(ru||(ws.errorUtil=ru={}))});var mu=Y(y=>{"use strict";Object.defineProperty(y,"__esModule",{value:!0});y.discriminatedUnion=y.date=y.boolean=y.bigint=y.array=y.any=y.coerce=y.ZodFirstPartyTypeKind=y.late=y.ZodSchema=y.Schema=y.ZodReadonly=y.ZodPipeline=y.ZodBranded=y.BRAND=y.ZodNaN=y.ZodCatch=y.ZodDefault=y.ZodNullable=y.ZodOptional=y.ZodTransformer=y.ZodEffects=y.ZodPromise=y.ZodNativeEnum=y.ZodEnum=y.ZodLiteral=y.ZodLazy=y.ZodFunction=y.ZodSet=y.ZodMap=y.ZodRecord=y.ZodTuple=y.ZodIntersection=y.ZodDiscriminatedUnion=y.ZodUnion=y.ZodObject=y.ZodArray=y.ZodVoid=y.ZodNever=y.ZodUnknown=y.ZodAny=y.ZodNull=y.ZodUndefined=y.ZodSymbol=y.ZodDate=y.ZodBoolean=y.ZodBigInt=y.ZodNumber=y.ZodString=y.ZodType=void 0;y.NEVER=y.void=y.unknown=y.union=y.undefined=y.tuple=y.transformer=y.symbol=y.string=y.strictObject=y.set=y.record=y.promise=y.preprocess=y.pipeline=y.ostring=y.optional=y.onumber=y.oboolean=y.object=y.number=y.nullable=y.null=y.never=y.nativeEnum=y.nan=y.map=y.literal=y.lazy=y.intersection=y.instanceof=y.function=y.enum=y.effect=void 0;y.datetimeRegex=uu;y.custom=cu;var E=_s(),ks=bs(),O=nu(),v=Ui(),I=Rn(),je=class{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,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}},su=(r,e)=>{if((0,v.isValid)(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new E.ZodError(r.common.issues);return this._error=t,this._error}}};function K(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))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,a)=>{let{message:l}=r;return o.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??n??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:l??t??a.defaultError}},description:s}}var V=class{get description(){return this._def.description}_getType(e){return(0,I.getParsedType)(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:(0,I.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new v.ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:(0,I.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if((0,v.isAsync)(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,I.getParsedType)(e)},s=this._parseSync({data:e,path:n.path,parent:n});return su(n,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,I.getParsedType)(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return(0,v.isValid)(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>(0,v.isValid)(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,I.getParsedType)(e)},s=this._parse({data:e,path:n.path,parent:n}),i=await((0,v.isAsync)(s)?s:Promise.resolve(s));return su(n,i)}refine(e,t){let n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,i)=>{let o=e(s),a=()=>i.addIssue({code:E.ZodIssueCode.custom,...n(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new Te({schema:this,typeName:U.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return Pe.create(this,this._def)}nullable(){return We.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return lt.create(this)}promise(){return Rt.create(this,this._def)}or(e){return ar.create([this,e],this._def)}and(e){return ur.create(this,e,this._def)}transform(e){return new Te({...K(this._def),schema:this,typeName:U.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new fr({...K(this._def),innerType:this,defaultValue:t,typeName:U.ZodDefault})}brand(){return new Pn({typeName:U.ZodBranded,type:this,...K(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new pr({...K(this._def),innerType:this,catchValue:t,typeName:U.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return jn.create(this,e)}readonly(){return mr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};y.ZodType=V;y.Schema=V;y.ZodSchema=V;var Cf=/^c[^\s-]{8,}$/i,Ef=/^[0-9a-z]+$/,If=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Af=/^[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,Rf=/^[a-z0-9_-]{21}$/i,$f=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Pf=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,jf=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Of="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",qi,Nf=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Mf=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Lf=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Df=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,zf=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Uf=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ou="((\\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])))",qf=new RegExp(`^${ou}$`);function au(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Bf(r){return new RegExp(`^${au(r)}$`)}function uu(r){let e=`${ou}T${au(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Ff(r,e){return!!((e==="v4"||!e)&&Nf.test(r)||(e==="v6"||!e)&&Lf.test(r))}function Zf(r,e){if(!$f.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function Kf(r,e){return!!((e==="v4"||!e)&&Mf.test(r)||(e==="v6"||!e)&&Df.test(r))}var It=class r extends V{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==I.ZodParsedType.string){let i=this._getOrReturnCtx(e);return(0,v.addIssueToContext)(i,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.string,received:i.parsedType}),v.INVALID}let n=new v.ParseStatus,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{code:E.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{code:E.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(s=this._getOrReturnCtx(e,s),o?(0,v.addIssueToContext)(s,{code:E.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&(0,v.addIssueToContext)(s,{code:E.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")jf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{validation:"email",code:E.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")qi||(qi=new RegExp(Of,"u")),qi.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{validation:"emoji",code:E.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")Af.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{validation:"uuid",code:E.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")Rf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{validation:"nanoid",code:E.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")Cf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{validation:"cuid",code:E.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")Ef.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{validation:"cuid2",code:E.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")If.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{validation:"ulid",code:E.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{validation:"url",code:E.ZodIssueCode.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{validation:"regex",code:E.ZodIssueCode.invalid_string,message:i.message}),n.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,v.addIssueToContext)(s,{code:E.ZodIssueCode.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.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,v.addIssueToContext)(s,{code:E.ZodIssueCode.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{code:E.ZodIssueCode.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?uu(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{code:E.ZodIssueCode.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?qf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{code:E.ZodIssueCode.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?Bf(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{code:E.ZodIssueCode.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?Pf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{validation:"duration",code:E.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?Ff(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{validation:"ip",code:E.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?Zf(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{validation:"jwt",code:E.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?Kf(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{validation:"cidr",code:E.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?zf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{validation:"base64",code:E.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?Uf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{validation:"base64url",code:E.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):I.util.assertNever(i);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:E.ZodIssueCode.invalid_string,...O.errorUtil.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...O.errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...O.errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...O.errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...O.errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...O.errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...O.errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...O.errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...O.errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...O.errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...O.errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...O.errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...O.errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...O.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,...O.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,...O.errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...O.errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...O.errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...O.errorUtil.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...O.errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...O.errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...O.errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...O.errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...O.errorUtil.errToObj(t)})}nonempty(e){return this.min(1,O.errorUtil.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};y.ZodString=It;It.create=r=>new It({checks:[],typeName:U.ZodString,coerce:r?.coerce??!1,...K(r)});function Vf(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,i=Number.parseInt(r.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var tr=class r extends V{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)!==I.ZodParsedType.number){let i=this._getOrReturnCtx(e);return(0,v.addIssueToContext)(i,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.number,received:i.parsedType}),v.INVALID}let n,s=new v.ParseStatus;for(let i of this._def.checks)i.kind==="int"?I.util.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Vf(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.not_finite,message:i.message}),s.dirty()):I.util.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,O.errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,O.errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,O.errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,O.errorUtil.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:O.errorUtil.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:O.errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:O.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:O.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:O.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:O.errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:O.errorUtil.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:O.errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:O.errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:O.errorUtil.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&I.util.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};y.ZodNumber=tr;tr.create=r=>new tr({checks:[],typeName:U.ZodNumber,coerce:r?.coerce||!1,...K(r)});var rr=class r extends V{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)!==I.ZodParsedType.bigint)return this._getInvalidInput(e);let n,s=new v.ParseStatus;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):I.util.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return(0,v.addIssueToContext)(t,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.bigint,received:t.parsedType}),v.INVALID}gte(e,t){return this.setLimit("min",e,!0,O.errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,O.errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,O.errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,O.errorUtil.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:O.errorUtil.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:O.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:O.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:O.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:O.errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:O.errorUtil.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};y.ZodBigInt=rr;rr.create=r=>new rr({checks:[],typeName:U.ZodBigInt,coerce:r?.coerce??!1,...K(r)});var nr=class extends V{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==I.ZodParsedType.boolean){let n=this._getOrReturnCtx(e);return(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.boolean,received:n.parsedType}),v.INVALID}return(0,v.OK)(e.data)}};y.ZodBoolean=nr;nr.create=r=>new nr({typeName:U.ZodBoolean,coerce:r?.coerce||!1,...K(r)});var sr=class r extends V{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==I.ZodParsedType.date){let i=this._getOrReturnCtx(e);return(0,v.addIssueToContext)(i,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.date,received:i.parsedType}),v.INVALID}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return(0,v.addIssueToContext)(i,{code:E.ZodIssueCode.invalid_date}),v.INVALID}let n=new v.ParseStatus,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{code:E.ZodIssueCode.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{code:E.ZodIssueCode.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):I.util.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:O.errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:O.errorUtil.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};y.ZodDate=sr;sr.create=r=>new sr({checks:[],coerce:r?.coerce||!1,typeName:U.ZodDate,...K(r)});var Hr=class extends V{_parse(e){if(this._getType(e)!==I.ZodParsedType.symbol){let n=this._getOrReturnCtx(e);return(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.symbol,received:n.parsedType}),v.INVALID}return(0,v.OK)(e.data)}};y.ZodSymbol=Hr;Hr.create=r=>new Hr({typeName:U.ZodSymbol,...K(r)});var ir=class extends V{_parse(e){if(this._getType(e)!==I.ZodParsedType.undefined){let n=this._getOrReturnCtx(e);return(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.undefined,received:n.parsedType}),v.INVALID}return(0,v.OK)(e.data)}};y.ZodUndefined=ir;ir.create=r=>new ir({typeName:U.ZodUndefined,...K(r)});var or=class extends V{_parse(e){if(this._getType(e)!==I.ZodParsedType.null){let n=this._getOrReturnCtx(e);return(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.null,received:n.parsedType}),v.INVALID}return(0,v.OK)(e.data)}};y.ZodNull=or;or.create=r=>new or({typeName:U.ZodNull,...K(r)});var At=class extends V{constructor(){super(...arguments),this._any=!0}_parse(e){return(0,v.OK)(e.data)}};y.ZodAny=At;At.create=r=>new At({typeName:U.ZodAny,...K(r)});var ut=class extends V{constructor(){super(...arguments),this._unknown=!0}_parse(e){return(0,v.OK)(e.data)}};y.ZodUnknown=ut;ut.create=r=>new ut({typeName:U.ZodUnknown,...K(r)});var Ue=class extends V{_parse(e){let t=this._getOrReturnCtx(e);return(0,v.addIssueToContext)(t,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.never,received:t.parsedType}),v.INVALID}};y.ZodNever=Ue;Ue.create=r=>new Ue({typeName:U.ZodNever,...K(r)});var Wr=class extends V{_parse(e){if(this._getType(e)!==I.ZodParsedType.undefined){let n=this._getOrReturnCtx(e);return(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.void,received:n.parsedType}),v.INVALID}return(0,v.OK)(e.data)}};y.ZodVoid=Wr;Wr.create=r=>new Wr({typeName:U.ZodVoid,...K(r)});var lt=class r extends V{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==I.ZodParsedType.array)return(0,v.addIssueToContext)(t,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.array,received:t.parsedType}),v.INVALID;if(s.exactLength!==null){let o=t.data.length>s.exactLength.value,a=t.data.length<s.exactLength.value;(o||a)&&((0,v.addIssueToContext)(t,{code:o?E.ZodIssueCode.too_big:E.ZodIssueCode.too_small,minimum:a?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&((0,v.addIssueToContext)(t,{code:E.ZodIssueCode.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&((0,v.addIssueToContext)(t,{code:E.ZodIssueCode.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>s.type._parseAsync(new je(t,o,t.path,a)))).then(o=>v.ParseStatus.mergeArray(n,o));let i=[...t.data].map((o,a)=>s.type._parseSync(new je(t,o,t.path,a)));return v.ParseStatus.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:O.errorUtil.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:O.errorUtil.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:O.errorUtil.toString(t)}})}nonempty(e){return this.min(1,e)}};y.ZodArray=lt;lt.create=(r,e)=>new lt({type:r,minLength:null,maxLength:null,exactLength:null,typeName:U.ZodArray,...K(e)});function Gr(r){if(r instanceof we){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=Pe.create(Gr(n))}return new we({...r._def,shape:()=>e})}else return r instanceof lt?new lt({...r._def,type:Gr(r.element)}):r instanceof Pe?Pe.create(Gr(r.unwrap())):r instanceof We?We.create(Gr(r.unwrap())):r instanceof He?He.create(r.items.map(e=>Gr(e))):r}var we=class r extends V{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=I.util.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==I.ZodParsedType.object){let c=this._getOrReturnCtx(e);return(0,v.addIssueToContext)(c,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.object,received:c.parsedType}),v.INVALID}let{status:n,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ue&&this._def.unknownKeys==="strip"))for(let c in s.data)o.includes(c)||a.push(c);let l=[];for(let c of o){let d=i[c],p=s.data[c];l.push({key:{status:"valid",value:c},value:d._parse(new je(s,p,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof Ue){let c=this._def.unknownKeys;if(c==="passthrough")for(let d of a)l.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(c==="strict")a.length>0&&((0,v.addIssueToContext)(s,{code:E.ZodIssueCode.unrecognized_keys,keys:a}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let d of a){let p=s.data[d];l.push({key:{status:"valid",value:d},value:c._parse(new je(s,p,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let c=[];for(let d of l){let p=await d.key,_=await d.value;c.push({key:p,value:_,alwaysSet:d.alwaysSet})}return c}).then(c=>v.ParseStatus.mergeObjectSync(n,c)):v.ParseStatus.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return O.errorUtil.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let s=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:O.errorUtil.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:U.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let n of I.util.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let n of I.util.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return Gr(this)}partial(e){let t={};for(let n of I.util.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let n of I.util.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof Pe;)i=i._def.innerType;t[n]=i}return new r({...this._def,shape:()=>t})}keyof(){return lu(I.util.objectKeys(this.shape))}};y.ZodObject=we;we.create=(r,e)=>new we({shape:()=>r,unknownKeys:"strip",catchall:Ue.create(),typeName:U.ZodObject,...K(e)});we.strictCreate=(r,e)=>new we({shape:()=>r,unknownKeys:"strict",catchall:Ue.create(),typeName:U.ZodObject,...K(e)});we.lazycreate=(r,e)=>new we({shape:r,unknownKeys:"strip",catchall:Ue.create(),typeName:U.ZodObject,...K(e)});var ar=class extends V{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function s(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return t.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(a=>new E.ZodError(a.ctx.common.issues));return(0,v.addIssueToContext)(t,{code:E.ZodIssueCode.invalid_union,unionErrors:o}),v.INVALID}if(t.common.async)return Promise.all(n.map(async i=>{let o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let l of n){let c={...t,common:{...t.common,issues:[]},parent:null},d=l._parseSync({data:t.data,path:t.path,parent:c});if(d.status==="valid")return d;d.status==="dirty"&&!i&&(i={result:d,ctx:c}),c.common.issues.length&&o.push(c.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let a=o.map(l=>new E.ZodError(l));return(0,v.addIssueToContext)(t,{code:E.ZodIssueCode.invalid_union,unionErrors:a}),v.INVALID}}get options(){return this._def.options}};y.ZodUnion=ar;ar.create=(r,e)=>new ar({options:r,typeName:U.ZodUnion,...K(e)});var at=r=>r instanceof lr?at(r.schema):r instanceof Te?at(r.innerType()):r instanceof cr?[r.value]:r instanceof dr?r.options:r instanceof hr?I.util.objectValues(r.enum):r instanceof fr?at(r._def.innerType):r instanceof ir?[void 0]:r instanceof or?[null]:r instanceof Pe?[void 0,...at(r.unwrap())]:r instanceof We?[null,...at(r.unwrap())]:r instanceof Pn||r instanceof mr?at(r.unwrap()):r instanceof pr?at(r._def.innerType):[],Ss=class r extends V{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==I.ZodParsedType.object)return(0,v.addIssueToContext)(t,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.object,received:t.parsedType}),v.INVALID;let n=this.discriminator,s=t.data[n],i=this.optionsMap.get(s);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):((0,v.addIssueToContext)(t,{code:E.ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),v.INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let s=new Map;for(let i of t){let o=at(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of o){if(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,i)}}return new r({typeName:U.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...K(n)})}};y.ZodDiscriminatedUnion=Ss;function Bi(r,e){let t=(0,I.getParsedType)(r),n=(0,I.getParsedType)(e);if(r===e)return{valid:!0,data:r};if(t===I.ZodParsedType.object&&n===I.ZodParsedType.object){let s=I.util.objectKeys(e),i=I.util.objectKeys(r).filter(a=>s.indexOf(a)!==-1),o={...r,...e};for(let a of i){let l=Bi(r[a],e[a]);if(!l.valid)return{valid:!1};o[a]=l.data}return{valid:!0,data:o}}else if(t===I.ZodParsedType.array&&n===I.ZodParsedType.array){if(r.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<r.length;i++){let o=r[i],a=e[i],l=Bi(o,a);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return t===I.ZodParsedType.date&&n===I.ZodParsedType.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var ur=class extends V{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=(i,o)=>{if((0,v.isAborted)(i)||(0,v.isAborted)(o))return v.INVALID;let a=Bi(i.value,o.value);return a.valid?(((0,v.isDirty)(i)||(0,v.isDirty)(o))&&t.dirty(),{status:t.value,value:a.data}):((0,v.addIssueToContext)(n,{code:E.ZodIssueCode.invalid_intersection_types}),v.INVALID)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};y.ZodIntersection=ur;ur.create=(r,e,t)=>new ur({left:r,right:e,typeName:U.ZodIntersection,...K(t)});var He=class r extends V{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==I.ZodParsedType.array)return(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.array,received:n.parsedType}),v.INVALID;if(n.data.length<this._def.items.length)return(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),v.INVALID;!this._def.rest&&n.data.length>this._def.items.length&&((0,v.addIssueToContext)(n,{code:E.ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...n.data].map((o,a)=>{let l=this._def.items[a]||this._def.rest;return l?l._parse(new je(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(i).then(o=>v.ParseStatus.mergeArray(t,o)):v.ParseStatus.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};y.ZodTuple=He;He.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new He({items:r,typeName:U.ZodTuple,rest:null,...K(e)})};var Ts=class r extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==I.ZodParsedType.object)return(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.object,received:n.parsedType}),v.INVALID;let s=[],i=this._def.keyType,o=this._def.valueType;for(let a in n.data)s.push({key:i._parse(new je(n,a,n.path,a)),value:o._parse(new je(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?v.ParseStatus.mergeObjectAsync(t,s):v.ParseStatus.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof V?new r({keyType:e,valueType:t,typeName:U.ZodRecord,...K(n)}):new r({keyType:It.create(),valueType:e,typeName:U.ZodRecord,...K(t)})}};y.ZodRecord=Ts;var Jr=class extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==I.ZodParsedType.map)return(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.map,received:n.parsedType}),v.INVALID;let s=this._def.keyType,i=this._def.valueType,o=[...n.data.entries()].map(([a,l],c)=>({key:s._parse(new je(n,a,n.path,[c,"key"])),value:i._parse(new je(n,l,n.path,[c,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let l of o){let c=await l.key,d=await l.value;if(c.status==="aborted"||d.status==="aborted")return v.INVALID;(c.status==="dirty"||d.status==="dirty")&&t.dirty(),a.set(c.value,d.value)}return{status:t.value,value:a}})}else{let a=new Map;for(let l of o){let c=l.key,d=l.value;if(c.status==="aborted"||d.status==="aborted")return v.INVALID;(c.status==="dirty"||d.status==="dirty")&&t.dirty(),a.set(c.value,d.value)}return{status:t.value,value:a}}}};y.ZodMap=Jr;Jr.create=(r,e,t)=>new Jr({valueType:e,keyType:r,typeName:U.ZodMap,...K(t)});var Yr=class r extends V{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==I.ZodParsedType.set)return(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.set,received:n.parsedType}),v.INVALID;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&((0,v.addIssueToContext)(n,{code:E.ZodIssueCode.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&((0,v.addIssueToContext)(n,{code:E.ZodIssueCode.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let i=this._def.valueType;function o(l){let c=new Set;for(let d of l){if(d.status==="aborted")return v.INVALID;d.status==="dirty"&&t.dirty(),c.add(d.value)}return{status:t.value,value:c}}let a=[...n.data.values()].map((l,c)=>i._parse(new je(n,l,n.path,c)));return n.common.async?Promise.all(a).then(l=>o(l)):o(a)}min(e,t){return new r({...this._def,minSize:{value:e,message:O.errorUtil.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:O.errorUtil.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};y.ZodSet=Yr;Yr.create=(r,e)=>new Yr({valueType:r,minSize:null,maxSize:null,typeName:U.ZodSet,...K(e)});var xs=class r extends V{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==I.ZodParsedType.function)return(0,v.addIssueToContext)(t,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.function,received:t.parsedType}),v.INVALID;function n(a,l){return(0,v.makeIssue)({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,(0,ks.getErrorMap)(),ks.defaultErrorMap].filter(c=>!!c),issueData:{code:E.ZodIssueCode.invalid_arguments,argumentsError:l}})}function s(a,l){return(0,v.makeIssue)({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,(0,ks.getErrorMap)(),ks.defaultErrorMap].filter(c=>!!c),issueData:{code:E.ZodIssueCode.invalid_return_type,returnTypeError:l}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof Rt){let a=this;return(0,v.OK)(async function(...l){let c=new E.ZodError([]),d=await a._def.args.parseAsync(l,i).catch(S=>{throw c.addIssue(n(l,S)),c}),p=await Reflect.apply(o,this,d);return await a._def.returns._def.type.parseAsync(p,i).catch(S=>{throw c.addIssue(s(p,S)),c})})}else{let a=this;return(0,v.OK)(function(...l){let c=a._def.args.safeParse(l,i);if(!c.success)throw new E.ZodError([n(l,c.error)]);let d=Reflect.apply(o,this,c.data),p=a._def.returns.safeParse(d,i);if(!p.success)throw new E.ZodError([s(d,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:He.create(e).rest(ut.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||He.create([]).rest(ut.create()),returns:t||ut.create(),typeName:U.ZodFunction,...K(n)})}};y.ZodFunction=xs;var lr=class extends V{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};y.ZodLazy=lr;lr.create=(r,e)=>new lr({getter:r,typeName:U.ZodLazy,...K(e)});var cr=class extends V{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return(0,v.addIssueToContext)(t,{received:t.data,code:E.ZodIssueCode.invalid_literal,expected:this._def.value}),v.INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}};y.ZodLiteral=cr;cr.create=(r,e)=>new cr({value:r,typeName:U.ZodLiteral,...K(e)});function lu(r,e){return new dr({values:r,typeName:U.ZodEnum,...K(e)})}var dr=class r extends V{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return(0,v.addIssueToContext)(t,{expected:I.util.joinValues(n),received:t.parsedType,code:E.ZodIssueCode.invalid_type}),v.INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return(0,v.addIssueToContext)(t,{received:t.data,code:E.ZodIssueCode.invalid_enum_value,options:n}),v.INVALID}return(0,v.OK)(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};y.ZodEnum=dr;dr.create=lu;var hr=class extends V{_parse(e){let t=I.util.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==I.ZodParsedType.string&&n.parsedType!==I.ZodParsedType.number){let s=I.util.objectValues(t);return(0,v.addIssueToContext)(n,{expected:I.util.joinValues(s),received:n.parsedType,code:E.ZodIssueCode.invalid_type}),v.INVALID}if(this._cache||(this._cache=new Set(I.util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=I.util.objectValues(t);return(0,v.addIssueToContext)(n,{received:n.data,code:E.ZodIssueCode.invalid_enum_value,options:s}),v.INVALID}return(0,v.OK)(e.data)}get enum(){return this._def.values}};y.ZodNativeEnum=hr;hr.create=(r,e)=>new hr({values:r,typeName:U.ZodNativeEnum,...K(e)});var Rt=class extends V{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==I.ZodParsedType.promise&&t.common.async===!1)return(0,v.addIssueToContext)(t,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.promise,received:t.parsedType}),v.INVALID;let n=t.parsedType===I.ZodParsedType.promise?t.data:Promise.resolve(t.data);return(0,v.OK)(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};y.ZodPromise=Rt;Rt.create=(r,e)=>new Rt({type:r,typeName:U.ZodPromise,...K(e)});var Te=class extends V{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===U.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{(0,v.addIssueToContext)(n,o),o.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(n.data,i);if(n.common.async)return Promise.resolve(o).then(async a=>{if(t.value==="aborted")return v.INVALID;let l=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return l.status==="aborted"?v.INVALID:l.status==="dirty"||t.value==="dirty"?(0,v.DIRTY)(l.value):l});{if(t.value==="aborted")return v.INVALID;let a=this._def.schema._parseSync({data:o,path:n.path,parent:n});return a.status==="aborted"?v.INVALID:a.status==="dirty"||t.value==="dirty"?(0,v.DIRTY)(a.value):a}}if(s.type==="refinement"){let o=a=>{let l=s.refinement(a,i);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?v.INVALID:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?v.INVALID:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.value,value:a.value}))))}if(s.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!(0,v.isValid)(o))return v.INVALID;let a=s.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>(0,v.isValid)(o)?Promise.resolve(s.transform(o.value,i)).then(a=>({status:t.value,value:a})):v.INVALID);I.util.assertNever(s)}};y.ZodEffects=Te;y.ZodTransformer=Te;Te.create=(r,e,t)=>new Te({schema:r,typeName:U.ZodEffects,effect:e,...K(t)});Te.createWithPreprocess=(r,e,t)=>new Te({schema:e,effect:{type:"preprocess",transform:r},typeName:U.ZodEffects,...K(t)});var Pe=class extends V{_parse(e){return this._getType(e)===I.ZodParsedType.undefined?(0,v.OK)(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};y.ZodOptional=Pe;Pe.create=(r,e)=>new Pe({innerType:r,typeName:U.ZodOptional,...K(e)});var We=class extends V{_parse(e){return this._getType(e)===I.ZodParsedType.null?(0,v.OK)(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};y.ZodNullable=We;We.create=(r,e)=>new We({innerType:r,typeName:U.ZodNullable,...K(e)});var fr=class extends V{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===I.ZodParsedType.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};y.ZodDefault=fr;fr.create=(r,e)=>new fr({innerType:r,typeName:U.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...K(e)});var pr=class extends V{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return(0,v.isAsync)(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new E.ZodError(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new E.ZodError(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};y.ZodCatch=pr;pr.create=(r,e)=>new pr({innerType:r,typeName:U.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...K(e)});var Xr=class extends V{_parse(e){if(this._getType(e)!==I.ZodParsedType.nan){let n=this._getOrReturnCtx(e);return(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.nan,received:n.parsedType}),v.INVALID}return{status:"valid",value:e.data}}};y.ZodNaN=Xr;Xr.create=r=>new Xr({typeName:U.ZodNaN,...K(r)});y.BRAND=Symbol("zod_brand");var Pn=class extends V{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}};y.ZodBranded=Pn;var jn=class r extends V{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?v.INVALID:i.status==="dirty"?(t.dirty(),(0,v.DIRTY)(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?v.INVALID:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:U.ZodPipeline})}};y.ZodPipeline=jn;var mr=class extends V{_parse(e){let t=this._def.innerType._parse(e),n=s=>((0,v.isValid)(s)&&(s.value=Object.freeze(s.value)),s);return(0,v.isAsync)(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}};y.ZodReadonly=mr;mr.create=(r,e)=>new mr({innerType:r,typeName:U.ZodReadonly,...K(e)});function iu(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function cu(r,e={},t){return r?At.create().superRefine((n,s)=>{let i=r(n);if(i instanceof Promise)return i.then(o=>{if(!o){let a=iu(e,n),l=a.fatal??t??!0;s.addIssue({code:"custom",...a,fatal:l})}});if(!i){let o=iu(e,n),a=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:a})}}):At.create()}y.late={object:we.lazycreate};var U;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(U||(y.ZodFirstPartyTypeKind=U={}));var Gf=(r,e={message:`Input not instance of ${r.name}`})=>cu(t=>t instanceof r,e);y.instanceof=Gf;var du=It.create;y.string=du;var hu=tr.create;y.number=hu;var Hf=Xr.create;y.nan=Hf;var Wf=rr.create;y.bigint=Wf;var fu=nr.create;y.boolean=fu;var Jf=sr.create;y.date=Jf;var Yf=Hr.create;y.symbol=Yf;var Xf=ir.create;y.undefined=Xf;var Qf=or.create;y.null=Qf;var ep=At.create;y.any=ep;var tp=ut.create;y.unknown=tp;var rp=Ue.create;y.never=rp;var np=Wr.create;y.void=np;var sp=lt.create;y.array=sp;var ip=we.create;y.object=ip;var op=we.strictCreate;y.strictObject=op;var ap=ar.create;y.union=ap;var up=Ss.create;y.discriminatedUnion=up;var lp=ur.create;y.intersection=lp;var cp=He.create;y.tuple=cp;var dp=Ts.create;y.record=dp;var hp=Jr.create;y.map=hp;var fp=Yr.create;y.set=fp;var pp=xs.create;y.function=pp;var mp=lr.create;y.lazy=mp;var gp=cr.create;y.literal=gp;var yp=dr.create;y.enum=yp;var vp=hr.create;y.nativeEnum=vp;var _p=Rt.create;y.promise=_p;var pu=Te.create;y.effect=pu;y.transformer=pu;var bp=Pe.create;y.optional=bp;var wp=We.create;y.nullable=wp;var kp=Te.createWithPreprocess;y.preprocess=kp;var Sp=jn.create;y.pipeline=Sp;var Tp=()=>du().optional();y.ostring=Tp;var xp=()=>hu().optional();y.onumber=xp;var Cp=()=>fu().optional();y.oboolean=Cp;y.coerce={string:(r=>It.create({...r,coerce:!0})),number:(r=>tr.create({...r,coerce:!0})),boolean:(r=>nr.create({...r,coerce:!0})),bigint:(r=>rr.create({...r,coerce:!0})),date:(r=>sr.create({...r,coerce:!0}))};y.NEVER=v.INVALID});var Fi=Y(Oe=>{"use strict";var Ep=Oe&&Oe.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),Qr=Oe&&Oe.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Ep(e,r,t)};Object.defineProperty(Oe,"__esModule",{value:!0});Qr(bs(),Oe);Qr(Ui(),Oe);Qr(tu(),Oe);Qr(Rn(),Oe);Qr(mu(),Oe);Qr(_s(),Oe)});var vu=Y(ke=>{"use strict";var gu=ke&&ke.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),Ip=ke&&ke.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Ap=ke&&ke.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&gu(e,r,t);return Ip(e,r),e},Rp=ke&&ke.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&gu(e,r,t)};Object.defineProperty(ke,"__esModule",{value:!0});ke.z=void 0;var yu=Ap(Fi());ke.z=yu;Rp(Fi(),ke);ke.default=yu});var xe=Y(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.EpicListResultMsg=h.EpicChild=h.EpicListMsg=h.BoardTriggerResultMsg=h.BoardTriggerMsg=h.BoardFetchResultMsg=h.BoardFetchMsg=h.ChatLoadResultMsg=h.ChatLoadMsg=h.ChatListResultMsg=h.ChatListMsg=h.ChatStreamMsg=h.JiraUsersResultMsg=h.DeployClaimResultMsg=h.DeployClaimMsg=h.RuleDiagnoseResultMsg=h.ProjectTestResultMsg=h.RunStatusMsg=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_MARKER=h.BRANCH_DEPLOY_ISSUE_KEY=h.REQUIRED_AGENT_CAPABILITIES=h.DEFAULT_AGENT_ID=h.REGISTERED_AGENTS=h.PROTOCOL_VERSION=void 0;h.DeploySuggestMsg=h.DeployStartMsg=h.RunRetryPushMsg=h.RunRejectedMsg=h.RunApprovedMsg=h.RunCancelMsg=h.RuleDiagnoseMsg=h.ProjectTestMsg=h.RunClaimResultMsg=h.ConfigMsg=h.HelloAckMsg=h.RunnerToServerMsg=h.RunnerUpdateResultMsg=h.RunnerUpdateMsg=h.SetupClaudeMdSaveResultMsg=h.SetupClaudeMdSaveMsg=h.SetupClaudeMdGenerateResultMsg=h.SetupClaudeMdGenerateMsg=h.SetupStatusResultMsg=h.SetupStatusMsg=h.DeploySuggestResultMsg=h.EnvPreflightResultMsg=h.EnvPreflightMsg=h.ChatCreateTicketResultMsg=h.ChatCreateTicketMsg=h.ChatTurnResultMsg=h.ChatTurnMsg=h.ChatFile=h.TeamCredsResultMsg=h.TeamCredsMsg=h.KnowledgeSaveResultMsg=h.KnowledgeSaveMsg=h.KnowledgeListResultMsg=h.KnowledgeFile=h.KnowledgeListMsg=h.AuditReviewResultMsg=h.AuditReviewMsg=h.AuditGetResultMsg=h.AuditGetMsg=h.AuditListResultMsg=h.AuditListMsg=h.AuditStartResultMsg=h.AuditStartMsg=h.AuditRecord=h.AuditFinding=h.AuditScope=h.AuditSeverity=h.AuditRole=h.EpicSuggestResultMsg=h.EpicSuggestMsg=void 0;h.DEFAULT_DEPLOY_SUGGEST_PROMPT_TEMPLATE=h.DEPLOY_DOC_SUGGEST_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.DEFAULT_PLAN_PROMPT_TEMPLATE=h.EnrollResponse=h.EnrollRequest=h.ServerToRunnerMsg=h.JiraUsersMsg=void 0;h.missingAgentCapabilities=$p;h.parseRunnerMsg=jp;h.parseServerMsg=Op;var u=vu();h.PROTOCOL_VERSION="1.27";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:[]};function $p(r,e){let t=h.REGISTERED_AGENTS.find(n=>n.id===r);return t?(h.REQUIRED_AGENT_CAPABILITIES[e]??[]).filter(n=>!t.capabilities[n]):null}h.BRANCH_DEPLOY_ISSUE_KEY="(branch deploy)";h.NEEDS_INPUT_MARKER="NEEDS-INPUT";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 Pp=r=>r.includes(h.NEEDS_INPUT_COMMENT_MARKER)||h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS.some(e=>r.includes(e));h.needsInputMarkerIn=Pp;h.RunStatus=u.z.enum(["queued","running","posting","awaiting_approval","needs_input","succeeded","failed","timed_out"]);h.ACTIVE_RUN_STATUSES=["queued","running","posting","awaiting_approval"];h.TriggerType=u.z.enum(["label_added","comment_keyword","status_changed"]);h.ActionType=u.z.enum(["plan_only","implement","respond","deploy"]);h.LabelAddedTrigger=u.z.object({type:u.z.literal("label_added"),label:u.z.string().min(1),doneLabel:u.z.string().min(1).default("agent-planned"),failedLabel:u.z.string().min(1).default("agent-failed")});h.CommentKeywordTrigger=u.z.object({type:u.z.literal("comment_keyword"),keyword:u.z.string().min(1),doneLabel:u.z.string().min(1).default("agent-implemented"),failedLabel:u.z.string().min(1).default("agent-failed")});h.StatusChangedTrigger=u.z.object({type:u.z.literal("status_changed"),status:u.z.string().min(1),doneLabel:u.z.string().min(1).default("agent-deployed"),failedLabel:u.z.string().min(1).default("agent-failed")});h.TriggerConfig=u.z.discriminatedUnion("type",[h.LabelAddedTrigger,h.CommentKeywordTrigger,h.StatusChangedTrigger]);h.PlanOnlyAction=u.z.object({type:u.z.literal("plan_only"),promptTemplate:u.z.string().min(1),timeoutSeconds:u.z.number().int().positive().max(3600).default(900),agent:u.z.string().default(h.DEFAULT_AGENT_ID),model:u.z.string().default("")});h.ImplementAction=u.z.object({type:u.z.literal("implement"),promptTemplate:u.z.string().min(1),timeoutSeconds:u.z.number().int().positive().max(7200).default(1800),maxTurns:u.z.number().int().positive().max(500).default(120),requireApproval:u.z.boolean().default(!0),branchTemplate:u.z.string().min(1).default("agent/{{issueKey}}").refine(r=>r.includes("{{issueKey}}"),{message:"branchTemplate must contain {{issueKey}}"}),baseBranch:u.z.string().min(1).default("main"),jiraTransition:u.z.string().optional(),jiraTransitionOnStart:u.z.string().optional(),jiraTransitionOnMerge:u.z.string().optional(),agent:u.z.string().default(h.DEFAULT_AGENT_ID),model:u.z.string().default(""),updateMemory:u.z.boolean().default(!1)});h.RespondAction=u.z.object({type:u.z.literal("respond"),promptTemplate:u.z.string().min(1),timeoutSeconds:u.z.number().int().positive().max(3600).default(600),agent:u.z.string().default(h.DEFAULT_AGENT_ID),model:u.z.string().default("")});h.DeployStep=u.z.object({name:u.z.string().min(1).max(120),run:u.z.string().min(1).max(4e3),continueOnError:u.z.boolean().default(!1)});h.PromotionMode=u.z.enum(["deploy_only","merge_and_deploy"]);h.EnvironmentConfig=u.z.object({id:u.z.string(),projectId:u.z.string(),name:u.z.string(),rank:u.z.number().int().nonnegative(),auditBeforeDeploy:u.z.enum(["","security","testing"]).default(""),branch:u.z.string().default(""),publicUrl:u.z.string().default(""),useDedicatedCheckout:u.z.boolean().default(!1),promotionMode:h.PromotionMode.default("deploy_only"),ticketBranchTemplate:u.z.string().default("agent/{{issueKey}}"),steps:u.z.array(h.DeployStep).default([]),workdir:u.z.string().default(""),timeoutSeconds:u.z.number().int().positive().max(21600).default(1800),requiredSecrets:u.z.array(u.z.string()).default([]),requireApproval:u.z.boolean().default(!1),requireSyncCheck:u.z.boolean().default(!1),previousEnvBranch:u.z.string().optional(),deployFromColumn:u.z.string().default(""),deployToColumn:u.z.string().default("")});h.DeployAction=u.z.object({type:u.z.literal("deploy"),envSelection:u.z.enum(["fixed","from_comment"]).default("from_comment"),environmentId:u.z.string().optional(),requireStatus:u.z.string().optional()});h.ActionConfig=u.z.discriminatedUnion("type",[h.PlanOnlyAction,h.ImplementAction,h.RespondAction,h.DeployAction]);h.ProjectConfig=u.z.object({id:u.z.string(),name:u.z.string(),jiraProjectKey:u.z.string(),repoName:u.z.string(),componentRoutes:u.z.array(u.z.object({component:u.z.string().min(1),repoName:u.z.string().min(1)})).default([])});h.RuleConfig=u.z.object({id:u.z.string(),projectId:u.z.string(),name:u.z.string(),enabled:u.z.boolean(),trigger:h.TriggerConfig,action:h.ActionConfig});h.HelloMsg=u.z.object({type:u.z.literal("hello"),protocolVersion:u.z.string(),runnerVersion:u.z.string(),platform:u.z.string(),justBooted:u.z.boolean().optional()});h.HeartbeatMsg=u.z.object({type:u.z.literal("heartbeat"),ts:u.z.string()});h.RunClaimMsg=u.z.object({type:u.z.literal("run.claim"),requestId:u.z.string(),ruleId:u.z.string(),issueKey:u.z.string(),issueSummary:u.z.string().default(""),triggerFingerprint:u.z.string(),dedupKey:u.z.string().optional(),triggeredByAccountId:u.z.string().optional()});h.RunLogMsg=u.z.object({type:u.z.literal("run.log"),runId:u.z.string(),seq:u.z.number().int().nonnegative(),ts:u.z.string(),level:u.z.enum(["info","warn","error","agent"]),message:u.z.string().max(16384)});h.RunStatusMsg=u.z.object({type:u.z.literal("run.status"),runId:u.z.string(),status:h.RunStatus,error:u.z.string().optional(),errorKind:u.z.enum(["guard"]).optional(),costUsd:u.z.number().nonnegative().optional(),inputTokens:u.z.number().int().nonnegative().optional(),outputTokens:u.z.number().int().nonnegative().optional(),resultSummary:u.z.string().max(2e3).optional(),billingMode:u.z.enum(["subscription","api","unknown"]).optional(),model:u.z.string().max(200).optional(),prUrl:u.z.string().optional(),headSha:u.z.string().optional(),deployedRef:u.z.string().optional(),retryAvailable:u.z.boolean().optional()});h.ProjectTestResultMsg=u.z.object({type:u.z.literal("project.test.result"),requestId:u.z.string(),ok:u.z.boolean(),checks:u.z.array(u.z.object({name:u.z.string(),ok:u.z.boolean(),detail:u.z.string()}))});h.RuleDiagnoseResultMsg=u.z.object({type:u.z.literal("rule.diagnose.result"),requestId:u.z.string(),checks:u.z.array(u.z.object({name:u.z.string(),ok:u.z.boolean(),detail:u.z.string()})),matchedCount:u.z.number().int().nonnegative(),excludedCount:u.z.number().int().nonnegative(),excludedSample:u.z.array(u.z.string()).max(5)});h.DeployClaimMsg=u.z.object({type:u.z.literal("deploy.claim"),requestId:u.z.string(),projectId:u.z.string(),ruleId:u.z.string(),issueKey:u.z.string(),issueSummary:u.z.string().default(""),environmentName:u.z.string(),requestedByAccountId:u.z.string().optional(),requestedByDisplayName:u.z.string().default(""),dedupKey:u.z.string(),triggerFingerprint:u.z.string()});h.DeployClaimResultMsg=u.z.object({type:u.z.literal("deploy.claim.result"),requestId:u.z.string(),accepted:u.z.boolean(),runId:u.z.string().optional(),environment:h.EnvironmentConfig.optional(),reason:u.z.string().optional(),code:u.z.enum(["ok","duplicate","unknown_environment","not_permitted","unlinked_jira_account","promotion_order","jira_disabled","rule_disabled","cap"]).optional()});h.JiraUsersResultMsg=u.z.object({type:u.z.literal("jira.users.result"),requestId:u.z.string(),ok:u.z.boolean(),users:u.z.array(u.z.object({accountId:u.z.string(),displayName:u.z.string(),email:u.z.string().default(""),active:u.z.boolean().default(!0)})).default([]),error:u.z.string().optional()});h.ChatStreamMsg=u.z.object({type:u.z.literal("chat.stream"),requestId:u.z.string(),seq:u.z.number().int().nonnegative(),text:u.z.string().max(8e3)});h.ChatListMsg=u.z.object({type:u.z.literal("chat.list"),requestId:u.z.string(),projectId:u.z.string()});h.ChatListResultMsg=u.z.object({type:u.z.literal("chat.list.result"),requestId:u.z.string(),sessions:u.z.array(u.z.object({sessionId:u.z.string(),title:u.z.string().default(""),updatedAt:u.z.string().default(""),messageCount:u.z.number().int().nonnegative().default(0)})).default([])});h.ChatLoadMsg=u.z.object({type:u.z.literal("chat.load"),requestId:u.z.string(),sessionId:u.z.string()});h.ChatLoadResultMsg=u.z.object({type:u.z.literal("chat.load.result"),requestId:u.z.string(),ok:u.z.boolean(),projectId:u.z.string().default(""),messages:u.z.array(u.z.object({role:u.z.enum(["user","agent"]),text:u.z.string()})).default([]),error:u.z.string().optional()});h.BoardFetchMsg=u.z.object({type:u.z.literal("board.fetch"),requestId:u.z.string(),projectId:u.z.string()});h.BoardFetchResultMsg=u.z.object({type:u.z.literal("board.fetch.result"),requestId:u.z.string(),ok:u.z.boolean(),browseBaseUrl:u.z.string().default(""),columns:u.z.array(u.z.object({name:u.z.string(),issues:u.z.array(u.z.object({key:u.z.string(),summary:u.z.string(),labels:u.z.array(u.z.string()).default([])})).default([])})).default([]),error:u.z.string().optional()});h.BoardTriggerMsg=u.z.object({type:u.z.literal("board.trigger"),requestId:u.z.string(),projectId:u.z.string(),issueKey:u.z.string(),comment:u.z.string().max(2e3).default(""),removeLabel:u.z.string().default(""),requestedBy:u.z.string().default(""),requestedByEmail:u.z.string().default(""),reimplement:u.z.boolean().default(!1)});h.BoardTriggerResultMsg=u.z.object({type:u.z.literal("board.trigger.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional()});h.EpicListMsg=u.z.object({type:u.z.literal("epic.list"),requestId:u.z.string(),projectId:u.z.string(),epicKey:u.z.string().default("")});h.EpicChild=u.z.object({key:u.z.string(),summary:u.z.string(),status:u.z.string(),statusCategory:u.z.string(),labels:u.z.array(u.z.string()).default([])});h.EpicListResultMsg=u.z.object({type:u.z.literal("epic.list.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),epics:u.z.array(u.z.object({key:u.z.string(),summary:u.z.string(),status:u.z.string()})).default([]),children:u.z.array(h.EpicChild).default([])});h.EpicSuggestMsg=u.z.object({type:u.z.literal("epic.suggest"),requestId:u.z.string(),projectId:u.z.string(),epicKey:u.z.string().min(1),model:u.z.string().default("")});h.EpicSuggestResultMsg=u.z.object({type:u.z.literal("epic.suggest.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),issueKey:u.z.string().default(""),reason:u.z.string().default(""),considered:u.z.number().int().default(0)});h.AuditRole=u.z.enum(["security","testing","architecture"]);h.AuditSeverity=u.z.enum(["critical","high","medium","low","info"]);h.AuditScope=u.z.object({kind:u.z.enum(["repo","ticket","branch"]).default("repo"),ref:u.z.string().default("")});h.AuditFinding=u.z.object({id:u.z.string().min(1),title:u.z.string().min(1),ruleId:u.z.string().max(20).default(""),severity:h.AuditSeverity,area:u.z.string().default(""),evidence:u.z.array(u.z.object({file:u.z.string().min(1),line:u.z.number().int().positive().optional(),note:u.z.string().default("")})).min(1),fix:u.z.string().default("")});h.AuditRecord=u.z.object({id:u.z.string(),role:h.AuditRole,createdAt:u.z.string(),model:u.z.string().default(""),summary:u.z.string().default(""),packNames:u.z.array(u.z.string()).default([]),findings:u.z.array(h.AuditFinding).default([]),costUsd:u.z.number().default(0),review:u.z.object({selected:u.z.array(u.z.string()),updatedAt:u.z.string()}).optional(),verdicts:u.z.record(u.z.object({verdict:u.z.enum(["valid","false-positive","wont-fix"]),note:u.z.string().default(""),by:u.z.string().default(""),at:u.z.string().default("")})).default({}),lessonsWritten:u.z.array(u.z.string()).default([]),ticketed:u.z.record(u.z.string()).default({}),scope:h.AuditScope.default({kind:"repo",ref:""}),testRun:u.z.array(u.z.object({command:u.z.string(),exitCode:u.z.number().int(),durationMs:u.z.number().int().default(0),tail:u.z.string().default("")})).optional()});h.AuditStartMsg=u.z.object({type:u.z.literal("audit.start"),requestId:u.z.string(),projectId:u.z.string(),role:h.AuditRole,model:u.z.string().default(""),scope:h.AuditScope.default({kind:"repo",ref:""})});h.AuditStartResultMsg=u.z.object({type:u.z.literal("audit.start.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),audit:h.AuditRecord.optional()});h.AuditListMsg=u.z.object({type:u.z.literal("audit.list"),requestId:u.z.string(),projectId:u.z.string()});h.AuditListResultMsg=u.z.object({type:u.z.literal("audit.list.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),audits:u.z.array(u.z.object({id:u.z.string(),role:h.AuditRole,createdAt:u.z.string(),findingCount:u.z.number().int(),bySeverity:u.z.record(u.z.number().int()).default({})})).default([])});h.AuditGetMsg=u.z.object({type:u.z.literal("audit.get"),requestId:u.z.string(),projectId:u.z.string(),auditId:u.z.string()});h.AuditGetResultMsg=u.z.object({type:u.z.literal("audit.get.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),audit:h.AuditRecord.optional()});h.AuditReviewMsg=u.z.object({type:u.z.literal("audit.review"),requestId:u.z.string(),projectId:u.z.string(),auditId:u.z.string(),selected:u.z.array(u.z.string()).optional(),ticketed:u.z.array(u.z.object({findingId:u.z.string(),issueKey:u.z.string()})).default([]),verdicts:u.z.array(u.z.object({findingId:u.z.string(),verdict:u.z.enum(["valid","false-positive","wont-fix"]),note:u.z.string().max(2e3).default("")})).default([]),verdictBy:u.z.string().default("")});h.AuditReviewResultMsg=u.z.object({type:u.z.literal("audit.review.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),audit:h.AuditRecord.optional()});h.KnowledgeListMsg=u.z.object({type:u.z.literal("knowledge.list"),requestId:u.z.string(),projectId:u.z.string()});h.KnowledgeFile=u.z.object({role:h.AuditRole,level:u.z.enum(["global","org","project"]),source:u.z.enum(["pack","lessons"]),name:u.z.string(),content:u.z.string(),editable:u.z.boolean().default(!1)});h.KnowledgeListResultMsg=u.z.object({type:u.z.literal("knowledge.list.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),files:u.z.array(h.KnowledgeFile).default([])});h.KnowledgeSaveMsg=u.z.object({type:u.z.literal("knowledge.save"),requestId:u.z.string(),projectId:u.z.string(),role:h.AuditRole,level:u.z.enum(["org","project"]),source:u.z.enum(["pack","lessons"]),name:u.z.string().min(1).max(100),content:u.z.string().max(6e4),append:u.z.boolean().default(!1),by:u.z.string().default("")});h.KnowledgeSaveResultMsg=u.z.object({type:u.z.literal("knowledge.save.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional()});h.TeamCredsMsg=u.z.object({type:u.z.literal("team.creds"),requestId:u.z.string(),emails:u.z.array(u.z.string()).max(200)});h.TeamCredsResultMsg=u.z.object({type:u.z.literal("team.creds.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),githubShared:u.z.boolean().default(!1),sharedGithubLogin:u.z.string().default(""),entries:u.z.array(u.z.object({email:u.z.string(),jira:u.z.enum(["own","runner-account","missing"]),jiraAs:u.z.string().default(""),github:u.z.enum(["own","shared","missing"]),githubAs:u.z.string().default("")})).default([])});h.ChatFile=u.z.object({name:u.z.string().min(1).max(255),contentBase64:u.z.string().min(1).max(6e6)});h.ChatTurnMsg=u.z.object({type:u.z.literal("chat.turn"),requestId:u.z.string(),projectId:u.z.string(),sessionId:u.z.string().optional(),message:u.z.string().min(1).max(2e4),userName:u.z.string().default(""),model:u.z.string().default(""),files:u.z.array(h.ChatFile).max(8).default([])});h.ChatTurnResultMsg=u.z.object({type:u.z.literal("chat.turn.result"),requestId:u.z.string(),ok:u.z.boolean(),sessionId:u.z.string().default(""),reply:u.z.string().default(""),error:u.z.string().optional()});h.ChatCreateTicketMsg=u.z.object({type:u.z.literal("chat.create.ticket"),requestId:u.z.string(),projectId:u.z.string(),summary:u.z.string().min(1).max(250),description:u.z.string().default(""),triggerComment:u.z.string().default(""),requestedBy:u.z.string().default(""),requestedByEmail:u.z.string().default(""),asEpic:u.z.boolean().default(!1),children:u.z.array(u.z.object({summary:u.z.string().min(1),description:u.z.string().default("")})).max(20).default([]),files:u.z.array(h.ChatFile).max(8).default([])});h.ChatCreateTicketResultMsg=u.z.object({type:u.z.literal("chat.create.ticket.result"),requestId:u.z.string(),ok:u.z.boolean(),issueKey:u.z.string().default(""),error:u.z.string().optional(),childKeys:u.z.array(u.z.string()).default([])});h.EnvPreflightMsg=u.z.object({type:u.z.literal("env.preflight"),requestId:u.z.string(),projectId:u.z.string(),environmentName:u.z.string().default(""),steps:u.z.array(h.DeployStep).default([]),requiredSecrets:u.z.array(u.z.string()).default([]),workdir:u.z.string().default(""),branch:u.z.string().default(""),publicUrl:u.z.string().default("")});h.EnvPreflightResultMsg=u.z.object({type:u.z.literal("env.preflight.result"),requestId:u.z.string(),ok:u.z.boolean(),checks:u.z.array(u.z.object({name:u.z.string(),ok:u.z.boolean(),detail:u.z.string().default("")})).default([])});h.DeploySuggestResultMsg=u.z.object({type:u.z.literal("deploy.suggest.result"),requestId:u.z.string(),ok:u.z.boolean(),steps:u.z.array(h.DeployStep).default([]),requiredSecrets:u.z.array(u.z.string()).default([]),notes:u.z.string().default(""),error:u.z.string().optional()});h.SetupStatusMsg=u.z.object({type:u.z.literal("setup.status"),requestId:u.z.string(),repoNames:u.z.array(u.z.string()).max(100).default([])});h.SetupStatusResultMsg=u.z.object({type:u.z.literal("setup.status.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),jiraConfigured:u.z.boolean().default(!1),jiraEmail:u.z.string().default(""),claude:u.z.object({installed:u.z.boolean(),version:u.z.string().default(""),loggedIn:u.z.boolean()}).optional(),githubTokenSet:u.z.boolean().default(!1),githubLogin:u.z.string().default(""),deploysEnabled:u.z.boolean().default(!1),jiraUserCount:u.z.number().int().default(0),repos:u.z.array(u.z.object({repoName:u.z.string(),mapped:u.z.boolean(),pathExists:u.z.boolean().default(!1),isGit:u.z.boolean().default(!1),claudeMd:u.z.boolean().default(!1),deployMd:u.z.boolean().default(!1),testMd:u.z.boolean().default(!1)})).default([])});h.SetupClaudeMdGenerateMsg=u.z.object({type:u.z.literal("setup.claudemd.generate"),requestId:u.z.string(),projectId:u.z.string(),kind:u.z.enum(["claude","deploy"]).default("claude"),streamId:u.z.string().default("")});h.SetupClaudeMdGenerateResultMsg=u.z.object({type:u.z.literal("setup.claudemd.generate.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),content:u.z.string().default("")});h.SetupClaudeMdSaveMsg=u.z.object({type:u.z.literal("setup.claudemd.save"),requestId:u.z.string(),projectId:u.z.string(),kind:u.z.enum(["claude","deploy"]).default("claude"),overwrite:u.z.boolean().default(!1),content:u.z.string().max(1e5)});h.SetupClaudeMdSaveResultMsg=u.z.object({type:u.z.literal("setup.claudemd.save.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),note:u.z.string().default("")});h.RunnerUpdateMsg=u.z.object({type:u.z.literal("runner.update"),requestId:u.z.string()});h.RunnerUpdateResultMsg=u.z.object({type:u.z.literal("runner.update.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),note:u.z.string().default("")});h.RunnerToServerMsg=u.z.discriminatedUnion("type",[h.HelloMsg,h.HeartbeatMsg,h.RunClaimMsg,h.RunLogMsg,h.RunStatusMsg,h.ProjectTestResultMsg,h.RuleDiagnoseResultMsg,h.DeployClaimMsg,h.DeploySuggestResultMsg,h.EnvPreflightResultMsg,h.ChatTurnResultMsg,h.ChatStreamMsg,h.ChatCreateTicketResultMsg,h.ChatListResultMsg,h.ChatLoadResultMsg,h.BoardFetchResultMsg,h.BoardTriggerResultMsg,h.TeamCredsResultMsg,h.AuditStartResultMsg,h.AuditListResultMsg,h.AuditGetResultMsg,h.AuditReviewResultMsg,h.KnowledgeListResultMsg,h.KnowledgeSaveResultMsg,h.EpicListResultMsg,h.EpicSuggestResultMsg,h.JiraUsersResultMsg,h.SetupStatusResultMsg,h.SetupClaudeMdGenerateResultMsg,h.SetupClaudeMdSaveResultMsg,h.RunnerUpdateResultMsg]);h.HelloAckMsg=u.z.object({type:u.z.literal("hello.ack"),runnerId:u.z.string(),runnerName:u.z.string(),serverTime:u.z.string()});h.ConfigMsg=u.z.object({type:u.z.literal("config"),projects:u.z.array(h.ProjectConfig),rules:u.z.array(h.RuleConfig),environments:u.z.array(h.EnvironmentConfig).default([]),pollingPaused:u.z.boolean().default(!1)});h.RunClaimResultMsg=u.z.object({type:u.z.literal("run.claim.result"),requestId:u.z.string(),accepted:u.z.boolean(),runId:u.z.string().optional(),reason:u.z.string().optional(),claudeProfile:u.z.string().optional(),actorEmail:u.z.string().optional()});h.ProjectTestMsg=u.z.object({type:u.z.literal("project.test"),requestId:u.z.string(),projectId:u.z.string()});h.RuleDiagnoseMsg=u.z.object({type:u.z.literal("rule.diagnose"),requestId:u.z.string(),ruleId:u.z.string()});h.RunCancelMsg=u.z.object({type:u.z.literal("run.cancel"),runId:u.z.string()});h.RunApprovedMsg=u.z.object({type:u.z.literal("run.approved"),runId:u.z.string(),headSha:u.z.string().optional()});h.RunRejectedMsg=u.z.object({type:u.z.literal("run.rejected"),runId:u.z.string()});h.RunRetryPushMsg=u.z.object({type:u.z.literal("run.retryPush"),runId:u.z.string()});h.DeployStartMsg=u.z.object({type:u.z.literal("deploy.start"),runId:u.z.string(),projectId:u.z.string(),issueKey:u.z.string(),issueSummary:u.z.string().default(""),environment:h.EnvironmentConfig,requestedBy:u.z.string().default(""),attempt:u.z.number().int().positive().default(1)});h.DeploySuggestMsg=u.z.object({type:u.z.literal("deploy.suggest"),requestId:u.z.string(),projectId:u.z.string(),environmentName:u.z.string(),notes:u.z.string().default(""),timeoutSeconds:u.z.number().int().positive().max(1800).default(300)});h.JiraUsersMsg=u.z.object({type:u.z.literal("jira.users"),requestId:u.z.string(),query:u.z.string().default("")});h.ServerToRunnerMsg=u.z.discriminatedUnion("type",[h.HelloAckMsg,h.ConfigMsg,h.RunClaimResultMsg,h.ProjectTestMsg,h.RuleDiagnoseMsg,h.RunCancelMsg,h.RunApprovedMsg,h.RunRejectedMsg,h.RunRetryPushMsg,h.DeployClaimResultMsg,h.DeployStartMsg,h.DeploySuggestMsg,h.EnvPreflightMsg,h.ChatTurnMsg,h.ChatCreateTicketMsg,h.ChatListMsg,h.ChatLoadMsg,h.BoardFetchMsg,h.BoardTriggerMsg,h.TeamCredsMsg,h.AuditStartMsg,h.AuditListMsg,h.AuditGetMsg,h.AuditReviewMsg,h.KnowledgeListMsg,h.KnowledgeSaveMsg,h.EpicListMsg,h.EpicSuggestMsg,h.JiraUsersMsg,h.SetupStatusMsg,h.SetupClaudeMdGenerateMsg,h.SetupClaudeMdSaveMsg,h.RunnerUpdateMsg]);h.EnrollRequest=u.z.object({enrollToken:u.z.string().min(10),name:u.z.string().min(1).max(100),platform:u.z.string(),runnerVersion:u.z.string()});h.EnrollResponse=u.z.object({runnerId:u.z.string(),runnerToken:u.z.string(),controlPlaneWsUrl:u.z.string()});function jp(r){return h.RunnerToServerMsg.parse(r)}function Op(r){return h.ServerToRunnerMsg.parse(r)}h.DEFAULT_PLAN_PROMPT_TEMPLATE=`You are a senior engineer asked to assess a Jira ticket. You have read-only access to the repository \u2014 do not attempt to modify anything.
|
|
23
|
+
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(s=>t.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function wa(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",s="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?t=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=i[1],/^\d+$/.test(i[3])?s=i[3]:n=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],s=i[4]),t&&s!=="0"?`${t}=${n}:${parseInt(s)+1}`:e})}ka.Command=$i});var Ea=Y(Ie=>{var{Argument:xa}=os(),{Command:Pi}=Sa(),{CommanderError:Hd,InvalidArgumentError:Ta}=Tn(),{Help:Wd}=Si(),{Option:Ca}=Ei();Ie.program=new Pi;Ie.createCommand=r=>new Pi(r);Ie.createOption=(r,e)=>new Ca(r,e);Ie.createArgument=(r,e)=>new xa(r,e);Ie.Command=Pi;Ie.Option=Ca;Ie.Argument=xa;Ie.Help=Wd;Ie.CommanderError=Hd;Ie.InvalidArgumentError=Ta;Ie.InvalidOptionArgumentError=Ta});var $n=Y(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.getParsedType=te.ZodParsedType=te.objectUtil=te.util=void 0;var Ui;(function(r){r.assertEqual=s=>{};function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},r.getValidEnumValues=s=>{let i=r.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),o={};for(let a of i)o[a]=s[a];return r.objectValues(o)},r.objectValues=s=>r.objectKeys(s).map(function(i){return s[i]}),r.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},r.find=(s,i)=>{for(let o of s)if(i(o))return o},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}r.joinValues=n,r.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(Ui||(te.util=Ui={}));var Ya;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(Ya||(te.objectUtil=Ya={}));te.ZodParsedType=Ui.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var pf=r=>{switch(typeof r){case"undefined":return te.ZodParsedType.undefined;case"string":return te.ZodParsedType.string;case"number":return Number.isNaN(r)?te.ZodParsedType.nan:te.ZodParsedType.number;case"boolean":return te.ZodParsedType.boolean;case"function":return te.ZodParsedType.function;case"bigint":return te.ZodParsedType.bigint;case"symbol":return te.ZodParsedType.symbol;case"object":return Array.isArray(r)?te.ZodParsedType.array:r===null?te.ZodParsedType.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?te.ZodParsedType.promise:typeof Map<"u"&&r instanceof Map?te.ZodParsedType.map:typeof Set<"u"&&r instanceof Set?te.ZodParsedType.set:typeof Date<"u"&&r instanceof Date?te.ZodParsedType.date:te.ZodParsedType.object;default:return te.ZodParsedType.unknown}};te.getParsedType=pf});var bs=Y(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.ZodError=Ct.quotelessJson=Ct.ZodIssueCode=void 0;var Xa=$n();Ct.ZodIssueCode=Xa.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 mf=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:");Ct.quotelessJson=mf;var Pn=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},n={_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)n._errors.push(t(o));else{let a=n,l=0;for(;l<o.path.length;){let c=o.path[l];l===o.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(t(o))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return s(this),n}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Xa.util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},n=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];t[i]=t[i]||[],t[i].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};Ct.ZodError=Pn;Pn.create=r=>new Pn(r)});var Fi=Y(qi=>{"use strict";Object.defineProperty(qi,"__esModule",{value:!0});var me=bs(),er=$n(),gf=(r,e)=>{let t;switch(r.code){case me.ZodIssueCode.invalid_type:r.received===er.ZodParsedType.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case me.ZodIssueCode.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,er.util.jsonStringifyReplacer)}`;break;case me.ZodIssueCode.unrecognized_keys:t=`Unrecognized key(s) in object: ${er.util.joinValues(r.keys,", ")}`;break;case me.ZodIssueCode.invalid_union:t="Invalid input";break;case me.ZodIssueCode.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${er.util.joinValues(r.options)}`;break;case me.ZodIssueCode.invalid_enum_value:t=`Invalid enum value. Expected ${er.util.joinValues(r.options)}, received '${r.received}'`;break;case me.ZodIssueCode.invalid_arguments:t="Invalid function arguments";break;case me.ZodIssueCode.invalid_return_type:t="Invalid function return type";break;case me.ZodIssueCode.invalid_date:t="Invalid date";break;case me.ZodIssueCode.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:er.util.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case me.ZodIssueCode.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case me.ZodIssueCode.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case me.ZodIssueCode.custom:t="Invalid input";break;case me.ZodIssueCode.invalid_intersection_types:t="Intersection results could not be merged";break;case me.ZodIssueCode.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case me.ZodIssueCode.not_finite:t="Number must be finite";break;default:t=e.defaultError,er.util.assertNever(r)}return{message:t}};qi.default=gf});var ws=Y(Et=>{"use strict";var yf=Et&&Et.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Et,"__esModule",{value:!0});Et.defaultErrorMap=void 0;Et.setErrorMap=vf;Et.getErrorMap=_f;var Qa=yf(Fi());Et.defaultErrorMap=Qa.default;var eu=Qa.default;function vf(r){eu=r}function _f(){return eu}});var Zi=Y(X=>{"use strict";var bf=X&&X.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(X,"__esModule",{value:!0});X.isAsync=X.isValid=X.isDirty=X.isAborted=X.OK=X.DIRTY=X.INVALID=X.ParseStatus=X.EMPTY_PATH=X.makeIssue=void 0;X.addIssueToContext=Sf;var wf=ws(),tu=bf(Fi()),kf=r=>{let{data:e,path:t,errorMaps:n,issueData:s}=r,i=[...t,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let a="",l=n.filter(c=>!!c).slice().reverse();for(let c of l)a=c(o,{data:e,defaultError:a}).message;return{...s,path:i,message:a}};X.makeIssue=kf;X.EMPTY_PATH=[];function Sf(r,e){let t=(0,wf.getErrorMap)(),n=(0,X.makeIssue)({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===tu.default?void 0:tu.default].filter(s=>!!s)});r.common.issues.push(n)}var Bi=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let s of t){if(s.status==="aborted")return X.INVALID;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let s of t){let i=await s.key,o=await s.value;n.push({key:i,value:o})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let s of t){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return X.INVALID;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(n[i.value]=o.value)}return{status:e.value,value:n}}};X.ParseStatus=Bi;X.INVALID=Object.freeze({status:"aborted"});var xf=r=>({status:"dirty",value:r});X.DIRTY=xf;var Tf=r=>({status:"valid",value:r});X.OK=Tf;var Cf=r=>r.status==="aborted";X.isAborted=Cf;var Ef=r=>r.status==="dirty";X.isDirty=Ef;var If=r=>r.status==="valid";X.isValid=If;var Af=r=>typeof Promise<"u"&&r instanceof Promise;X.isAsync=Af});var nu=Y(ru=>{"use strict";Object.defineProperty(ru,"__esModule",{value:!0})});var iu=Y(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});ks.errorUtil=void 0;var su;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(su||(ks.errorUtil=su={}))});var yu=Y(y=>{"use strict";Object.defineProperty(y,"__esModule",{value:!0});y.discriminatedUnion=y.date=y.boolean=y.bigint=y.array=y.any=y.coerce=y.ZodFirstPartyTypeKind=y.late=y.ZodSchema=y.Schema=y.ZodReadonly=y.ZodPipeline=y.ZodBranded=y.BRAND=y.ZodNaN=y.ZodCatch=y.ZodDefault=y.ZodNullable=y.ZodOptional=y.ZodTransformer=y.ZodEffects=y.ZodPromise=y.ZodNativeEnum=y.ZodEnum=y.ZodLiteral=y.ZodLazy=y.ZodFunction=y.ZodSet=y.ZodMap=y.ZodRecord=y.ZodTuple=y.ZodIntersection=y.ZodDiscriminatedUnion=y.ZodUnion=y.ZodObject=y.ZodArray=y.ZodVoid=y.ZodNever=y.ZodUnknown=y.ZodAny=y.ZodNull=y.ZodUndefined=y.ZodSymbol=y.ZodDate=y.ZodBoolean=y.ZodBigInt=y.ZodNumber=y.ZodString=y.ZodType=void 0;y.NEVER=y.void=y.unknown=y.union=y.undefined=y.tuple=y.transformer=y.symbol=y.string=y.strictObject=y.set=y.record=y.promise=y.preprocess=y.pipeline=y.ostring=y.optional=y.onumber=y.oboolean=y.object=y.number=y.nullable=y.null=y.never=y.nativeEnum=y.nan=y.map=y.literal=y.lazy=y.intersection=y.instanceof=y.function=y.enum=y.effect=void 0;y.datetimeRegex=cu;y.custom=hu;var E=bs(),Ss=ws(),O=iu(),v=Zi(),I=$n(),je=class{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},ou=(r,e)=>{if((0,v.isValid)(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new E.ZodError(r.common.issues);return this._error=t,this._error}}};function K(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))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,a)=>{let{message:l}=r;return o.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??n??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:l??t??a.defaultError}},description:s}}var V=class{get description(){return this._def.description}_getType(e){return(0,I.getParsedType)(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:(0,I.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new v.ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:(0,I.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if((0,v.isAsync)(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,I.getParsedType)(e)},s=this._parseSync({data:e,path:n.path,parent:n});return ou(n,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,I.getParsedType)(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return(0,v.isValid)(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>(0,v.isValid)(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,I.getParsedType)(e)},s=this._parse({data:e,path:n.path,parent:n}),i=await((0,v.isAsync)(s)?s:Promise.resolve(s));return ou(n,i)}refine(e,t){let n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,i)=>{let o=e(s),a=()=>i.addIssue({code:E.ZodIssueCode.custom,...n(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new xe({schema:this,typeName:U.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return Pe.create(this,this._def)}nullable(){return We.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return lt.create(this)}promise(){return Rt.create(this,this._def)}or(e){return ar.create([this,e],this._def)}and(e){return ur.create(this,e,this._def)}transform(e){return new xe({...K(this._def),schema:this,typeName:U.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new fr({...K(this._def),innerType:this,defaultValue:t,typeName:U.ZodDefault})}brand(){return new jn({typeName:U.ZodBranded,type:this,...K(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new pr({...K(this._def),innerType:this,catchValue:t,typeName:U.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return On.create(this,e)}readonly(){return mr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};y.ZodType=V;y.Schema=V;y.ZodSchema=V;var Rf=/^c[^\s-]{8,}$/i,$f=/^[0-9a-z]+$/,Pf=/^[0-9A-HJKMNP-TV-Z]{26}$/i,jf=/^[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,Of=/^[a-z0-9_-]{21}$/i,Nf=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Mf=/^[-+]?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)?)??$/,zf=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Lf="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ki,Df=/^(?:(?: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])$/,Uf=/^(?:(?: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])$/,qf=/^(([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]))$/,Ff=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Bf=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Zf=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,uu="((\\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])))",Kf=new RegExp(`^${uu}$`);function lu(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Vf(r){return new RegExp(`^${lu(r)}$`)}function cu(r){let e=`${uu}T${lu(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Gf(r,e){return!!((e==="v4"||!e)&&Df.test(r)||(e==="v6"||!e)&&qf.test(r))}function Hf(r,e){if(!Nf.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function Wf(r,e){return!!((e==="v4"||!e)&&Uf.test(r)||(e==="v6"||!e)&&Ff.test(r))}var It=class r extends V{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==I.ZodParsedType.string){let i=this._getOrReturnCtx(e);return(0,v.addIssueToContext)(i,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.string,received:i.parsedType}),v.INVALID}let n=new v.ParseStatus,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{code:E.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{code:E.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(s=this._getOrReturnCtx(e,s),o?(0,v.addIssueToContext)(s,{code:E.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&(0,v.addIssueToContext)(s,{code:E.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")zf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{validation:"email",code:E.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")Ki||(Ki=new RegExp(Lf,"u")),Ki.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{validation:"emoji",code:E.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")jf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{validation:"uuid",code:E.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")Of.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{validation:"nanoid",code:E.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")Rf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{validation:"cuid",code:E.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")$f.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{validation:"cuid2",code:E.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")Pf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{validation:"ulid",code:E.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{validation:"url",code:E.ZodIssueCode.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{validation:"regex",code:E.ZodIssueCode.invalid_string,message:i.message}),n.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,v.addIssueToContext)(s,{code:E.ZodIssueCode.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.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,v.addIssueToContext)(s,{code:E.ZodIssueCode.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{code:E.ZodIssueCode.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?cu(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{code:E.ZodIssueCode.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?Kf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{code:E.ZodIssueCode.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?Vf(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{code:E.ZodIssueCode.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?Mf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{validation:"duration",code:E.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?Gf(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{validation:"ip",code:E.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?Hf(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{validation:"jwt",code:E.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?Wf(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{validation:"cidr",code:E.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?Bf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{validation:"base64",code:E.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?Zf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{validation:"base64url",code:E.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):I.util.assertNever(i);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:E.ZodIssueCode.invalid_string,...O.errorUtil.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...O.errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...O.errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...O.errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...O.errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...O.errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...O.errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...O.errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...O.errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...O.errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...O.errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...O.errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...O.errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...O.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,...O.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,...O.errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...O.errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...O.errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...O.errorUtil.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...O.errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...O.errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...O.errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...O.errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...O.errorUtil.errToObj(t)})}nonempty(e){return this.min(1,O.errorUtil.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};y.ZodString=It;It.create=r=>new It({checks:[],typeName:U.ZodString,coerce:r?.coerce??!1,...K(r)});function Jf(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,i=Number.parseInt(r.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var tr=class r extends V{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)!==I.ZodParsedType.number){let i=this._getOrReturnCtx(e);return(0,v.addIssueToContext)(i,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.number,received:i.parsedType}),v.INVALID}let n,s=new v.ParseStatus;for(let i of this._def.checks)i.kind==="int"?I.util.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Jf(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.not_finite,message:i.message}),s.dirty()):I.util.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,O.errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,O.errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,O.errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,O.errorUtil.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:O.errorUtil.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:O.errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:O.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:O.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:O.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:O.errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:O.errorUtil.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:O.errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:O.errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:O.errorUtil.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&I.util.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};y.ZodNumber=tr;tr.create=r=>new tr({checks:[],typeName:U.ZodNumber,coerce:r?.coerce||!1,...K(r)});var rr=class r extends V{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)!==I.ZodParsedType.bigint)return this._getInvalidInput(e);let n,s=new v.ParseStatus;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):I.util.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return(0,v.addIssueToContext)(t,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.bigint,received:t.parsedType}),v.INVALID}gte(e,t){return this.setLimit("min",e,!0,O.errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,O.errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,O.errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,O.errorUtil.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:O.errorUtil.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:O.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:O.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:O.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:O.errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:O.errorUtil.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};y.ZodBigInt=rr;rr.create=r=>new rr({checks:[],typeName:U.ZodBigInt,coerce:r?.coerce??!1,...K(r)});var nr=class extends V{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==I.ZodParsedType.boolean){let n=this._getOrReturnCtx(e);return(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.boolean,received:n.parsedType}),v.INVALID}return(0,v.OK)(e.data)}};y.ZodBoolean=nr;nr.create=r=>new nr({typeName:U.ZodBoolean,coerce:r?.coerce||!1,...K(r)});var sr=class r extends V{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==I.ZodParsedType.date){let i=this._getOrReturnCtx(e);return(0,v.addIssueToContext)(i,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.date,received:i.parsedType}),v.INVALID}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return(0,v.addIssueToContext)(i,{code:E.ZodIssueCode.invalid_date}),v.INVALID}let n=new v.ParseStatus,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{code:E.ZodIssueCode.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),(0,v.addIssueToContext)(s,{code:E.ZodIssueCode.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):I.util.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:O.errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:O.errorUtil.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};y.ZodDate=sr;sr.create=r=>new sr({checks:[],coerce:r?.coerce||!1,typeName:U.ZodDate,...K(r)});var Hr=class extends V{_parse(e){if(this._getType(e)!==I.ZodParsedType.symbol){let n=this._getOrReturnCtx(e);return(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.symbol,received:n.parsedType}),v.INVALID}return(0,v.OK)(e.data)}};y.ZodSymbol=Hr;Hr.create=r=>new Hr({typeName:U.ZodSymbol,...K(r)});var ir=class extends V{_parse(e){if(this._getType(e)!==I.ZodParsedType.undefined){let n=this._getOrReturnCtx(e);return(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.undefined,received:n.parsedType}),v.INVALID}return(0,v.OK)(e.data)}};y.ZodUndefined=ir;ir.create=r=>new ir({typeName:U.ZodUndefined,...K(r)});var or=class extends V{_parse(e){if(this._getType(e)!==I.ZodParsedType.null){let n=this._getOrReturnCtx(e);return(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.null,received:n.parsedType}),v.INVALID}return(0,v.OK)(e.data)}};y.ZodNull=or;or.create=r=>new or({typeName:U.ZodNull,...K(r)});var At=class extends V{constructor(){super(...arguments),this._any=!0}_parse(e){return(0,v.OK)(e.data)}};y.ZodAny=At;At.create=r=>new At({typeName:U.ZodAny,...K(r)});var ut=class extends V{constructor(){super(...arguments),this._unknown=!0}_parse(e){return(0,v.OK)(e.data)}};y.ZodUnknown=ut;ut.create=r=>new ut({typeName:U.ZodUnknown,...K(r)});var Ue=class extends V{_parse(e){let t=this._getOrReturnCtx(e);return(0,v.addIssueToContext)(t,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.never,received:t.parsedType}),v.INVALID}};y.ZodNever=Ue;Ue.create=r=>new Ue({typeName:U.ZodNever,...K(r)});var Wr=class extends V{_parse(e){if(this._getType(e)!==I.ZodParsedType.undefined){let n=this._getOrReturnCtx(e);return(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.void,received:n.parsedType}),v.INVALID}return(0,v.OK)(e.data)}};y.ZodVoid=Wr;Wr.create=r=>new Wr({typeName:U.ZodVoid,...K(r)});var lt=class r extends V{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==I.ZodParsedType.array)return(0,v.addIssueToContext)(t,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.array,received:t.parsedType}),v.INVALID;if(s.exactLength!==null){let o=t.data.length>s.exactLength.value,a=t.data.length<s.exactLength.value;(o||a)&&((0,v.addIssueToContext)(t,{code:o?E.ZodIssueCode.too_big:E.ZodIssueCode.too_small,minimum:a?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&((0,v.addIssueToContext)(t,{code:E.ZodIssueCode.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&((0,v.addIssueToContext)(t,{code:E.ZodIssueCode.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>s.type._parseAsync(new je(t,o,t.path,a)))).then(o=>v.ParseStatus.mergeArray(n,o));let i=[...t.data].map((o,a)=>s.type._parseSync(new je(t,o,t.path,a)));return v.ParseStatus.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:O.errorUtil.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:O.errorUtil.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:O.errorUtil.toString(t)}})}nonempty(e){return this.min(1,e)}};y.ZodArray=lt;lt.create=(r,e)=>new lt({type:r,minLength:null,maxLength:null,exactLength:null,typeName:U.ZodArray,...K(e)});function Gr(r){if(r instanceof we){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=Pe.create(Gr(n))}return new we({...r._def,shape:()=>e})}else return r instanceof lt?new lt({...r._def,type:Gr(r.element)}):r instanceof Pe?Pe.create(Gr(r.unwrap())):r instanceof We?We.create(Gr(r.unwrap())):r instanceof He?He.create(r.items.map(e=>Gr(e))):r}var we=class r extends V{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=I.util.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==I.ZodParsedType.object){let c=this._getOrReturnCtx(e);return(0,v.addIssueToContext)(c,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.object,received:c.parsedType}),v.INVALID}let{status:n,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ue&&this._def.unknownKeys==="strip"))for(let c in s.data)o.includes(c)||a.push(c);let l=[];for(let c of o){let h=i[c],p=s.data[c];l.push({key:{status:"valid",value:c},value:h._parse(new je(s,p,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof Ue){let c=this._def.unknownKeys;if(c==="passthrough")for(let h of a)l.push({key:{status:"valid",value:h},value:{status:"valid",value:s.data[h]}});else if(c==="strict")a.length>0&&((0,v.addIssueToContext)(s,{code:E.ZodIssueCode.unrecognized_keys,keys:a}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let h of a){let p=s.data[h];l.push({key:{status:"valid",value:h},value:c._parse(new je(s,p,s.path,h)),alwaysSet:h in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let c=[];for(let h of l){let p=await h.key,_=await h.value;c.push({key:p,value:_,alwaysSet:h.alwaysSet})}return c}).then(c=>v.ParseStatus.mergeObjectSync(n,c)):v.ParseStatus.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return O.errorUtil.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let s=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:O.errorUtil.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:U.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let n of I.util.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let n of I.util.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return Gr(this)}partial(e){let t={};for(let n of I.util.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let n of I.util.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof Pe;)i=i._def.innerType;t[n]=i}return new r({...this._def,shape:()=>t})}keyof(){return du(I.util.objectKeys(this.shape))}};y.ZodObject=we;we.create=(r,e)=>new we({shape:()=>r,unknownKeys:"strip",catchall:Ue.create(),typeName:U.ZodObject,...K(e)});we.strictCreate=(r,e)=>new we({shape:()=>r,unknownKeys:"strict",catchall:Ue.create(),typeName:U.ZodObject,...K(e)});we.lazycreate=(r,e)=>new we({shape:r,unknownKeys:"strip",catchall:Ue.create(),typeName:U.ZodObject,...K(e)});var ar=class extends V{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function s(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return t.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(a=>new E.ZodError(a.ctx.common.issues));return(0,v.addIssueToContext)(t,{code:E.ZodIssueCode.invalid_union,unionErrors:o}),v.INVALID}if(t.common.async)return Promise.all(n.map(async i=>{let o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let l of n){let c={...t,common:{...t.common,issues:[]},parent:null},h=l._parseSync({data:t.data,path:t.path,parent:c});if(h.status==="valid")return h;h.status==="dirty"&&!i&&(i={result:h,ctx:c}),c.common.issues.length&&o.push(c.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let a=o.map(l=>new E.ZodError(l));return(0,v.addIssueToContext)(t,{code:E.ZodIssueCode.invalid_union,unionErrors:a}),v.INVALID}}get options(){return this._def.options}};y.ZodUnion=ar;ar.create=(r,e)=>new ar({options:r,typeName:U.ZodUnion,...K(e)});var at=r=>r instanceof lr?at(r.schema):r instanceof xe?at(r.innerType()):r instanceof cr?[r.value]:r instanceof dr?r.options:r instanceof hr?I.util.objectValues(r.enum):r instanceof fr?at(r._def.innerType):r instanceof ir?[void 0]:r instanceof or?[null]:r instanceof Pe?[void 0,...at(r.unwrap())]:r instanceof We?[null,...at(r.unwrap())]:r instanceof jn||r instanceof mr?at(r.unwrap()):r instanceof pr?at(r._def.innerType):[],xs=class r extends V{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==I.ZodParsedType.object)return(0,v.addIssueToContext)(t,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.object,received:t.parsedType}),v.INVALID;let n=this.discriminator,s=t.data[n],i=this.optionsMap.get(s);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):((0,v.addIssueToContext)(t,{code:E.ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),v.INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let s=new Map;for(let i of t){let o=at(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of o){if(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,i)}}return new r({typeName:U.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...K(n)})}};y.ZodDiscriminatedUnion=xs;function Vi(r,e){let t=(0,I.getParsedType)(r),n=(0,I.getParsedType)(e);if(r===e)return{valid:!0,data:r};if(t===I.ZodParsedType.object&&n===I.ZodParsedType.object){let s=I.util.objectKeys(e),i=I.util.objectKeys(r).filter(a=>s.indexOf(a)!==-1),o={...r,...e};for(let a of i){let l=Vi(r[a],e[a]);if(!l.valid)return{valid:!1};o[a]=l.data}return{valid:!0,data:o}}else if(t===I.ZodParsedType.array&&n===I.ZodParsedType.array){if(r.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<r.length;i++){let o=r[i],a=e[i],l=Vi(o,a);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return t===I.ZodParsedType.date&&n===I.ZodParsedType.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var ur=class extends V{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=(i,o)=>{if((0,v.isAborted)(i)||(0,v.isAborted)(o))return v.INVALID;let a=Vi(i.value,o.value);return a.valid?(((0,v.isDirty)(i)||(0,v.isDirty)(o))&&t.dirty(),{status:t.value,value:a.data}):((0,v.addIssueToContext)(n,{code:E.ZodIssueCode.invalid_intersection_types}),v.INVALID)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};y.ZodIntersection=ur;ur.create=(r,e,t)=>new ur({left:r,right:e,typeName:U.ZodIntersection,...K(t)});var He=class r extends V{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==I.ZodParsedType.array)return(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.array,received:n.parsedType}),v.INVALID;if(n.data.length<this._def.items.length)return(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),v.INVALID;!this._def.rest&&n.data.length>this._def.items.length&&((0,v.addIssueToContext)(n,{code:E.ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...n.data].map((o,a)=>{let l=this._def.items[a]||this._def.rest;return l?l._parse(new je(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(i).then(o=>v.ParseStatus.mergeArray(t,o)):v.ParseStatus.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};y.ZodTuple=He;He.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new He({items:r,typeName:U.ZodTuple,rest:null,...K(e)})};var Ts=class r extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==I.ZodParsedType.object)return(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.object,received:n.parsedType}),v.INVALID;let s=[],i=this._def.keyType,o=this._def.valueType;for(let a in n.data)s.push({key:i._parse(new je(n,a,n.path,a)),value:o._parse(new je(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?v.ParseStatus.mergeObjectAsync(t,s):v.ParseStatus.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof V?new r({keyType:e,valueType:t,typeName:U.ZodRecord,...K(n)}):new r({keyType:It.create(),valueType:e,typeName:U.ZodRecord,...K(t)})}};y.ZodRecord=Ts;var Jr=class extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==I.ZodParsedType.map)return(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.map,received:n.parsedType}),v.INVALID;let s=this._def.keyType,i=this._def.valueType,o=[...n.data.entries()].map(([a,l],c)=>({key:s._parse(new je(n,a,n.path,[c,"key"])),value:i._parse(new je(n,l,n.path,[c,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let l of o){let c=await l.key,h=await l.value;if(c.status==="aborted"||h.status==="aborted")return v.INVALID;(c.status==="dirty"||h.status==="dirty")&&t.dirty(),a.set(c.value,h.value)}return{status:t.value,value:a}})}else{let a=new Map;for(let l of o){let c=l.key,h=l.value;if(c.status==="aborted"||h.status==="aborted")return v.INVALID;(c.status==="dirty"||h.status==="dirty")&&t.dirty(),a.set(c.value,h.value)}return{status:t.value,value:a}}}};y.ZodMap=Jr;Jr.create=(r,e,t)=>new Jr({valueType:e,keyType:r,typeName:U.ZodMap,...K(t)});var Yr=class r extends V{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==I.ZodParsedType.set)return(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.set,received:n.parsedType}),v.INVALID;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&((0,v.addIssueToContext)(n,{code:E.ZodIssueCode.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&((0,v.addIssueToContext)(n,{code:E.ZodIssueCode.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let i=this._def.valueType;function o(l){let c=new Set;for(let h of l){if(h.status==="aborted")return v.INVALID;h.status==="dirty"&&t.dirty(),c.add(h.value)}return{status:t.value,value:c}}let a=[...n.data.values()].map((l,c)=>i._parse(new je(n,l,n.path,c)));return n.common.async?Promise.all(a).then(l=>o(l)):o(a)}min(e,t){return new r({...this._def,minSize:{value:e,message:O.errorUtil.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:O.errorUtil.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};y.ZodSet=Yr;Yr.create=(r,e)=>new Yr({valueType:r,minSize:null,maxSize:null,typeName:U.ZodSet,...K(e)});var Cs=class r extends V{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==I.ZodParsedType.function)return(0,v.addIssueToContext)(t,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.function,received:t.parsedType}),v.INVALID;function n(a,l){return(0,v.makeIssue)({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,(0,Ss.getErrorMap)(),Ss.defaultErrorMap].filter(c=>!!c),issueData:{code:E.ZodIssueCode.invalid_arguments,argumentsError:l}})}function s(a,l){return(0,v.makeIssue)({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,(0,Ss.getErrorMap)(),Ss.defaultErrorMap].filter(c=>!!c),issueData:{code:E.ZodIssueCode.invalid_return_type,returnTypeError:l}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof Rt){let a=this;return(0,v.OK)(async function(...l){let c=new E.ZodError([]),h=await a._def.args.parseAsync(l,i).catch(b=>{throw c.addIssue(n(l,b)),c}),p=await Reflect.apply(o,this,h);return await a._def.returns._def.type.parseAsync(p,i).catch(b=>{throw c.addIssue(s(p,b)),c})})}else{let a=this;return(0,v.OK)(function(...l){let c=a._def.args.safeParse(l,i);if(!c.success)throw new E.ZodError([n(l,c.error)]);let h=Reflect.apply(o,this,c.data),p=a._def.returns.safeParse(h,i);if(!p.success)throw new E.ZodError([s(h,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:He.create(e).rest(ut.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||He.create([]).rest(ut.create()),returns:t||ut.create(),typeName:U.ZodFunction,...K(n)})}};y.ZodFunction=Cs;var lr=class extends V{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};y.ZodLazy=lr;lr.create=(r,e)=>new lr({getter:r,typeName:U.ZodLazy,...K(e)});var cr=class extends V{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return(0,v.addIssueToContext)(t,{received:t.data,code:E.ZodIssueCode.invalid_literal,expected:this._def.value}),v.INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}};y.ZodLiteral=cr;cr.create=(r,e)=>new cr({value:r,typeName:U.ZodLiteral,...K(e)});function du(r,e){return new dr({values:r,typeName:U.ZodEnum,...K(e)})}var dr=class r extends V{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return(0,v.addIssueToContext)(t,{expected:I.util.joinValues(n),received:t.parsedType,code:E.ZodIssueCode.invalid_type}),v.INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return(0,v.addIssueToContext)(t,{received:t.data,code:E.ZodIssueCode.invalid_enum_value,options:n}),v.INVALID}return(0,v.OK)(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};y.ZodEnum=dr;dr.create=du;var hr=class extends V{_parse(e){let t=I.util.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==I.ZodParsedType.string&&n.parsedType!==I.ZodParsedType.number){let s=I.util.objectValues(t);return(0,v.addIssueToContext)(n,{expected:I.util.joinValues(s),received:n.parsedType,code:E.ZodIssueCode.invalid_type}),v.INVALID}if(this._cache||(this._cache=new Set(I.util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=I.util.objectValues(t);return(0,v.addIssueToContext)(n,{received:n.data,code:E.ZodIssueCode.invalid_enum_value,options:s}),v.INVALID}return(0,v.OK)(e.data)}get enum(){return this._def.values}};y.ZodNativeEnum=hr;hr.create=(r,e)=>new hr({values:r,typeName:U.ZodNativeEnum,...K(e)});var Rt=class extends V{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==I.ZodParsedType.promise&&t.common.async===!1)return(0,v.addIssueToContext)(t,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.promise,received:t.parsedType}),v.INVALID;let n=t.parsedType===I.ZodParsedType.promise?t.data:Promise.resolve(t.data);return(0,v.OK)(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};y.ZodPromise=Rt;Rt.create=(r,e)=>new Rt({type:r,typeName:U.ZodPromise,...K(e)});var xe=class extends V{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===U.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{(0,v.addIssueToContext)(n,o),o.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(n.data,i);if(n.common.async)return Promise.resolve(o).then(async a=>{if(t.value==="aborted")return v.INVALID;let l=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return l.status==="aborted"?v.INVALID:l.status==="dirty"||t.value==="dirty"?(0,v.DIRTY)(l.value):l});{if(t.value==="aborted")return v.INVALID;let a=this._def.schema._parseSync({data:o,path:n.path,parent:n});return a.status==="aborted"?v.INVALID:a.status==="dirty"||t.value==="dirty"?(0,v.DIRTY)(a.value):a}}if(s.type==="refinement"){let o=a=>{let l=s.refinement(a,i);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?v.INVALID:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?v.INVALID:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.value,value:a.value}))))}if(s.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!(0,v.isValid)(o))return v.INVALID;let a=s.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>(0,v.isValid)(o)?Promise.resolve(s.transform(o.value,i)).then(a=>({status:t.value,value:a})):v.INVALID);I.util.assertNever(s)}};y.ZodEffects=xe;y.ZodTransformer=xe;xe.create=(r,e,t)=>new xe({schema:r,typeName:U.ZodEffects,effect:e,...K(t)});xe.createWithPreprocess=(r,e,t)=>new xe({schema:e,effect:{type:"preprocess",transform:r},typeName:U.ZodEffects,...K(t)});var Pe=class extends V{_parse(e){return this._getType(e)===I.ZodParsedType.undefined?(0,v.OK)(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};y.ZodOptional=Pe;Pe.create=(r,e)=>new Pe({innerType:r,typeName:U.ZodOptional,...K(e)});var We=class extends V{_parse(e){return this._getType(e)===I.ZodParsedType.null?(0,v.OK)(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};y.ZodNullable=We;We.create=(r,e)=>new We({innerType:r,typeName:U.ZodNullable,...K(e)});var fr=class extends V{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===I.ZodParsedType.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};y.ZodDefault=fr;fr.create=(r,e)=>new fr({innerType:r,typeName:U.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...K(e)});var pr=class extends V{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return(0,v.isAsync)(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new E.ZodError(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new E.ZodError(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};y.ZodCatch=pr;pr.create=(r,e)=>new pr({innerType:r,typeName:U.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...K(e)});var Xr=class extends V{_parse(e){if(this._getType(e)!==I.ZodParsedType.nan){let n=this._getOrReturnCtx(e);return(0,v.addIssueToContext)(n,{code:E.ZodIssueCode.invalid_type,expected:I.ZodParsedType.nan,received:n.parsedType}),v.INVALID}return{status:"valid",value:e.data}}};y.ZodNaN=Xr;Xr.create=r=>new Xr({typeName:U.ZodNaN,...K(r)});y.BRAND=Symbol("zod_brand");var jn=class extends V{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}};y.ZodBranded=jn;var On=class r extends V{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?v.INVALID:i.status==="dirty"?(t.dirty(),(0,v.DIRTY)(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?v.INVALID:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:U.ZodPipeline})}};y.ZodPipeline=On;var mr=class extends V{_parse(e){let t=this._def.innerType._parse(e),n=s=>((0,v.isValid)(s)&&(s.value=Object.freeze(s.value)),s);return(0,v.isAsync)(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}};y.ZodReadonly=mr;mr.create=(r,e)=>new mr({innerType:r,typeName:U.ZodReadonly,...K(e)});function au(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function hu(r,e={},t){return r?At.create().superRefine((n,s)=>{let i=r(n);if(i instanceof Promise)return i.then(o=>{if(!o){let a=au(e,n),l=a.fatal??t??!0;s.addIssue({code:"custom",...a,fatal:l})}});if(!i){let o=au(e,n),a=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:a})}}):At.create()}y.late={object:we.lazycreate};var U;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(U||(y.ZodFirstPartyTypeKind=U={}));var Yf=(r,e={message:`Input not instance of ${r.name}`})=>hu(t=>t instanceof r,e);y.instanceof=Yf;var fu=It.create;y.string=fu;var pu=tr.create;y.number=pu;var Xf=Xr.create;y.nan=Xf;var Qf=rr.create;y.bigint=Qf;var mu=nr.create;y.boolean=mu;var ep=sr.create;y.date=ep;var tp=Hr.create;y.symbol=tp;var rp=ir.create;y.undefined=rp;var np=or.create;y.null=np;var sp=At.create;y.any=sp;var ip=ut.create;y.unknown=ip;var op=Ue.create;y.never=op;var ap=Wr.create;y.void=ap;var up=lt.create;y.array=up;var lp=we.create;y.object=lp;var cp=we.strictCreate;y.strictObject=cp;var dp=ar.create;y.union=dp;var hp=xs.create;y.discriminatedUnion=hp;var fp=ur.create;y.intersection=fp;var pp=He.create;y.tuple=pp;var mp=Ts.create;y.record=mp;var gp=Jr.create;y.map=gp;var yp=Yr.create;y.set=yp;var vp=Cs.create;y.function=vp;var _p=lr.create;y.lazy=_p;var bp=cr.create;y.literal=bp;var wp=dr.create;y.enum=wp;var kp=hr.create;y.nativeEnum=kp;var Sp=Rt.create;y.promise=Sp;var gu=xe.create;y.effect=gu;y.transformer=gu;var xp=Pe.create;y.optional=xp;var Tp=We.create;y.nullable=Tp;var Cp=xe.createWithPreprocess;y.preprocess=Cp;var Ep=On.create;y.pipeline=Ep;var Ip=()=>fu().optional();y.ostring=Ip;var Ap=()=>pu().optional();y.onumber=Ap;var Rp=()=>mu().optional();y.oboolean=Rp;y.coerce={string:(r=>It.create({...r,coerce:!0})),number:(r=>tr.create({...r,coerce:!0})),boolean:(r=>nr.create({...r,coerce:!0})),bigint:(r=>rr.create({...r,coerce:!0})),date:(r=>sr.create({...r,coerce:!0}))};y.NEVER=v.INVALID});var Gi=Y(Oe=>{"use strict";var $p=Oe&&Oe.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),Qr=Oe&&Oe.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&$p(e,r,t)};Object.defineProperty(Oe,"__esModule",{value:!0});Qr(ws(),Oe);Qr(Zi(),Oe);Qr(nu(),Oe);Qr($n(),Oe);Qr(yu(),Oe);Qr(bs(),Oe)});var bu=Y(ke=>{"use strict";var vu=ke&&ke.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),Pp=ke&&ke.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),jp=ke&&ke.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&vu(e,r,t);return Pp(e,r),e},Op=ke&&ke.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&vu(e,r,t)};Object.defineProperty(ke,"__esModule",{value:!0});ke.z=void 0;var _u=jp(Gi());ke.z=_u;Op(Gi(),ke);ke.default=_u});var Te=Y(d=>{"use strict";Object.defineProperty(d,"__esModule",{value:!0});d.EpicListResultMsg=d.EpicChild=d.EpicListMsg=d.BoardTriggerResultMsg=d.BoardTriggerMsg=d.BoardFetchResultMsg=d.BoardFetchMsg=d.ChatLoadResultMsg=d.ChatLoadMsg=d.ChatListResultMsg=d.ChatListMsg=d.ChatStreamMsg=d.JiraUsersResultMsg=d.DeployClaimResultMsg=d.DeployClaimMsg=d.RuleDiagnoseResultMsg=d.ProjectTestResultMsg=d.RunStatusMsg=d.RunLogMsg=d.RunClaimMsg=d.HeartbeatMsg=d.HelloMsg=d.RuleConfig=d.ProjectConfig=d.ActionConfig=d.DeployAction=d.EnvironmentConfig=d.PromotionMode=d.DeployStep=d.RespondAction=d.ImplementAction=d.PlanOnlyAction=d.TriggerConfig=d.StatusChangedTrigger=d.CommentKeywordTrigger=d.LabelAddedTrigger=d.ActionType=d.TriggerType=d.ACTIVE_RUN_STATUSES=d.RunStatus=d.needsInputMarkerIn=d.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=d.NEEDS_INPUT_COMMENT_MARKER=d.NEEDS_INPUT_LABEL=d.NEEDS_INPUT_MARKER=d.BRANCH_DEPLOY_ISSUE_KEY=d.REQUIRED_AGENT_CAPABILITIES=d.DEFAULT_AGENT_ID=d.REGISTERED_AGENTS=d.PROTOCOL_VERSION=void 0;d.RunCancelMsg=d.RuleDiagnoseMsg=d.ProjectTestMsg=d.RunClaimResultMsg=d.ConfigMsg=d.HelloAckMsg=d.RunnerToServerMsg=d.AutopilotReportMsg=d.AutopilotNextResultMsg=d.AutopilotNextMsg=d.RunnerUpdateResultMsg=d.RunnerUpdateMsg=d.SetupClaudeMdSaveResultMsg=d.SetupClaudeMdSaveMsg=d.SetupClaudeMdGenerateResultMsg=d.SetupClaudeMdGenerateMsg=d.SetupStatusResultMsg=d.SetupStatusMsg=d.DeploySuggestResultMsg=d.EnvPreflightResultMsg=d.EnvPreflightMsg=d.ChatCreateTicketResultMsg=d.ChatCreateTicketMsg=d.ChatTurnResultMsg=d.ChatTurnMsg=d.ChatFile=d.TeamCredsResultMsg=d.TeamCredsMsg=d.KnowledgeSaveResultMsg=d.KnowledgeSaveMsg=d.KnowledgeListResultMsg=d.KnowledgeFile=d.KnowledgeListMsg=d.AuditReviewResultMsg=d.AuditReviewMsg=d.AuditGetResultMsg=d.AuditGetMsg=d.AuditListResultMsg=d.AuditStatsResultMsg=d.AuditStatsMsg=d.AuditListMsg=d.AuditStartResultMsg=d.AuditStartMsg=d.AuditRecord=d.AuditFinding=d.AuditScope=d.AuditSeverity=d.AuditRole=d.EpicSuggestResultMsg=d.EpicSuggestMsg=void 0;d.DEFAULT_DEPLOY_SUGGEST_PROMPT_TEMPLATE=d.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE=d.PROMPT_PRESETS=d.DEFAULT_RESPOND_PROMPT_TEMPLATE=d.BUGFIX_IMPLEMENT_PROMPT_TEMPLATE=d.BUG_INVESTIGATION_PROMPT_TEMPLATE=d.TECHNICAL_PLAN_PROMPT_TEMPLATE=d.MEMORY_UPDATE_PROMPT=d.DEFAULT_IMPLEMENT_PROMPT_TEMPLATE=d.DEFAULT_PLAN_PROMPT_TEMPLATE=d.EnrollResponse=d.EnrollRequest=d.ServerToRunnerMsg=d.JiraUsersMsg=d.DeploySuggestMsg=d.DeployStartMsg=d.RunRetryPushMsg=d.RunRejectedMsg=d.RunApprovedMsg=void 0;d.missingAgentCapabilities=Np;d.parseRunnerMsg=zp;d.parseServerMsg=Lp;var u=bu();d.PROTOCOL_VERSION="1.29";d.REGISTERED_AGENTS=[{id:"claude-code",displayName:"Claude Code",capabilities:{readOnlyJail:!0,editNoShellJail:!0,sessionResume:!0,costReporting:!0,modelSelection:!0,loginProfiles:!0},suggestedModels:["claude-fable-5","claude-opus-5","claude-sonnet-5","claude-haiku-4-5-20251001"],experimental:!1},{id:"codex",displayName:"OpenAI Codex CLI (experimental)",capabilities:{readOnlyJail:!0,editNoShellJail:!1,sessionResume:!1,costReporting:!1,modelSelection:!0,loginProfiles:!1},suggestedModels:[],experimental:!0}];d.DEFAULT_AGENT_ID="claude-code";d.REQUIRED_AGENT_CAPABILITIES={plan_only:["readOnlyJail","sessionResume"],respond:["readOnlyJail"],implement:["editNoShellJail","sessionResume"],deploy:[]};function Np(r,e){let t=d.REGISTERED_AGENTS.find(n=>n.id===r);return t?(d.REQUIRED_AGENT_CAPABILITIES[e]??[]).filter(n=>!t.capabilities[n]):null}d.BRANCH_DEPLOY_ISSUE_KEY="(branch deploy)";d.NEEDS_INPUT_MARKER="NEEDS-INPUT";d.NEEDS_INPUT_LABEL="agent-needs-input";d.NEEDS_INPUT_COMMENT_MARKER="Allwright needs your input";d.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=["TicketPilot needs your input"];var Mp=r=>r.includes(d.NEEDS_INPUT_COMMENT_MARKER)||d.LEGACY_NEEDS_INPUT_COMMENT_MARKERS.some(e=>r.includes(e));d.needsInputMarkerIn=Mp;d.RunStatus=u.z.enum(["queued","running","posting","awaiting_approval","needs_input","succeeded","failed","timed_out"]);d.ACTIVE_RUN_STATUSES=["queued","running","posting","awaiting_approval"];d.TriggerType=u.z.enum(["label_added","comment_keyword","status_changed"]);d.ActionType=u.z.enum(["plan_only","implement","respond","deploy"]);d.LabelAddedTrigger=u.z.object({type:u.z.literal("label_added"),label:u.z.string().min(1),doneLabel:u.z.string().min(1).default("agent-planned"),failedLabel:u.z.string().min(1).default("agent-failed")});d.CommentKeywordTrigger=u.z.object({type:u.z.literal("comment_keyword"),keyword:u.z.string().min(1),doneLabel:u.z.string().min(1).default("agent-implemented"),failedLabel:u.z.string().min(1).default("agent-failed")});d.StatusChangedTrigger=u.z.object({type:u.z.literal("status_changed"),status:u.z.string().min(1),doneLabel:u.z.string().min(1).default("agent-deployed"),failedLabel:u.z.string().min(1).default("agent-failed")});d.TriggerConfig=u.z.discriminatedUnion("type",[d.LabelAddedTrigger,d.CommentKeywordTrigger,d.StatusChangedTrigger]);d.PlanOnlyAction=u.z.object({type:u.z.literal("plan_only"),promptTemplate:u.z.string().min(1),timeoutSeconds:u.z.number().int().positive().max(3600).default(900),agent:u.z.string().default(d.DEFAULT_AGENT_ID),model:u.z.string().default("")});d.ImplementAction=u.z.object({type:u.z.literal("implement"),promptTemplate:u.z.string().min(1),timeoutSeconds:u.z.number().int().positive().max(7200).default(1800),maxTurns:u.z.number().int().positive().max(500).default(120),requireApproval:u.z.boolean().default(!0),branchTemplate:u.z.string().min(1).default("agent/{{issueKey}}").refine(r=>r.includes("{{issueKey}}"),{message:"branchTemplate must contain {{issueKey}}"}),baseBranch:u.z.string().min(1).default("main"),jiraTransition:u.z.string().optional(),jiraTransitionOnStart:u.z.string().optional(),jiraTransitionOnMerge:u.z.string().optional(),agent:u.z.string().default(d.DEFAULT_AGENT_ID),model:u.z.string().default(""),updateMemory:u.z.boolean().default(!1)});d.RespondAction=u.z.object({type:u.z.literal("respond"),promptTemplate:u.z.string().min(1),timeoutSeconds:u.z.number().int().positive().max(3600).default(600),agent:u.z.string().default(d.DEFAULT_AGENT_ID),model:u.z.string().default("")});d.DeployStep=u.z.object({name:u.z.string().min(1).max(120),run:u.z.string().min(1).max(4e3),continueOnError:u.z.boolean().default(!1)});d.PromotionMode=u.z.enum(["deploy_only","merge_and_deploy"]);d.EnvironmentConfig=u.z.object({id:u.z.string(),projectId:u.z.string(),name:u.z.string(),rank:u.z.number().int().nonnegative(),auditBeforeDeploy:u.z.enum(["","security","testing"]).default(""),branch:u.z.string().default(""),publicUrl:u.z.string().default(""),useDedicatedCheckout:u.z.boolean().default(!1),promotionMode:d.PromotionMode.default("deploy_only"),ticketBranchTemplate:u.z.string().default("agent/{{issueKey}}"),steps:u.z.array(d.DeployStep).default([]),workdir:u.z.string().default(""),timeoutSeconds:u.z.number().int().positive().max(21600).default(1800),requiredSecrets:u.z.array(u.z.string()).default([]),requireApproval:u.z.boolean().default(!1),requireSyncCheck:u.z.boolean().default(!1),previousEnvBranch:u.z.string().optional(),deployFromColumn:u.z.string().default(""),deployToColumn:u.z.string().default("")});d.DeployAction=u.z.object({type:u.z.literal("deploy"),envSelection:u.z.enum(["fixed","from_comment"]).default("from_comment"),environmentId:u.z.string().optional(),requireStatus:u.z.string().optional()});d.ActionConfig=u.z.discriminatedUnion("type",[d.PlanOnlyAction,d.ImplementAction,d.RespondAction,d.DeployAction]);d.ProjectConfig=u.z.object({id:u.z.string(),name:u.z.string(),jiraProjectKey:u.z.string(),repoName:u.z.string(),componentRoutes:u.z.array(u.z.object({component:u.z.string().min(1),repoName:u.z.string().min(1)})).default([])});d.RuleConfig=u.z.object({id:u.z.string(),projectId:u.z.string(),name:u.z.string(),enabled:u.z.boolean(),trigger:d.TriggerConfig,action:d.ActionConfig});d.HelloMsg=u.z.object({type:u.z.literal("hello"),protocolVersion:u.z.string(),runnerVersion:u.z.string(),platform:u.z.string(),justBooted:u.z.boolean().optional()});d.HeartbeatMsg=u.z.object({type:u.z.literal("heartbeat"),ts:u.z.string()});d.RunClaimMsg=u.z.object({type:u.z.literal("run.claim"),requestId:u.z.string(),ruleId:u.z.string(),issueKey:u.z.string(),issueSummary:u.z.string().default(""),triggerFingerprint:u.z.string(),dedupKey:u.z.string().optional(),triggeredByAccountId:u.z.string().optional()});d.RunLogMsg=u.z.object({type:u.z.literal("run.log"),runId:u.z.string(),seq:u.z.number().int().nonnegative(),ts:u.z.string(),level:u.z.enum(["info","warn","error","agent"]),message:u.z.string().max(16384)});d.RunStatusMsg=u.z.object({type:u.z.literal("run.status"),runId:u.z.string(),status:d.RunStatus,error:u.z.string().optional(),errorKind:u.z.enum(["guard"]).optional(),costUsd:u.z.number().nonnegative().optional(),inputTokens:u.z.number().int().nonnegative().optional(),outputTokens:u.z.number().int().nonnegative().optional(),resultSummary:u.z.string().max(2e3).optional(),billingMode:u.z.enum(["subscription","api","unknown"]).optional(),model:u.z.string().max(200).optional(),prUrl:u.z.string().optional(),headSha:u.z.string().optional(),deployedRef:u.z.string().optional(),retryAvailable:u.z.boolean().optional()});d.ProjectTestResultMsg=u.z.object({type:u.z.literal("project.test.result"),requestId:u.z.string(),ok:u.z.boolean(),checks:u.z.array(u.z.object({name:u.z.string(),ok:u.z.boolean(),detail:u.z.string()}))});d.RuleDiagnoseResultMsg=u.z.object({type:u.z.literal("rule.diagnose.result"),requestId:u.z.string(),checks:u.z.array(u.z.object({name:u.z.string(),ok:u.z.boolean(),detail:u.z.string()})),matchedCount:u.z.number().int().nonnegative(),excludedCount:u.z.number().int().nonnegative(),excludedSample:u.z.array(u.z.string()).max(5)});d.DeployClaimMsg=u.z.object({type:u.z.literal("deploy.claim"),requestId:u.z.string(),projectId:u.z.string(),ruleId:u.z.string(),issueKey:u.z.string(),issueSummary:u.z.string().default(""),environmentName:u.z.string(),requestedByAccountId:u.z.string().optional(),requestedByDisplayName:u.z.string().default(""),dedupKey:u.z.string(),triggerFingerprint:u.z.string()});d.DeployClaimResultMsg=u.z.object({type:u.z.literal("deploy.claim.result"),requestId:u.z.string(),accepted:u.z.boolean(),runId:u.z.string().optional(),environment:d.EnvironmentConfig.optional(),reason:u.z.string().optional(),code:u.z.enum(["ok","duplicate","unknown_environment","not_permitted","unlinked_jira_account","promotion_order","jira_disabled","rule_disabled","cap"]).optional()});d.JiraUsersResultMsg=u.z.object({type:u.z.literal("jira.users.result"),requestId:u.z.string(),ok:u.z.boolean(),users:u.z.array(u.z.object({accountId:u.z.string(),displayName:u.z.string(),email:u.z.string().default(""),active:u.z.boolean().default(!0)})).default([]),error:u.z.string().optional()});d.ChatStreamMsg=u.z.object({type:u.z.literal("chat.stream"),requestId:u.z.string(),seq:u.z.number().int().nonnegative(),text:u.z.string().max(8e3)});d.ChatListMsg=u.z.object({type:u.z.literal("chat.list"),requestId:u.z.string(),projectId:u.z.string()});d.ChatListResultMsg=u.z.object({type:u.z.literal("chat.list.result"),requestId:u.z.string(),sessions:u.z.array(u.z.object({sessionId:u.z.string(),title:u.z.string().default(""),updatedAt:u.z.string().default(""),messageCount:u.z.number().int().nonnegative().default(0)})).default([])});d.ChatLoadMsg=u.z.object({type:u.z.literal("chat.load"),requestId:u.z.string(),sessionId:u.z.string()});d.ChatLoadResultMsg=u.z.object({type:u.z.literal("chat.load.result"),requestId:u.z.string(),ok:u.z.boolean(),projectId:u.z.string().default(""),messages:u.z.array(u.z.object({role:u.z.enum(["user","agent"]),text:u.z.string()})).default([]),error:u.z.string().optional()});d.BoardFetchMsg=u.z.object({type:u.z.literal("board.fetch"),requestId:u.z.string(),projectId:u.z.string()});d.BoardFetchResultMsg=u.z.object({type:u.z.literal("board.fetch.result"),requestId:u.z.string(),ok:u.z.boolean(),browseBaseUrl:u.z.string().default(""),columns:u.z.array(u.z.object({name:u.z.string(),issues:u.z.array(u.z.object({key:u.z.string(),summary:u.z.string(),labels:u.z.array(u.z.string()).default([])})).default([])})).default([]),error:u.z.string().optional()});d.BoardTriggerMsg=u.z.object({type:u.z.literal("board.trigger"),requestId:u.z.string(),projectId:u.z.string(),issueKey:u.z.string(),comment:u.z.string().max(2e3).default(""),removeLabel:u.z.string().default(""),requestedBy:u.z.string().default(""),requestedByEmail:u.z.string().default(""),reimplement:u.z.boolean().default(!1)});d.BoardTriggerResultMsg=u.z.object({type:u.z.literal("board.trigger.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional()});d.EpicListMsg=u.z.object({type:u.z.literal("epic.list"),requestId:u.z.string(),projectId:u.z.string(),epicKey:u.z.string().default("")});d.EpicChild=u.z.object({key:u.z.string(),summary:u.z.string(),status:u.z.string(),statusCategory:u.z.string(),labels:u.z.array(u.z.string()).default([])});d.EpicListResultMsg=u.z.object({type:u.z.literal("epic.list.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),epics:u.z.array(u.z.object({key:u.z.string(),summary:u.z.string(),status:u.z.string()})).default([]),children:u.z.array(d.EpicChild).default([])});d.EpicSuggestMsg=u.z.object({type:u.z.literal("epic.suggest"),requestId:u.z.string(),projectId:u.z.string(),epicKey:u.z.string().min(1),model:u.z.string().default("")});d.EpicSuggestResultMsg=u.z.object({type:u.z.literal("epic.suggest.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),issueKey:u.z.string().default(""),reason:u.z.string().default(""),considered:u.z.number().int().default(0)});d.AuditRole=u.z.enum(["security","testing","architecture"]);d.AuditSeverity=u.z.enum(["critical","high","medium","low","info"]);d.AuditScope=u.z.object({kind:u.z.enum(["repo","ticket","branch"]).default("repo"),ref:u.z.string().default("")});d.AuditFinding=u.z.object({id:u.z.string().min(1),title:u.z.string().min(1),ruleId:u.z.string().max(20).default(""),severity:d.AuditSeverity,area:u.z.string().default(""),evidence:u.z.array(u.z.object({file:u.z.string().min(1),line:u.z.number().int().positive().optional(),note:u.z.string().default("")})).min(1),fix:u.z.string().default("")});d.AuditRecord=u.z.object({id:u.z.string(),role:d.AuditRole,createdAt:u.z.string(),model:u.z.string().default(""),summary:u.z.string().default(""),packNames:u.z.array(u.z.string()).default([]),findings:u.z.array(d.AuditFinding).default([]),costUsd:u.z.number().default(0),review:u.z.object({selected:u.z.array(u.z.string()),updatedAt:u.z.string()}).optional(),verdicts:u.z.record(u.z.object({verdict:u.z.enum(["valid","false-positive","wont-fix"]),note:u.z.string().default(""),by:u.z.string().default(""),at:u.z.string().default("")})).default({}),lessonsWritten:u.z.array(u.z.string()).default([]),ticketed:u.z.record(u.z.string()).default({}),scope:d.AuditScope.default({kind:"repo",ref:""}),testRun:u.z.array(u.z.object({command:u.z.string(),exitCode:u.z.number().int(),durationMs:u.z.number().int().default(0),tail:u.z.string().default("")})).optional()});d.AuditStartMsg=u.z.object({type:u.z.literal("audit.start"),requestId:u.z.string(),projectId:u.z.string(),role:d.AuditRole,model:u.z.string().default(""),scope:d.AuditScope.default({kind:"repo",ref:""})});d.AuditStartResultMsg=u.z.object({type:u.z.literal("audit.start.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),audit:d.AuditRecord.optional()});d.AuditListMsg=u.z.object({type:u.z.literal("audit.list"),requestId:u.z.string(),projectId:u.z.string()});d.AuditStatsMsg=u.z.object({type:u.z.literal("audit.stats"),requestId:u.z.string(),projectIds:u.z.array(u.z.string()).max(200).default([]),since:u.z.string().default("")});d.AuditStatsResultMsg=u.z.object({type:u.z.literal("audit.stats.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),byProject:u.z.record(u.z.object({audits:u.z.number().int().default(0),findings:u.z.number().int().default(0),valid:u.z.number().int().default(0),falsePositive:u.z.number().int().default(0),wontFix:u.z.number().int().default(0),unreviewed:u.z.number().int().default(0)})).default({})});d.AuditListResultMsg=u.z.object({type:u.z.literal("audit.list.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),audits:u.z.array(u.z.object({id:u.z.string(),role:d.AuditRole,createdAt:u.z.string(),findingCount:u.z.number().int(),bySeverity:u.z.record(u.z.number().int()).default({})})).default([])});d.AuditGetMsg=u.z.object({type:u.z.literal("audit.get"),requestId:u.z.string(),projectId:u.z.string(),auditId:u.z.string()});d.AuditGetResultMsg=u.z.object({type:u.z.literal("audit.get.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),audit:d.AuditRecord.optional()});d.AuditReviewMsg=u.z.object({type:u.z.literal("audit.review"),requestId:u.z.string(),projectId:u.z.string(),auditId:u.z.string(),selected:u.z.array(u.z.string()).optional(),ticketed:u.z.array(u.z.object({findingId:u.z.string(),issueKey:u.z.string()})).default([]),verdicts:u.z.array(u.z.object({findingId:u.z.string(),verdict:u.z.enum(["valid","false-positive","wont-fix"]),note:u.z.string().max(2e3).default("")})).default([]),verdictBy:u.z.string().default("")});d.AuditReviewResultMsg=u.z.object({type:u.z.literal("audit.review.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),audit:d.AuditRecord.optional()});d.KnowledgeListMsg=u.z.object({type:u.z.literal("knowledge.list"),requestId:u.z.string(),projectId:u.z.string()});d.KnowledgeFile=u.z.object({role:d.AuditRole,level:u.z.enum(["global","org","project"]),source:u.z.enum(["pack","lessons"]),name:u.z.string(),content:u.z.string(),editable:u.z.boolean().default(!1)});d.KnowledgeListResultMsg=u.z.object({type:u.z.literal("knowledge.list.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),files:u.z.array(d.KnowledgeFile).default([])});d.KnowledgeSaveMsg=u.z.object({type:u.z.literal("knowledge.save"),requestId:u.z.string(),projectId:u.z.string(),role:d.AuditRole,level:u.z.enum(["org","project"]),source:u.z.enum(["pack","lessons"]),name:u.z.string().min(1).max(100),content:u.z.string().max(6e4),append:u.z.boolean().default(!1),by:u.z.string().default("")});d.KnowledgeSaveResultMsg=u.z.object({type:u.z.literal("knowledge.save.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional()});d.TeamCredsMsg=u.z.object({type:u.z.literal("team.creds"),requestId:u.z.string(),emails:u.z.array(u.z.string()).max(200)});d.TeamCredsResultMsg=u.z.object({type:u.z.literal("team.creds.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),githubShared:u.z.boolean().default(!1),sharedGithubLogin:u.z.string().default(""),entries:u.z.array(u.z.object({email:u.z.string(),jira:u.z.enum(["own","runner-account","missing"]),jiraAs:u.z.string().default(""),github:u.z.enum(["own","shared","missing"]),githubAs:u.z.string().default("")})).default([])});d.ChatFile=u.z.object({name:u.z.string().min(1).max(255),contentBase64:u.z.string().min(1).max(6e6)});d.ChatTurnMsg=u.z.object({type:u.z.literal("chat.turn"),requestId:u.z.string(),projectId:u.z.string(),sessionId:u.z.string().optional(),message:u.z.string().min(1).max(2e4),userName:u.z.string().default(""),model:u.z.string().default(""),files:u.z.array(d.ChatFile).max(8).default([])});d.ChatTurnResultMsg=u.z.object({type:u.z.literal("chat.turn.result"),requestId:u.z.string(),ok:u.z.boolean(),sessionId:u.z.string().default(""),reply:u.z.string().default(""),error:u.z.string().optional()});d.ChatCreateTicketMsg=u.z.object({type:u.z.literal("chat.create.ticket"),requestId:u.z.string(),projectId:u.z.string(),summary:u.z.string().min(1).max(250),description:u.z.string().default(""),triggerComment:u.z.string().default(""),requestedBy:u.z.string().default(""),requestedByEmail:u.z.string().default(""),asEpic:u.z.boolean().default(!1),children:u.z.array(u.z.object({summary:u.z.string().min(1),description:u.z.string().default("")})).max(20).default([]),files:u.z.array(d.ChatFile).max(8).default([])});d.ChatCreateTicketResultMsg=u.z.object({type:u.z.literal("chat.create.ticket.result"),requestId:u.z.string(),ok:u.z.boolean(),issueKey:u.z.string().default(""),error:u.z.string().optional(),childKeys:u.z.array(u.z.string()).default([])});d.EnvPreflightMsg=u.z.object({type:u.z.literal("env.preflight"),requestId:u.z.string(),projectId:u.z.string(),environmentName:u.z.string().default(""),steps:u.z.array(d.DeployStep).default([]),requiredSecrets:u.z.array(u.z.string()).default([]),workdir:u.z.string().default(""),branch:u.z.string().default(""),publicUrl:u.z.string().default("")});d.EnvPreflightResultMsg=u.z.object({type:u.z.literal("env.preflight.result"),requestId:u.z.string(),ok:u.z.boolean(),checks:u.z.array(u.z.object({name:u.z.string(),ok:u.z.boolean(),detail:u.z.string().default("")})).default([])});d.DeploySuggestResultMsg=u.z.object({type:u.z.literal("deploy.suggest.result"),requestId:u.z.string(),ok:u.z.boolean(),steps:u.z.array(d.DeployStep).default([]),requiredSecrets:u.z.array(u.z.string()).default([]),notes:u.z.string().default(""),error:u.z.string().optional()});d.SetupStatusMsg=u.z.object({type:u.z.literal("setup.status"),requestId:u.z.string(),repoNames:u.z.array(u.z.string()).max(100).default([])});d.SetupStatusResultMsg=u.z.object({type:u.z.literal("setup.status.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),jiraConfigured:u.z.boolean().default(!1),jiraEmail:u.z.string().default(""),claude:u.z.object({installed:u.z.boolean(),version:u.z.string().default(""),loggedIn:u.z.boolean()}).optional(),githubTokenSet:u.z.boolean().default(!1),githubLogin:u.z.string().default(""),deploysEnabled:u.z.boolean().default(!1),jiraUserCount:u.z.number().int().default(0),repos:u.z.array(u.z.object({repoName:u.z.string(),mapped:u.z.boolean(),pathExists:u.z.boolean().default(!1),isGit:u.z.boolean().default(!1),claudeMd:u.z.boolean().default(!1),deployMd:u.z.boolean().default(!1),testMd:u.z.boolean().default(!1)})).default([])});d.SetupClaudeMdGenerateMsg=u.z.object({type:u.z.literal("setup.claudemd.generate"),requestId:u.z.string(),projectId:u.z.string(),kind:u.z.enum(["claude","deploy"]).default("claude"),streamId:u.z.string().default("")});d.SetupClaudeMdGenerateResultMsg=u.z.object({type:u.z.literal("setup.claudemd.generate.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),content:u.z.string().default("")});d.SetupClaudeMdSaveMsg=u.z.object({type:u.z.literal("setup.claudemd.save"),requestId:u.z.string(),projectId:u.z.string(),kind:u.z.enum(["claude","deploy"]).default("claude"),overwrite:u.z.boolean().default(!1),content:u.z.string().max(1e5)});d.SetupClaudeMdSaveResultMsg=u.z.object({type:u.z.literal("setup.claudemd.save.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),note:u.z.string().default("")});d.RunnerUpdateMsg=u.z.object({type:u.z.literal("runner.update"),requestId:u.z.string()});d.RunnerUpdateResultMsg=u.z.object({type:u.z.literal("runner.update.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),note:u.z.string().default("")});d.AutopilotNextMsg=u.z.object({type:u.z.literal("autopilot.next"),requestId:u.z.string()});d.AutopilotNextResultMsg=u.z.object({type:u.z.literal("autopilot.next.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),item:u.z.object({id:u.z.string(),projectId:u.z.string(),issueKey:u.z.string(),ruleId:u.z.string()}).nullable().default(null),pausedUntil:u.z.string().default("")});d.AutopilotReportMsg=u.z.object({type:u.z.literal("autopilot.report"),requestId:u.z.string(),itemId:u.z.string(),outcome:u.z.enum(["claimed","failed","paused"]),runId:u.z.string().default(""),error:u.z.string().default("")});d.RunnerToServerMsg=u.z.discriminatedUnion("type",[d.HelloMsg,d.HeartbeatMsg,d.RunClaimMsg,d.RunLogMsg,d.RunStatusMsg,d.ProjectTestResultMsg,d.RuleDiagnoseResultMsg,d.DeployClaimMsg,d.DeploySuggestResultMsg,d.EnvPreflightResultMsg,d.ChatTurnResultMsg,d.ChatStreamMsg,d.ChatCreateTicketResultMsg,d.ChatListResultMsg,d.ChatLoadResultMsg,d.BoardFetchResultMsg,d.BoardTriggerResultMsg,d.TeamCredsResultMsg,d.AuditStartResultMsg,d.AuditListResultMsg,d.AuditGetResultMsg,d.AuditReviewResultMsg,d.KnowledgeListResultMsg,d.KnowledgeSaveResultMsg,d.EpicListResultMsg,d.EpicSuggestResultMsg,d.JiraUsersResultMsg,d.SetupStatusResultMsg,d.SetupClaudeMdGenerateResultMsg,d.SetupClaudeMdSaveResultMsg,d.RunnerUpdateResultMsg,d.AuditStatsResultMsg,d.AutopilotNextMsg,d.AutopilotReportMsg]);d.HelloAckMsg=u.z.object({type:u.z.literal("hello.ack"),runnerId:u.z.string(),runnerName:u.z.string(),serverTime:u.z.string()});d.ConfigMsg=u.z.object({type:u.z.literal("config"),projects:u.z.array(d.ProjectConfig),rules:u.z.array(d.RuleConfig),environments:u.z.array(d.EnvironmentConfig).default([]),pollingPaused:u.z.boolean().default(!1)});d.RunClaimResultMsg=u.z.object({type:u.z.literal("run.claim.result"),requestId:u.z.string(),accepted:u.z.boolean(),runId:u.z.string().optional(),reason:u.z.string().optional(),claudeProfile:u.z.string().optional(),actorEmail:u.z.string().optional()});d.ProjectTestMsg=u.z.object({type:u.z.literal("project.test"),requestId:u.z.string(),projectId:u.z.string()});d.RuleDiagnoseMsg=u.z.object({type:u.z.literal("rule.diagnose"),requestId:u.z.string(),ruleId:u.z.string()});d.RunCancelMsg=u.z.object({type:u.z.literal("run.cancel"),runId:u.z.string()});d.RunApprovedMsg=u.z.object({type:u.z.literal("run.approved"),runId:u.z.string(),headSha:u.z.string().optional()});d.RunRejectedMsg=u.z.object({type:u.z.literal("run.rejected"),runId:u.z.string()});d.RunRetryPushMsg=u.z.object({type:u.z.literal("run.retryPush"),runId:u.z.string()});d.DeployStartMsg=u.z.object({type:u.z.literal("deploy.start"),runId:u.z.string(),projectId:u.z.string(),issueKey:u.z.string(),issueSummary:u.z.string().default(""),environment:d.EnvironmentConfig,requestedBy:u.z.string().default(""),attempt:u.z.number().int().positive().default(1)});d.DeploySuggestMsg=u.z.object({type:u.z.literal("deploy.suggest"),requestId:u.z.string(),projectId:u.z.string(),environmentName:u.z.string(),notes:u.z.string().default(""),timeoutSeconds:u.z.number().int().positive().max(1800).default(300)});d.JiraUsersMsg=u.z.object({type:u.z.literal("jira.users"),requestId:u.z.string(),query:u.z.string().default("")});d.ServerToRunnerMsg=u.z.discriminatedUnion("type",[d.HelloAckMsg,d.ConfigMsg,d.RunClaimResultMsg,d.ProjectTestMsg,d.RuleDiagnoseMsg,d.RunCancelMsg,d.RunApprovedMsg,d.RunRejectedMsg,d.RunRetryPushMsg,d.DeployClaimResultMsg,d.DeployStartMsg,d.DeploySuggestMsg,d.EnvPreflightMsg,d.ChatTurnMsg,d.ChatCreateTicketMsg,d.ChatListMsg,d.ChatLoadMsg,d.BoardFetchMsg,d.BoardTriggerMsg,d.TeamCredsMsg,d.AuditStartMsg,d.AuditListMsg,d.AuditGetMsg,d.AuditReviewMsg,d.KnowledgeListMsg,d.KnowledgeSaveMsg,d.EpicListMsg,d.EpicSuggestMsg,d.JiraUsersMsg,d.SetupStatusMsg,d.SetupClaudeMdGenerateMsg,d.SetupClaudeMdSaveMsg,d.RunnerUpdateMsg,d.AuditStatsMsg,d.AutopilotNextResultMsg]);d.EnrollRequest=u.z.object({enrollToken:u.z.string().min(10),name:u.z.string().min(1).max(100),platform:u.z.string(),runnerVersion:u.z.string()});d.EnrollResponse=u.z.object({runnerId:u.z.string(),runnerToken:u.z.string(),controlPlaneWsUrl:u.z.string()});function zp(r){return d.RunnerToServerMsg.parse(r)}function Lp(r){return d.ServerToRunnerMsg.parse(r)}d.DEFAULT_PLAN_PROMPT_TEMPLATE=`You are a senior engineer asked to assess a Jira ticket. You have read-only access to the repository - do not attempt to modify anything.
|
|
24
24
|
|
|
25
25
|
Ticket {{issueKey}}: {{summary}}
|
|
26
26
|
|
|
@@ -36,13 +36,13 @@ Explore the repository as needed, then write your answer.
|
|
|
36
36
|
|
|
37
37
|
YOUR ANSWER WILL BE POSTED AS A JIRA COMMENT, AND THE PERSON READING IT IS USUALLY NOT A PROGRAMMER. Write for them:
|
|
38
38
|
- Plain, everyday language. No jargon, no function names, no code snippets. Mention a file name only if the reader genuinely needs it.
|
|
39
|
-
- Short. As long as needed, no longer
|
|
40
|
-
- Cover, in this order: what will be done (in product terms
|
|
41
|
-
- Do not describe your exploration process or list implementation steps
|
|
39
|
+
- Short. As long as needed, no longer - a few sentences for a small ticket, at most ~200 words for a big one.
|
|
40
|
+
- Cover, in this order: what will be done (in product terms - what the user of the software will notice), roughly how big the job is (small / medium / large), and any assumption you had to make, stated simply.
|
|
41
|
+
- Do not describe your exploration process or list implementation steps - the developer doing the work will figure those out from the code.
|
|
42
42
|
|
|
43
|
-
IF THE TICKET IS TOO AMBIGUOUS to assess honestly
|
|
44
|
-
${
|
|
45
|
-
followed by at most 3 numbered questions, in the same plain language, that the ticket author can answer without reading code. They will be posted as a comment on the ticket, and you will be resumed
|
|
43
|
+
IF THE TICKET IS TOO AMBIGUOUS to assess honestly - you cannot tell what is being asked, or two reasonable readings lead to very different work - do NOT guess. Instead make your ENTIRE final message start with the line:
|
|
44
|
+
${d.NEEDS_INPUT_MARKER}
|
|
45
|
+
followed by at most 3 numbered questions, in the same plain language, that the ticket author can answer without reading code. They will be posted as a comment on the ticket, and you will be resumed - with this exact conversation, not a fresh one - as soon as someone replies. Minor ambiguity is NOT a reason to ask - prefer a stated assumption; ask only when you are truly blocked.`;d.DEFAULT_IMPLEMENT_PROMPT_TEMPLATE=`You are a senior engineer implementing a Jira ticket in this repository. You can read the code and edit/create files. You cannot run commands, so be careful and conservative: follow the existing code style, keep the change minimal, and do not refactor unrelated code.
|
|
46
46
|
|
|
47
47
|
Ticket {{issueKey}}: {{summary}}
|
|
48
48
|
|
|
@@ -56,20 +56,20 @@ The comments are in chronological order and may supersede the description: when
|
|
|
56
56
|
|
|
57
57
|
Explore the repository, then implement the change.
|
|
58
58
|
|
|
59
|
-
DELETING FILES: you cannot delete a file directly. If the ticket requires removing files, create a file named .ticketpilot-delete at the repository root containing one repo-relative path per line
|
|
59
|
+
DELETING FILES: you cannot delete a file directly. If the ticket requires removing files, create a file named .ticketpilot-delete at the repository root containing one repo-relative path per line - those files are deleted automatically just before your work is committed (CI/workflow paths are refused, and the manifest itself is never committed). Mention the deletions in your summary.
|
|
60
60
|
|
|
61
|
-
BEFORE editing anything: if the ticket is too ambiguous to implement
|
|
62
|
-
${
|
|
63
|
-
followed by at most 3 numbered questions in plain, non-technical language that the ticket author can answer without reading code. They will be posted as a comment on the ticket, and you will be resumed
|
|
61
|
+
BEFORE editing anything: if the ticket is too ambiguous to implement - you cannot tell what is being asked, or two reasonable readings lead to very different code - do NOT guess and do NOT edit any file. Instead make your ENTIRE final message start with the line:
|
|
62
|
+
${d.NEEDS_INPUT_MARKER}
|
|
63
|
+
followed by at most 3 numbered questions in plain, non-technical language that the ticket author can answer without reading code. They will be posted as a comment on the ticket, and you will be resumed - with this exact conversation, not a fresh one - as soon as someone replies. Minor ambiguity is NOT a reason to ask - prefer a stated assumption; ask only when you are truly blocked.
|
|
64
64
|
|
|
65
65
|
When you are done, END your final message with a section titled "## Summary of changes" describing:
|
|
66
66
|
1. What you changed and why, file by file.
|
|
67
67
|
2. Anything you could NOT verify because you cannot run tests or commands.
|
|
68
68
|
3. Anything ambiguous in the ticket and the assumption you made.
|
|
69
69
|
|
|
70
|
-
That summary will become the pull request description a human reviews
|
|
70
|
+
That summary will become the pull request description a human reviews - write it for them.`;d.MEMORY_UPDATE_PROMPT=`
|
|
71
71
|
|
|
72
|
-
ALSO: after the implementation is complete, update the CLAUDE.md file at the repository root (create it if it does not exist). Record only durable knowledge about this codebase that would help someone working on a FUTURE ticket: where key modules live, non-obvious conventions, tricky couplings, gotchas you hit while working. Keep it short and general
|
|
72
|
+
ALSO: after the implementation is complete, update the CLAUDE.md file at the repository root (create it if it does not exist). Record only durable knowledge about this codebase that would help someone working on a FUTURE ticket: where key modules live, non-obvious conventions, tricky couplings, gotchas you hit while working. Keep it short and general - do NOT log what this ticket changed, and do not repeat what the file already says. If nothing durable was learned, leave the file unchanged.`;d.TECHNICAL_PLAN_PROMPT_TEMPLATE=`You are a senior engineer asked to produce an implementation plan for a Jira ticket. You have read-only access to the repository - do not attempt to modify anything.
|
|
73
73
|
|
|
74
74
|
Ticket {{issueKey}}: {{summary}}
|
|
75
75
|
|
|
@@ -88,11 +88,11 @@ Explore the repository as needed, then write a concise implementation plan with:
|
|
|
88
88
|
4. Risks, open questions, and anything the ticket leaves ambiguous.
|
|
89
89
|
5. A rough size estimate (S/M/L).
|
|
90
90
|
|
|
91
|
-
Write the plan in Markdown. It will be posted as a comment on the ticket for a developer to review
|
|
91
|
+
Write the plan in Markdown. It will be posted as a comment on the ticket for a developer to review - be specific to THIS codebase, not generic.
|
|
92
92
|
|
|
93
93
|
IF THE TICKET IS TOO AMBIGUOUS to plan honestly, do NOT guess. Instead make your ENTIRE final message start with the line:
|
|
94
|
-
${
|
|
95
|
-
followed by at most 3 numbered questions the ticket author can answer. They will be posted as a comment on the ticket, and you will be resumed
|
|
94
|
+
${d.NEEDS_INPUT_MARKER}
|
|
95
|
+
followed by at most 3 numbered questions the ticket author can answer. They will be posted as a comment on the ticket, and you will be resumed - with this exact conversation, not a fresh one - as soon as someone replies. Minor ambiguity is NOT a reason to ask - prefer a stated assumption; ask only when you are truly blocked.`;d.BUG_INVESTIGATION_PROMPT_TEMPLATE=`You are a senior engineer investigating a bug reported in a Jira ticket. You have read-only access to the repository - do not attempt to modify anything.
|
|
96
96
|
|
|
97
97
|
Ticket {{issueKey}}: {{summary}}
|
|
98
98
|
|
|
@@ -106,15 +106,15 @@ The comments are in chronological order and may supersede the description: when
|
|
|
106
106
|
|
|
107
107
|
Trace the reported behavior through the code, then write, in Markdown:
|
|
108
108
|
1. The bug, restated in one sentence.
|
|
109
|
-
2. The most likely root cause
|
|
109
|
+
2. The most likely root cause - name the specific file(s) and logic responsible, and say how confident you are.
|
|
110
110
|
3. If several causes are plausible, list them in order of likelihood.
|
|
111
111
|
4. The fix you would make, and any regression risk around it.
|
|
112
112
|
|
|
113
|
-
The reader is a developer. Do not pad
|
|
113
|
+
The reader is a developer. Do not pad - a short, confident answer beats a long, hedged one.
|
|
114
114
|
|
|
115
115
|
IF YOU CANNOT investigate meaningfully (the ticket does not say what happened, or how to see it), make your ENTIRE final message start with the line:
|
|
116
|
-
${
|
|
117
|
-
followed by at most 3 numbered questions (steps to reproduce, expected vs actual behavior). They will be posted on the ticket, and you will be resumed
|
|
116
|
+
${d.NEEDS_INPUT_MARKER}
|
|
117
|
+
followed by at most 3 numbered questions (steps to reproduce, expected vs actual behavior). They will be posted on the ticket, and you will be resumed - with this exact conversation, not a fresh one - as soon as someone replies.`;d.BUGFIX_IMPLEMENT_PROMPT_TEMPLATE=`You are a senior engineer fixing a bug reported in a Jira ticket. You can read the code and edit/create files. You cannot run commands, so be careful and conservative.
|
|
118
118
|
|
|
119
119
|
Ticket {{issueKey}}: {{summary}}
|
|
120
120
|
|
|
@@ -128,18 +128,18 @@ The comments are in chronological order and may supersede the description: when
|
|
|
128
128
|
|
|
129
129
|
Find the root cause, then make the SMALLEST change that fixes it. Do not refactor, do not fix unrelated issues you notice, do not change formatting beyond the fix.
|
|
130
130
|
|
|
131
|
-
DELETING FILES: you cannot delete a file directly. If the fix requires removing a file, create a file named .ticketpilot-delete at the repository root containing one repo-relative path per line
|
|
131
|
+
DELETING FILES: you cannot delete a file directly. If the fix requires removing a file, create a file named .ticketpilot-delete at the repository root containing one repo-relative path per line - those files are deleted automatically just before your work is committed (CI/workflow paths are refused, and the manifest itself is never committed). Mention the deletions in your summary.
|
|
132
132
|
|
|
133
133
|
BEFORE editing anything: if you cannot tell what the bug is, or cannot locate a plausible cause, do NOT guess and do NOT edit any file. Instead make your ENTIRE final message start with the line:
|
|
134
|
-
${
|
|
135
|
-
followed by at most 3 numbered questions (steps to reproduce, expected vs actual behavior). They will be posted on the ticket, and you will be resumed
|
|
134
|
+
${d.NEEDS_INPUT_MARKER}
|
|
135
|
+
followed by at most 3 numbered questions (steps to reproduce, expected vs actual behavior). They will be posted on the ticket, and you will be resumed - with this exact conversation, not a fresh one - as soon as someone replies.
|
|
136
136
|
|
|
137
137
|
When you are done, END your final message with a section titled "## Summary of changes" describing:
|
|
138
138
|
1. The root cause.
|
|
139
139
|
2. The fix, file by file.
|
|
140
140
|
3. Regression risk, and what you could not verify (you cannot run tests).
|
|
141
141
|
|
|
142
|
-
That summary will become the pull request description a human reviews
|
|
142
|
+
That summary will become the pull request description a human reviews - write it for them.`;d.DEFAULT_RESPOND_PROMPT_TEMPLATE=`You are the engineering assistant for this repository, answering a question asked in a Jira ticket comment. You have read-only access to the code - explore it as needed to answer accurately.
|
|
143
143
|
|
|
144
144
|
Ticket {{issueKey}}: {{summary}}
|
|
145
145
|
|
|
@@ -154,7 +154,7 @@ The comments are in chronological order and may supersede the description: when
|
|
|
154
154
|
The question you are answering, asked by {{questionAuthor}}:
|
|
155
155
|
{{question}}
|
|
156
156
|
|
|
157
|
-
Write your answer as a Jira comment addressed to {{questionAuthor}}. Match their technical level
|
|
157
|
+
Write your answer as a Jira comment addressed to {{questionAuthor}}. Match their technical level - if they sound non-technical, answer in plain language with no jargon or code. Be direct, and only as long as the answer needs. If the code contradicts an assumption in the question, say so plainly. If you cannot answer from the ticket and the code alone, say exactly what information you would need - your reply IS the conversation, so just ask.`;d.PROMPT_PRESETS=[{id:"plan-simple",name:"Simple plan - plain language",action:"plan_only",whenToUse:"Default. The Jira comment is read by non-technical people: short, no jargon, describes the work in product terms.",template:d.DEFAULT_PLAN_PROMPT_TEMPLATE},{id:"plan-technical",name:"Technical plan - for developers",action:"plan_only",whenToUse:"The readers are developers: files to change, ordered steps, risks, and a size estimate.",template:d.TECHNICAL_PLAN_PROMPT_TEMPLATE},{id:"plan-bug",name:"Bug investigation",action:"plan_only",whenToUse:"The ticket reports a bug: trace the root cause in the code and propose the fix - without changing anything.",template:d.BUG_INVESTIGATION_PROMPT_TEMPLATE},{id:"impl-standard",name:"Standard implement",action:"implement",whenToUse:"Default. Careful, minimal implementation that follows the existing code style.",template:d.DEFAULT_IMPLEMENT_PROMPT_TEMPLATE},{id:"impl-bugfix",name:"Bug fix - smallest change",action:"implement",whenToUse:"The ticket is a bug: find the root cause and make the smallest possible fix, nothing else.",template:d.BUGFIX_IMPLEMENT_PROMPT_TEMPLATE},{id:"respond-default",name:"Answer a question",action:"respond",whenToUse:"Default for reply rules. Reads the code and answers the comment at the asker's technical level.",template:d.DEFAULT_RESPOND_PROMPT_TEMPLATE}];d.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE=`You are a release engineer. This repository ships a deploy document written by its operators - it is the ground truth for how "{{envName}}" is deployed. Your ONLY job is to translate that document into executable steps.
|
|
158
158
|
|
|
159
159
|
The document ({{docPath}}):
|
|
160
160
|
---
|
|
@@ -180,19 +180,19 @@ Reply with a single fenced \`\`\`json block and nothing else, in this shape:
|
|
|
180
180
|
Output rules: emit the fenced block and nothing else. Use exactly the key names above. Keep each "name" under 100 characters; explanations go in "notes".
|
|
181
181
|
|
|
182
182
|
Rules for the steps:
|
|
183
|
-
- The runner executes every step ON the machine it is installed on. If the document wraps commands in ssh, check the machine facts above first: when the paths/services the document deploys actually EXIST on this machine, the runner is already sitting on the deploy target
|
|
184
|
-
- Translate ONLY what the document says. Do NOT invent commands, hosts, paths or tooling the document does not mention
|
|
183
|
+
- The runner executes every step ON the machine it is installed on. If the document wraps commands in ssh, check the machine facts above first: when the paths/services the document deploys actually EXIST on this machine, the runner is already sitting on the deploy target - emit plain local commands WITHOUT the ssh wrapper (and no SSH secrets), and explain why in "notes". Keep the ssh wrapper only when the target is genuinely a different machine.
|
|
184
|
+
- Translate ONLY what the document says. Do NOT invent commands, hosts, paths or tooling the document does not mention - if the document is missing something a deploy obviously needs, say so in "notes" instead of guessing.
|
|
185
185
|
- If the document describes several environments, extract the "{{envName}}" parts; if it doesn't distinguish, say so in "notes".
|
|
186
186
|
- Each "run" is one bash command line, executed in the repo checkout on the machine the runner is installed on.
|
|
187
187
|
- Reference secrets as environment variables ($DEPLOY_HOST), never literal values, and list every variable you use in "requiredSecrets".
|
|
188
|
-
- Prefer commands that are safe to re-run; a deploy may be retried.`;
|
|
188
|
+
- Prefer commands that are safe to re-run; a deploy may be retried.`;d.DEFAULT_DEPLOY_SUGGEST_PROMPT_TEMPLATE=`You are a release engineer. Inspect this repository read-only and propose the shell steps needed to deploy it to the "{{envName}}" environment.
|
|
189
189
|
|
|
190
190
|
What the operator told us about this environment:
|
|
191
191
|
{{notes}}
|
|
192
192
|
|
|
193
193
|
{{machineContext}}
|
|
194
194
|
|
|
195
|
-
Ground your answer in what is ACTUALLY in this repo: package manager and scripts in package.json / Makefile / Dockerfile / docker-compose.yml, CI workflows, existing deploy or release scripts, framework conventions, and any deployment docs. Do not invent tooling the repo does not use
|
|
195
|
+
Ground your answer in what is ACTUALLY in this repo: package manager and scripts in package.json / Makefile / Dockerfile / docker-compose.yml, CI workflows, existing deploy or release scripts, framework conventions, and any deployment docs. Do not invent tooling the repo does not use - and do not reference tools the machine context above says are missing.
|
|
196
196
|
|
|
197
197
|
Reply with a single fenced \`\`\`json block and nothing else, in this shape:
|
|
198
198
|
|
|
@@ -205,61 +205,61 @@ Reply with a single fenced \`\`\`json block and nothing else, in this shape:
|
|
|
205
205
|
"notes": "Anything the human must check or fill in before saving."
|
|
206
206
|
}
|
|
207
207
|
|
|
208
|
-
Output rules, which matter as much as the content: emit the fenced block and nothing else
|
|
208
|
+
Output rules, which matter as much as the content: emit the fenced block and nothing else - no preamble, no commentary after it. Use exactly the key names above ("steps", "run", "name", "requiredSecrets", "notes"). Keep each "name" under 100 characters and put any explanation in "notes" instead.
|
|
209
209
|
|
|
210
210
|
Rules for the steps:
|
|
211
211
|
- Each "run" is one bash command line, executed in the repo checkout on the machine the runner is installed on.
|
|
212
212
|
- Reference secrets as environment variables ($DEPLOY_HOST), never literal values, and list every variable you use in "requiredSecrets".
|
|
213
213
|
- Prefer commands that are safe to re-run; a deploy may be retried.
|
|
214
214
|
- Order matters: install, build, test (if cheap), then release.
|
|
215
|
-
- If you genuinely cannot tell how this repo is deployed, return an empty "steps" array and explain what is missing in "notes".`});var
|
|
216
|
-
`).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#"));for(let i of s.slice(0,200)){if(ne.default.isAbsolute(i)){e.refused.push(`${i}
|
|
215
|
+
- If you genuinely cannot tell how this repo is deployed, return an empty "steps" array and explain what is missing in "notes".`});var Pu={};ss(Pu,{DELETE_MANIFEST_FILE:()=>en,MAX_CHANGED_FILES:()=>As,MAX_CHANGED_LINES:()=>Rs,applyDeleteManifest:()=>Hi,branchForIssue:()=>ro,branchSha:()=>js,branchesDiffer:()=>oo,checkDiffSafety:()=>Qi,commitAll:()=>Ps,deleteStaleBranch:()=>Yi,diffAgainstDefault:()=>Os,envCheckoutPath:()=>$u,envCheckoutsRoot:()=>Ru,fetchBase:()=>tn,headSha:()=>zn,mergeTicketBranch:()=>so,originUrl:()=>yr,parseOwnerRepo:()=>vr,prepareEnvCheckout:()=>no,pruneWorktrees:()=>to,pushBranch:()=>eo,pushEnvBranch:()=>io,pushWipBranch:()=>Wi,removeWorktree:()=>rn,statusSnapshot:()=>Ji,worktreeAdd:()=>Xi,worktreeFingerprint:()=>$s,worktreesRoot:()=>Mn});async function G(r,e,t={}){try{let{stdout:n}=await Cu("git",["-C",r,...e],{timeout:t.timeoutMs??12e4,maxBuffer:16777216,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});return n}catch(n){let s=n;throw new Error(`git ${e[0]} failed: ${(s.stderr||s.message||"").trim().slice(0,500)}`)}}async function Hi(r){let e={deleted:[],refused:[]},t=ne.default.join(r,en);if(!de.default.existsSync(t))return e;let n=ne.default.resolve(r),s=de.default.readFileSync(t,"utf8").split(`
|
|
216
|
+
`).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#"));for(let i of s.slice(0,200)){if(ne.default.isAbsolute(i)){e.refused.push(`${i} - absolute paths are not allowed`);continue}let o=ne.default.resolve(n,i);if(o!==n&&!o.startsWith(n+ne.default.sep)){e.refused.push(`${i} - escapes the worktree`);continue}let a=ne.default.relative(n,o).split(ne.default.sep).join("/");if(a===en)continue;if(Au.some(c=>c.test(a))){e.refused.push(`${i} - protected path (CI/hook files are never touched)`);continue}let l;try{l=de.default.lstatSync(o)}catch{e.refused.push(`${i} - no such file`);continue}if(l.isDirectory()){e.refused.push(`${i} - is a directory (list the files inside it instead)`);continue}try{de.default.rmSync(o),e.deleted.push(a)}catch(c){e.refused.push(`${i} - ${c instanceof Error?c.message:"delete failed"}`)}}return de.default.rmSync(t,{force:!0}),e}async function Wi(r,e){await G(r,["push","--force","origin",`HEAD:refs/heads/${e}`],{timeoutMs:3e5})}async function $s(r){let e=await G(r,["status","--porcelain"]),t=await G(r,["diff","--numstat"]),n=e.split(`
|
|
217
217
|
`).filter(s=>s.startsWith("??")).map(s=>s.slice(3).trim()).slice(0,500).map(s=>{try{let i=de.default.statSync(ne.default.join(r,s));return`${s}:${i.size}:${i.mtimeMs}`}catch{return s}}).join(`
|
|
218
218
|
`);return`${e}
|
|
219
219
|
--
|
|
220
220
|
${t}
|
|
221
221
|
--
|
|
222
|
-
${n}`}async function
|
|
222
|
+
${n}`}async function Ji(r){let e=(await G(r,["rev-parse","--abbrev-ref","HEAD"])).trim(),t=(await G(r,["log","--oneline","-1"])).trim(),n=(await G(r,["status","--porcelain"])).trim(),s=n?n.split(`
|
|
223
223
|
`):[],i=s.slice(0,15).join(`
|
|
224
224
|
`),o=s.length>15?`
|
|
225
225
|
(\u2026 ${s.length-15} more)`:"";return`branch ${e} @ ${t}
|
|
226
226
|
working tree: ${s.length?`
|
|
227
|
-
${i}${o}`:"clean"}`}function
|
|
228
|
-
`))i.startsWith("worktree ")&&(s=i.slice(9).trim()),i===`branch refs/heads/${e}`&&s&&s.startsWith(n)&&await G(r,["worktree","remove","--force",s]);await G(r,["worktree","prune"])}catch{}try{await G(r,["branch","-D",e])}catch{}}async function
|
|
229
|
-
`).filter(Boolean),s=n.filter(c=>
|
|
230
|
-
`).map(s=>s.trim()).filter(s=>s&&!s.includes("->"))[0]??null}async function js(r,e,t=6e4){let s=(await G(r,["symbolic-ref","refs/remotes/origin/HEAD"]).catch(()=>"")).trim().replace("refs/remotes/","")||"origin/main",i=await G(r,["diff","--stat",`${s}...${e}`]),o=await G(r,["diff",`${s}...${e}`]);return{base:s,stat:i.slice(0,4e3),diff:o.slice(0,t)}}function Iu(){let r=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(de.default.existsSync(ne.default.join(gr.default.homedir(),".cache","ticketpilot"))?ne.default.join(gr.default.homedir(),".cache","ticketpilot"):ne.default.join(gr.default.homedir(),".cache","allwright"));return ne.default.join(r,"env-checkouts")}function wu(r){return r.replace(/[^\w.-]+/g,"_")}function Au(r,e){return ne.default.join(Iu(),wu(r),wu(e))}async function Qi(r){let e=Au(r.repoName,r.envName);return await G(r.repoPath,["fetch","origin",r.branch],{timeoutMs:3e5}),de.default.existsSync(ne.default.join(e,".git"))?await G(e,["fetch","origin",r.branch],{timeoutMs:3e5}):(de.default.rmSync(e,{recursive:!0,force:!0}),de.default.mkdirSync(ne.default.dirname(e),{recursive:!0,mode:448}),await G(r.repoPath,["worktree","prune"]).catch(()=>{}),await G(r.repoPath,["worktree","add","--detach",e,`origin/${r.branch}`])),r.attached?await G(e,["checkout","-B",r.branch,`origin/${r.branch}`]):await G(e,["checkout","--force","--detach",`origin/${r.branch}`]),e}async function eo(r,e,t){try{await G(r,["fetch","origin",e],{timeoutMs:3e5})}catch{return{ok:!1,reason:`branch "${e}" does not exist on origin \u2014 nothing to promote. Check the environment's ticket branch template against the branch your implement rule creates.`}}try{return await G(r,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyMerged:!0}}catch{}try{return await G(r,["-c",`user.name=${xu}`,"-c",`user.email=${Cu}`,"merge","--no-ff","-m",t,`origin/${e}`]),{ok:!0}}catch(n){return await G(r,["merge","--abort"]).catch(()=>{}),{ok:!1,reason:`could not merge "${e}" into the environment branch \u2014 ${n instanceof Error?n.message:n}. Resolve it manually and deploy again.`}}}async function to(r,e){try{await G(r,["push","origin",e],{timeoutMs:3e5})}catch(t){throw new Error(`could not push "${e}" \u2014 ${t instanceof Error?t.message:t}. Someone may have pushed to it since this deploy started; retry.`)}}async function ro(r,e,t){try{return await Tu("git",["-C",r,"diff","--quiet",e,t,"--"],{timeout:12e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),!1}catch(n){let s=n;if(s.code===1)return!0;throw new Error(`git diff failed comparing ${e}..${t}: ${(s.stderr||s.message||"").trim().slice(0,500)}`)}}async function yr(r){return(await G(r,["config","--get","remote.origin.url"])).trim()}function vr(r){let e=/^git@github\.com(?:-[\w.-]+)?:([^/]+)\/(.+?)(\.git)?$/.exec(r)??/^https:\/\/github\.com\/([^/]+)\/(.+?)(\.git)?\/?$/.exec(r)??/^ssh:\/\/git@github\.com(?:-[\w.-]+)?\/([^/]+)\/(.+?)(\.git)?$/.exec(r);return e?{owner:e[1],repo:e[2]}:null}var de,gr,ne,ku,Su,Tu,xu,Cu,Is,As,Eu,en,_r=fi(()=>{"use strict";de=P(require("node:fs"),1),gr=P(require("node:os"),1),ne=P(require("node:path"),1),ku=require("node:child_process"),Su=require("node:util"),Tu=(0,Su.promisify)(ku.execFile),xu="Allwright Agent",Cu="agent@ticketpilot.local",Is=200,As=2e4,Eu=[/^\.github\/workflows\//,/^\.git\b/,/(^|\/)\.githooks\//];en=".ticketpilot-delete"});var an={};ns(an,{GitHubClient:()=>Me});var Yp,Me,ct=fi(()=>{"use strict";Yp=process.env.TICKETPILOT_GITHUB_API??"https://api.github.com",Me=class{constructor(e){this.token=e}token;async request(e,t,n){let s=await fetch(`${Yp}${t}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"allwright",...n!==void 0?{"Content-Type":"application/json"}:{}},body:n===void 0?void 0:JSON.stringify(n)}),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) \u2014 expired or revoked? Run `allwright github set-token`");if(!s.ok&&s.status!==422){let a=o?.message??i.slice(0,300);throw new Error(`GitHub ${e} ${t} -> ${s.status}: ${a}`)}return{status:s.status,data:o}}async whoami(){let{data:e}=await this.request("GET","/user");return e.login}async createPullRequest(e,t,n){let{status:s,data:i}=await this.request("POST",`/repos/${e}/${t}/pulls`,n);if(s===422){let{data:o}=await this.request("GET",`/repos/${e}/${t}/pulls?head=${encodeURIComponent(`${e}:${n.head}`)}&state=open`);if(o?.length){let a=o[0];return{number:a.number,url:a.html_url,state:a.state,merged:a.merged??!1,headSha:a.head.sha,mergeableState:null}}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}}async getReviews(e,t,n){let{data:s}=await this.request("GET",`/repos/${e}/${t}/pulls/${n}/reviews?per_page=100`);return(s??[]).map(i=>({state:i.state??"",commitId:i.commit_id??"",user:i.user?.login??"",submittedAt:i.submitted_at??""}))}async getPullRequest(e,t,n){try{let{data:s}=await this.request("GET",`/repos/${e}/${t}/pulls/${n}`);return{number:s.number,url:s.html_url,state:s.state,merged:s.merged,headSha:s.head.sha,mergeableState:s.mergeable_state??null}}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return null;throw s}}async closePullRequest(e,t,n){await this.request("PATCH",`/repos/${e}/${t}/pulls/${n}`,{state:"closed"})}async deleteBranch(e,t,n){try{await this.request("DELETE",`/repos/${e}/${t}/git/refs/heads/${encodeURIComponent(n)}`)}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return;throw s}}}});var ft=Y((H_,hc)=>{"use strict";var cc=["nodebuffer","arraybuffer","fragments"],dc=typeof Blob<"u";dc&&cc.push("blob");hc.exports={BINARY_TYPES:cc,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:dc,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Gn=Y((W_,Ws)=>{"use strict";var{EMPTY_BUFFER:Dm}=ft(),Lo=Buffer[Symbol.species];function zm(r,e){if(r.length===0)return Dm;if(r.length===1)return r[0];let t=Buffer.allocUnsafe(e),n=0;for(let s=0;s<r.length;s++){let i=r[s];t.set(i,n),n+=i.length}return n<e?new Lo(t.buffer,t.byteOffset,n):t}function fc(r,e,t,n,s){for(let i=0;i<s;i++)t[n+i]=r[i]^e[i&3]}function pc(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function Um(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function Do(r){if(Do.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new Lo(r):ArrayBuffer.isView(r)?e=new Lo(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),Do.readOnly=!1),e}Ws.exports={concat:zm,mask:fc,toArrayBuffer:Um,toBuffer:Do,unmask:pc};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=require("bufferutil");Ws.exports.mask=function(e,t,n,s,i){i<48?fc(e,t,n,s,i):r.mask(e,t,n,s,i)},Ws.exports.unmask=function(e,t){e.length<32?pc(e,t):r.unmask(e,t)}}catch{}});var yc=Y((J_,gc)=>{"use strict";var mc=Symbol("kDone"),zo=Symbol("kRun"),Uo=class{constructor(e){this[mc]=()=>{this.pending--,this[zo]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[zo]()}[zo](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[mc])}}};gc.exports=Uo});var mn=Y((Y_,wc)=>{"use strict";var Hn=require("zlib"),vc=Gn(),qm=yc(),{kStatusCode:_c}=ft(),Bm=Buffer[Symbol.species],Fm=Buffer.from([0,0,255,255]),Ys=Symbol("permessage-deflate"),pt=Symbol("total-length"),fn=Symbol("callback"),jt=Symbol("buffers"),pn=Symbol("error"),Js,qo=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,!Js){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Js=new qm(t)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[fn];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,n=e.find(s=>!(t.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>s.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(n=>{let s=t[n];if(s.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(s=s[0],n==="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 "${n}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else if(n==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else throw new Error(`Unknown parameter "${n}"`);t[n]=s})}),e}decompress(e,t,n){Js.add(s=>{this._decompress(e,t,(i,o)=>{s(),n(i,o)})})}compress(e,t,n){Js.add(s=>{this._compress(e,t,(i,o)=>{s(),n(i,o)})})}_decompress(e,t,n){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Hn.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Hn.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Ys]=this,this._inflate[pt]=0,this._inflate[jt]=[],this._inflate.on("error",Km),this._inflate.on("data",bc)}this._inflate[fn]=n,this._inflate.write(e),t&&this._inflate.write(Fm),this._inflate.flush(()=>{let i=this._inflate[pn];if(i){this._inflate.close(),this._inflate=null,n(i);return}let o=vc.concat(this._inflate[jt],this._inflate[pt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[pt]=0,this._inflate[jt]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),n(null,o)})}_compress(e,t,n){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Hn.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Hn.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[pt]=0,this._deflate[jt]=[],this._deflate.on("data",Zm)}this._deflate[fn]=n,this._deflate.write(e),this._deflate.flush(Hn.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=vc.concat(this._deflate[jt],this._deflate[pt]);t&&(i=new Bm(i.buffer,i.byteOffset,i.length-4)),this._deflate[fn]=null,this._deflate[pt]=0,this._deflate[jt]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),n(null,i)})}};wc.exports=qo;function Zm(r){this[jt].push(r),this[pt]+=r.length}function bc(r){if(this[pt]+=r.length,this[Ys]._maxPayload<1||this[pt]<=this[Ys]._maxPayload){this[jt].push(r);return}this[pn]=new RangeError("Max payload size exceeded"),this[pn].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[pn][_c]=1009,this.removeListener("data",bc),this.reset()}function Km(r){if(this[Ys]._inflate=null,this[pn]){this[fn](this[pn]);return}r[_c]=1007,this[fn](r)}});var gn=Y((X_,Xs)=>{"use strict";var{isUtf8:kc}=require("buffer"),{hasBlob:Vm}=ft(),Gm=[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 Hm(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function Bo(r){let e=r.length,t=0;for(;t<e;)if((r[t]&128)===0)t++;else if((r[t]&224)===192){if(t+1===e||(r[t+1]&192)!==128||(r[t]&254)===192)return!1;t+=2}else if((r[t]&240)===224){if(t+2>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||r[t]===224&&(r[t+1]&224)===128||r[t]===237&&(r[t+1]&224)===160)return!1;t+=3}else if((r[t]&248)===240){if(t+3>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||(r[t+3]&192)!==128||r[t]===240&&(r[t+1]&240)===128||r[t]===244&&r[t+1]>143||r[t]>244)return!1;t+=4}else return!1;return!0}function Wm(r){return Vm&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}Xs.exports={isBlob:Wm,isValidStatusCode:Hm,isValidUTF8:Bo,tokenChars:Gm};if(kc)Xs.exports.isValidUTF8=function(r){return r.length<24?Bo(r):kc(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=require("utf-8-validate");Xs.exports.isValidUTF8=function(e){return e.length<32?Bo(e):r(e)}}catch{}});var Go=Y((Q_,Ac)=>{"use strict";var{Writable:Jm}=require("stream"),Sc=mn(),{BINARY_TYPES:Ym,EMPTY_BUFFER:Tc,kStatusCode:Xm,kWebSocket:Qm}=ft(),{concat:Fo,toArrayBuffer:eg,unmask:tg}=Gn(),{isValidStatusCode:rg,isValidUTF8:xc}=gn(),Qs=Buffer[Symbol.species],Le=0,Cc=1,Ec=2,Ic=3,Zo=4,Ko=5,ei=6,Vo=class extends Jm{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Ym[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[Qm]=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=Le}_write(e,t,n){if(this._opcode===8&&this._state==Le)return n();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){n(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(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new Qs(n.buffer,n.byteOffset+e,n.length-e),new Qs(n.buffer,n.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],s=t.length-e;e>=n.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),s),this._buffers[0]=new Qs(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case Le:this.getInfo(e);break;case Cc:this.getPayloadLength16(e);break;case Ec:this.getPayloadLength64(e);break;case Ic:this.getMask();break;case Zo:this.getData(e);break;case Ko:case ei:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((t[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let n=(t[0]&64)===64;if(n&&!this._extensions[Sc.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){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=n}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(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=Cc:this._payloadLength===127?this._state=Ec:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>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=n*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=Ic:this._state=Zo}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Zo}getData(e){let t=Tc;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&tg(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let n=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(n);return}if(this._compressed){this._state=Ko,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Sc.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return t(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(o);return}this._fragments.push(i)}this.dataMessage(t),this._state===Le&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=Le;return}let t=this._messageLength,n=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=Fo(n,t):this._binaryType==="arraybuffer"?s=eg(Fo(n,t)):this._binaryType==="blob"?s=new Blob(n):s=n,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=Le):(this._state=ei,setImmediate(()=>{this.emit("message",s,!0),this._state=Le,this.startLoop(e)}))}else{let s=Fo(n,t);if(!this._skipUTF8Validation&&!xc(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Ko||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=Le):(this._state=ei,setImmediate(()=>{this.emit("message",s,!1),this._state=Le,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Tc),this.end();else{let n=e.readUInt16BE(0);if(!rg(n)){let i=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new Qs(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!xc(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(i);return}this._loop=!1,this.emit("conclude",n,s),this.end()}this._state=Le;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Le):(this._state=ei,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Le,this.startLoop(t)}))}createError(e,t,n,s,i){this._loop=!1,this._errored=!0;let o=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[Xm]=s,o}};Ac.exports=Vo});var Jo=Y((tb,Pc)=>{"use strict";var{Duplex:eb}=require("stream"),{randomFillSync:ng}=require("crypto"),{types:{isUint8Array:sg}}=require("util"),Rc=mn(),{EMPTY_BUFFER:ig,kWebSocket:og,NOOP:ag}=ft(),{isBlob:yn,isValidStatusCode:ug}=gn(),{mask:$c,toBuffer:Ir}=Gn(),De=Symbol("kByteLength"),lg=Buffer.alloc(4),ti=8*1024,Ar,vn=ti,Fe=0,cg=1,dg=2,Ho=class r{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Fe,this.onerror=ag,this[og]=void 0}static frame(e,t){let n,s=!1,i=2,o=!1;t.mask&&(n=t.maskBuffer||lg,t.generateMask?t.generateMask(n):(vn===ti&&(Ar===void 0&&(Ar=Buffer.alloc(ti)),ng(Ar,0,ti),vn=0),n[0]=Ar[vn++],n[1]=Ar[vn++],n[2]=Ar[vn++],n[3]=Ar[vn++]),o=(n[0]|n[1]|n[2]|n[3])===0,i=6);let a;typeof e=="string"?(!t.mask||o)&&t[De]!==void 0?a=t[De]:(e=Buffer.from(e),a=e.length):(a=e.length,s=t.mask&&t.readOnly&&!o);let l=a;a>=65536?(i+=8,l=127):a>125&&(i+=2,l=126);let c=Buffer.allocUnsafe(s?a+i:i);return c[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(c[0]|=64),c[1]=l,l===126?c.writeUInt16BE(a,2):l===127&&(c[2]=c[3]=0,c.writeUIntBE(a,4,6)),t.mask?(c[1]|=128,c[i-4]=n[0],c[i-3]=n[1],c[i-2]=n[2],c[i-1]=n[3],o?[c,e]:s?($c(e,n,c,i,a),[c]):($c(e,n,e,0,a),[c,e])):[c,e]}close(e,t,n,s){let i;if(e===void 0)i=ig;else{if(typeof e!="number"||!ug(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(t);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");if(i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof t=="string")i.write(t,2);else if(sg(t))i.set(t,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[De]:i.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Fe?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(r.frame(i,o),s)}ping(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):yn(e)?(s=e.size,i=!1):(e=Ir(e),s=e.length,i=Ir.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[De]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};yn(e)?this._state!==Fe?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==Fe?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(r.frame(e,o),n)}pong(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):yn(e)?(s=e.size,i=!1):(e=Ir(e),s=e.length,i=Ir.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[De]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};yn(e)?this._state!==Fe?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==Fe?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(r.frame(e,o),n)}send(e,t,n){let s=this._extensions[Rc.extensionName],i=t.binary?2:1,o=t.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):yn(e)?(a=e.size,l=!1):(e=Ir(e),a=e.length,l=Ir.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=s._threshold),this._compress=o):(o=!1,i=0),t.fin&&(this._firstFragment=!0);let c={[De]:a,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:l,rsv1:o};yn(e)?this._state!==Fe?this.enqueue([this.getBlobData,e,this._compress,c,n]):this.getBlobData(e,this._compress,c,n):this._state!==Fe?this.enqueue([this.dispatch,e,this._compress,c,n]):this.dispatch(e,this._compress,c,n)}getBlobData(e,t,n,s){this._bufferedBytes+=n[De],this._state=dg,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Wo,this,a,s);return}this._bufferedBytes-=n[De];let o=Ir(i);t?this.dispatch(o,t,n,s):(this._state=Fe,this.sendFrame(r.frame(o,n),s),this.dequeue())}).catch(i=>{process.nextTick(hg,this,i,s)})}dispatch(e,t,n,s){if(!t){this.sendFrame(r.frame(e,n),s);return}let i=this._extensions[Rc.extensionName];this._bufferedBytes+=n[De],this._state=cg,i.compress(e,n.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");Wo(this,l,s);return}this._bufferedBytes-=n[De],this._state=Fe,n.readOnly=!1,this.sendFrame(r.frame(a,n),s),this.dequeue()})}dequeue(){for(;this._state===Fe&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][De],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][De],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};Pc.exports=Ho;function Wo(r,e,t){typeof t=="function"&&t(e);for(let n=0;n<r._queue.length;n++){let s=r._queue[n],i=s[s.length-1];typeof i=="function"&&i(e)}}function hg(r,e,t){Wo(r,e,t),r.onerror(e)}});var qc=Y((rb,Uc)=>{"use strict";var{kForOnEventAttribute:Wn,kListener:Yo}=ft(),jc=Symbol("kCode"),Oc=Symbol("kData"),Nc=Symbol("kError"),Mc=Symbol("kMessage"),Lc=Symbol("kReason"),_n=Symbol("kTarget"),Dc=Symbol("kType"),zc=Symbol("kWasClean"),mt=class{constructor(e){this[_n]=null,this[Dc]=e}get target(){return this[_n]}get type(){return this[Dc]}};Object.defineProperty(mt.prototype,"target",{enumerable:!0});Object.defineProperty(mt.prototype,"type",{enumerable:!0});var Rr=class extends mt{constructor(e,t={}){super(e),this[jc]=t.code===void 0?0:t.code,this[Lc]=t.reason===void 0?"":t.reason,this[zc]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[jc]}get reason(){return this[Lc]}get wasClean(){return this[zc]}};Object.defineProperty(Rr.prototype,"code",{enumerable:!0});Object.defineProperty(Rr.prototype,"reason",{enumerable:!0});Object.defineProperty(Rr.prototype,"wasClean",{enumerable:!0});var bn=class extends mt{constructor(e,t={}){super(e),this[Nc]=t.error===void 0?null:t.error,this[Mc]=t.message===void 0?"":t.message}get error(){return this[Nc]}get message(){return this[Mc]}};Object.defineProperty(bn.prototype,"error",{enumerable:!0});Object.defineProperty(bn.prototype,"message",{enumerable:!0});var Jn=class extends mt{constructor(e,t={}){super(e),this[Oc]=t.data===void 0?null:t.data}get data(){return this[Oc]}};Object.defineProperty(Jn.prototype,"data",{enumerable:!0});var fg={addEventListener(r,e,t={}){for(let s of this.listeners(r))if(!t[Wn]&&s[Yo]===e&&!s[Wn])return;let n;if(r==="message")n=function(i,o){let a=new Jn("message",{data:o?i:i.toString()});a[_n]=this,ri(e,this,a)};else if(r==="close")n=function(i,o){let a=new Rr("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[_n]=this,ri(e,this,a)};else if(r==="error")n=function(i){let o=new bn("error",{error:i,message:i.message});o[_n]=this,ri(e,this,o)};else if(r==="open")n=function(){let i=new mt("open");i[_n]=this,ri(e,this,i)};else return;n[Wn]=!!t[Wn],n[Yo]=e,t.once?this.once(r,n):this.on(r,n)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[Yo]===e&&!t[Wn]){this.removeListener(r,t);break}}};Uc.exports={CloseEvent:Rr,ErrorEvent:bn,Event:mt,EventTarget:fg,MessageEvent:Jn};function ri(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var ni=Y((nb,Bc)=>{"use strict";var{tokenChars:Yn}=gn();function Qe(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function pg(r){let e=Object.create(null),t=Object.create(null),n=!1,s=!1,i=!1,o,a,l=-1,c=-1,d=-1,p=0;for(;p<r.length;p++)if(c=r.charCodeAt(p),o===void 0)if(d===-1&&Yn[c]===1)l===-1&&(l=p);else if(p!==0&&(c===32||c===9))d===-1&&l!==-1&&(d=p);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1&&(d=p);let S=r.slice(l,d);c===44?(Qe(e,S,t),t=Object.create(null)):o=S,l=d=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(a===void 0)if(d===-1&&Yn[c]===1)l===-1&&(l=p);else if(c===32||c===9)d===-1&&l!==-1&&(d=p);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1&&(d=p),Qe(t,r.slice(l,d),!0),c===44&&(Qe(e,o,t),t=Object.create(null),o=void 0),l=d=-1}else if(c===61&&l!==-1&&d===-1)a=r.slice(l,p),l=d=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(s){if(Yn[c]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);l===-1?l=p:n||(n=!0),s=!1}else if(i)if(Yn[c]===1)l===-1&&(l=p);else if(c===34&&l!==-1)i=!1,d=p;else if(c===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(c===34&&r.charCodeAt(p-1)===61)i=!0;else if(d===-1&&Yn[c]===1)l===-1&&(l=p);else if(l!==-1&&(c===32||c===9))d===-1&&(d=p);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1&&(d=p);let S=r.slice(l,d);n&&(S=S.replace(/\\/g,""),n=!1),Qe(t,a,S),c===44&&(Qe(e,o,t),t=Object.create(null),o=void 0),a=void 0,l=d=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(l===-1||i||c===32||c===9)throw new SyntaxError("Unexpected end of input");d===-1&&(d=p);let _=r.slice(l,d);return o===void 0?Qe(e,_,t):(a===void 0?Qe(t,_,!0):n?Qe(t,a,_.replace(/\\/g,"")):Qe(t,a,_),Qe(e,o,t)),e}function mg(r){return Object.keys(r).map(e=>{let t=r[e];return Array.isArray(t)||(t=[t]),t.map(n=>[e].concat(Object.keys(n).map(s=>{let i=n[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Bc.exports={format:mg,parse:pg}});var ai=Y((ob,ed)=>{"use strict";var gg=require("events"),yg=require("https"),vg=require("http"),Kc=require("net"),_g=require("tls"),{randomBytes:bg,createHash:wg}=require("crypto"),{Duplex:sb,Readable:ib}=require("stream"),{URL:Xo}=require("url"),Ot=mn(),kg=Go(),Sg=Jo(),{isBlob:Tg}=gn(),{BINARY_TYPES:Fc,CLOSE_TIMEOUT:xg,EMPTY_BUFFER:si,GUID:Cg,kForOnEventAttribute:Qo,kListener:Eg,kStatusCode:Ig,kWebSocket:ae,NOOP:Vc}=ft(),{EventTarget:{addEventListener:Ag,removeEventListener:Rg}}=qc(),{format:$g,parse:Pg}=ni(),{toBuffer:jg}=Gn(),Gc=Symbol("kAborted"),ea=[8,13],gt=["CONNECTING","OPEN","CLOSING","CLOSED"],Og=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,se=class r extends gg{constructor(e,t,n){super(),this._binaryType=Fc[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=si,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=r.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(n=t,t=[]):t=[t]),Hc(this,e,t,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Fc.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,n){let s=new kg({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:n.maxBufferedChunks,maxFragments:n.maxFragments,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),i=new Sg(e,this._extensions,n.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[ae]=this,i[ae]=this,e[ae]=this,s.on("conclude",Lg),s.on("drain",Dg),s.on("error",zg),s.on("message",Ug),s.on("ping",qg),s.on("pong",Bg),i.onerror=Fg,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Yc),e.on("data",oi),e.on("end",Xc),e.on("error",Qc),this._readyState=r.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Ot.extensionName]&&this._extensions[Ot.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){Ee(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===r.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=r.CLOSING,this._sender.close(e,t,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Jc(this)}}pause(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){ta(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||si,t,n)}pong(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){ta(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||si,t,n)}resume(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(n=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){ta(this,e,n);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Ot.extensionName]||(s.compress=!1),this._sender.send(e||si,s,n)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){Ee(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(se,"CONNECTING",{enumerable:!0,value:gt.indexOf("CONNECTING")});Object.defineProperty(se.prototype,"CONNECTING",{enumerable:!0,value:gt.indexOf("CONNECTING")});Object.defineProperty(se,"OPEN",{enumerable:!0,value:gt.indexOf("OPEN")});Object.defineProperty(se.prototype,"OPEN",{enumerable:!0,value:gt.indexOf("OPEN")});Object.defineProperty(se,"CLOSING",{enumerable:!0,value:gt.indexOf("CLOSING")});Object.defineProperty(se.prototype,"CLOSING",{enumerable:!0,value:gt.indexOf("CLOSING")});Object.defineProperty(se,"CLOSED",{enumerable:!0,value:gt.indexOf("CLOSED")});Object.defineProperty(se.prototype,"CLOSED",{enumerable:!0,value:gt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(se.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(se.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[Qo])return e[Eg];return null},set(e){for(let t of this.listeners(r))if(t[Qo]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[Qo]:!0})}})});se.prototype.addEventListener=Ag;se.prototype.removeEventListener=Rg;ed.exports=se;function Hc(r,e,t,n){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:xg,protocolVersion:ea[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(r._autoPong=s.autoPong,r._closeTimeout=s.closeTimeout,!ea.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${ea.join(", ")})`);let i;if(e instanceof Xo)i=e;else try{i=new Xo(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),r._url=i.href;let o=i.protocol==="wss:",a=i.protocol==="ws+unix:",l;if(i.protocol!=="ws:"&&!o&&!a?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?l="The URL's pathname is empty":i.hash&&(l="The URL contains a fragment identifier"),l){let C=new SyntaxError(l);if(r._redirects===0)throw C;ii(r,C);return}let c=o?443:80,d=bg(16).toString("base64"),p=o?yg.request:vg.request,_=new Set,S;if(s.createConnection=s.createConnection||(o?Mg:Ng),s.defaultPort=s.defaultPort||c,s.port=i.port||c,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(S=new Ot({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=$g({[Ot.extensionName]:S.offer()})),t.length){for(let C of t){if(typeof C!="string"||!Og.test(C)||_.has(C))throw new SyntaxError("An invalid or duplicated subprotocol was specified");_.add(C)}s.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){let C=s.path.split(":");s.socketPath=C[0],s.path=C[1]}let T;if(s.followRedirects){if(r._redirects===0){r._originalIpc=a,r._originalSecure=o,r._originalHostOrSocketPath=a?s.socketPath:i.host;let C=n&&n.headers;if(n={...n,headers:{}},C)for(let[k,B]of Object.entries(C))n.headers[k.toLowerCase()]=B}else if(r.listenerCount("redirect")===0){let C=a?r._originalIpc?s.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:i.host===r._originalHostOrSocketPath;(!C||r._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,C||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),T=r._req=p(s),r._redirects&&r.emit("redirect",r.url,T)}else T=r._req=p(s);s.timeout&&T.on("timeout",()=>{Ee(r,T,"Opening handshake has timed out")}),T.on("error",C=>{T===null||T[Gc]||(T=r._req=null,ii(r,C))}),T.on("response",C=>{let k=C.headers.location,B=C.statusCode;if(k&&s.followRedirects&&B>=300&&B<400){if(++r._redirects>s.maxRedirects){Ee(r,T,"Maximum redirects exceeded");return}T.abort();let q;try{q=new Xo(k,e)}catch{let m=new SyntaxError(`Invalid URL: ${k}`);ii(r,m);return}Hc(r,q,t,n)}else r.emit("unexpected-response",T,C)||Ee(r,T,`Unexpected server response: ${C.statusCode}`)}),T.on("upgrade",(C,k,B)=>{if(r.emit("upgrade",C),r.readyState!==se.CONNECTING)return;T=r._req=null;let q=C.headers.upgrade;if(q===void 0||q.toLowerCase()!=="websocket"){Ee(r,k,"Invalid Upgrade header");return}let f=wg("sha1").update(d+Cg).digest("base64");if(C.headers["sec-websocket-accept"]!==f){Ee(r,k,"Invalid Sec-WebSocket-Accept header");return}let m=C.headers["sec-websocket-protocol"],b;if(m!==void 0?_.size?_.has(m)||(b="Server sent an invalid subprotocol"):b="Server sent a subprotocol but none was requested":_.size&&(b="Server sent no subprotocol"),b){Ee(r,k,b);return}m&&(r._protocol=m);let A=C.headers["sec-websocket-extensions"];if(A!==void 0){if(!S){Ee(r,k,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let N;try{N=Pg(A)}catch{Ee(r,k,"Invalid Sec-WebSocket-Extensions header");return}let F=Object.keys(N);if(F.length!==1||F[0]!==Ot.extensionName){Ee(r,k,"Server indicated an extension that was not requested");return}try{S.accept(N[Ot.extensionName])}catch{Ee(r,k,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[Ot.extensionName]=S}r.setSocket(k,B,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(T,r):T.end()}function ii(r,e){r._readyState=se.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function Ng(r){return r.path=r.socketPath,Kc.connect(r)}function Mg(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=Kc.isIP(r.host)?"":r.host),_g.connect(r)}function Ee(r,e,t){r._readyState=se.CLOSING;let n=new Error(t);Error.captureStackTrace(n,Ee),e.setHeader?(e[Gc]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ii,r,n)):(e.destroy(n),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function ta(r,e,t){if(e){let n=Tg(e)?e.size:jg(e).length;r._socket?r._sender._bufferedBytes+=n:r._bufferedAmount+=n}if(t){let n=new Error(`WebSocket is not open: readyState ${r.readyState} (${gt[r.readyState]})`);process.nextTick(t,n)}}function Lg(r,e){let t=this[ae];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[ae]!==void 0&&(t._socket.removeListener("data",oi),process.nextTick(Wc,t._socket),r===1005?t.close():t.close(r,e))}function Dg(){let r=this[ae];r.isPaused||r._socket.resume()}function zg(r){let e=this[ae];e._socket[ae]!==void 0&&(e._socket.removeListener("data",oi),process.nextTick(Wc,e._socket),e.close(r[Ig])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function Zc(){this[ae].emitClose()}function Ug(r,e){this[ae].emit("message",r,e)}function qg(r){let e=this[ae];e._autoPong&&e.pong(r,!this._isServer,Vc),e.emit("ping",r)}function Bg(r){this[ae].emit("pong",r)}function Wc(r){r.resume()}function Fg(r){let e=this[ae];e.readyState!==se.CLOSED&&(e.readyState===se.OPEN&&(e._readyState=se.CLOSING,Jc(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function Jc(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),r._closeTimeout)}function Yc(){let r=this[ae];if(this.removeListener("close",Yc),this.removeListener("data",oi),this.removeListener("end",Xc),r._readyState=se.CLOSING,!this._readableState.endEmitted&&!r._closeFrameReceived&&!r._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);r._receiver.write(e)}r._receiver.end(),this[ae]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",Zc),r._receiver.on("finish",Zc))}function oi(r){this[ae]._receiver.write(r)||this.pause()}function Xc(){let r=this[ae];r._readyState=se.CLOSING,r._receiver.end(),this.end()}function Qc(){let r=this[ae];this.removeListener("error",Qc),this.on("error",Vc),r&&(r._readyState=se.CLOSING,this.destroy())}});var sd=Y((ub,nd)=>{"use strict";var ab=ai(),{Duplex:Zg}=require("stream");function td(r){r.emit("close")}function Kg(){!this.destroyed&&this._writableState.finished&&this.destroy()}function rd(r){this.removeListener("error",rd),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function Vg(r,e){let t=!0,n=new Zg({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(i,o){let a=!o&&n._readableState.objectMode?i.toString():i;n.push(a)||r.pause()}),r.once("error",function(i){n.destroyed||(t=!1,n.destroy(i))}),r.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(s,i){if(r.readyState===r.CLOSED){i(s),process.nextTick(td,n);return}let o=!1;r.once("error",function(l){o=!0,i(l)}),r.once("close",function(){o||i(s),process.nextTick(td,n)}),t&&r.terminate()},n._final=function(s){if(r.readyState===r.CONNECTING){r.once("open",function(){n._final(s)});return}r._socket!==null&&(r._socket._writableState.finished?(s(),n._readableState.endEmitted&&n.destroy()):(r._socket.once("finish",function(){s()}),r.close()))},n._read=function(){r.isPaused&&r.resume()},n._write=function(s,i,o){if(r.readyState===r.CONNECTING){r.once("open",function(){n._write(s,i,o)});return}r.send(s,o)},n.on("end",Kg),n.on("error",rd),n}nd.exports=Vg});var ra=Y((lb,id)=>{"use strict";var{tokenChars:Gg}=gn();function Hg(r){let e=new Set,t=-1,n=-1,s=0;for(s;s<r.length;s++){let o=r.charCodeAt(s);if(n===-1&&Gg[o]===1)t===-1&&(t=s);else if(s!==0&&(o===32||o===9))n===-1&&t!==-1&&(n=s);else if(o===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${s}`);n===-1&&(n=s);let a=r.slice(t,n);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),t=n=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(t===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let i=r.slice(t,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}id.exports={parse:Hg}});var hd=Y((db,dd)=>{"use strict";var Wg=require("events"),ui=require("http"),{Duplex:cb}=require("stream"),{createHash:Jg}=require("crypto"),od=ni(),$r=mn(),Yg=ra(),Xg=ai(),{CLOSE_TIMEOUT:Qg,GUID:ey,kWebSocket:ty}=ft(),ry=/^[+/0-9A-Za-z]{22}==$/,ad=0,ud=1,cd=2,na=class extends Wg{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Qg,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Xg,...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=ui.createServer((n,s)=>{let i=ui.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=ny(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=ad}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===cd){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Xn,this);return}if(e&&this.once("close",e),this._state!==ud)if(this._state=ud,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(Xn,this):process.nextTick(Xn,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{Xn(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,s){t.on("error",ld);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Pr(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Pr(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!ry.test(i)){Pr(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Pr(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Qn(t,400);return}let l=e.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=Yg.parse(l)}catch{Pr(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let d=e.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&d!==void 0){let _=new $r({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let S=od.parse(d);S[$r.extensionName]&&(_.accept(S[$r.extensionName]),p[$r.extensionName]=_)}catch{Pr(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let _={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(_,(S,T,C,k)=>{if(!S)return Qn(t,T||401,C,k);this.completeUpgrade(p,i,c,e,t,n,s)});return}if(!this.options.verifyClient(_))return Qn(t,401)}this.completeUpgrade(p,i,c,e,t,n,s)}completeUpgrade(e,t,n,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[ty])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>ad)return Qn(i,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Jg("sha1").update(t+ey).digest("base64")}`],d=new this.options.WebSocket(null,void 0,this.options);if(n.size){let p=this.options.handleProtocols?this.options.handleProtocols(n,s):n.values().next().value;p&&(c.push(`Sec-WebSocket-Protocol: ${p}`),d._protocol=p)}if(e[$r.extensionName]){let p=e[$r.extensionName].params,_=od.format({[$r.extensionName]:[p]});c.push(`Sec-WebSocket-Extensions: ${_}`),d._extensions=e}this.emit("headers",c,s),i.write(c.concat(`\r
|
|
227
|
+
${i}${o}`:"clean"}`}function Mn(){let r=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(de.default.existsSync(ne.default.join(gr.default.homedir(),".cache","ticketpilot"))?ne.default.join(gr.default.homedir(),".cache","ticketpilot"):ne.default.join(gr.default.homedir(),".cache","allwright"));return ne.default.join(r,"worktrees")}async function tn(r,e){try{await G(r,["fetch","origin",e])}catch(t){throw new Error(`could not fetch base branch "${e}" from origin - check the rule's base branch and that this machine can reach the remote (${t instanceof Error?t.message:t})`)}}async function Yi(r,e){try{let t=await G(r,["worktree","list","--porcelain"]),n=Mn(),s=null;for(let i of t.split(`
|
|
228
|
+
`))i.startsWith("worktree ")&&(s=i.slice(9).trim()),i===`branch refs/heads/${e}`&&s&&s.startsWith(n)&&await G(r,["worktree","remove","--force",s]);await G(r,["worktree","prune"])}catch{}try{await G(r,["branch","-D",e])}catch{}}async function Xi(r,e,t,n){de.default.mkdirSync(ne.default.dirname(e),{recursive:!0,mode:448}),await G(r,["worktree","add","-b",t,e,`origin/${n}`])}async function Ps(r,e){if(await G(r,["add","-A"]),!(await G(r,["status","--porcelain"])).trim())throw new Error("Claude wrote no changes - nothing to commit");await G(r,["-c",`user.name=${Eu}`,"-c",`user.email=${Iu}`,"commit","-m",e])}async function Qi(r,e){let n=(await G(r,["diff","--name-only",`origin/${e}...HEAD`])).split(`
|
|
229
|
+
`).filter(Boolean),s=n.filter(c=>Au.some(h=>h.test(c))),i=await G(r,["diff","--shortstat",`origin/${e}...HEAD`]),o=Number(/(\d+) insertion/.exec(i)?.[1]??0),a=Number(/(\d+) deletion/.exec(i)?.[1]??0);return{ok:s.length===0&&n.length<=As&&o+a<=Rs,files:n.length,insertions:o,deletions:a,forbidden:s}}async function eo(r,e){await G(r,["fetch","--prune","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],{timeoutMs:12e4}).catch(()=>G(r,["update-ref","-d",`refs/remotes/origin/${e}`]).catch(()=>{})),await G(r,["push","--force-with-lease","-u","origin",e],{timeoutMs:3e5})}async function zn(r){return(await G(r,["rev-parse","HEAD"])).trim()}async function js(r,e){try{return(await G(r,["rev-parse","--verify",`refs/heads/${e}`])).trim()}catch{return null}}async function rn(r,e){try{await G(r,["worktree","remove","--force",e])}catch{de.default.rmSync(e,{recursive:!0,force:!0})}}async function to(r,e=[]){let t=new Set(e.map(s=>ne.default.basename(ne.default.resolve(s))).filter(s=>s.length>0)),n=Mn();if(de.default.existsSync(n))for(let s of de.default.readdirSync(n))t.has(s)||de.default.rmSync(ne.default.join(n,s),{recursive:!0,force:!0});for(let s of r)try{await G(s,["worktree","prune"])}catch{}}async function ro(r,e){return await G(r,["fetch","origin","--prune"]).catch(()=>{}),(await G(r,["branch","-r","--list",`*${e}*`])).split(`
|
|
230
|
+
`).map(s=>s.trim()).filter(s=>s&&!s.includes("->"))[0]??null}async function Os(r,e,t=6e4){let s=(await G(r,["symbolic-ref","refs/remotes/origin/HEAD"]).catch(()=>"")).trim().replace("refs/remotes/","")||"origin/main",i=await G(r,["diff","--stat",`${s}...${e}`]),o=await G(r,["diff",`${s}...${e}`]);return{base:s,stat:i.slice(0,4e3),diff:o.slice(0,t)}}function Ru(){let r=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(de.default.existsSync(ne.default.join(gr.default.homedir(),".cache","ticketpilot"))?ne.default.join(gr.default.homedir(),".cache","ticketpilot"):ne.default.join(gr.default.homedir(),".cache","allwright"));return ne.default.join(r,"env-checkouts")}function Su(r){return r.replace(/[^\w.-]+/g,"_")}function $u(r,e){return ne.default.join(Ru(),Su(r),Su(e))}async function no(r){let e=$u(r.repoName,r.envName);return await G(r.repoPath,["fetch","origin",r.branch],{timeoutMs:3e5}),de.default.existsSync(ne.default.join(e,".git"))?await G(e,["fetch","origin",r.branch],{timeoutMs:3e5}):(de.default.rmSync(e,{recursive:!0,force:!0}),de.default.mkdirSync(ne.default.dirname(e),{recursive:!0,mode:448}),await G(r.repoPath,["worktree","prune"]).catch(()=>{}),await G(r.repoPath,["worktree","add","--detach",e,`origin/${r.branch}`])),r.attached?await G(e,["checkout","-B",r.branch,`origin/${r.branch}`]):await G(e,["checkout","--force","--detach",`origin/${r.branch}`]),e}async function so(r,e,t){try{await G(r,["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 G(r,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyMerged:!0}}catch{}try{return await G(r,["-c",`user.name=${Eu}`,"-c",`user.email=${Iu}`,"merge","--no-ff","-m",t,`origin/${e}`]),{ok:!0}}catch(n){return await G(r,["merge","--abort"]).catch(()=>{}),{ok:!1,reason:`could not merge "${e}" into the environment branch - ${n instanceof Error?n.message:n}. Resolve it manually and deploy again.`}}}async function io(r,e){try{await G(r,["push","origin",e],{timeoutMs:3e5})}catch(t){throw new Error(`could not push "${e}" - ${t instanceof Error?t.message:t}. Someone may have pushed to it since this deploy started; retry.`)}}async function oo(r,e,t){try{return await Cu("git",["-C",r,"diff","--quiet",e,t,"--"],{timeout:12e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),!1}catch(n){let s=n;if(s.code===1)return!0;throw new Error(`git diff failed comparing ${e}..${t}: ${(s.stderr||s.message||"").trim().slice(0,500)}`)}}async function yr(r){return(await G(r,["config","--get","remote.origin.url"])).trim()}function vr(r){let e=/^git@github\.com(?:-[\w.-]+)?:([^/]+)\/(.+?)(\.git)?$/.exec(r)??/^https:\/\/github\.com\/([^/]+)\/(.+?)(\.git)?\/?$/.exec(r)??/^ssh:\/\/git@github\.com(?:-[\w.-]+)?\/([^/]+)\/(.+?)(\.git)?$/.exec(r);return e?{owner:e[1],repo:e[2]}:null}var de,gr,ne,xu,Tu,Cu,Eu,Iu,As,Rs,Au,en,_r=yi(()=>{"use strict";de=$(require("node:fs"),1),gr=$(require("node:os"),1),ne=$(require("node:path"),1),xu=require("node:child_process"),Tu=require("node:util"),Cu=(0,Tu.promisify)(xu.execFile),Eu="Allwright Agent",Iu="agent@ticketpilot.local",As=200,Rs=2e4,Au=[/^\.github\/workflows\//,/^\.git\b/,/(^|\/)\.githooks\//];en=".ticketpilot-delete"});var un={};ss(un,{GitHubClient:()=>Me});var rm,Me,ct=yi(()=>{"use strict";rm=process.env.TICKETPILOT_GITHUB_API??"https://api.github.com",Me=class{constructor(e){this.token=e}token;async request(e,t,n){let s=await fetch(`${rm}${t}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"allwright",...n!==void 0?{"Content-Type":"application/json"}:{}},body:n===void 0?void 0:JSON.stringify(n)}),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 a=o?.message??i.slice(0,300);throw new Error(`GitHub ${e} ${t} -> ${s.status}: ${a}`)}return{status:s.status,data:o}}async whoami(){let{data:e}=await this.request("GET","/user");return e.login}async createPullRequest(e,t,n){let{status:s,data:i}=await this.request("POST",`/repos/${e}/${t}/pulls`,n);if(s===422){let{data:o}=await this.request("GET",`/repos/${e}/${t}/pulls?head=${encodeURIComponent(`${e}:${n.head}`)}&state=open`);if(o?.length){let a=o[0];return{number:a.number,url:a.html_url,state:a.state,merged:a.merged??!1,headSha:a.head.sha,mergeableState:null}}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}}async getReviews(e,t,n){let{data:s}=await this.request("GET",`/repos/${e}/${t}/pulls/${n}/reviews?per_page=100`);return(s??[]).map(i=>({state:i.state??"",commitId:i.commit_id??"",user:i.user?.login??"",submittedAt:i.submitted_at??""}))}async getPullRequest(e,t,n){try{let{data:s}=await this.request("GET",`/repos/${e}/${t}/pulls/${n}`);return{number:s.number,url:s.html_url,state:s.state,merged:s.merged,headSha:s.head.sha,mergeableState:s.mergeable_state??null}}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return null;throw s}}async closePullRequest(e,t,n){await this.request("PATCH",`/repos/${e}/${t}/pulls/${n}`,{state:"closed"})}async deleteBranch(e,t,n){try{await this.request("DELETE",`/repos/${e}/${t}/git/refs/heads/${encodeURIComponent(n)}`)}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return;throw s}}}});var ft=Y((Q_,gc)=>{"use strict";var pc=["nodebuffer","arraybuffer","fragments"],mc=typeof Blob<"u";mc&&pc.push("blob");gc.exports={BINARY_TYPES:pc,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:mc,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Gn=Y((eb,Qs)=>{"use strict";var{EMPTY_BUFFER:Bm}=ft(),Uo=Buffer[Symbol.species];function Zm(r,e){if(r.length===0)return Bm;if(r.length===1)return r[0];let t=Buffer.allocUnsafe(e),n=0;for(let s=0;s<r.length;s++){let i=r[s];t.set(i,n),n+=i.length}return n<e?new Uo(t.buffer,t.byteOffset,n):t}function yc(r,e,t,n,s){for(let i=0;i<s;i++)t[n+i]=r[i]^e[i&3]}function vc(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function Km(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function qo(r){if(qo.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new Uo(r):ArrayBuffer.isView(r)?e=new Uo(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),qo.readOnly=!1),e}Qs.exports={concat:Zm,mask:yc,toArrayBuffer:Km,toBuffer:qo,unmask:vc};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=require("bufferutil");Qs.exports.mask=function(e,t,n,s,i){i<48?yc(e,t,n,s,i):r.mask(e,t,n,s,i)},Qs.exports.unmask=function(e,t){e.length<32?vc(e,t):r.unmask(e,t)}}catch{}});var wc=Y((tb,bc)=>{"use strict";var _c=Symbol("kDone"),Fo=Symbol("kRun"),Bo=class{constructor(e){this[_c]=()=>{this.pending--,this[Fo]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Fo]()}[Fo](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[_c])}}};bc.exports=Bo});var gn=Y((rb,Tc)=>{"use strict";var Hn=require("zlib"),kc=Gn(),Vm=wc(),{kStatusCode:Sc}=ft(),Gm=Buffer[Symbol.species],Hm=Buffer.from([0,0,255,255]),ti=Symbol("permessage-deflate"),pt=Symbol("total-length"),pn=Symbol("callback"),jt=Symbol("buffers"),mn=Symbol("error"),ei,Zo=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,!ei){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;ei=new Vm(t)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[pn];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,n=e.find(s=>!(t.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>s.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(n=>{let s=t[n];if(s.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(s=s[0],n==="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 "${n}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else if(n==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else throw new Error(`Unknown parameter "${n}"`);t[n]=s})}),e}decompress(e,t,n){ei.add(s=>{this._decompress(e,t,(i,o)=>{s(),n(i,o)})})}compress(e,t,n){ei.add(s=>{this._compress(e,t,(i,o)=>{s(),n(i,o)})})}_decompress(e,t,n){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Hn.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Hn.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[ti]=this,this._inflate[pt]=0,this._inflate[jt]=[],this._inflate.on("error",Jm),this._inflate.on("data",xc)}this._inflate[pn]=n,this._inflate.write(e),t&&this._inflate.write(Hm),this._inflate.flush(()=>{let i=this._inflate[mn];if(i){this._inflate.close(),this._inflate=null,n(i);return}let o=kc.concat(this._inflate[jt],this._inflate[pt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[pt]=0,this._inflate[jt]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),n(null,o)})}_compress(e,t,n){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Hn.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Hn.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[pt]=0,this._deflate[jt]=[],this._deflate.on("data",Wm)}this._deflate[pn]=n,this._deflate.write(e),this._deflate.flush(Hn.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=kc.concat(this._deflate[jt],this._deflate[pt]);t&&(i=new Gm(i.buffer,i.byteOffset,i.length-4)),this._deflate[pn]=null,this._deflate[pt]=0,this._deflate[jt]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),n(null,i)})}};Tc.exports=Zo;function Wm(r){this[jt].push(r),this[pt]+=r.length}function xc(r){if(this[pt]+=r.length,this[ti]._maxPayload<1||this[pt]<=this[ti]._maxPayload){this[jt].push(r);return}this[mn]=new RangeError("Max payload size exceeded"),this[mn].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[mn][Sc]=1009,this.removeListener("data",xc),this.reset()}function Jm(r){if(this[ti]._inflate=null,this[mn]){this[pn](this[mn]);return}r[Sc]=1007,this[pn](r)}});var yn=Y((nb,ri)=>{"use strict";var{isUtf8:Cc}=require("buffer"),{hasBlob:Ym}=ft(),Xm=[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 Qm(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function Ko(r){let e=r.length,t=0;for(;t<e;)if((r[t]&128)===0)t++;else if((r[t]&224)===192){if(t+1===e||(r[t+1]&192)!==128||(r[t]&254)===192)return!1;t+=2}else if((r[t]&240)===224){if(t+2>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||r[t]===224&&(r[t+1]&224)===128||r[t]===237&&(r[t+1]&224)===160)return!1;t+=3}else if((r[t]&248)===240){if(t+3>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||(r[t+3]&192)!==128||r[t]===240&&(r[t+1]&240)===128||r[t]===244&&r[t+1]>143||r[t]>244)return!1;t+=4}else return!1;return!0}function eg(r){return Ym&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}ri.exports={isBlob:eg,isValidStatusCode:Qm,isValidUTF8:Ko,tokenChars:Xm};if(Cc)ri.exports.isValidUTF8=function(r){return r.length<24?Ko(r):Cc(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=require("utf-8-validate");ri.exports.isValidUTF8=function(e){return e.length<32?Ko(e):r(e)}}catch{}});var Jo=Y((sb,jc)=>{"use strict";var{Writable:tg}=require("stream"),Ec=gn(),{BINARY_TYPES:rg,EMPTY_BUFFER:Ic,kStatusCode:ng,kWebSocket:sg}=ft(),{concat:Vo,toArrayBuffer:ig,unmask:og}=Gn(),{isValidStatusCode:ag,isValidUTF8:Ac}=yn(),ni=Buffer[Symbol.species],ze=0,Rc=1,$c=2,Pc=3,Go=4,Ho=5,si=6,Wo=class extends tg{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||rg[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[sg]=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=ze}_write(e,t,n){if(this._opcode===8&&this._state==ze)return n();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){n(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(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new ni(n.buffer,n.byteOffset+e,n.length-e),new ni(n.buffer,n.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],s=t.length-e;e>=n.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),s),this._buffers[0]=new ni(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case ze:this.getInfo(e);break;case Rc:this.getPayloadLength16(e);break;case $c:this.getPayloadLength64(e);break;case Pc:this.getMask();break;case Go:this.getData(e);break;case Ho:case si:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((t[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let n=(t[0]&64)===64;if(n&&!this._extensions[Ec.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){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=n}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(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=Rc:this._payloadLength===127?this._state=$c:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>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=n*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=Pc:this._state=Go}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Go}getData(e){let t=Ic;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&og(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let n=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(n);return}if(this._compressed){this._state=Ho,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Ec.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return t(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(o);return}this._fragments.push(i)}this.dataMessage(t),this._state===ze&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=ze;return}let t=this._messageLength,n=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=Vo(n,t):this._binaryType==="arraybuffer"?s=ig(Vo(n,t)):this._binaryType==="blob"?s=new Blob(n):s=n,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=ze):(this._state=si,setImmediate(()=>{this.emit("message",s,!0),this._state=ze,this.startLoop(e)}))}else{let s=Vo(n,t);if(!this._skipUTF8Validation&&!Ac(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Ho||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=ze):(this._state=si,setImmediate(()=>{this.emit("message",s,!1),this._state=ze,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Ic),this.end();else{let n=e.readUInt16BE(0);if(!ag(n)){let i=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new ni(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Ac(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(i);return}this._loop=!1,this.emit("conclude",n,s),this.end()}this._state=ze;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=ze):(this._state=si,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=ze,this.startLoop(t)}))}createError(e,t,n,s,i){this._loop=!1,this._errored=!0;let o=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[ng]=s,o}};jc.exports=Wo});var Qo=Y((ob,Mc)=>{"use strict";var{Duplex:ib}=require("stream"),{randomFillSync:ug}=require("crypto"),{types:{isUint8Array:lg}}=require("util"),Oc=gn(),{EMPTY_BUFFER:cg,kWebSocket:dg,NOOP:hg}=ft(),{isBlob:vn,isValidStatusCode:fg}=yn(),{mask:Nc,toBuffer:Ir}=Gn(),Le=Symbol("kByteLength"),pg=Buffer.alloc(4),ii=8*1024,Ar,_n=ii,Be=0,mg=1,gg=2,Yo=class r{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Be,this.onerror=hg,this[dg]=void 0}static frame(e,t){let n,s=!1,i=2,o=!1;t.mask&&(n=t.maskBuffer||pg,t.generateMask?t.generateMask(n):(_n===ii&&(Ar===void 0&&(Ar=Buffer.alloc(ii)),ug(Ar,0,ii),_n=0),n[0]=Ar[_n++],n[1]=Ar[_n++],n[2]=Ar[_n++],n[3]=Ar[_n++]),o=(n[0]|n[1]|n[2]|n[3])===0,i=6);let a;typeof e=="string"?(!t.mask||o)&&t[Le]!==void 0?a=t[Le]:(e=Buffer.from(e),a=e.length):(a=e.length,s=t.mask&&t.readOnly&&!o);let l=a;a>=65536?(i+=8,l=127):a>125&&(i+=2,l=126);let c=Buffer.allocUnsafe(s?a+i:i);return c[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(c[0]|=64),c[1]=l,l===126?c.writeUInt16BE(a,2):l===127&&(c[2]=c[3]=0,c.writeUIntBE(a,4,6)),t.mask?(c[1]|=128,c[i-4]=n[0],c[i-3]=n[1],c[i-2]=n[2],c[i-1]=n[3],o?[c,e]:s?(Nc(e,n,c,i,a),[c]):(Nc(e,n,e,0,a),[c,e])):[c,e]}close(e,t,n,s){let i;if(e===void 0)i=cg;else{if(typeof e!="number"||!fg(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(t);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");if(i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof t=="string")i.write(t,2);else if(lg(t))i.set(t,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[Le]:i.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Be?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(r.frame(i,o),s)}ping(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):vn(e)?(s=e.size,i=!1):(e=Ir(e),s=e.length,i=Ir.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Le]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};vn(e)?this._state!==Be?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==Be?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(r.frame(e,o),n)}pong(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):vn(e)?(s=e.size,i=!1):(e=Ir(e),s=e.length,i=Ir.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Le]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};vn(e)?this._state!==Be?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==Be?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(r.frame(e,o),n)}send(e,t,n){let s=this._extensions[Oc.extensionName],i=t.binary?2:1,o=t.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):vn(e)?(a=e.size,l=!1):(e=Ir(e),a=e.length,l=Ir.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=s._threshold),this._compress=o):(o=!1,i=0),t.fin&&(this._firstFragment=!0);let c={[Le]:a,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:l,rsv1:o};vn(e)?this._state!==Be?this.enqueue([this.getBlobData,e,this._compress,c,n]):this.getBlobData(e,this._compress,c,n):this._state!==Be?this.enqueue([this.dispatch,e,this._compress,c,n]):this.dispatch(e,this._compress,c,n)}getBlobData(e,t,n,s){this._bufferedBytes+=n[Le],this._state=gg,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Xo,this,a,s);return}this._bufferedBytes-=n[Le];let o=Ir(i);t?this.dispatch(o,t,n,s):(this._state=Be,this.sendFrame(r.frame(o,n),s),this.dequeue())}).catch(i=>{process.nextTick(yg,this,i,s)})}dispatch(e,t,n,s){if(!t){this.sendFrame(r.frame(e,n),s);return}let i=this._extensions[Oc.extensionName];this._bufferedBytes+=n[Le],this._state=mg,i.compress(e,n.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");Xo(this,l,s);return}this._bufferedBytes-=n[Le],this._state=Be,n.readOnly=!1,this.sendFrame(r.frame(a,n),s),this.dequeue()})}dequeue(){for(;this._state===Be&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Le],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Le],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};Mc.exports=Yo;function Xo(r,e,t){typeof t=="function"&&t(e);for(let n=0;n<r._queue.length;n++){let s=r._queue[n],i=s[s.length-1];typeof i=="function"&&i(e)}}function yg(r,e,t){Xo(r,e,t),r.onerror(e)}});var Kc=Y((ab,Zc)=>{"use strict";var{kForOnEventAttribute:Wn,kListener:ea}=ft(),zc=Symbol("kCode"),Lc=Symbol("kData"),Dc=Symbol("kError"),Uc=Symbol("kMessage"),qc=Symbol("kReason"),bn=Symbol("kTarget"),Fc=Symbol("kType"),Bc=Symbol("kWasClean"),mt=class{constructor(e){this[bn]=null,this[Fc]=e}get target(){return this[bn]}get type(){return this[Fc]}};Object.defineProperty(mt.prototype,"target",{enumerable:!0});Object.defineProperty(mt.prototype,"type",{enumerable:!0});var Rr=class extends mt{constructor(e,t={}){super(e),this[zc]=t.code===void 0?0:t.code,this[qc]=t.reason===void 0?"":t.reason,this[Bc]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[zc]}get reason(){return this[qc]}get wasClean(){return this[Bc]}};Object.defineProperty(Rr.prototype,"code",{enumerable:!0});Object.defineProperty(Rr.prototype,"reason",{enumerable:!0});Object.defineProperty(Rr.prototype,"wasClean",{enumerable:!0});var wn=class extends mt{constructor(e,t={}){super(e),this[Dc]=t.error===void 0?null:t.error,this[Uc]=t.message===void 0?"":t.message}get error(){return this[Dc]}get message(){return this[Uc]}};Object.defineProperty(wn.prototype,"error",{enumerable:!0});Object.defineProperty(wn.prototype,"message",{enumerable:!0});var Jn=class extends mt{constructor(e,t={}){super(e),this[Lc]=t.data===void 0?null:t.data}get data(){return this[Lc]}};Object.defineProperty(Jn.prototype,"data",{enumerable:!0});var vg={addEventListener(r,e,t={}){for(let s of this.listeners(r))if(!t[Wn]&&s[ea]===e&&!s[Wn])return;let n;if(r==="message")n=function(i,o){let a=new Jn("message",{data:o?i:i.toString()});a[bn]=this,oi(e,this,a)};else if(r==="close")n=function(i,o){let a=new Rr("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[bn]=this,oi(e,this,a)};else if(r==="error")n=function(i){let o=new wn("error",{error:i,message:i.message});o[bn]=this,oi(e,this,o)};else if(r==="open")n=function(){let i=new mt("open");i[bn]=this,oi(e,this,i)};else return;n[Wn]=!!t[Wn],n[ea]=e,t.once?this.once(r,n):this.on(r,n)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[ea]===e&&!t[Wn]){this.removeListener(r,t);break}}};Zc.exports={CloseEvent:Rr,ErrorEvent:wn,Event:mt,EventTarget:vg,MessageEvent:Jn};function oi(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var ai=Y((ub,Vc)=>{"use strict";var{tokenChars:Yn}=yn();function Qe(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function _g(r){let e=Object.create(null),t=Object.create(null),n=!1,s=!1,i=!1,o,a,l=-1,c=-1,h=-1,p=0;for(;p<r.length;p++)if(c=r.charCodeAt(p),o===void 0)if(h===-1&&Yn[c]===1)l===-1&&(l=p);else if(p!==0&&(c===32||c===9))h===-1&&l!==-1&&(h=p);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${p}`);h===-1&&(h=p);let b=r.slice(l,h);c===44?(Qe(e,b,t),t=Object.create(null)):o=b,l=h=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(a===void 0)if(h===-1&&Yn[c]===1)l===-1&&(l=p);else if(c===32||c===9)h===-1&&l!==-1&&(h=p);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${p}`);h===-1&&(h=p),Qe(t,r.slice(l,h),!0),c===44&&(Qe(e,o,t),t=Object.create(null),o=void 0),l=h=-1}else if(c===61&&l!==-1&&h===-1)a=r.slice(l,p),l=h=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(s){if(Yn[c]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);l===-1?l=p:n||(n=!0),s=!1}else if(i)if(Yn[c]===1)l===-1&&(l=p);else if(c===34&&l!==-1)i=!1,h=p;else if(c===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(c===34&&r.charCodeAt(p-1)===61)i=!0;else if(h===-1&&Yn[c]===1)l===-1&&(l=p);else if(l!==-1&&(c===32||c===9))h===-1&&(h=p);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${p}`);h===-1&&(h=p);let b=r.slice(l,h);n&&(b=b.replace(/\\/g,""),n=!1),Qe(t,a,b),c===44&&(Qe(e,o,t),t=Object.create(null),o=void 0),a=void 0,l=h=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(l===-1||i||c===32||c===9)throw new SyntaxError("Unexpected end of input");h===-1&&(h=p);let _=r.slice(l,h);return o===void 0?Qe(e,_,t):(a===void 0?Qe(t,_,!0):n?Qe(t,a,_.replace(/\\/g,"")):Qe(t,a,_),Qe(e,o,t)),e}function bg(r){return Object.keys(r).map(e=>{let t=r[e];return Array.isArray(t)||(t=[t]),t.map(n=>[e].concat(Object.keys(n).map(s=>{let i=n[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Vc.exports={format:bg,parse:_g}});var di=Y((db,sd)=>{"use strict";var wg=require("events"),kg=require("https"),Sg=require("http"),Wc=require("net"),xg=require("tls"),{randomBytes:Tg,createHash:Cg}=require("crypto"),{Duplex:lb,Readable:cb}=require("stream"),{URL:ta}=require("url"),Ot=gn(),Eg=Jo(),Ig=Qo(),{isBlob:Ag}=yn(),{BINARY_TYPES:Gc,CLOSE_TIMEOUT:Rg,EMPTY_BUFFER:ui,GUID:$g,kForOnEventAttribute:ra,kListener:Pg,kStatusCode:jg,kWebSocket:ae,NOOP:Jc}=ft(),{EventTarget:{addEventListener:Og,removeEventListener:Ng}}=Kc(),{format:Mg,parse:zg}=ai(),{toBuffer:Lg}=Gn(),Yc=Symbol("kAborted"),na=[8,13],gt=["CONNECTING","OPEN","CLOSING","CLOSED"],Dg=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,se=class r extends wg{constructor(e,t,n){super(),this._binaryType=Gc[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=ui,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=r.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(n=t,t=[]):t=[t]),Xc(this,e,t,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Gc.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,n){let s=new Eg({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:n.maxBufferedChunks,maxFragments:n.maxFragments,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),i=new Ig(e,this._extensions,n.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[ae]=this,i[ae]=this,e[ae]=this,s.on("conclude",Fg),s.on("drain",Bg),s.on("error",Zg),s.on("message",Kg),s.on("ping",Vg),s.on("pong",Gg),i.onerror=Hg,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",td),e.on("data",ci),e.on("end",rd),e.on("error",nd),this._readyState=r.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Ot.extensionName]&&this._extensions[Ot.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){Ee(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===r.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=r.CLOSING,this._sender.close(e,t,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),ed(this)}}pause(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){sa(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||ui,t,n)}pong(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){sa(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||ui,t,n)}resume(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(n=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){sa(this,e,n);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Ot.extensionName]||(s.compress=!1),this._sender.send(e||ui,s,n)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){Ee(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(se,"CONNECTING",{enumerable:!0,value:gt.indexOf("CONNECTING")});Object.defineProperty(se.prototype,"CONNECTING",{enumerable:!0,value:gt.indexOf("CONNECTING")});Object.defineProperty(se,"OPEN",{enumerable:!0,value:gt.indexOf("OPEN")});Object.defineProperty(se.prototype,"OPEN",{enumerable:!0,value:gt.indexOf("OPEN")});Object.defineProperty(se,"CLOSING",{enumerable:!0,value:gt.indexOf("CLOSING")});Object.defineProperty(se.prototype,"CLOSING",{enumerable:!0,value:gt.indexOf("CLOSING")});Object.defineProperty(se,"CLOSED",{enumerable:!0,value:gt.indexOf("CLOSED")});Object.defineProperty(se.prototype,"CLOSED",{enumerable:!0,value:gt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(se.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(se.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[ra])return e[Pg];return null},set(e){for(let t of this.listeners(r))if(t[ra]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[ra]:!0})}})});se.prototype.addEventListener=Og;se.prototype.removeEventListener=Ng;sd.exports=se;function Xc(r,e,t,n){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Rg,protocolVersion:na[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(r._autoPong=s.autoPong,r._closeTimeout=s.closeTimeout,!na.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${na.join(", ")})`);let i;if(e instanceof ta)i=e;else try{i=new ta(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),r._url=i.href;let o=i.protocol==="wss:",a=i.protocol==="ws+unix:",l;if(i.protocol!=="ws:"&&!o&&!a?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?l="The URL's pathname is empty":i.hash&&(l="The URL contains a fragment identifier"),l){let C=new SyntaxError(l);if(r._redirects===0)throw C;li(r,C);return}let c=o?443:80,h=Tg(16).toString("base64"),p=o?kg.request:Sg.request,_=new Set,b;if(s.createConnection=s.createConnection||(o?qg:Ug),s.defaultPort=s.defaultPort||c,s.port=i.port||c,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":h,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(b=new Ot({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=Mg({[Ot.extensionName]:b.offer()})),t.length){for(let C of t){if(typeof C!="string"||!Dg.test(C)||_.has(C))throw new SyntaxError("An invalid or duplicated subprotocol was specified");_.add(C)}s.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){let C=s.path.split(":");s.socketPath=C[0],s.path=C[1]}let x;if(s.followRedirects){if(r._redirects===0){r._originalIpc=a,r._originalSecure=o,r._originalHostOrSocketPath=a?s.socketPath:i.host;let C=n&&n.headers;if(n={...n,headers:{}},C)for(let[S,F]of Object.entries(C))n.headers[S.toLowerCase()]=F}else if(r.listenerCount("redirect")===0){let C=a?r._originalIpc?s.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:i.host===r._originalHostOrSocketPath;(!C||r._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,C||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),x=r._req=p(s),r._redirects&&r.emit("redirect",r.url,x)}else x=r._req=p(s);s.timeout&&x.on("timeout",()=>{Ee(r,x,"Opening handshake has timed out")}),x.on("error",C=>{x===null||x[Yc]||(x=r._req=null,li(r,C))}),x.on("response",C=>{let S=C.headers.location,F=C.statusCode;if(S&&s.followRedirects&&F>=300&&F<400){if(++r._redirects>s.maxRedirects){Ee(r,x,"Maximum redirects exceeded");return}x.abort();let q;try{q=new ta(S,e)}catch{let m=new SyntaxError(`Invalid URL: ${S}`);li(r,m);return}Xc(r,q,t,n)}else r.emit("unexpected-response",x,C)||Ee(r,x,`Unexpected server response: ${C.statusCode}`)}),x.on("upgrade",(C,S,F)=>{if(r.emit("upgrade",C),r.readyState!==se.CONNECTING)return;x=r._req=null;let q=C.headers.upgrade;if(q===void 0||q.toLowerCase()!=="websocket"){Ee(r,S,"Invalid Upgrade header");return}let f=Cg("sha1").update(h+$g).digest("base64");if(C.headers["sec-websocket-accept"]!==f){Ee(r,S,"Invalid Sec-WebSocket-Accept header");return}let m=C.headers["sec-websocket-protocol"],w;if(m!==void 0?_.size?_.has(m)||(w="Server sent an invalid subprotocol"):w="Server sent a subprotocol but none was requested":_.size&&(w="Server sent no subprotocol"),w){Ee(r,S,w);return}m&&(r._protocol=m);let A=C.headers["sec-websocket-extensions"];if(A!==void 0){if(!b){Ee(r,S,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let N;try{N=zg(A)}catch{Ee(r,S,"Invalid Sec-WebSocket-Extensions header");return}let B=Object.keys(N);if(B.length!==1||B[0]!==Ot.extensionName){Ee(r,S,"Server indicated an extension that was not requested");return}try{b.accept(N[Ot.extensionName])}catch{Ee(r,S,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[Ot.extensionName]=b}r.setSocket(S,F,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(x,r):x.end()}function li(r,e){r._readyState=se.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function Ug(r){return r.path=r.socketPath,Wc.connect(r)}function qg(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=Wc.isIP(r.host)?"":r.host),xg.connect(r)}function Ee(r,e,t){r._readyState=se.CLOSING;let n=new Error(t);Error.captureStackTrace(n,Ee),e.setHeader?(e[Yc]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(li,r,n)):(e.destroy(n),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function sa(r,e,t){if(e){let n=Ag(e)?e.size:Lg(e).length;r._socket?r._sender._bufferedBytes+=n:r._bufferedAmount+=n}if(t){let n=new Error(`WebSocket is not open: readyState ${r.readyState} (${gt[r.readyState]})`);process.nextTick(t,n)}}function Fg(r,e){let t=this[ae];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[ae]!==void 0&&(t._socket.removeListener("data",ci),process.nextTick(Qc,t._socket),r===1005?t.close():t.close(r,e))}function Bg(){let r=this[ae];r.isPaused||r._socket.resume()}function Zg(r){let e=this[ae];e._socket[ae]!==void 0&&(e._socket.removeListener("data",ci),process.nextTick(Qc,e._socket),e.close(r[jg])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function Hc(){this[ae].emitClose()}function Kg(r,e){this[ae].emit("message",r,e)}function Vg(r){let e=this[ae];e._autoPong&&e.pong(r,!this._isServer,Jc),e.emit("ping",r)}function Gg(r){this[ae].emit("pong",r)}function Qc(r){r.resume()}function Hg(r){let e=this[ae];e.readyState!==se.CLOSED&&(e.readyState===se.OPEN&&(e._readyState=se.CLOSING,ed(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function ed(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),r._closeTimeout)}function td(){let r=this[ae];if(this.removeListener("close",td),this.removeListener("data",ci),this.removeListener("end",rd),r._readyState=se.CLOSING,!this._readableState.endEmitted&&!r._closeFrameReceived&&!r._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);r._receiver.write(e)}r._receiver.end(),this[ae]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",Hc),r._receiver.on("finish",Hc))}function ci(r){this[ae]._receiver.write(r)||this.pause()}function rd(){let r=this[ae];r._readyState=se.CLOSING,r._receiver.end(),this.end()}function nd(){let r=this[ae];this.removeListener("error",nd),this.on("error",Jc),r&&(r._readyState=se.CLOSING,this.destroy())}});var ud=Y((fb,ad)=>{"use strict";var hb=di(),{Duplex:Wg}=require("stream");function id(r){r.emit("close")}function Jg(){!this.destroyed&&this._writableState.finished&&this.destroy()}function od(r){this.removeListener("error",od),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function Yg(r,e){let t=!0,n=new Wg({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(i,o){let a=!o&&n._readableState.objectMode?i.toString():i;n.push(a)||r.pause()}),r.once("error",function(i){n.destroyed||(t=!1,n.destroy(i))}),r.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(s,i){if(r.readyState===r.CLOSED){i(s),process.nextTick(id,n);return}let o=!1;r.once("error",function(l){o=!0,i(l)}),r.once("close",function(){o||i(s),process.nextTick(id,n)}),t&&r.terminate()},n._final=function(s){if(r.readyState===r.CONNECTING){r.once("open",function(){n._final(s)});return}r._socket!==null&&(r._socket._writableState.finished?(s(),n._readableState.endEmitted&&n.destroy()):(r._socket.once("finish",function(){s()}),r.close()))},n._read=function(){r.isPaused&&r.resume()},n._write=function(s,i,o){if(r.readyState===r.CONNECTING){r.once("open",function(){n._write(s,i,o)});return}r.send(s,o)},n.on("end",Jg),n.on("error",od),n}ad.exports=Yg});var ia=Y((pb,ld)=>{"use strict";var{tokenChars:Xg}=yn();function Qg(r){let e=new Set,t=-1,n=-1,s=0;for(s;s<r.length;s++){let o=r.charCodeAt(s);if(n===-1&&Xg[o]===1)t===-1&&(t=s);else if(s!==0&&(o===32||o===9))n===-1&&t!==-1&&(n=s);else if(o===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${s}`);n===-1&&(n=s);let a=r.slice(t,n);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),t=n=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(t===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let i=r.slice(t,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}ld.exports={parse:Qg}});var gd=Y((gb,md)=>{"use strict";var ey=require("events"),hi=require("http"),{Duplex:mb}=require("stream"),{createHash:ty}=require("crypto"),cd=ai(),$r=gn(),ry=ia(),ny=di(),{CLOSE_TIMEOUT:sy,GUID:iy,kWebSocket:oy}=ft(),ay=/^[+/0-9A-Za-z]{22}==$/,dd=0,hd=1,pd=2,oa=class extends ey{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:sy,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:ny,...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=hi.createServer((n,s)=>{let i=hi.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=uy(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=dd}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===pd){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Xn,this);return}if(e&&this.once("close",e),this._state!==hd)if(this._state=hd,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(Xn,this):process.nextTick(Xn,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{Xn(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,s){t.on("error",fd);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Pr(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Pr(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!ay.test(i)){Pr(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Pr(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Qn(t,400);return}let l=e.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=ry.parse(l)}catch{Pr(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let h=e.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&h!==void 0){let _=new $r({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let b=cd.parse(h);b[$r.extensionName]&&(_.accept(b[$r.extensionName]),p[$r.extensionName]=_)}catch{Pr(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let _={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(_,(b,x,C,S)=>{if(!b)return Qn(t,x||401,C,S);this.completeUpgrade(p,i,c,e,t,n,s)});return}if(!this.options.verifyClient(_))return Qn(t,401)}this.completeUpgrade(p,i,c,e,t,n,s)}completeUpgrade(e,t,n,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[oy])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>dd)return Qn(i,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${ty("sha1").update(t+iy).digest("base64")}`],h=new this.options.WebSocket(null,void 0,this.options);if(n.size){let p=this.options.handleProtocols?this.options.handleProtocols(n,s):n.values().next().value;p&&(c.push(`Sec-WebSocket-Protocol: ${p}`),h._protocol=p)}if(e[$r.extensionName]){let p=e[$r.extensionName].params,_=cd.format({[$r.extensionName]:[p]});c.push(`Sec-WebSocket-Extensions: ${_}`),h._extensions=e}this.emit("headers",c,s),i.write(c.concat(`\r
|
|
231
231
|
`).join(`\r
|
|
232
|
-
`)),i.removeListener("error",
|
|
232
|
+
`)),i.removeListener("error",fd),h.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(h),h.on("close",()=>{this.clients.delete(h),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Xn,this)})),a(h,s)}};md.exports=oa;function uy(r,e){for(let t of Object.keys(e))r.on(t,e[t]);return function(){for(let n of Object.keys(e))r.removeListener(n,e[n])}}function Xn(r){r._state=pd,r.emit("close")}function fd(){this.destroy()}function Qn(r,e,t,n){t=t||hi.STATUS_CODES[e],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...n},r.once("finish",r.destroy),r.end(`HTTP/1.1 ${e} ${hi.STATUS_CODES[e]}\r
|
|
233
233
|
`+Object.keys(n).map(s=>`${s}: ${n[s]}`).join(`\r
|
|
234
234
|
`)+`\r
|
|
235
235
|
\r
|
|
236
|
-
`+t)}function Pr(r,e,t,n,s,i){if(r.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,Pr),r.emit("wsClientError",o,t,e)}else Qn(t,n,s,i)}});var wd={};ns(wd,{buildSetupReport:()=>yy,claudeLoggedIn:()=>bd});function bd(r=vd.default.homedir()){if(Nt.default.existsSync(jr.default.join(r,".claude",".credentials.json")))return!0;try{return!!JSON.parse(Nt.default.readFileSync(jr.default.join(r,".claude.json"),"utf8")).oauthAccount}catch{return!1}}async function yy(r,e){let t=!1,n="";if(ts&&Date.now()-ts.at<6e4)t=ts.installed,n=ts.version;else{try{let{stdout:o}=await gy(r.claudeBin,["--version"],{timeout:1e4});t=!0,n=o.trim().slice(0,60)}catch{t=!1}ts={at:Date.now(),installed:t,version:n}}let s=e.map(o=>{let a=r.repos[o];if(!a)return{repoName:o,mapped:!1,pathExists:!1,isGit:!1,claudeMd:!1,deployMd:!1,testMd:!1};let l=Nt.default.existsSync(a.path);return{repoName:o,mapped:!0,pathExists:l,isGit:l&&Nt.default.existsSync(jr.default.join(a.path,".git")),claudeMd:l&&Nt.default.existsSync(jr.default.join(a.path,"CLAUDE.md")),deployMd:l&&Nt.default.existsSync(jr.default.join(a.path,"DEPLOY.md")),testMd:l&&Nt.default.existsSync(jr.default.join(a.path,"TEST.md"))}}),i=Object.values(r.repos).find(o=>o.github?.token);return{jiraConfigured:!!r.jira,jiraEmail:r.jira?.email??"",claude:{installed:t,version:n,loggedIn:bd()},githubTokenSet:!!(r.github?.token||i),githubLogin:r.github?.login??i?.github?.login??"",deploysEnabled:r.deploy.enabled,jiraUserCount:Object.keys(r.jiraUsers).length,repos:s}}var yd,Nt,vd,jr,_d,gy,ts,kd=fi(()=>{"use strict";yd=require("node:child_process"),Nt=P(require("node:fs"),1),vd=P(require("node:os"),1),jr=P(require("node:path"),1),_d=require("node:util"),gy=(0,_d.promisify)(yd.execFile);ts=null});var yt=P(require("node:fs"),1),Sd=P(require("node:os"),1),kn=P(require("node:path"),1),Mt=require("node:child_process"),di=require("node:crypto"),Or=P(require("node:readline/promises"),1);var Ca=P(xa(),1),{program:Ey,createCommand:Iy,createArgument:Ay,createOption:Ry,CommanderError:$y,InvalidArgumentError:Py,InvalidOptionArgumentError:jy,Command:Ea,Argument:Oy,Option:Ny,Help:My}=Ca.default;var ot=P(require("node:fs"),1),ds=P(require("node:os"),1),hs=P(require("node:path"),1);var w={};ns(w,{BRAND:()=>yh,DIRTY:()=>Lt,EMPTY_PATH:()=>Wd,INVALID:()=>D,NEVER:()=>tf,OK:()=>fe,ParseStatus:()=>le,Schema:()=>H,ZodAny:()=>wt,ZodArray:()=>it,ZodBigInt:()=>zt,ZodBoolean:()=>Ut,ZodBranded:()=>Cn,ZodCatch:()=>Yt,ZodDate:()=>qt,ZodDefault:()=>Jt,ZodDiscriminatedUnion:()=>us,ZodEffects:()=>$e,ZodEnum:()=>Ht,ZodError:()=>_e,ZodFirstPartyTypeKind:()=>z,ZodFunction:()=>cs,ZodIntersection:()=>Kt,ZodIssueCode:()=>x,ZodLazy:()=>Vt,ZodLiteral:()=>Gt,ZodMap:()=>Ur,ZodNaN:()=>Br,ZodNativeEnum:()=>Wt,ZodNever:()=>ze,ZodNull:()=>Ft,ZodNullable:()=>Ge,ZodNumber:()=>Dt,ZodObject:()=>be,ZodOptional:()=>Ae,ZodParsedType:()=>$,ZodPipeline:()=>En,ZodPromise:()=>kt,ZodReadonly:()=>Xt,ZodRecord:()=>ls,ZodSchema:()=>H,ZodSet:()=>qr,ZodString:()=>bt,ZodSymbol:()=>Dr,ZodTransformer:()=>$e,ZodTuple:()=>Ve,ZodType:()=>H,ZodUndefined:()=>Bt,ZodUnion:()=>Zt,ZodUnknown:()=>st,ZodVoid:()=>zr,addIssueToContext:()=>R,any:()=>Ch,array:()=>Rh,bigint:()=>wh,boolean:()=>Da,coerce:()=>ef,custom:()=>Na,date:()=>kh,datetimeRegex:()=>ja,defaultErrorMap:()=>rt,discriminatedUnion:()=>Oh,effect:()=>Vh,enum:()=>Fh,function:()=>Uh,getErrorMap:()=>Nr,getParsedType:()=>Ke,instanceof:()=>_h,intersection:()=>Nh,isAborted:()=>os,isAsync:()=>Mr,isDirty:()=>as,isValid:()=>_t,late:()=>vh,lazy:()=>qh,literal:()=>Bh,makeIssue:()=>xn,map:()=>Dh,nan:()=>bh,nativeEnum:()=>Zh,never:()=>Ih,null:()=>xh,nullable:()=>Hh,number:()=>La,object:()=>$h,objectUtil:()=>Ai,oboolean:()=>Qh,onumber:()=>Xh,optional:()=>Gh,ostring:()=>Yh,pipeline:()=>Jh,preprocess:()=>Wh,promise:()=>Kh,quotelessJson:()=>Vd,record:()=>Lh,set:()=>zh,setErrorMap:()=>Hd,strictObject:()=>Ph,string:()=>Ma,symbol:()=>Sh,transformer:()=>Vh,tuple:()=>Mh,undefined:()=>Th,union:()=>jh,unknown:()=>Eh,util:()=>W,void:()=>Ah});var W;(function(r){r.assertEqual=s=>{};function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},r.getValidEnumValues=s=>{let i=r.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),o={};for(let a of i)o[a]=s[a];return r.objectValues(o)},r.objectValues=s=>r.objectKeys(s).map(function(i){return s[i]}),r.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},r.find=(s,i)=>{for(let o of s)if(i(o))return o},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}r.joinValues=n,r.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(W||(W={}));var Ai;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(Ai||(Ai={}));var $=W.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ke=r=>{switch(typeof r){case"undefined":return $.undefined;case"string":return $.string;case"number":return Number.isNaN(r)?$.nan:$.number;case"boolean":return $.boolean;case"function":return $.function;case"bigint":return $.bigint;case"symbol":return $.symbol;case"object":return Array.isArray(r)?$.array:r===null?$.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?$.promise:typeof Map<"u"&&r instanceof Map?$.map:typeof Set<"u"&&r instanceof Set?$.set:typeof Date<"u"&&r instanceof Date?$.date:$.object;default:return $.unknown}};var x=W.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"]),Vd=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),_e=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},n={_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)n._errors.push(t(o));else{let a=n,l=0;for(;l<o.path.length;){let c=o.path[l];l===o.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(t(o))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return s(this),n}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,W.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},n=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];t[i]=t[i]||[],t[i].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};_e.create=r=>new _e(r);var Gd=(r,e)=>{let t;switch(r.code){case x.invalid_type:r.received===$.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case x.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,W.jsonStringifyReplacer)}`;break;case x.unrecognized_keys:t=`Unrecognized key(s) in object: ${W.joinValues(r.keys,", ")}`;break;case x.invalid_union:t="Invalid input";break;case x.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${W.joinValues(r.options)}`;break;case x.invalid_enum_value:t=`Invalid enum value. Expected ${W.joinValues(r.options)}, received '${r.received}'`;break;case x.invalid_arguments:t="Invalid function arguments";break;case x.invalid_return_type:t="Invalid function return type";break;case x.invalid_date:t="Invalid date";break;case x.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:W.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case x.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case x.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case x.custom:t="Invalid input";break;case x.invalid_intersection_types:t="Intersection results could not be merged";break;case x.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case x.not_finite:t="Number must be finite";break;default:t=e.defaultError,W.assertNever(r)}return{message:t}},rt=Gd;var Ia=rt;function Hd(r){Ia=r}function Nr(){return Ia}var xn=r=>{let{data:e,path:t,errorMaps:n,issueData:s}=r,i=[...t,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let a="",l=n.filter(c=>!!c).slice().reverse();for(let c of l)a=c(o,{data:e,defaultError:a}).message;return{...s,path:i,message:a}},Wd=[];function R(r,e){let t=Nr(),n=xn({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===rt?void 0:rt].filter(s=>!!s)});r.common.issues.push(n)}var le=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let s of t){if(s.status==="aborted")return D;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let s of t){let i=await s.key,o=await s.value;n.push({key:i,value:o})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let s of t){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return D;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(n[i.value]=o.value)}return{status:e.value,value:n}}},D=Object.freeze({status:"aborted"}),Lt=r=>({status:"dirty",value:r}),fe=r=>({status:"valid",value:r}),os=r=>r.status==="aborted",as=r=>r.status==="dirty",_t=r=>r.status==="valid",Mr=r=>typeof Promise<"u"&&r instanceof Promise;var j;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(j||(j={}));var Re=class{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,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}},Aa=(r,e)=>{if(_t(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new _e(r.common.issues);return this._error=t,this._error}}};function Z(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))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,a)=>{let{message:l}=r;return o.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??n??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:l??t??a.defaultError}},description:s}}var H=class{get description(){return this._def.description}_getType(e){return Ke(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Ke(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new le,ctx:{common:e.parent.common,data:e.data,parsedType:Ke(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Mr(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ke(e)},s=this._parseSync({data:e,path:n.path,parent:n});return Aa(n,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ke(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return _t(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>_t(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ke(e)},s=this._parse({data:e,path:n.path,parent:n}),i=await(Mr(s)?s:Promise.resolve(s));return Aa(n,i)}refine(e,t){let n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,i)=>{let o=e(s),a=()=>i.addIssue({code:x.custom,...n(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new $e({schema:this,typeName:z.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return Ae.create(this,this._def)}nullable(){return Ge.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return it.create(this)}promise(){return kt.create(this,this._def)}or(e){return Zt.create([this,e],this._def)}and(e){return Kt.create(this,e,this._def)}transform(e){return new $e({...Z(this._def),schema:this,typeName:z.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Jt({...Z(this._def),innerType:this,defaultValue:t,typeName:z.ZodDefault})}brand(){return new Cn({typeName:z.ZodBranded,type:this,...Z(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Yt({...Z(this._def),innerType:this,catchValue:t,typeName:z.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return En.create(this,e)}readonly(){return Xt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Jd=/^c[^\s-]{8,}$/i,Yd=/^[0-9a-z]+$/,Xd=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Qd=/^[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,eh=/^[a-z0-9_-]{21}$/i,th=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,rh=/^[-+]?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)?)??$/,nh=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,sh="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ri,ih=/^(?:(?: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])$/,oh=/^(?:(?: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])$/,ah=/^(([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]))$/,uh=/^(([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])$/,lh=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ch=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,$a="((\\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])))",dh=new RegExp(`^${$a}$`);function Pa(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function hh(r){return new RegExp(`^${Pa(r)}$`)}function ja(r){let e=`${$a}T${Pa(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function fh(r,e){return!!((e==="v4"||!e)&&ih.test(r)||(e==="v6"||!e)&&ah.test(r))}function ph(r,e){if(!th.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function mh(r,e){return!!((e==="v4"||!e)&&oh.test(r)||(e==="v6"||!e)&&uh.test(r))}var bt=class r extends H{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==$.string){let i=this._getOrReturnCtx(e);return R(i,{code:x.invalid_type,expected:$.string,received:i.parsedType}),D}let n=new le,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),R(s,{code:x.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),R(s,{code:x.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(s=this._getOrReturnCtx(e,s),o?R(s,{code:x.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&R(s,{code:x.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")nh.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"email",code:x.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")Ri||(Ri=new RegExp(sh,"u")),Ri.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"emoji",code:x.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")Qd.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"uuid",code:x.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")eh.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"nanoid",code:x.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")Jd.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"cuid",code:x.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")Yd.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"cuid2",code:x.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")Xd.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"ulid",code:x.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),R(s,{validation:"url",code:x.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"regex",code:x.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),R(s,{code:x.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.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),R(s,{code:x.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),R(s,{code:x.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?ja(i).test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{code:x.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?dh.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{code:x.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?hh(i).test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{code:x.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?rh.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"duration",code:x.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?fh(e.data,i.version)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"ip",code:x.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?ph(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"jwt",code:x.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?mh(e.data,i.version)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"cidr",code:x.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?lh.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"base64",code:x.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?ch.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"base64url",code:x.invalid_string,message:i.message}),n.dirty()):W.assertNever(i);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:x.invalid_string,...j.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...j.errToObj(e)})}url(e){return this._addCheck({kind:"url",...j.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...j.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...j.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...j.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...j.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...j.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...j.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...j.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...j.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...j.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...j.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...j.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,...j.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,...j.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...j.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...j.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...j.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...j.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...j.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...j.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...j.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...j.errToObj(t)})}nonempty(e){return this.min(1,j.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};bt.create=r=>new bt({checks:[],typeName:z.ZodString,coerce:r?.coerce??!1,...Z(r)});function gh(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,i=Number.parseInt(r.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var Dt=class r extends H{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)!==$.number){let i=this._getOrReturnCtx(e);return R(i,{code:x.invalid_type,expected:$.number,received:i.parsedType}),D}let n,s=new le;for(let i of this._def.checks)i.kind==="int"?W.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),R(n,{code:x.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),R(n,{code:x.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)&&(n=this._getOrReturnCtx(e,n),R(n,{code:x.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?gh(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),R(n,{code:x.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),R(n,{code:x.not_finite,message:i.message}),s.dirty()):W.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,j.toString(t))}gt(e,t){return this.setLimit("min",e,!1,j.toString(t))}lte(e,t){return this.setLimit("max",e,!0,j.toString(t))}lt(e,t){return this.setLimit("max",e,!1,j.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:j.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:j.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:j.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:j.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:j.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:j.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:j.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:j.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:j.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:j.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&W.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};Dt.create=r=>new Dt({checks:[],typeName:z.ZodNumber,coerce:r?.coerce||!1,...Z(r)});var zt=class r extends H{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)!==$.bigint)return this._getInvalidInput(e);let n,s=new le;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),R(n,{code:x.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)&&(n=this._getOrReturnCtx(e,n),R(n,{code:x.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),R(n,{code:x.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):W.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return R(t,{code:x.invalid_type,expected:$.bigint,received:t.parsedType}),D}gte(e,t){return this.setLimit("min",e,!0,j.toString(t))}gt(e,t){return this.setLimit("min",e,!1,j.toString(t))}lte(e,t){return this.setLimit("max",e,!0,j.toString(t))}lt(e,t){return this.setLimit("max",e,!1,j.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:j.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:j.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:j.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:j.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:j.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:j.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};zt.create=r=>new zt({checks:[],typeName:z.ZodBigInt,coerce:r?.coerce??!1,...Z(r)});var Ut=class extends H{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==$.boolean){let n=this._getOrReturnCtx(e);return R(n,{code:x.invalid_type,expected:$.boolean,received:n.parsedType}),D}return fe(e.data)}};Ut.create=r=>new Ut({typeName:z.ZodBoolean,coerce:r?.coerce||!1,...Z(r)});var qt=class r extends H{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==$.date){let i=this._getOrReturnCtx(e);return R(i,{code:x.invalid_type,expected:$.date,received:i.parsedType}),D}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return R(i,{code:x.invalid_date}),D}let n=new le,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),R(s,{code:x.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),R(s,{code:x.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):W.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:j.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:j.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};qt.create=r=>new qt({checks:[],coerce:r?.coerce||!1,typeName:z.ZodDate,...Z(r)});var Dr=class extends H{_parse(e){if(this._getType(e)!==$.symbol){let n=this._getOrReturnCtx(e);return R(n,{code:x.invalid_type,expected:$.symbol,received:n.parsedType}),D}return fe(e.data)}};Dr.create=r=>new Dr({typeName:z.ZodSymbol,...Z(r)});var Bt=class extends H{_parse(e){if(this._getType(e)!==$.undefined){let n=this._getOrReturnCtx(e);return R(n,{code:x.invalid_type,expected:$.undefined,received:n.parsedType}),D}return fe(e.data)}};Bt.create=r=>new Bt({typeName:z.ZodUndefined,...Z(r)});var Ft=class extends H{_parse(e){if(this._getType(e)!==$.null){let n=this._getOrReturnCtx(e);return R(n,{code:x.invalid_type,expected:$.null,received:n.parsedType}),D}return fe(e.data)}};Ft.create=r=>new Ft({typeName:z.ZodNull,...Z(r)});var wt=class extends H{constructor(){super(...arguments),this._any=!0}_parse(e){return fe(e.data)}};wt.create=r=>new wt({typeName:z.ZodAny,...Z(r)});var st=class extends H{constructor(){super(...arguments),this._unknown=!0}_parse(e){return fe(e.data)}};st.create=r=>new st({typeName:z.ZodUnknown,...Z(r)});var ze=class extends H{_parse(e){let t=this._getOrReturnCtx(e);return R(t,{code:x.invalid_type,expected:$.never,received:t.parsedType}),D}};ze.create=r=>new ze({typeName:z.ZodNever,...Z(r)});var zr=class extends H{_parse(e){if(this._getType(e)!==$.undefined){let n=this._getOrReturnCtx(e);return R(n,{code:x.invalid_type,expected:$.void,received:n.parsedType}),D}return fe(e.data)}};zr.create=r=>new zr({typeName:z.ZodVoid,...Z(r)});var it=class r extends H{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==$.array)return R(t,{code:x.invalid_type,expected:$.array,received:t.parsedType}),D;if(s.exactLength!==null){let o=t.data.length>s.exactLength.value,a=t.data.length<s.exactLength.value;(o||a)&&(R(t,{code:o?x.too_big:x.too_small,minimum:a?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(R(t,{code:x.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(R(t,{code:x.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>s.type._parseAsync(new Re(t,o,t.path,a)))).then(o=>le.mergeArray(n,o));let i=[...t.data].map((o,a)=>s.type._parseSync(new Re(t,o,t.path,a)));return le.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:j.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:j.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:j.toString(t)}})}nonempty(e){return this.min(1,e)}};it.create=(r,e)=>new it({type:r,minLength:null,maxLength:null,exactLength:null,typeName:z.ZodArray,...Z(e)});function Lr(r){if(r instanceof be){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=Ae.create(Lr(n))}return new be({...r._def,shape:()=>e})}else return r instanceof it?new it({...r._def,type:Lr(r.element)}):r instanceof Ae?Ae.create(Lr(r.unwrap())):r instanceof Ge?Ge.create(Lr(r.unwrap())):r instanceof Ve?Ve.create(r.items.map(e=>Lr(e))):r}var be=class r extends H{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=W.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==$.object){let c=this._getOrReturnCtx(e);return R(c,{code:x.invalid_type,expected:$.object,received:c.parsedType}),D}let{status:n,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof ze&&this._def.unknownKeys==="strip"))for(let c in s.data)o.includes(c)||a.push(c);let l=[];for(let c of o){let d=i[c],p=s.data[c];l.push({key:{status:"valid",value:c},value:d._parse(new Re(s,p,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof ze){let c=this._def.unknownKeys;if(c==="passthrough")for(let d of a)l.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(c==="strict")a.length>0&&(R(s,{code:x.unrecognized_keys,keys:a}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let d of a){let p=s.data[d];l.push({key:{status:"valid",value:d},value:c._parse(new Re(s,p,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let c=[];for(let d of l){let p=await d.key,_=await d.value;c.push({key:p,value:_,alwaysSet:d.alwaysSet})}return c}).then(c=>le.mergeObjectSync(n,c)):le.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return j.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let s=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:j.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:z.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let n of W.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let n of W.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return Lr(this)}partial(e){let t={};for(let n of W.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let n of W.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof Ae;)i=i._def.innerType;t[n]=i}return new r({...this._def,shape:()=>t})}keyof(){return Oa(W.objectKeys(this.shape))}};be.create=(r,e)=>new be({shape:()=>r,unknownKeys:"strip",catchall:ze.create(),typeName:z.ZodObject,...Z(e)});be.strictCreate=(r,e)=>new be({shape:()=>r,unknownKeys:"strict",catchall:ze.create(),typeName:z.ZodObject,...Z(e)});be.lazycreate=(r,e)=>new be({shape:r,unknownKeys:"strip",catchall:ze.create(),typeName:z.ZodObject,...Z(e)});var Zt=class extends H{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function s(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return t.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(a=>new _e(a.ctx.common.issues));return R(t,{code:x.invalid_union,unionErrors:o}),D}if(t.common.async)return Promise.all(n.map(async i=>{let o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let l of n){let c={...t,common:{...t.common,issues:[]},parent:null},d=l._parseSync({data:t.data,path:t.path,parent:c});if(d.status==="valid")return d;d.status==="dirty"&&!i&&(i={result:d,ctx:c}),c.common.issues.length&&o.push(c.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let a=o.map(l=>new _e(l));return R(t,{code:x.invalid_union,unionErrors:a}),D}}get options(){return this._def.options}};Zt.create=(r,e)=>new Zt({options:r,typeName:z.ZodUnion,...Z(e)});var nt=r=>r instanceof Vt?nt(r.schema):r instanceof $e?nt(r.innerType()):r instanceof Gt?[r.value]:r instanceof Ht?r.options:r instanceof Wt?W.objectValues(r.enum):r instanceof Jt?nt(r._def.innerType):r instanceof Bt?[void 0]:r instanceof Ft?[null]:r instanceof Ae?[void 0,...nt(r.unwrap())]:r instanceof Ge?[null,...nt(r.unwrap())]:r instanceof Cn||r instanceof Xt?nt(r.unwrap()):r instanceof Yt?nt(r._def.innerType):[],us=class r extends H{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==$.object)return R(t,{code:x.invalid_type,expected:$.object,received:t.parsedType}),D;let n=this.discriminator,s=t.data[n],i=this.optionsMap.get(s);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(R(t,{code:x.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),D)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let s=new Map;for(let i of t){let o=nt(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 a of o){if(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,i)}}return new r({typeName:z.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...Z(n)})}};function $i(r,e){let t=Ke(r),n=Ke(e);if(r===e)return{valid:!0,data:r};if(t===$.object&&n===$.object){let s=W.objectKeys(e),i=W.objectKeys(r).filter(a=>s.indexOf(a)!==-1),o={...r,...e};for(let a of i){let l=$i(r[a],e[a]);if(!l.valid)return{valid:!1};o[a]=l.data}return{valid:!0,data:o}}else if(t===$.array&&n===$.array){if(r.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<r.length;i++){let o=r[i],a=e[i],l=$i(o,a);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return t===$.date&&n===$.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var Kt=class extends H{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=(i,o)=>{if(os(i)||os(o))return D;let a=$i(i.value,o.value);return a.valid?((as(i)||as(o))&&t.dirty(),{status:t.value,value:a.data}):(R(n,{code:x.invalid_intersection_types}),D)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Kt.create=(r,e,t)=>new Kt({left:r,right:e,typeName:z.ZodIntersection,...Z(t)});var Ve=class r extends H{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==$.array)return R(n,{code:x.invalid_type,expected:$.array,received:n.parsedType}),D;if(n.data.length<this._def.items.length)return R(n,{code:x.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),D;!this._def.rest&&n.data.length>this._def.items.length&&(R(n,{code:x.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...n.data].map((o,a)=>{let l=this._def.items[a]||this._def.rest;return l?l._parse(new Re(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(i).then(o=>le.mergeArray(t,o)):le.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};Ve.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ve({items:r,typeName:z.ZodTuple,rest:null,...Z(e)})};var ls=class r extends H{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==$.object)return R(n,{code:x.invalid_type,expected:$.object,received:n.parsedType}),D;let s=[],i=this._def.keyType,o=this._def.valueType;for(let a in n.data)s.push({key:i._parse(new Re(n,a,n.path,a)),value:o._parse(new Re(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?le.mergeObjectAsync(t,s):le.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof H?new r({keyType:e,valueType:t,typeName:z.ZodRecord,...Z(n)}):new r({keyType:bt.create(),valueType:e,typeName:z.ZodRecord,...Z(t)})}},Ur=class extends H{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==$.map)return R(n,{code:x.invalid_type,expected:$.map,received:n.parsedType}),D;let s=this._def.keyType,i=this._def.valueType,o=[...n.data.entries()].map(([a,l],c)=>({key:s._parse(new Re(n,a,n.path,[c,"key"])),value:i._parse(new Re(n,l,n.path,[c,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let l of o){let c=await l.key,d=await l.value;if(c.status==="aborted"||d.status==="aborted")return D;(c.status==="dirty"||d.status==="dirty")&&t.dirty(),a.set(c.value,d.value)}return{status:t.value,value:a}})}else{let a=new Map;for(let l of o){let c=l.key,d=l.value;if(c.status==="aborted"||d.status==="aborted")return D;(c.status==="dirty"||d.status==="dirty")&&t.dirty(),a.set(c.value,d.value)}return{status:t.value,value:a}}}};Ur.create=(r,e,t)=>new Ur({valueType:e,keyType:r,typeName:z.ZodMap,...Z(t)});var qr=class r extends H{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==$.set)return R(n,{code:x.invalid_type,expected:$.set,received:n.parsedType}),D;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(R(n,{code:x.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(R(n,{code:x.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let i=this._def.valueType;function o(l){let c=new Set;for(let d of l){if(d.status==="aborted")return D;d.status==="dirty"&&t.dirty(),c.add(d.value)}return{status:t.value,value:c}}let a=[...n.data.values()].map((l,c)=>i._parse(new Re(n,l,n.path,c)));return n.common.async?Promise.all(a).then(l=>o(l)):o(a)}min(e,t){return new r({...this._def,minSize:{value:e,message:j.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:j.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};qr.create=(r,e)=>new qr({valueType:r,minSize:null,maxSize:null,typeName:z.ZodSet,...Z(e)});var cs=class r extends H{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==$.function)return R(t,{code:x.invalid_type,expected:$.function,received:t.parsedType}),D;function n(a,l){return xn({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Nr(),rt].filter(c=>!!c),issueData:{code:x.invalid_arguments,argumentsError:l}})}function s(a,l){return xn({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Nr(),rt].filter(c=>!!c),issueData:{code:x.invalid_return_type,returnTypeError:l}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof kt){let a=this;return fe(async function(...l){let c=new _e([]),d=await a._def.args.parseAsync(l,i).catch(S=>{throw c.addIssue(n(l,S)),c}),p=await Reflect.apply(o,this,d);return await a._def.returns._def.type.parseAsync(p,i).catch(S=>{throw c.addIssue(s(p,S)),c})})}else{let a=this;return fe(function(...l){let c=a._def.args.safeParse(l,i);if(!c.success)throw new _e([n(l,c.error)]);let d=Reflect.apply(o,this,c.data),p=a._def.returns.safeParse(d,i);if(!p.success)throw new _e([s(d,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:Ve.create(e).rest(st.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||Ve.create([]).rest(st.create()),returns:t||st.create(),typeName:z.ZodFunction,...Z(n)})}},Vt=class extends H{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Vt.create=(r,e)=>new Vt({getter:r,typeName:z.ZodLazy,...Z(e)});var Gt=class extends H{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return R(t,{received:t.data,code:x.invalid_literal,expected:this._def.value}),D}return{status:"valid",value:e.data}}get value(){return this._def.value}};Gt.create=(r,e)=>new Gt({value:r,typeName:z.ZodLiteral,...Z(e)});function Oa(r,e){return new Ht({values:r,typeName:z.ZodEnum,...Z(e)})}var Ht=class r extends H{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return R(t,{expected:W.joinValues(n),received:t.parsedType,code:x.invalid_type}),D}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return R(t,{received:t.data,code:x.invalid_enum_value,options:n}),D}return fe(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};Ht.create=Oa;var Wt=class extends H{_parse(e){let t=W.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==$.string&&n.parsedType!==$.number){let s=W.objectValues(t);return R(n,{expected:W.joinValues(s),received:n.parsedType,code:x.invalid_type}),D}if(this._cache||(this._cache=new Set(W.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=W.objectValues(t);return R(n,{received:n.data,code:x.invalid_enum_value,options:s}),D}return fe(e.data)}get enum(){return this._def.values}};Wt.create=(r,e)=>new Wt({values:r,typeName:z.ZodNativeEnum,...Z(e)});var kt=class extends H{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==$.promise&&t.common.async===!1)return R(t,{code:x.invalid_type,expected:$.promise,received:t.parsedType}),D;let n=t.parsedType===$.promise?t.data:Promise.resolve(t.data);return fe(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};kt.create=(r,e)=>new kt({type:r,typeName:z.ZodPromise,...Z(e)});var $e=class extends H{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===z.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{R(n,o),o.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(n.data,i);if(n.common.async)return Promise.resolve(o).then(async a=>{if(t.value==="aborted")return D;let l=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return l.status==="aborted"?D:l.status==="dirty"?Lt(l.value):t.value==="dirty"?Lt(l.value):l});{if(t.value==="aborted")return D;let a=this._def.schema._parseSync({data:o,path:n.path,parent:n});return a.status==="aborted"?D:a.status==="dirty"?Lt(a.value):t.value==="dirty"?Lt(a.value):a}}if(s.type==="refinement"){let o=a=>{let l=s.refinement(a,i);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?D:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?D:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.value,value:a.value}))))}if(s.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!_t(o))return D;let a=s.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>_t(o)?Promise.resolve(s.transform(o.value,i)).then(a=>({status:t.value,value:a})):D);W.assertNever(s)}};$e.create=(r,e,t)=>new $e({schema:r,typeName:z.ZodEffects,effect:e,...Z(t)});$e.createWithPreprocess=(r,e,t)=>new $e({schema:e,effect:{type:"preprocess",transform:r},typeName:z.ZodEffects,...Z(t)});var Ae=class extends H{_parse(e){return this._getType(e)===$.undefined?fe(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ae.create=(r,e)=>new Ae({innerType:r,typeName:z.ZodOptional,...Z(e)});var Ge=class extends H{_parse(e){return this._getType(e)===$.null?fe(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ge.create=(r,e)=>new Ge({innerType:r,typeName:z.ZodNullable,...Z(e)});var Jt=class extends H{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===$.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Jt.create=(r,e)=>new Jt({innerType:r,typeName:z.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Z(e)});var Yt=class extends H{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Mr(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new _e(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new _e(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Yt.create=(r,e)=>new Yt({innerType:r,typeName:z.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Z(e)});var Br=class extends H{_parse(e){if(this._getType(e)!==$.nan){let n=this._getOrReturnCtx(e);return R(n,{code:x.invalid_type,expected:$.nan,received:n.parsedType}),D}return{status:"valid",value:e.data}}};Br.create=r=>new Br({typeName:z.ZodNaN,...Z(r)});var yh=Symbol("zod_brand"),Cn=class extends H{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},En=class r extends H{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?D:i.status==="dirty"?(t.dirty(),Lt(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?D:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:z.ZodPipeline})}},Xt=class extends H{_parse(e){let t=this._def.innerType._parse(e),n=s=>(_t(s)&&(s.value=Object.freeze(s.value)),s);return Mr(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}};Xt.create=(r,e)=>new Xt({innerType:r,typeName:z.ZodReadonly,...Z(e)});function Ra(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function Na(r,e={},t){return r?wt.create().superRefine((n,s)=>{let i=r(n);if(i instanceof Promise)return i.then(o=>{if(!o){let a=Ra(e,n),l=a.fatal??t??!0;s.addIssue({code:"custom",...a,fatal:l})}});if(!i){let o=Ra(e,n),a=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:a})}}):wt.create()}var vh={object:be.lazycreate},z;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(z||(z={}));var _h=(r,e={message:`Input not instance of ${r.name}`})=>Na(t=>t instanceof r,e),Ma=bt.create,La=Dt.create,bh=Br.create,wh=zt.create,Da=Ut.create,kh=qt.create,Sh=Dr.create,Th=Bt.create,xh=Ft.create,Ch=wt.create,Eh=st.create,Ih=ze.create,Ah=zr.create,Rh=it.create,$h=be.create,Ph=be.strictCreate,jh=Zt.create,Oh=us.create,Nh=Kt.create,Mh=Ve.create,Lh=ls.create,Dh=Ur.create,zh=qr.create,Uh=cs.create,qh=Vt.create,Bh=Gt.create,Fh=Ht.create,Zh=Wt.create,Kh=kt.create,Vh=$e.create,Gh=Ae.create,Hh=Ge.create,Wh=$e.createWithPreprocess,Jh=En.create,Yh=()=>Ma().optional(),Xh=()=>La().optional(),Qh=()=>Da().optional(),ef={string:(r=>bt.create({...r,coerce:!0})),number:(r=>Dt.create({...r,coerce:!0})),boolean:(r=>Ut.create({...r,coerce:!0})),bigint:(r=>zt.create({...r,coerce:!0})),date:(r=>qt.create({...r,coerce:!0}))};var tf=D;var za=w.object({baseUrl:w.string().url(),email:w.string().email(),apiToken:w.string().min(1)}),Pi=w.object({controlPlaneUrl:w.string().url(),runnerId:w.string().optional(),runnerToken:w.string().optional(),runnerName:w.string().default(ds.default.hostname()),jira:za.optional(),repos:w.record(w.object({path:w.string(),jira:za.optional(),github:w.object({token:w.string().min(1),login:w.string().optional()}).optional()})).default({}),github:w.object({token:w.string().min(1),login:w.string().optional()}).optional(),githubUsers:w.record(w.object({token:w.string().min(1),login:w.string().optional()})).default({}),deploy:w.object({enabled:w.boolean().default(!1)}).default({enabled:!1}),environments:w.record(w.object({secrets:w.record(w.string()).default({})})).default({}),claudeProfiles:w.record(w.object({configDir:w.string()})).default({}),claudeBin:w.string().default("claude"),agents:w.record(w.object({bin:w.string()})).default({}),jiraUsers:w.record(w.object({email:w.string().email(),apiToken:w.string().min(1)})).default({}),auditSchedules:w.array(w.object({repoName:w.string(),role:w.enum(["security","testing"]),intervalHours:w.number().int().min(6).max(720)})).default([]),pollIntervalSeconds:w.number().int().min(10).max(600).default(30)});function Q(){let r=process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR;if(r)return r;let e=hs.default.join(ds.default.homedir(),".config","allwright"),t=hs.default.join(ds.default.homedir(),".config","ticketpilot");return!ot.default.existsSync(e)&&ot.default.existsSync(t)?t:e}function St(){return hs.default.join(Q(),"runner.json")}function ce(){let r=St();if(!ot.default.existsSync(r))return null;let e=JSON.parse(ot.default.readFileSync(r,"utf8"));return Pi.parse(e)}function oe(r){let e=Q();ot.default.mkdirSync(e,{recursive:!0,mode:448});let t=St(),n=t+".tmp";ot.default.writeFileSync(n,JSON.stringify(r,null,2)+`
|
|
237
|
-
`,{mode:384}),ot.default.renameSync(n,t),ot.default.chmodSync(t,384)}function
|
|
238
|
-
`).filter(Boolean);for(let i of t)if(i.startsWith("/")||i.split("/").includes(".."))throw new Error(`refusing to import
|
|
236
|
+
`+t)}function Pr(r,e,t,n,s,i){if(r.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,Pr),r.emit("wsClientError",o,t,e)}else Qn(t,n,s,i)}});var Td={};ss(Td,{buildSetupReport:()=>ky,claudeLoggedIn:()=>xd});function xd(r=kd.default.homedir()){if(Nt.default.existsSync(jr.default.join(r,".claude",".credentials.json")))return!0;try{return!!JSON.parse(Nt.default.readFileSync(jr.default.join(r,".claude.json"),"utf8")).oauthAccount}catch{return!1}}async function ky(r,e){let t=!1,n="";if(rs&&Date.now()-rs.at<6e4)t=rs.installed,n=rs.version;else{try{let{stdout:o}=await wy(r.claudeBin,["--version"],{timeout:1e4});t=!0,n=o.trim().slice(0,60)}catch{t=!1}rs={at:Date.now(),installed:t,version:n}}let s=e.map(o=>{let a=r.repos[o];if(!a)return{repoName:o,mapped:!1,pathExists:!1,isGit:!1,claudeMd:!1,deployMd:!1,testMd:!1};let l=Nt.default.existsSync(a.path);return{repoName:o,mapped:!0,pathExists:l,isGit:l&&Nt.default.existsSync(jr.default.join(a.path,".git")),claudeMd:l&&Nt.default.existsSync(jr.default.join(a.path,"CLAUDE.md")),deployMd:l&&Nt.default.existsSync(jr.default.join(a.path,"DEPLOY.md")),testMd:l&&Nt.default.existsSync(jr.default.join(a.path,"TEST.md"))}}),i=Object.values(r.repos).find(o=>o.github?.token);return{jiraConfigured:!!r.jira,jiraEmail:r.jira?.email??"",claude:{installed:t,version:n,loggedIn:xd()},githubTokenSet:!!(r.github?.token||i),githubLogin:r.github?.login??i?.github?.login??"",deploysEnabled:r.deploy.enabled,jiraUserCount:Object.keys(r.jiraUsers).length,repos:s}}var wd,Nt,kd,jr,Sd,wy,rs,Cd=yi(()=>{"use strict";wd=require("node:child_process"),Nt=$(require("node:fs"),1),kd=$(require("node:os"),1),jr=$(require("node:path"),1),Sd=require("node:util"),wy=(0,Sd.promisify)(wd.execFile);rs=null});var yt=$(require("node:fs"),1),Ed=$(require("node:os"),1),Sn=$(require("node:path"),1),Mt=require("node:child_process"),mi=require("node:crypto"),Or=$(require("node:readline/promises"),1);var Ia=$(Ea(),1),{program:Py,createCommand:jy,createArgument:Oy,createOption:Ny,CommanderError:My,InvalidArgumentError:zy,InvalidOptionArgumentError:Ly,Command:Aa,Argument:Dy,Option:Uy,Help:qy}=Ia.default;var ot=$(require("node:fs"),1),hs=$(require("node:os"),1),fs=$(require("node:path"),1);var k={};ss(k,{BRAND:()=>wh,DIRTY:()=>zt,EMPTY_PATH:()=>Qd,INVALID:()=>L,NEVER:()=>of,OK:()=>fe,ParseStatus:()=>le,Schema:()=>H,ZodAny:()=>wt,ZodArray:()=>it,ZodBigInt:()=>Dt,ZodBoolean:()=>Ut,ZodBranded:()=>En,ZodCatch:()=>Yt,ZodDate:()=>qt,ZodDefault:()=>Jt,ZodDiscriminatedUnion:()=>ls,ZodEffects:()=>$e,ZodEnum:()=>Ht,ZodError:()=>_e,ZodFirstPartyTypeKind:()=>D,ZodFunction:()=>ds,ZodIntersection:()=>Kt,ZodIssueCode:()=>T,ZodLazy:()=>Vt,ZodLiteral:()=>Gt,ZodMap:()=>Ur,ZodNaN:()=>Fr,ZodNativeEnum:()=>Wt,ZodNever:()=>De,ZodNull:()=>Bt,ZodNullable:()=>Ge,ZodNumber:()=>Lt,ZodObject:()=>be,ZodOptional:()=>Ae,ZodParsedType:()=>P,ZodPipeline:()=>In,ZodPromise:()=>kt,ZodReadonly:()=>Xt,ZodRecord:()=>cs,ZodSchema:()=>H,ZodSet:()=>qr,ZodString:()=>bt,ZodSymbol:()=>Lr,ZodTransformer:()=>$e,ZodTuple:()=>Ve,ZodType:()=>H,ZodUndefined:()=>Ft,ZodUnion:()=>Zt,ZodUnknown:()=>st,ZodVoid:()=>Dr,addIssueToContext:()=>R,any:()=>Rh,array:()=>Oh,bigint:()=>Th,boolean:()=>Ua,coerce:()=>sf,custom:()=>za,date:()=>Ch,datetimeRegex:()=>Na,defaultErrorMap:()=>rt,discriminatedUnion:()=>Lh,effect:()=>Jh,enum:()=>Gh,function:()=>Zh,getErrorMap:()=>Nr,getParsedType:()=>Ke,instanceof:()=>Sh,intersection:()=>Dh,isAborted:()=>as,isAsync:()=>Mr,isDirty:()=>us,isValid:()=>_t,late:()=>kh,lazy:()=>Kh,literal:()=>Vh,makeIssue:()=>Cn,map:()=>Fh,nan:()=>xh,nativeEnum:()=>Hh,never:()=>Ph,null:()=>Ah,nullable:()=>Xh,number:()=>Da,object:()=>Nh,objectUtil:()=>ji,oboolean:()=>nf,onumber:()=>rf,optional:()=>Yh,ostring:()=>tf,pipeline:()=>ef,preprocess:()=>Qh,promise:()=>Wh,quotelessJson:()=>Jd,record:()=>qh,set:()=>Bh,setErrorMap:()=>Xd,strictObject:()=>Mh,string:()=>La,symbol:()=>Eh,transformer:()=>Jh,tuple:()=>Uh,undefined:()=>Ih,union:()=>zh,unknown:()=>$h,util:()=>W,void:()=>jh});var W;(function(r){r.assertEqual=s=>{};function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},r.getValidEnumValues=s=>{let i=r.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),o={};for(let a of i)o[a]=s[a];return r.objectValues(o)},r.objectValues=s=>r.objectKeys(s).map(function(i){return s[i]}),r.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},r.find=(s,i)=>{for(let o of s)if(i(o))return o},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}r.joinValues=n,r.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(W||(W={}));var ji;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(ji||(ji={}));var P=W.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ke=r=>{switch(typeof r){case"undefined":return P.undefined;case"string":return P.string;case"number":return Number.isNaN(r)?P.nan:P.number;case"boolean":return P.boolean;case"function":return P.function;case"bigint":return P.bigint;case"symbol":return P.symbol;case"object":return Array.isArray(r)?P.array:r===null?P.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?P.promise:typeof Map<"u"&&r instanceof Map?P.map:typeof Set<"u"&&r instanceof Set?P.set:typeof Date<"u"&&r instanceof Date?P.date:P.object;default:return P.unknown}};var T=W.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"]),Jd=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),_e=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},n={_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)n._errors.push(t(o));else{let a=n,l=0;for(;l<o.path.length;){let c=o.path[l];l===o.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(t(o))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return s(this),n}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,W.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},n=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];t[i]=t[i]||[],t[i].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};_e.create=r=>new _e(r);var Yd=(r,e)=>{let t;switch(r.code){case T.invalid_type:r.received===P.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case T.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,W.jsonStringifyReplacer)}`;break;case T.unrecognized_keys:t=`Unrecognized key(s) in object: ${W.joinValues(r.keys,", ")}`;break;case T.invalid_union:t="Invalid input";break;case T.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${W.joinValues(r.options)}`;break;case T.invalid_enum_value:t=`Invalid enum value. Expected ${W.joinValues(r.options)}, received '${r.received}'`;break;case T.invalid_arguments:t="Invalid function arguments";break;case T.invalid_return_type:t="Invalid function return type";break;case T.invalid_date:t="Invalid date";break;case T.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:W.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case T.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case T.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case T.custom:t="Invalid input";break;case T.invalid_intersection_types:t="Intersection results could not be merged";break;case T.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case T.not_finite:t="Number must be finite";break;default:t=e.defaultError,W.assertNever(r)}return{message:t}},rt=Yd;var Ra=rt;function Xd(r){Ra=r}function Nr(){return Ra}var Cn=r=>{let{data:e,path:t,errorMaps:n,issueData:s}=r,i=[...t,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let a="",l=n.filter(c=>!!c).slice().reverse();for(let c of l)a=c(o,{data:e,defaultError:a}).message;return{...s,path:i,message:a}},Qd=[];function R(r,e){let t=Nr(),n=Cn({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===rt?void 0:rt].filter(s=>!!s)});r.common.issues.push(n)}var le=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let s of t){if(s.status==="aborted")return L;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let s of t){let i=await s.key,o=await s.value;n.push({key:i,value:o})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let s of t){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return L;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(n[i.value]=o.value)}return{status:e.value,value:n}}},L=Object.freeze({status:"aborted"}),zt=r=>({status:"dirty",value:r}),fe=r=>({status:"valid",value:r}),as=r=>r.status==="aborted",us=r=>r.status==="dirty",_t=r=>r.status==="valid",Mr=r=>typeof Promise<"u"&&r instanceof Promise;var j;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(j||(j={}));var Re=class{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,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}},$a=(r,e)=>{if(_t(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new _e(r.common.issues);return this._error=t,this._error}}};function Z(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))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,a)=>{let{message:l}=r;return o.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??n??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:l??t??a.defaultError}},description:s}}var H=class{get description(){return this._def.description}_getType(e){return Ke(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Ke(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new le,ctx:{common:e.parent.common,data:e.data,parsedType:Ke(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Mr(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ke(e)},s=this._parseSync({data:e,path:n.path,parent:n});return $a(n,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ke(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return _t(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>_t(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ke(e)},s=this._parse({data:e,path:n.path,parent:n}),i=await(Mr(s)?s:Promise.resolve(s));return $a(n,i)}refine(e,t){let n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,i)=>{let o=e(s),a=()=>i.addIssue({code:T.custom,...n(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new $e({schema:this,typeName:D.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return Ae.create(this,this._def)}nullable(){return Ge.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return it.create(this)}promise(){return kt.create(this,this._def)}or(e){return Zt.create([this,e],this._def)}and(e){return Kt.create(this,e,this._def)}transform(e){return new $e({...Z(this._def),schema:this,typeName:D.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Jt({...Z(this._def),innerType:this,defaultValue:t,typeName:D.ZodDefault})}brand(){return new En({typeName:D.ZodBranded,type:this,...Z(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Yt({...Z(this._def),innerType:this,catchValue:t,typeName:D.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return In.create(this,e)}readonly(){return Xt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},eh=/^c[^\s-]{8,}$/i,th=/^[0-9a-z]+$/,rh=/^[0-9A-HJKMNP-TV-Z]{26}$/i,nh=/^[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,sh=/^[a-z0-9_-]{21}$/i,ih=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,oh=/^[-+]?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)?)??$/,ah=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,uh="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Oi,lh=/^(?:(?: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])$/,ch=/^(?:(?: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])$/,dh=/^(([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]))$/,hh=/^(([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])$/,fh=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ph=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ja="((\\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])))",mh=new RegExp(`^${ja}$`);function Oa(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function gh(r){return new RegExp(`^${Oa(r)}$`)}function Na(r){let e=`${ja}T${Oa(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function yh(r,e){return!!((e==="v4"||!e)&&lh.test(r)||(e==="v6"||!e)&&dh.test(r))}function vh(r,e){if(!ih.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function _h(r,e){return!!((e==="v4"||!e)&&ch.test(r)||(e==="v6"||!e)&&hh.test(r))}var bt=class r extends H{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==P.string){let i=this._getOrReturnCtx(e);return R(i,{code:T.invalid_type,expected:P.string,received:i.parsedType}),L}let n=new le,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),R(s,{code:T.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),R(s,{code:T.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(s=this._getOrReturnCtx(e,s),o?R(s,{code:T.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&R(s,{code:T.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")ah.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"email",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")Oi||(Oi=new RegExp(uh,"u")),Oi.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"emoji",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")nh.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"uuid",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")sh.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"nanoid",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")eh.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"cuid",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")th.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"cuid2",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")rh.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"ulid",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),R(s,{validation:"url",code:T.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"regex",code:T.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),R(s,{code:T.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.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),R(s,{code:T.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),R(s,{code:T.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?Na(i).test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{code:T.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?mh.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{code:T.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?gh(i).test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{code:T.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?oh.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"duration",code:T.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?yh(e.data,i.version)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"ip",code:T.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?vh(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"jwt",code:T.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?_h(e.data,i.version)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"cidr",code:T.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?fh.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"base64",code:T.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?ph.test(e.data)||(s=this._getOrReturnCtx(e,s),R(s,{validation:"base64url",code:T.invalid_string,message:i.message}),n.dirty()):W.assertNever(i);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:T.invalid_string,...j.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...j.errToObj(e)})}url(e){return this._addCheck({kind:"url",...j.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...j.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...j.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...j.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...j.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...j.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...j.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...j.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...j.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...j.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...j.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...j.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,...j.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,...j.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...j.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...j.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...j.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...j.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...j.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...j.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...j.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...j.errToObj(t)})}nonempty(e){return this.min(1,j.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};bt.create=r=>new bt({checks:[],typeName:D.ZodString,coerce:r?.coerce??!1,...Z(r)});function bh(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,i=Number.parseInt(r.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var Lt=class r extends H{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==P.number){let i=this._getOrReturnCtx(e);return R(i,{code:T.invalid_type,expected:P.number,received:i.parsedType}),L}let n,s=new le;for(let i of this._def.checks)i.kind==="int"?W.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),R(n,{code:T.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),R(n,{code:T.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)&&(n=this._getOrReturnCtx(e,n),R(n,{code:T.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?bh(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),R(n,{code:T.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),R(n,{code:T.not_finite,message:i.message}),s.dirty()):W.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,j.toString(t))}gt(e,t){return this.setLimit("min",e,!1,j.toString(t))}lte(e,t){return this.setLimit("max",e,!0,j.toString(t))}lt(e,t){return this.setLimit("max",e,!1,j.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:j.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:j.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:j.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:j.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:j.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:j.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:j.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:j.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:j.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:j.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&W.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};Lt.create=r=>new Lt({checks:[],typeName:D.ZodNumber,coerce:r?.coerce||!1,...Z(r)});var Dt=class r extends H{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==P.bigint)return this._getInvalidInput(e);let n,s=new le;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),R(n,{code:T.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)&&(n=this._getOrReturnCtx(e,n),R(n,{code:T.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),R(n,{code:T.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):W.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return R(t,{code:T.invalid_type,expected:P.bigint,received:t.parsedType}),L}gte(e,t){return this.setLimit("min",e,!0,j.toString(t))}gt(e,t){return this.setLimit("min",e,!1,j.toString(t))}lte(e,t){return this.setLimit("max",e,!0,j.toString(t))}lt(e,t){return this.setLimit("max",e,!1,j.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:j.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:j.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:j.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:j.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:j.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:j.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Dt.create=r=>new Dt({checks:[],typeName:D.ZodBigInt,coerce:r?.coerce??!1,...Z(r)});var Ut=class extends H{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==P.boolean){let n=this._getOrReturnCtx(e);return R(n,{code:T.invalid_type,expected:P.boolean,received:n.parsedType}),L}return fe(e.data)}};Ut.create=r=>new Ut({typeName:D.ZodBoolean,coerce:r?.coerce||!1,...Z(r)});var qt=class r extends H{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==P.date){let i=this._getOrReturnCtx(e);return R(i,{code:T.invalid_type,expected:P.date,received:i.parsedType}),L}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return R(i,{code:T.invalid_date}),L}let n=new le,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),R(s,{code:T.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),R(s,{code:T.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):W.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:j.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:j.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};qt.create=r=>new qt({checks:[],coerce:r?.coerce||!1,typeName:D.ZodDate,...Z(r)});var Lr=class extends H{_parse(e){if(this._getType(e)!==P.symbol){let n=this._getOrReturnCtx(e);return R(n,{code:T.invalid_type,expected:P.symbol,received:n.parsedType}),L}return fe(e.data)}};Lr.create=r=>new Lr({typeName:D.ZodSymbol,...Z(r)});var Ft=class extends H{_parse(e){if(this._getType(e)!==P.undefined){let n=this._getOrReturnCtx(e);return R(n,{code:T.invalid_type,expected:P.undefined,received:n.parsedType}),L}return fe(e.data)}};Ft.create=r=>new Ft({typeName:D.ZodUndefined,...Z(r)});var Bt=class extends H{_parse(e){if(this._getType(e)!==P.null){let n=this._getOrReturnCtx(e);return R(n,{code:T.invalid_type,expected:P.null,received:n.parsedType}),L}return fe(e.data)}};Bt.create=r=>new Bt({typeName:D.ZodNull,...Z(r)});var wt=class extends H{constructor(){super(...arguments),this._any=!0}_parse(e){return fe(e.data)}};wt.create=r=>new wt({typeName:D.ZodAny,...Z(r)});var st=class extends H{constructor(){super(...arguments),this._unknown=!0}_parse(e){return fe(e.data)}};st.create=r=>new st({typeName:D.ZodUnknown,...Z(r)});var De=class extends H{_parse(e){let t=this._getOrReturnCtx(e);return R(t,{code:T.invalid_type,expected:P.never,received:t.parsedType}),L}};De.create=r=>new De({typeName:D.ZodNever,...Z(r)});var Dr=class extends H{_parse(e){if(this._getType(e)!==P.undefined){let n=this._getOrReturnCtx(e);return R(n,{code:T.invalid_type,expected:P.void,received:n.parsedType}),L}return fe(e.data)}};Dr.create=r=>new Dr({typeName:D.ZodVoid,...Z(r)});var it=class r extends H{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==P.array)return R(t,{code:T.invalid_type,expected:P.array,received:t.parsedType}),L;if(s.exactLength!==null){let o=t.data.length>s.exactLength.value,a=t.data.length<s.exactLength.value;(o||a)&&(R(t,{code:o?T.too_big:T.too_small,minimum:a?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(R(t,{code:T.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(R(t,{code:T.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>s.type._parseAsync(new Re(t,o,t.path,a)))).then(o=>le.mergeArray(n,o));let i=[...t.data].map((o,a)=>s.type._parseSync(new Re(t,o,t.path,a)));return le.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:j.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:j.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:j.toString(t)}})}nonempty(e){return this.min(1,e)}};it.create=(r,e)=>new it({type:r,minLength:null,maxLength:null,exactLength:null,typeName:D.ZodArray,...Z(e)});function zr(r){if(r instanceof be){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=Ae.create(zr(n))}return new be({...r._def,shape:()=>e})}else return r instanceof it?new it({...r._def,type:zr(r.element)}):r instanceof Ae?Ae.create(zr(r.unwrap())):r instanceof Ge?Ge.create(zr(r.unwrap())):r instanceof Ve?Ve.create(r.items.map(e=>zr(e))):r}var be=class r extends H{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=W.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==P.object){let c=this._getOrReturnCtx(e);return R(c,{code:T.invalid_type,expected:P.object,received:c.parsedType}),L}let{status:n,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof De&&this._def.unknownKeys==="strip"))for(let c in s.data)o.includes(c)||a.push(c);let l=[];for(let c of o){let h=i[c],p=s.data[c];l.push({key:{status:"valid",value:c},value:h._parse(new Re(s,p,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof De){let c=this._def.unknownKeys;if(c==="passthrough")for(let h of a)l.push({key:{status:"valid",value:h},value:{status:"valid",value:s.data[h]}});else if(c==="strict")a.length>0&&(R(s,{code:T.unrecognized_keys,keys:a}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let h of a){let p=s.data[h];l.push({key:{status:"valid",value:h},value:c._parse(new Re(s,p,s.path,h)),alwaysSet:h in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let c=[];for(let h of l){let p=await h.key,_=await h.value;c.push({key:p,value:_,alwaysSet:h.alwaysSet})}return c}).then(c=>le.mergeObjectSync(n,c)):le.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return j.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let s=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:j.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:D.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let n of W.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let n of W.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return zr(this)}partial(e){let t={};for(let n of W.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let n of W.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof Ae;)i=i._def.innerType;t[n]=i}return new r({...this._def,shape:()=>t})}keyof(){return Ma(W.objectKeys(this.shape))}};be.create=(r,e)=>new be({shape:()=>r,unknownKeys:"strip",catchall:De.create(),typeName:D.ZodObject,...Z(e)});be.strictCreate=(r,e)=>new be({shape:()=>r,unknownKeys:"strict",catchall:De.create(),typeName:D.ZodObject,...Z(e)});be.lazycreate=(r,e)=>new be({shape:r,unknownKeys:"strip",catchall:De.create(),typeName:D.ZodObject,...Z(e)});var Zt=class extends H{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function s(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return t.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(a=>new _e(a.ctx.common.issues));return R(t,{code:T.invalid_union,unionErrors:o}),L}if(t.common.async)return Promise.all(n.map(async i=>{let o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let l of n){let c={...t,common:{...t.common,issues:[]},parent:null},h=l._parseSync({data:t.data,path:t.path,parent:c});if(h.status==="valid")return h;h.status==="dirty"&&!i&&(i={result:h,ctx:c}),c.common.issues.length&&o.push(c.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let a=o.map(l=>new _e(l));return R(t,{code:T.invalid_union,unionErrors:a}),L}}get options(){return this._def.options}};Zt.create=(r,e)=>new Zt({options:r,typeName:D.ZodUnion,...Z(e)});var nt=r=>r instanceof Vt?nt(r.schema):r instanceof $e?nt(r.innerType()):r instanceof Gt?[r.value]:r instanceof Ht?r.options:r instanceof Wt?W.objectValues(r.enum):r instanceof Jt?nt(r._def.innerType):r instanceof Ft?[void 0]:r instanceof Bt?[null]:r instanceof Ae?[void 0,...nt(r.unwrap())]:r instanceof Ge?[null,...nt(r.unwrap())]:r instanceof En||r instanceof Xt?nt(r.unwrap()):r instanceof Yt?nt(r._def.innerType):[],ls=class r extends H{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==P.object)return R(t,{code:T.invalid_type,expected:P.object,received:t.parsedType}),L;let n=this.discriminator,s=t.data[n],i=this.optionsMap.get(s);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(R(t,{code:T.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),L)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let s=new Map;for(let i of t){let o=nt(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 a of o){if(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,i)}}return new r({typeName:D.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...Z(n)})}};function Ni(r,e){let t=Ke(r),n=Ke(e);if(r===e)return{valid:!0,data:r};if(t===P.object&&n===P.object){let s=W.objectKeys(e),i=W.objectKeys(r).filter(a=>s.indexOf(a)!==-1),o={...r,...e};for(let a of i){let l=Ni(r[a],e[a]);if(!l.valid)return{valid:!1};o[a]=l.data}return{valid:!0,data:o}}else if(t===P.array&&n===P.array){if(r.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<r.length;i++){let o=r[i],a=e[i],l=Ni(o,a);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return t===P.date&&n===P.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var Kt=class extends H{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=(i,o)=>{if(as(i)||as(o))return L;let a=Ni(i.value,o.value);return a.valid?((us(i)||us(o))&&t.dirty(),{status:t.value,value:a.data}):(R(n,{code:T.invalid_intersection_types}),L)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Kt.create=(r,e,t)=>new Kt({left:r,right:e,typeName:D.ZodIntersection,...Z(t)});var Ve=class r extends H{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==P.array)return R(n,{code:T.invalid_type,expected:P.array,received:n.parsedType}),L;if(n.data.length<this._def.items.length)return R(n,{code:T.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),L;!this._def.rest&&n.data.length>this._def.items.length&&(R(n,{code:T.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...n.data].map((o,a)=>{let l=this._def.items[a]||this._def.rest;return l?l._parse(new Re(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(i).then(o=>le.mergeArray(t,o)):le.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};Ve.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ve({items:r,typeName:D.ZodTuple,rest:null,...Z(e)})};var cs=class r extends H{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==P.object)return R(n,{code:T.invalid_type,expected:P.object,received:n.parsedType}),L;let s=[],i=this._def.keyType,o=this._def.valueType;for(let a in n.data)s.push({key:i._parse(new Re(n,a,n.path,a)),value:o._parse(new Re(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?le.mergeObjectAsync(t,s):le.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof H?new r({keyType:e,valueType:t,typeName:D.ZodRecord,...Z(n)}):new r({keyType:bt.create(),valueType:e,typeName:D.ZodRecord,...Z(t)})}},Ur=class extends H{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==P.map)return R(n,{code:T.invalid_type,expected:P.map,received:n.parsedType}),L;let s=this._def.keyType,i=this._def.valueType,o=[...n.data.entries()].map(([a,l],c)=>({key:s._parse(new Re(n,a,n.path,[c,"key"])),value:i._parse(new Re(n,l,n.path,[c,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let l of o){let c=await l.key,h=await l.value;if(c.status==="aborted"||h.status==="aborted")return L;(c.status==="dirty"||h.status==="dirty")&&t.dirty(),a.set(c.value,h.value)}return{status:t.value,value:a}})}else{let a=new Map;for(let l of o){let c=l.key,h=l.value;if(c.status==="aborted"||h.status==="aborted")return L;(c.status==="dirty"||h.status==="dirty")&&t.dirty(),a.set(c.value,h.value)}return{status:t.value,value:a}}}};Ur.create=(r,e,t)=>new Ur({valueType:e,keyType:r,typeName:D.ZodMap,...Z(t)});var qr=class r extends H{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==P.set)return R(n,{code:T.invalid_type,expected:P.set,received:n.parsedType}),L;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(R(n,{code:T.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(R(n,{code:T.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let i=this._def.valueType;function o(l){let c=new Set;for(let h of l){if(h.status==="aborted")return L;h.status==="dirty"&&t.dirty(),c.add(h.value)}return{status:t.value,value:c}}let a=[...n.data.values()].map((l,c)=>i._parse(new Re(n,l,n.path,c)));return n.common.async?Promise.all(a).then(l=>o(l)):o(a)}min(e,t){return new r({...this._def,minSize:{value:e,message:j.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:j.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};qr.create=(r,e)=>new qr({valueType:r,minSize:null,maxSize:null,typeName:D.ZodSet,...Z(e)});var ds=class r extends H{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==P.function)return R(t,{code:T.invalid_type,expected:P.function,received:t.parsedType}),L;function n(a,l){return Cn({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Nr(),rt].filter(c=>!!c),issueData:{code:T.invalid_arguments,argumentsError:l}})}function s(a,l){return Cn({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Nr(),rt].filter(c=>!!c),issueData:{code:T.invalid_return_type,returnTypeError:l}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof kt){let a=this;return fe(async function(...l){let c=new _e([]),h=await a._def.args.parseAsync(l,i).catch(b=>{throw c.addIssue(n(l,b)),c}),p=await Reflect.apply(o,this,h);return await a._def.returns._def.type.parseAsync(p,i).catch(b=>{throw c.addIssue(s(p,b)),c})})}else{let a=this;return fe(function(...l){let c=a._def.args.safeParse(l,i);if(!c.success)throw new _e([n(l,c.error)]);let h=Reflect.apply(o,this,c.data),p=a._def.returns.safeParse(h,i);if(!p.success)throw new _e([s(h,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:Ve.create(e).rest(st.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||Ve.create([]).rest(st.create()),returns:t||st.create(),typeName:D.ZodFunction,...Z(n)})}},Vt=class extends H{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Vt.create=(r,e)=>new Vt({getter:r,typeName:D.ZodLazy,...Z(e)});var Gt=class extends H{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return R(t,{received:t.data,code:T.invalid_literal,expected:this._def.value}),L}return{status:"valid",value:e.data}}get value(){return this._def.value}};Gt.create=(r,e)=>new Gt({value:r,typeName:D.ZodLiteral,...Z(e)});function Ma(r,e){return new Ht({values:r,typeName:D.ZodEnum,...Z(e)})}var Ht=class r extends H{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return R(t,{expected:W.joinValues(n),received:t.parsedType,code:T.invalid_type}),L}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return R(t,{received:t.data,code:T.invalid_enum_value,options:n}),L}return fe(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};Ht.create=Ma;var Wt=class extends H{_parse(e){let t=W.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==P.string&&n.parsedType!==P.number){let s=W.objectValues(t);return R(n,{expected:W.joinValues(s),received:n.parsedType,code:T.invalid_type}),L}if(this._cache||(this._cache=new Set(W.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=W.objectValues(t);return R(n,{received:n.data,code:T.invalid_enum_value,options:s}),L}return fe(e.data)}get enum(){return this._def.values}};Wt.create=(r,e)=>new Wt({values:r,typeName:D.ZodNativeEnum,...Z(e)});var kt=class extends H{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==P.promise&&t.common.async===!1)return R(t,{code:T.invalid_type,expected:P.promise,received:t.parsedType}),L;let n=t.parsedType===P.promise?t.data:Promise.resolve(t.data);return fe(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};kt.create=(r,e)=>new kt({type:r,typeName:D.ZodPromise,...Z(e)});var $e=class extends H{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===D.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{R(n,o),o.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(n.data,i);if(n.common.async)return Promise.resolve(o).then(async a=>{if(t.value==="aborted")return L;let l=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return l.status==="aborted"?L:l.status==="dirty"?zt(l.value):t.value==="dirty"?zt(l.value):l});{if(t.value==="aborted")return L;let a=this._def.schema._parseSync({data:o,path:n.path,parent:n});return a.status==="aborted"?L:a.status==="dirty"?zt(a.value):t.value==="dirty"?zt(a.value):a}}if(s.type==="refinement"){let o=a=>{let l=s.refinement(a,i);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?L:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?L:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.value,value:a.value}))))}if(s.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!_t(o))return L;let a=s.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>_t(o)?Promise.resolve(s.transform(o.value,i)).then(a=>({status:t.value,value:a})):L);W.assertNever(s)}};$e.create=(r,e,t)=>new $e({schema:r,typeName:D.ZodEffects,effect:e,...Z(t)});$e.createWithPreprocess=(r,e,t)=>new $e({schema:e,effect:{type:"preprocess",transform:r},typeName:D.ZodEffects,...Z(t)});var Ae=class extends H{_parse(e){return this._getType(e)===P.undefined?fe(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ae.create=(r,e)=>new Ae({innerType:r,typeName:D.ZodOptional,...Z(e)});var Ge=class extends H{_parse(e){return this._getType(e)===P.null?fe(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ge.create=(r,e)=>new Ge({innerType:r,typeName:D.ZodNullable,...Z(e)});var Jt=class extends H{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===P.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Jt.create=(r,e)=>new Jt({innerType:r,typeName:D.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Z(e)});var Yt=class extends H{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Mr(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new _e(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new _e(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Yt.create=(r,e)=>new Yt({innerType:r,typeName:D.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Z(e)});var Fr=class extends H{_parse(e){if(this._getType(e)!==P.nan){let n=this._getOrReturnCtx(e);return R(n,{code:T.invalid_type,expected:P.nan,received:n.parsedType}),L}return{status:"valid",value:e.data}}};Fr.create=r=>new Fr({typeName:D.ZodNaN,...Z(r)});var wh=Symbol("zod_brand"),En=class extends H{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},In=class r extends H{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?L:i.status==="dirty"?(t.dirty(),zt(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?L:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:D.ZodPipeline})}},Xt=class extends H{_parse(e){let t=this._def.innerType._parse(e),n=s=>(_t(s)&&(s.value=Object.freeze(s.value)),s);return Mr(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}};Xt.create=(r,e)=>new Xt({innerType:r,typeName:D.ZodReadonly,...Z(e)});function Pa(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function za(r,e={},t){return r?wt.create().superRefine((n,s)=>{let i=r(n);if(i instanceof Promise)return i.then(o=>{if(!o){let a=Pa(e,n),l=a.fatal??t??!0;s.addIssue({code:"custom",...a,fatal:l})}});if(!i){let o=Pa(e,n),a=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:a})}}):wt.create()}var kh={object:be.lazycreate},D;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(D||(D={}));var Sh=(r,e={message:`Input not instance of ${r.name}`})=>za(t=>t instanceof r,e),La=bt.create,Da=Lt.create,xh=Fr.create,Th=Dt.create,Ua=Ut.create,Ch=qt.create,Eh=Lr.create,Ih=Ft.create,Ah=Bt.create,Rh=wt.create,$h=st.create,Ph=De.create,jh=Dr.create,Oh=it.create,Nh=be.create,Mh=be.strictCreate,zh=Zt.create,Lh=ls.create,Dh=Kt.create,Uh=Ve.create,qh=cs.create,Fh=Ur.create,Bh=qr.create,Zh=ds.create,Kh=Vt.create,Vh=Gt.create,Gh=Ht.create,Hh=Wt.create,Wh=kt.create,Jh=$e.create,Yh=Ae.create,Xh=Ge.create,Qh=$e.createWithPreprocess,ef=In.create,tf=()=>La().optional(),rf=()=>Da().optional(),nf=()=>Ua().optional(),sf={string:(r=>bt.create({...r,coerce:!0})),number:(r=>Lt.create({...r,coerce:!0})),boolean:(r=>Ut.create({...r,coerce:!0})),bigint:(r=>Dt.create({...r,coerce:!0})),date:(r=>qt.create({...r,coerce:!0}))};var of=L;var qa=k.object({baseUrl:k.string().url(),email:k.string().email(),apiToken:k.string().min(1)}),Mi=k.object({controlPlaneUrl:k.string().url(),runnerId:k.string().optional(),runnerToken:k.string().optional(),runnerName:k.string().default(hs.default.hostname()),jira:qa.optional(),repos:k.record(k.object({path:k.string(),jira:qa.optional(),github:k.object({token:k.string().min(1),login:k.string().optional()}).optional()})).default({}),github:k.object({token:k.string().min(1),login:k.string().optional()}).optional(),githubUsers:k.record(k.object({token:k.string().min(1),login:k.string().optional()})).default({}),deploy:k.object({enabled:k.boolean().default(!1)}).default({enabled:!1}),environments:k.record(k.object({secrets:k.record(k.string()).default({})})).default({}),claudeProfiles:k.record(k.object({configDir:k.string()})).default({}),claudeBin:k.string().default("claude"),agents:k.record(k.object({bin:k.string()})).default({}),jiraUsers:k.record(k.object({email:k.string().email(),apiToken:k.string().min(1)})).default({}),auditSchedules:k.array(k.object({repoName:k.string(),role:k.enum(["security","testing"]),intervalHours:k.number().int().min(6).max(720)})).default([]),pollIntervalSeconds:k.number().int().min(10).max(600).default(30)});function Q(){let r=process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR;if(r)return r;let e=fs.default.join(hs.default.homedir(),".config","allwright"),t=fs.default.join(hs.default.homedir(),".config","ticketpilot");return!ot.default.existsSync(e)&&ot.default.existsSync(t)?t:e}function St(){return fs.default.join(Q(),"runner.json")}function ce(){let r=St();if(!ot.default.existsSync(r))return null;let e=JSON.parse(ot.default.readFileSync(r,"utf8"));return Mi.parse(e)}function oe(r){let e=Q();ot.default.mkdirSync(e,{recursive:!0,mode:448});let t=St(),n=t+".tmp";ot.default.writeFileSync(n,JSON.stringify(r,null,2)+`
|
|
237
|
+
`,{mode:384}),ot.default.renameSync(n,t),ot.default.chmodSync(t,384)}function ps(r,e){return`${r}:${e}`}function Qt(r,e,t){return r.environments[ps(e,t)]?.secrets??{}}function ee(){let r=ce();if(!r)throw new Error(`No runner config found at ${St()}. Run \`allwright init\` first.`);return r}var ms=require("node:child_process"),Se=$(require("node:fs"),1),gs=$(require("node:path"),1);var af=new Set(["runner.log","runner.pid"]);function uf(r){return Se.default.readdirSync(r).filter(e=>!af.has(e)&&!/\.bak-\d+$/.test(e)).sort()}function Fa(r){let e=Q();if(!Se.default.existsSync(e))throw new Error(`nothing to export - ${e} does not exist`);let t=uf(e);if(!t.length)throw new Error(`nothing to export - ${e} is empty`);let n=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),s=gs.default.resolve(r||`ticketpilot-backup-${n}.tgz`);return Se.default.writeFileSync(s,"",{mode:384}),(0,ms.execFileSync)("tar",["-czf",s,"-C",e,...t]),Se.default.chmodSync(s,384),{file:s,entries:t}}function Ba(r){let e=gs.default.resolve(r);if(!Se.default.existsSync(e))throw new Error(`backup file not found: ${e}`);let t=(0,ms.execFileSync)("tar",["-tzf",e],{encoding:"utf8"}).split(`
|
|
238
|
+
`).filter(Boolean);for(let i of t)if(i.startsWith("/")||i.split("/").includes(".."))throw new Error(`refusing to import - unsafe path in archive: ${i}`);let n=Q(),s;Se.default.existsSync(n)&&Se.default.readdirSync(n).length&&(s=`${n}.bak-${Date.now()}`,Se.default.renameSync(n,s)),Se.default.mkdirSync(n,{recursive:!0,mode:448}),(0,ms.execFileSync)("tar",["-xzf",e,"-C",n]);for(let i of Se.default.readdirSync(n)){let o=gs.default.join(n,i);Se.default.statSync(o).isFile()&&Se.default.chmodSync(o,384)}return{restored:t.map(i=>i.replace(/\/$/,"")).sort(),previousDir:s}}var Br=$(require("node:fs"),1),xt=$(require("node:path"),1),ys=".ticketpilot-attachments",lf=15*1024*1024,cf=50*1024*1024,Za=20;function Ka(r,e){let t=xt.default.basename(r).replace(/[^\w.\- ()]/g,"_").replace(/^\.+/,"").slice(-100)||"file",n=t,s=1;for(;e.has(n);)n=`${s++}-${t}`;return e.add(n),n}async function Zr(r,e,t,n){if(!e.length)return"";let s=xt.default.join(t,ys);Br.default.mkdirSync(s,{recursive:!0});let i=new Set,o=[],a=0;for(let l of e){if(o.length>=Za){n("warn",`attachment cap reached (${Za} files) - skipping the rest`);break}if(l.size>lf){n("warn",`skipping attachment "${l.filename}" - ${ff(l.size)} MB exceeds the 15 MB limit`);continue}if(a+l.size>cf){n("warn",`attachment size budget reached - skipping "${l.filename}" and the rest`);break}try{let c=await r.downloadAttachment(l.contentUrl),h=Ka(l.filename,i);Br.default.writeFileSync(xt.default.join(s,h),c),a+=c.length,o.push(`- ${ys}/${h} (${l.mimeType||"unknown type"}, ${zi(c.length)} KB)`),n("info",`Downloaded attachment "${l.filename}" (${zi(c.length)} KB)`)}catch(c){n("warn",`could not download attachment "${l.filename}": ${c instanceof Error?c.message:c}`)}}return o.length?`
|
|
239
239
|
|
|
240
|
-
Files attached to the Jira ticket, downloaded locally for this run. They are reference material and NOT part of the repository
|
|
240
|
+
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:
|
|
241
241
|
${o.join(`
|
|
242
242
|
`)}
|
|
243
|
-
Read them with the Read tool when relevant; images (screenshots) can be viewed directly.`:(
|
|
243
|
+
Read them with the Read tool when relevant; images (screenshots) can be viewed directly.`:(Tt(t),"")}function Tt(r){Br.default.rmSync(xt.default.join(r,ys),{recursive:!0,force:!0})}var df=4*1024*1024,hf=16*1024*1024;function Va(r,e,t){let n=xt.default.join(r,ys,`chat-${e.replace(/[^\w-]/g,"")}`);if(!t.length)return{section:"",dir:n};Br.default.mkdirSync(n,{recursive:!0});let s=new Set,i=[],o=0,a=xt.default.relative(r,n);for(let c of t){let h=Buffer.from(c.contentBase64,"base64");if(h.length>df||o+h.length>hf){i.push(`- (skipped "${c.name}" - over the upload size budget)`);continue}let p=Ka(c.name,s);Br.default.writeFileSync(xt.default.join(n,p),h),o+=h.length,i.push(`- ${a}/${p} (${zi(h.length)} KB)`)}return{section:`
|
|
244
244
|
|
|
245
|
-
The user attached file(s) with this message, staged locally for you. They are reference material and NOT part of the repository
|
|
245
|
+
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:
|
|
246
246
|
${i.join(`
|
|
247
247
|
`)}
|
|
248
|
-
Read them with the Read tool; images can be viewed directly.`,dir:n}}var
|
|
248
|
+
Read them with the Read tool; images can be viewed directly.`,dir:n}}var zi=r=>Math.max(1,Math.round(r/1024)),ff=r=>Math.round(r/(1024*1024)*10)/10;var pe=$(require("node:fs"),1),_s=$(require("node:path"),1);function An(){return _s.default.join(Q(),"runner.pid")}function vs(){return _s.default.join(Q(),"runner.log")}function Ga(){pe.default.mkdirSync(Q(),{recursive:!0,mode:448});let r=pe.default.openSync(vs(),"a",384);try{pe.default.chmodSync(vs(),384)}catch{}return r}function Kr(){let r=An();if(!pe.default.existsSync(r))return null;let e=Number(pe.default.readFileSync(r,"utf8").trim());return Number.isFinite(e)&&e>0?e:null}function Vr(r){try{return process.kill(r,0),!0}catch{return!1}}function Ha(r){pe.default.mkdirSync(Q(),{recursive:!0,mode:448}),pe.default.writeFileSync(An(),String(r),{mode:384})}function Wa(r){Kr()===r&&pe.default.rmSync(An(),{force:!0})}function Li(){return _s.default.join(Q(),"runner.lock")}function Rn(){let r=Li();if(!pe.default.existsSync(r))return null;let e=Number(pe.default.readFileSync(r,"utf8").trim());return!Number.isFinite(e)||e<=0||e===process.pid?null:Vr(e)?e:null}function Ja(){let r=Rn();return r?{ok:!1,pid:r}:(pe.default.mkdirSync(Q(),{recursive:!0,mode:448}),pe.default.writeFileSync(Li(),String(process.pid),{mode:384}),{ok:!0})}function Di(){try{let r=Li();pe.default.existsSync(r)&&Number(pe.default.readFileSync(r,"utf8").trim())===process.pid&&pe.default.rmSync(r,{force:!0})}catch{}}var Es=$(require("node:fs"),1),Nn=$(require("node:path"),1),wu=$(Te(),1);async function ku(r,e){let t=await fetch(new URL("/api/runners/enroll",r.controlPlaneUrl),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enrollToken:e,name:r.runnerName,platform:`${process.platform}/${process.arch}`,runnerVersion:Is})});if(!t.ok){let i=await t.text().catch(()=>"");throw new Error(`enrollment failed (${t.status}): ${i.slice(0,300)}`)}let n=wu.EnrollResponse.parse(await t.json()),s={...r,runnerId:n.runnerId,runnerToken:n.runnerToken};return oe(s),s}function Dp(){try{let r=process.argv[1]?Es.default.realpathSync(process.argv[1]):"";for(let e of[Nn.default.dirname(r),Nn.default.dirname(Nn.default.dirname(r))]){let t=Nn.default.join(e,"package.json");if(!Es.default.existsSync(t))continue;let n=JSON.parse(Es.default.readFileSync(t,"utf8")).version;if(typeof n=="string"&&n)return n}}catch{}return"0.0.0"}var Is=Dp();_r();var Ou="Posted automatically by Allwright",Up=["Posted automatically by TicketPilot"],Je=r=>r.includes(Ou)||Up.some(e=>r.includes(e));var qe=class{constructor(e){this.auth=e}auth;headers(){return{Authorization:`Basic ${Buffer.from(`${this.auth.email}:${this.auth.apiToken}`).toString("base64")}`,Accept:"application/json","Content-Type":"application/json"}}async request(e,t,n){let s=new URL(t,this.auth.baseUrl).toString(),i=await fetch(s,{method:e,headers:this.headers(),body:n===void 0?void 0:JSON.stringify(n)});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`Jira ${e} ${t} -> ${i.status}: ${o.slice(0,500)}`)}if(i.status!==204)return await i.json()}async myself(){return this.request("GET","/rest/api/3/myself")}async searchUsers(e,t=20){let n=await this.userSearch(e,t);return n.length||!e.includes("@")?n:this.userSearch(e.slice(0,e.indexOf("@")),t)}async userSearch(e,t){return e.trim()?(await this.request("GET",`/rest/api/3/user/search?query=${encodeURIComponent(e)}&maxResults=${t}`)??[]).filter(s=>s.accountId&&(s.accountType??"atlassian")==="atlassian").map(s=>({accountId:s.accountId,displayName:s.displayName??"(no name)",email:s.emailAddress??"",active:s.active??!0})):[]}async search(e,t=20){return((await this.request("POST","/rest/api/3/search/jql",{jql:e,maxResults:t,fields:["summary","components"]})).issues??[]).map(s=>({key:s.key,summary:s.fields?.summary??"",components:(s.fields?.components??[]).map(i=>i.name??"").filter(Boolean)}))}async projectStatuses(e){let t=await this.request("GET",`/rest/api/3/project/${encodeURIComponent(e)}/statuses`),n=new Map;for(let i of t??[])for(let o of i.statuses??[])o.name&&!n.has(o.name)&&n.set(o.name,o.statusCategory?.key??"indeterminate");let s=i=>i==="new"?0:i==="done"?2:1;return[...n.entries()].sort((i,o)=>s(i[1])-s(o[1])).map(([i])=>i)}async searchEpics(e,t=20){return((await this.request("POST","/rest/api/3/search/jql",{jql:`project = "${e}" AND issuetype = Epic AND statusCategory != Done ORDER BY created DESC`,maxResults:t,fields:["summary","status"]})).issues??[]).map(s=>({key:s.key,summary:s.fields?.summary??"",status:s.fields?.status?.name??""}))}async epicChildren(e,t=50){return((await this.request("POST","/rest/api/3/search/jql",{jql:`parent = "${e}" ORDER BY created ASC`,maxResults:t,fields:["summary","status","labels"]})).issues??[]).map(s=>({key:s.key,summary:s.fields?.summary??"",status:s.fields?.status?.name??"",statusCategory:s.fields?.status?.statusCategory?.key??"indeterminate",labels:s.fields?.labels??[]}))}async searchBoard(e,t=100){return((await this.request("POST","/rest/api/3/search/jql",{jql:e,maxResults:t,fields:["summary","status","labels"]})).issues??[]).map(s=>({key:s.key,summary:s.fields?.summary??"",status:s.fields?.status?.name??"(no status)",statusId:s.fields?.status?.id??"",labels:s.fields?.labels??[]}))}async boardColumns(e){try{let n=(await this.request("GET",`/rest/agile/1.0/board?projectKeyOrId=${encodeURIComponent(e)}`)).values?.[0]?.id;if(!n)return null;let i=((await this.request("GET",`/rest/agile/1.0/board/${n}/configuration`)).columnConfig?.columns??[]).filter(o=>(o.statuses??[]).length>0&&o.name).map(o=>({name:o.name,statusIds:(o.statuses??[]).map(a=>a.id??"").filter(Boolean)}));return i.length?i:null}catch{return null}}async getIssue(e){let t=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}?fields=summary,description,labels,comment,status,attachment`),n;try{n=await this.listAllComments(e)}catch{n=t.fields.comment?.comments??[]}let s=n.map(o=>({id:o.id??"",author:o.author?.displayName??"unknown",authorAccountId:o.author?.accountId??null,created:o.created,body:ju(o.body)})),i=(t.fields.attachment??[]).filter(o=>o.id&&o.filename&&o.content).map(o=>({id:o.id,filename:o.filename,mimeType:o.mimeType??"",size:o.size??0,contentUrl:o.content}));return{key:t.key,summary:t.fields.summary??"",description:ju(t.fields.description),labels:t.fields.labels??[],status:t.fields.status?.name??"",comments:s,attachments:i}}async listAllComments(e){let t=await this.fetchCommentPage(e,0),n=t.total??t.comments.length;if(n<=t.comments.length)return t.comments;let s=Math.max(0,n-200),i=s===0?[...t.comments]:[];for(;i.length<Math.min(n,200);){let o=await this.fetchCommentPage(e,s+i.length);if(!o.comments.length)break;i.push(...o.comments)}return i.slice(-200)}async fetchCommentPage(e,t){let n=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}/comment?startAt=${t}&maxResults=100`);return{comments:n.comments??[],total:n.total}}async downloadAttachment(e){let t=await fetch(e,{headers:this.headers()});if(!t.ok)throw new Error(`attachment download failed: ${t.status}`);return Buffer.from(await t.arrayBuffer())}async lastEnteredStatus(e,t){let n=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}?expand=changelog&fields=status`),s=t.toLowerCase(),i=null;for(let o of n.changelog?.histories??[])(o.items??[]).some(l=>(l.field==="status"||l.fieldId==="status")&&(l.toString??"").toLowerCase()===s)&&(!i||new Date(o.created)>new Date(i.at))&&(i={at:o.created,author:o.author?.displayName??"unknown",authorAccountId:o.author?.accountId??null});return i}async createIssue(e,t,n,s="Task",i){return{key:(await this.request("POST","/rest/api/3/issue",{fields:{project:{key:e},issuetype:{name:s},summary:t.slice(0,250),description:ao(n),...i?{parent:{key:i}}:{}}})).key}}async addAttachments(e,t){if(!t.length)return;let n=new FormData;for(let a of t)n.append("file",new Blob([new Uint8Array(a.content)]),a.name.slice(0,255));let s=new URL(`/rest/api/3/issue/${encodeURIComponent(e)}/attachments`,this.auth.baseUrl).toString(),i=Buffer.from(`${this.auth.email}:${this.auth.apiToken}`).toString("base64"),o=await fetch(s,{method:"POST",headers:{Authorization:`Basic ${i}`,Accept:"application/json","X-Atlassian-Token":"no-check"},body:n});if(!o.ok)throw new Error(`Jira attachment upload failed: HTTP ${o.status}`)}async addTriggerComment(e,t){await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/comment`,{body:ao(t)})}async addComment(e,t){let n=`${t}
|
|
249
249
|
|
|
250
250
|
---
|
|
251
|
-
_${
|
|
251
|
+
_${Ou} - never treated as a trigger._`;await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/comment`,{body:ao(n)})}async editLabels(e,t){let n=[...(t.add??[]).map(s=>({add:s})),...(t.remove??[]).map(s=>({remove:s}))];await this.request("PUT",`/rest/api/3/issue/${encodeURIComponent(e)}`,{update:{labels:n}})}async getTransitions(e){return((await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}/transitions`)).transitions??[]).map(n=>({id:n.id,name:n.name}))}async transition(e,t){await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/transitions`,{transition:{id:t}})}async transitionByName(e,t){let s=(await this.getTransitions(e)).find(i=>i.name.toLowerCase()===t.toLowerCase());return s?(await this.transition(e,s.id),!0):!1}};function ju(r){if(!r)return"";let e=[],t=n=>{n.text&&e.push(n.text),n.type==="hardBreak"&&e.push(`
|
|
252
252
|
`);for(let s of n.content??[])t(s);n.type&&["paragraph","heading","listItem","codeBlock","blockquote"].includes(n.type)&&e.push(`
|
|
253
253
|
`)};return t(r),e.join("").replace(/\n{3,}/g,`
|
|
254
254
|
|
|
255
|
-
`).trim()}function
|
|
255
|
+
`).trim()}function ao(r){let e=r.replace(/\r\n/g,`
|
|
256
256
|
`).split(`
|
|
257
|
-
`),t=[],n=0,s=i=>{let o=[],a=/(\*\*[^*]+\*\*|`[^`]+`)/g,l=0,c;for(;(c=a.exec(i))!==null;){c.index>l&&o.push({type:"text",text:i.slice(l,c.index)});let
|
|
258
|
-
`)||" "}]});continue}let a=i.match(/^(#{1,6})\s+(.*)$/);if(a){t.push({type:"heading",attrs:{level:a[1].length},content:s(a[2])}),n++;continue}if(i.match(/^\s*[-*]\s+(.*)$/)){let p=[];for(;n<e.length;){let _=e[n].match(/^\s*[-*]\s+(.*)$/);if(!_)break;p.push({type:"listItem",content:[{type:"paragraph",content:s(_[1])}]}),n++}t.push({type:"bulletList",content:p});continue}if(i.match(/^\s*\d+[.)]\s+(.*)$/)){let p=[];for(;n<e.length;){let _=e[n].match(/^\s*\d+[.)]\s+(.*)$/);if(!_)break;p.push({type:"listItem",content:[{type:"paragraph",content:s(_[1])}]}),n++}t.push({type:"orderedList",content:p});continue}let
|
|
257
|
+
`),t=[],n=0,s=i=>{let o=[],a=/(\*\*[^*]+\*\*|`[^`]+`)/g,l=0,c;for(;(c=a.exec(i))!==null;){c.index>l&&o.push({type:"text",text:i.slice(l,c.index)});let h=c[0];h.startsWith("**")?o.push({type:"text",text:h.slice(2,-2),marks:[{type:"strong"}]}):o.push({type:"text",text:h.slice(1,-1),marks:[{type:"code"}]}),l=c.index+h.length}return l<i.length&&o.push({type:"text",text:i.slice(l)}),o.length?o:[{type:"text",text:" "}]};for(;n<e.length;){let i=e[n];if(i.trim()===""){n++;continue}let o=i.match(/^```(\w*)\s*$/);if(o){let p=[];for(n++;n<e.length&&!/^```\s*$/.test(e[n]);)p.push(e[n]),n++;n++,t.push({type:"codeBlock",attrs:o[1]?{language:o[1]}:{},content:[{type:"text",text:p.join(`
|
|
258
|
+
`)||" "}]});continue}let a=i.match(/^(#{1,6})\s+(.*)$/);if(a){t.push({type:"heading",attrs:{level:a[1].length},content:s(a[2])}),n++;continue}if(i.match(/^\s*[-*]\s+(.*)$/)){let p=[];for(;n<e.length;){let _=e[n].match(/^\s*[-*]\s+(.*)$/);if(!_)break;p.push({type:"listItem",content:[{type:"paragraph",content:s(_[1])}]}),n++}t.push({type:"bulletList",content:p});continue}if(i.match(/^\s*\d+[.)]\s+(.*)$/)){let p=[];for(;n<e.length;){let _=e[n].match(/^\s*\d+[.)]\s+(.*)$/);if(!_)break;p.push({type:"listItem",content:[{type:"paragraph",content:s(_[1])}]}),n++}t.push({type:"orderedList",content:p});continue}let h=[i];for(n++;n<e.length&&e[n].trim()!==""&&!/^(#{1,6}\s|```|\s*[-*]\s|\s*\d+[.)]\s)/.test(e[n]);)h.push(e[n]),n++;t.push({type:"paragraph",content:s(h.join(" "))})}return{type:"doc",version:1,content:t}}function Nu(r,e,t){let n=r.repos[e]?.jira??r.jira;if(!n)return{kind:"legacy"};let s=t.trim().toLowerCase();if(!s)return{kind:"legacy"};if(s===n.email.toLowerCase())return{kind:"self"};let i=r.jiraUsers[s];return i?{kind:"user",creds:{baseUrl:n.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:
|
|
259
259
|
|
|
260
260
|
allwright jira user-add ${s}
|
|
261
261
|
|
|
262
|
-
It prompts for your Atlassian email and an API token (create one at id.atlassian.com -> Security -> API tokens). Takes effect immediately
|
|
262
|
+
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 Ns(r,e,t){let n=(t??"").trim().toLowerCase(),s=n?r.githubUsers[n]?.token:void 0;if(s)return{token:s,source:"user"};let i=r.repos[e]?.github?.token;return i?{token:i,source:"repo"}:r.github?.token?{token:r.github.token,source:"global"}:null}function $t(r,e){return r.repos[e]?.github?.token??r.github?.token??null}function Mu(r,e){let t=[r.jira,...Object.values(r.repos).map(a=>a.jira)].filter(a=>!!a),n=new Set(t.map(a=>a.email.toLowerCase())),s=!!r.github?.token||Object.values(r.repos).some(a=>a.github?.token),i=r.github?.login??Object.values(r.repos).find(a=>a.github?.login)?.github?.login??"",o=e.map(a=>{let l=a.trim().toLowerCase(),c=r.jiraUsers[l]?"own":n.has(l)?"runner-account":"missing",h=c==="own"?r.jiraUsers[l].email:c==="runner-account"?l:"",p=r.githubUsers[l]?"own":s?"shared":"missing",_=p==="own"?r.githubUsers[l].login??"":p==="shared"?i:"";return{email:l,jira:c,jiraAs:h,github:p,githubAs:_}});return{githubShared:s,sharedGithubLogin:i,entries:o}}var br=require("node:child_process"),nn=$(require("node:fs"),1),uo=$(require("node:os"),1),co=$(require("node:path"),1);var Ln="allwright",zu=`/etc/systemd/system/${Ln}.service`,lo="ticketpilot-runner";function ho(){let r=process.env.SUDO_USER&&process.env.SUDO_USER!=="root"?process.env.SUDO_USER:"",e=r||uo.default.userInfo().username,t=r?co.default.join("/home",r):uo.default.homedir();return{nodePath:process.execPath,scriptPath:nn.default.realpathSync(process.argv[1]),user:e,home:t}}function fo(r){let e=co.default.dirname(r.nodePath);return`[Unit]
|
|
263
263
|
Description=Allwright runner
|
|
264
264
|
After=network-online.target
|
|
265
265
|
|
|
@@ -274,53 +274,54 @@ RestartSec=5
|
|
|
274
274
|
|
|
275
275
|
[Install]
|
|
276
276
|
WantedBy=multi-user.target
|
|
277
|
-
`}function
|
|
278
|
-
`+t);return}try{(0,br.execFileSync)("systemctl",["disable","--now",
|
|
277
|
+
`}function Lu(){return process.platform==="linux"&&nn.default.existsSync("/run/systemd/system")}function Du(r){if(!Lu())throw new Error(process.platform==="win32"?"Windows service install isn't built in yet - use NSSM: nssm install allwright <node> <this script> start --foreground":"no systemd on this machine - run `allwright start` (background mode) instead");let e=ho(),t=fo(e);if(typeof process.getuid=="function"&&process.getuid()!==0){r.info("Root is needed to write the unit. Re-run as:"),r.info(' sudo env "PATH=$PATH" allwright service install'),r.info("(the env PATH part matters when node is installed via nvm - plain sudo can't find it)"),r.info(""),r.info(`This is exactly what it will write to ${zu}:`),r.info(`
|
|
278
|
+
`+t);return}try{(0,br.execFileSync)("systemctl",["disable","--now",lo]),r.info(`stopped the old ${lo} service - this one replaces it`)}catch{}let n=Rn();if(n)try{process.kill(n,"SIGTERM"),r.info(`stopped the running runner (pid ${n}) - the service takes over`)}catch{}nn.default.writeFileSync(zu,t),(0,br.execFileSync)("systemctl",["daemon-reload"]),(0,br.execFileSync)("systemctl",["enable","--now",Ln]),(0,br.execFileSync)("systemctl",["restart",Ln]),r.info(`Installed and started (runs as ${e.user}, survives reboots).`),r.info(`Watch it: journalctl -u ${Ln} -f`),r.info("Status: allwright service status")}function Uu(r){if(!Lu())throw new Error("no systemd on this machine");if(typeof process.getuid=="function"&&process.getuid()!==0)throw new Error("root is needed - run: sudo allwright service uninstall");for(let e of[Ln,lo]){try{(0,br.execFileSync)("systemctl",["disable","--now",e])}catch{}let t=`/etc/systemd/system/${e}.service`;nn.default.existsSync(t)&&nn.default.rmSync(t)}(0,br.execFileSync)("systemctl",["daemon-reload"]),r.info("Service removed. The runner config and credentials were not touched.")}var qu=$(Te(),1);function Fu(r){return r.filter(e=>e.statusCategory!=="done"&&!e.labels.includes("agent-implemented")&&!e.labels.includes(qu.NEEDS_INPUT_LABEL))}function Bu(r,e,t){let n=t.map(s=>{let i=(s.description??"").trim().slice(0,600);return`- ${s.key} [${s.status}] ${s.summary}${i?`
|
|
279
279
|
${i.replace(/\n+/g," ")}`:""}`}).join(`
|
|
280
280
|
`);return`You are looking at this repository to help sequence work on the Jira epic ${r} ("${e}"). These child tickets are still pending:
|
|
281
281
|
|
|
282
282
|
${n}
|
|
283
283
|
|
|
284
|
-
Pick the ONE ticket that should be implemented FIRST. Weigh, in this order: (1) dependencies
|
|
284
|
+
Pick the ONE ticket that should be implemented FIRST. Weigh, in this order: (1) dependencies - does another ticket build on it? Foundations (schema, APIs, shared components) come before things that consume them; (2) risk - unknowns worth surfacing early; (3) user value. Use the code you can read to judge what already exists.
|
|
285
285
|
|
|
286
286
|
Answer with ONLY a fenced json block, nothing after it:
|
|
287
287
|
\`\`\`json
|
|
288
288
|
{"issueKey": "<one of the keys above>", "reason": "<2-3 sentences: why this one first, and what it unblocks>"}
|
|
289
|
-
\`\`\``}function
|
|
289
|
+
\`\`\``}function Zu(r,e){let n=r.match(/```(?:json)?\s*(\{[\s\S]*?\})\s*```/)?.[1]??r.match(/\{[\s\S]*"issueKey"[\s\S]*?\}/)?.[0];if(!n)return{error:"the agent's answer contained no JSON recommendation"};try{let s=JSON.parse(n),i=typeof s.issueKey=="string"?s.issueKey.trim():"",o=typeof s.reason=="string"?s.reason.trim():"";return e.includes(i)?{issueKey:i,reason:o||"(no reasoning given)"}:{error:`the agent recommended "${i}", which is not a pending child of this epic`}}catch{return{error:"the agent's JSON recommendation did not parse"}}}var ko=require("node:crypto"),kl=$(require("node:fs"),1);var po=$(require("node:fs"),1),Ku=$(require("node:os"),1),Ms=$(require("node:path"),1),Vu=require("node:child_process"),Gu=$(require("node:readline"),1),Hu=$(Te(),1),qp={read_only:["Read(./**)","Glob(./**)","Grep(./**)"],edit_no_shell:["Read(./**)","Glob(./**)","Grep(./**)","Edit(./**)","Write(./**)"]};function Fp(r){if(process.env.ANTHROPIC_API_KEY)return"API key";let e=r??Ms.default.join(Ku.default.homedir(),".claude");try{if(po.default.existsSync(Ms.default.join(e,".credentials.json"))||po.default.existsSync(Ms.default.join(e,"credentials.json")))return"subscription"}catch{}return"unknown"}async function Bp(r){let e=["-p","--output-format","stream-json","--verbose","--allowedTools",qp[r.mode].join(","),"--max-turns",String(r.maxTurns??60),...r.model?["--model",r.model]:[],...r.resume?["--resume",r.sessionId]:["--session-id",r.sessionId]],t=Fp(r.configDir);return t!=="unknown"&&r.onLog("info",t==="subscription"?"Billing: Claude subscription - costs shown are notional list prices, not money charged":"Billing: Anthropic API key - costs shown are actual metered spend"),new Promise(n=>{let s=(0,Vu.spawn)(r.bin,e,{cwd:r.repoPath,env:r.configDir?{...process.env,CLAUDE_CONFIG_DIR:r.configDir}:process.env,stdio:["pipe","pipe","pipe"]}),i={ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,billingMode:t==="subscription"?"subscription":t==="API key"?"api":"unknown"},o=!1,a=()=>{o||(o=!0,clearTimeout(l),n(i))},l=setTimeout(()=>{i.timedOut=!0,i.error=`run exceeded ${r.timeoutSeconds}s wall-clock limit`,r.onLog("error",i.error),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),5e3).unref()},r.timeoutSeconds*1e3);s.stdin.write(r.prompt),s.stdin.end(),Gu.default.createInterface({input:s.stdout}).on("line",p=>{if(!p.trim())return;let _;try{_=JSON.parse(p)}catch{r.onLog("agent",p.slice(0,1e3));return}if(_.type==="system"&&_.subtype==="init")i.model=typeof _.model=="string"?_.model:void 0,r.onLog("info",`Claude Code session started (model: ${_.model??"default"})`);else if(_.type==="assistant"){for(let b of _.message?.content??[])if(b.type==="text"&&b.text?.trim())r.onLog("agent",b.text.trim().slice(0,4e3));else if(b.type==="tool_use"){let x=JSON.stringify(b.input??{}).slice(0,300);r.onLog("info",`tool ${b.name} ${x}`)}}else _.type==="result"&&(i.costUsd=Number(_.total_cost_usd??0),i.inputTokens=Number(_.usage?.input_tokens??0),i.outputTokens=Number(_.usage?.output_tokens??0),_.subtype==="success"&&!_.is_error?(i.ok=!0,i.resultText=String(_.result??"")):_.subtype==="error_max_turns"?(i.turnLimitHit=!0,i.error=`hit the ${r.maxTurns??60}-turn limit before finishing`):(i.error=String(_.result??_.subtype??"unknown Claude Code error"),/rate.?limit|usage limit|limit (reached|exceeded)|overloaded/i.test(i.error)&&(i.error=`Claude usage limit hit for this account - the run will work again once the limit window resets. Original error: ${i.error.slice(0,400)}`)))});let h="";s.stderr.on("data",p=>{h=(h+p.toString()).slice(-2e3)}),s.on("error",p=>{i.error=`failed to start ${r.bin}: ${p.message}`,r.onLog("error",i.error),a()}),s.on("close",p=>{!i.ok&&!i.error&&(i.error=i.timedOut?i.error:`claude exited with code ${p}${h?`: ${h.slice(-500)}`:""}`),a()})})}var Ne={id:"claude-code",displayName:"Claude Code",capabilities:Hu.REGISTERED_AGENTS.find(r=>r.id==="claude-code").capabilities,run:Bp};var mo=$(require("node:fs"),1),zs=$(require("node:path"),1),Ls=$(Te(),1),Zp={security:"You are a security auditor. You can READ this repository; you can never run or change anything. Audit it against the knowledge packs below and report real, exploitable-here problems - not checklist theatre.",testing:"You are a test-coverage auditor. You can READ this repository (code and tests); you can never run anything. Find what is untested and fragile against the knowledge packs below - gaps that would actually bite this product, not generic coverage philosophy.",architecture:"You are a software architecture auditor. You can READ this repository; you can never run or change anything. Judge whether it is structurally HEALTHY for what it is trying to be, against the knowledge packs below - real structural pain for this team, not textbook purity."};function Ju(r,e,t,n={}){let s=e.map(l=>`### Pack: ${l.name}
|
|
290
290
|
|
|
291
291
|
${l.content}`).join(`
|
|
292
292
|
|
|
293
293
|
`),i=t.trim()?`
|
|
294
294
|
|
|
295
|
-
### Lessons from THIS project (read first
|
|
295
|
+
### Lessons from THIS project (read first - human-confirmed corrections; never re-raise what these mark as accepted/false-positive)
|
|
296
296
|
|
|
297
297
|
${t}`:"",o=n.scopeNote?`
|
|
298
298
|
|
|
299
|
-
### SCOPE
|
|
299
|
+
### SCOPE - audit ONLY this
|
|
300
300
|
|
|
301
301
|
${n.scopeNote}
|
|
302
302
|
|
|
303
303
|
Read whatever surrounding code you need for context, but every finding must be about the scope above.`:"",a=n.testResults?`
|
|
304
304
|
|
|
305
|
-
### Real test-run results (executed by the runner from TEST.md
|
|
305
|
+
### Real test-run results (executed by the runner from TEST.md - you cannot run anything yourself)
|
|
306
306
|
|
|
307
307
|
${n.testResults}
|
|
308
308
|
|
|
309
|
-
Fold what these results show
|
|
309
|
+
Fold what these results show - failures, flaky exits, suspiciously green suites - into your findings with the rest of the audit.`:"";return`${Zp[r]}
|
|
310
310
|
|
|
311
311
|
Knowledge below is LAYERED: global (product) -> org (this company) -> project (this repo). More specific levels OVERRIDE general ones; entries referencing a rule id (SEC-001 style) modify or disable that rule.
|
|
312
312
|
|
|
313
313
|
${s}${i}${o}${a}
|
|
314
314
|
|
|
315
|
-
Explore the repository first
|
|
315
|
+
Explore the repository first - entry points, routes, storage, tests - then audit. Finish with EXACTLY one fenced json block (nothing after it):
|
|
316
316
|
\`\`\`json
|
|
317
317
|
{"summary": "<3-5 sentences: overall posture, the theme of what you found>",
|
|
318
|
-
"findings": [{"id": "<stable-kebab-slug>", "title": "<one line>", "ruleId": "<the pack rule id this violates, e.g. SEC-013
|
|
318
|
+
"findings": [{"id": "<stable-kebab-slug>", "title": "<one line>", "ruleId": "<the pack rule id this violates, e.g. SEC-013 - "" only if genuinely no rule covers it>",
|
|
319
319
|
"severity": "critical|high|medium|low|info", "area": "<short group, e.g. auth>",
|
|
320
320
|
"evidence": [{"file": "<repo-relative path>", "line": <number, omit if n/a>, "note": "<what is there>"}],
|
|
321
321
|
"fix": "<2-4 sentences: concrete fix, specific to this code>"}]}
|
|
322
322
|
\`\`\`
|
|
323
|
-
Rules: every finding needs at least one evidence file you actually read
|
|
323
|
+
Rules: every finding needs at least one evidence file you actually read - findings without real evidence will be DELETED from your report. Max 25 findings, worst first. An empty findings list with an honest summary is a valid, good answer.`}function Yu(r){let t=r.match(/```(?:json)?\s*(\{[\s\S]*\})\s*```(?![\s\S]*```)/)?.[1]??r.match(/\{[\s\S]*"findings"[\s\S]*\}/)?.[0];if(!t)return{error:"the agent's report contained no JSON block"};let n;try{n=JSON.parse(t)}catch{return{error:"the agent's JSON report did not parse"}}if(!Array.isArray(n.findings))return{error:"the report has no findings array"};let s=[],i=0,o=new Set;for(let a of n.findings.slice(0,25)){let l=Kp(a),c=l?Ls.AuditFinding.safeParse(l):null;if(!c?.success){i++;continue}let h=c.data.id;for(;o.has(h);)h=`${h}-2`;o.add(h),s.push({...c.data,id:h})}return{summary:typeof n.summary=="string"?n.summary.trim().slice(0,2e3):"",findings:s,dropped:i}}function Kp(r){if(typeof r!="object"||r===null)return null;let e=r,t=typeof e.severity=="string"?e.severity.toLowerCase():"",n=Array.isArray(e.evidence)?e.evidence.filter(i=>typeof i=="object"&&i!==null).map(i=>({file:typeof i.file=="string"?i.file:"",...Wu(i.line)?{line:Wu(i.line)}:{},note:typeof i.note=="string"?i.note:""})).filter(i=>i.file):[],s=typeof e.ruleId=="string"?e.ruleId.trim().toUpperCase():"";return{id:Vp(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:Ls.AuditSeverity.options.includes(t)?t:void 0,area:typeof e.area=="string"?e.area.slice(0,60):"",evidence:n,fix:typeof e.fix=="string"?e.fix.slice(0,2e3):""}}function Wu(r){let e=typeof r=="number"?r:typeof r=="string"?parseInt(r,10):NaN;return Number.isInteger(e)&&e>0?e:void 0}function Vp(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"finding"}function Gp(r){try{let e=mo.default.readFileSync(r,"utf8");return e?e.split(`
|
|
324
|
+
`).length:0}catch{return null}}function Xu(r,e){let t=zs.default.resolve(r),n=[],s=[],i=0;for(let o of e){let a=[];for(let l of o.evidence){let c=l.file.trim().replace(/^\.\//,""),h=zs.default.resolve(t,c);if(h!==t&&!h.startsWith(t+zs.default.sep))continue;let p;try{p=mo.default.statSync(h)}catch{continue}if(p.isFile()){if(l.line!==void 0){let _=Gp(h);if(_!==null&&l.line>_){a.push({...l,line:void 0}),i++;continue}}a.push(l)}}if(!a.length){s.push({title:o.title,files:o.evidence.map(l=>l.file)});continue}n.push({...o,evidence:a})}return{findings:n,droppedFindings:s,correctedLines:i}}var Dn=$(require("node:fs"),1),go=$(require("node:path"),1),Qu=$(Te(),1);var Hp=20;function el(){return go.default.join(Q(),"audits.json")}function sn(){try{return{byProject:JSON.parse(Dn.default.readFileSync(el(),"utf8")).byProject??{}}}catch{return{byProject:{}}}}function tl(r){let e=el();Dn.default.mkdirSync(go.default.dirname(e),{recursive:!0,mode:448});let t=e+".tmp";Dn.default.writeFileSync(t,JSON.stringify(r,null,2),{mode:384}),Dn.default.renameSync(t,e)}function rl(r,e){let t=sn(),n=t.byProject[r]??[];n.unshift(Qu.AuditRecord.parse(e)),t.byProject[r]=n.slice(0,Hp),tl(t)}function nl(r){return(sn().byProject[r]??[]).map(e=>{let t={};for(let n of e.findings)t[n.severity]=(t[n.severity]??0)+1;return{id:e.id,role:e.role,createdAt:e.createdAt,findingCount:e.findings.length,bySeverity:t}})}function sl(r,e){let t=sn(),n=e?Date.parse(e):NaN,s={};for(let i of r){let o=(t.byProject[i]??[]).filter(l=>!Number.isFinite(n)||Date.parse(l.createdAt)>=n);if(!o.length)continue;let a={audits:o.length,findings:0,valid:0,falsePositive:0,wontFix:0,unreviewed:0};for(let l of o){a.findings+=l.findings.length;for(let c of l.findings){let h=l.verdicts[c.id]?.verdict;h==="valid"?a.valid++:h==="false-positive"?a.falsePositive++:h==="wont-fix"?a.wontFix++:a.unreviewed++}}s[i]=a}return s}function yo(r,e,t){let n=sn(),i=(n.byProject[r]??[]).find(a=>a.id===e);if(!i)return null;i.ticketed??={},i.verdicts??={},i.lessonsWritten??=[];let o=new Set(i.findings.map(a=>a.id));t.selected&&(i.review={selected:t.selected.filter(a=>o.has(a)),updatedAt:new Date().toISOString()});for(let a of t.ticketed??[])o.has(a.findingId)&&(i.ticketed={...i.ticketed,[a.findingId]:a.issueKey});for(let a of t.verdicts??[])o.has(a.findingId)&&(i.verdicts={...i.verdicts,[a.findingId]:{verdict:a.verdict,note:a.note,by:t.verdictBy??"",at:new Date().toISOString()}});for(let a of t.markLessonsWritten??[])o.has(a)&&!i.lessonsWritten.includes(a)&&i.lessonsWritten.push(a);return tl(n),i}function il(r,e){return(sn().byProject[r]??[]).find(s=>s.role===e&&(s.scope?.kind??"repo")==="repo")?.createdAt??null}function ol(r,e){return(sn().byProject[r]??[]).find(t=>t.id===e)??null}_r();var ge=$(require("node:fs"),1),Ye=$(require("node:path"),1),ul=$(Te(),1);var Wp=`# Security baseline - what to check in any repo
|
|
324
325
|
|
|
325
326
|
Every rule has a stable id. Findings must cite the id they violate.
|
|
326
327
|
|
|
@@ -342,7 +343,7 @@ Every rule has a stable id. Findings must cite the id they violate.
|
|
|
342
343
|
## AuthN / AuthZ
|
|
343
344
|
- **SEC-020** Routes or handlers missing an authentication check that their
|
|
344
345
|
siblings have.
|
|
345
|
-
- **SEC-021** Authorization done in the UI only
|
|
346
|
+
- **SEC-021** Authorization done in the UI only - server trusts the client's
|
|
346
347
|
claim of role or ownership (IDOR: records fetched/updated by id without an
|
|
347
348
|
owner check).
|
|
348
349
|
- **SEC-022** Password handling: plaintext or weak hashing, tokens that never
|
|
@@ -350,7 +351,7 @@ Every rule has a stable id. Findings must cite the id they violate.
|
|
|
350
351
|
|
|
351
352
|
## Data exposure
|
|
352
353
|
- **SEC-030** Endpoints returning more fields than the UI needs (emails,
|
|
353
|
-
tokens, internal ids)
|
|
354
|
+
tokens, internal ids) - especially list endpoints.
|
|
354
355
|
- **SEC-031** Uploads/static folders publicly reachable; user files served
|
|
355
356
|
without access control.
|
|
356
357
|
- **SEC-032** Missing rate limits on login/OTP/expensive endpoints.
|
|
@@ -363,14 +364,14 @@ Every rule has a stable id. Findings must cite the id they violate.
|
|
|
363
364
|
- **SEC-042** TLS/redirect handling that downgrades to http.
|
|
364
365
|
|
|
365
366
|
Prioritize by real exploitability in THIS codebase, not by rule order.
|
|
366
|
-
`,
|
|
367
|
+
`,Jp=`# Test gaps - what to check in any repo
|
|
367
368
|
|
|
368
369
|
Every rule has a stable id. Findings must cite the id they violate.
|
|
369
370
|
|
|
370
371
|
## Critical paths
|
|
371
372
|
- **TEST-001** A core product flow (from CLAUDE.md, routes, or entry points)
|
|
372
373
|
with no meaningful test covering it.
|
|
373
|
-
- **TEST-002** Money, auth, permissions or data-deletion paths without tests
|
|
374
|
+
- **TEST-002** Money, auth, permissions or data-deletion paths without tests -
|
|
374
375
|
these deserve coverage even when everything else is bare.
|
|
375
376
|
|
|
376
377
|
## Gap patterns
|
|
@@ -389,15 +390,15 @@ Every rule has a stable id. Findings must cite the id they violate.
|
|
|
389
390
|
the mock).
|
|
390
391
|
- **TEST-022** Snapshot/golden tests covering logic that deserves behavioral
|
|
391
392
|
assertions.
|
|
392
|
-
- **TEST-023** Time/order-dependent tests (sleeps, Date.now, shared state)
|
|
393
|
+
- **TEST-023** Time/order-dependent tests (sleeps, Date.now, shared state) -
|
|
393
394
|
flaky suspects.
|
|
394
395
|
|
|
395
396
|
Report the GAP and why it is risky here, not generic coverage philosophy.
|
|
396
|
-
`,
|
|
397
|
+
`,Yp=`# GDPR readiness - data-protection audit for repos with EU exposure
|
|
397
398
|
|
|
398
399
|
FIRST decide exposure: if this product clearly has no EU users, no personal
|
|
399
400
|
data, or is a purely static/internal tool, say so in ONE summary sentence and
|
|
400
|
-
skip deep GDPR analysis
|
|
401
|
+
skip deep GDPR analysis - do not manufacture findings. Otherwise audit the
|
|
401
402
|
rules below. Cite the rule id AND map the area to the closest GDPR article
|
|
402
403
|
(e.g. area "gdpr-art-17"). Evidence rules stay absolute.
|
|
403
404
|
|
|
@@ -428,7 +429,7 @@ rules below. Cite the rule id AND map the area to the closest GDPR article
|
|
|
428
429
|
|
|
429
430
|
## Processors & transfers (Art. 28, 44\u201349)
|
|
430
431
|
- **GDPR-050** Third-party services receiving personal data (analytics,
|
|
431
|
-
email, cloud)
|
|
432
|
+
email, cloud) - list what the CODE sends; flag transfers with no EU
|
|
432
433
|
region/SCC signal in configuration.
|
|
433
434
|
|
|
434
435
|
## Breach readiness (Art. 33\u201334)
|
|
@@ -437,11 +438,11 @@ rules below. Cite the rule id AND map the area to the closest GDPR article
|
|
|
437
438
|
|
|
438
439
|
Severity: many users' data exposed or a missing legal-basis mechanism is
|
|
439
440
|
high/critical; hygiene and documentation gaps are medium/low.
|
|
440
|
-
`,
|
|
441
|
+
`,Xp=`# Architecture health - is this repository structurally sound?
|
|
441
442
|
|
|
442
443
|
Every rule has a stable id. Findings must cite the id they violate. Judge
|
|
443
444
|
against what THIS codebase is trying to be (a static site does not need
|
|
444
|
-
hexagonal layers)
|
|
445
|
+
hexagonal layers) - flag structure that hurts THIS team, not textbook
|
|
445
446
|
deviations.
|
|
446
447
|
|
|
447
448
|
## Dependencies & boundaries
|
|
@@ -462,7 +463,7 @@ deviations.
|
|
|
462
463
|
|
|
463
464
|
## Structure & conventions
|
|
464
465
|
- **ARCH-020** Folder structure that fights the architecture (by-type folders
|
|
465
|
-
hiding feature boundaries, or vice versa
|
|
466
|
+
hiding feature boundaries, or vice versa - inconsistency is the flag).
|
|
466
467
|
- **ARCH-021** Naming that lies: modules whose name no longer matches what
|
|
467
468
|
they do.
|
|
468
469
|
- **ARCH-022** Configuration scattered/hard-coded instead of centralized.
|
|
@@ -476,72 +477,72 @@ deviations.
|
|
|
476
477
|
|
|
477
478
|
Summarize with an overall verdict: is this repository HEALTHY for its
|
|
478
479
|
purpose, and what are the 2-3 structural moves with the best payoff?
|
|
479
|
-
`,
|
|
480
|
+
`,al={security:[{name:"baseline.md",content:Wp},{name:"gdpr.md",content:Yp}],testing:[{name:"test-gaps.md",content:Jp}],architecture:[{name:"architecture-health.md",content:Xp}]},Qp=["You are auditing code you can READ but never run or change.","You are auditing test coverage by READING code and tests","\\`area\\`"];function vo(r){return Ye.default.join(Q(),"knowledge",r)}function ll(r,e){return Ye.default.join(r,".ticketpilot","knowledge",`${e}.md`)}function _o(r,e){return Ye.default.join(r,".ticketpilot","lessons",`${e}.md`)}function cl(r,e){let t=[],n=vo(r),s=[];if(ge.default.existsSync(n)){for(let l of ge.default.readdirSync(n)){if(!l.endsWith(".md"))continue;let c=Ye.default.join(n,l),h=ge.default.readFileSync(c,"utf8");if(Qp.some(p=>h.includes(p))&&al[r].map(_=>_.name).includes(l)&&!h.includes("SEC-0")&&!h.includes("TEST-0")&&!h.includes("GDPR-0")){ge.default.rmSync(c);continue}s.push(l)}s.sort()}let i=new Set(s);for(let l of al[r])i.has(l.name)||t.push({level:"global",source:"pack",name:l.name,content:l.content,editable:!1});for(let l of s)t.push({level:"org",source:"pack",name:l,content:ge.default.readFileSync(Ye.default.join(n,l),"utf8").slice(0,3e4),editable:!0});let o=ll(e,r);ge.default.existsSync(o)&&t.push({level:"project",source:"pack",name:`${r}.md`,content:ge.default.readFileSync(o,"utf8").slice(0,3e4),editable:!0});let a=_o(e,r);return ge.default.existsSync(a)&&t.push({level:"project",source:"lessons",name:`${r}.md`,content:ge.default.readFileSync(a,"utf8").slice(0,2e4),editable:!0}),t}function dl(r,e){let t=cl(r,e);return{packs:t.filter(n=>n.source==="pack").map(n=>({name:`${n.level}/${n.name}`,content:n.content})),lessons:t.find(n=>n.source==="lessons")?.content??"",layers:t}}function bo(r,e,t,n="project"){let s=n==="org"?Ye.default.join(vo(e),"org-lessons.md"):_o(r,e);ge.default.mkdirSync(Ye.default.dirname(s),{recursive:!0});let i=ge.default.existsSync(s)?"":`# ${e} lessons (${n} level)
|
|
480
481
|
|
|
481
482
|
Human-confirmed corrections and rules. Every ${e} audit reads this FIRST. Reference rule ids (SEC-001 style) when overriding a rule.
|
|
482
483
|
|
|
483
484
|
`;ge.default.appendFileSync(s,i+t.trimEnd()+`
|
|
484
485
|
|
|
485
|
-
`)}function
|
|
486
|
+
`)}function hl(r,e,t,n){let s=new Date().toISOString().slice(0,10),i=r.evidence[0]?` (${r.evidence[0].file}${r.evidence[0].line?`:${r.evidence[0].line}`:""})`:"",o=r.ruleId?` \xB7 rule ${r.ruleId}`:"";return`## ${s} \xB7 ${e}${o} \xB7 ${r.title}${i}
|
|
486
487
|
Finding \`${r.id}\` [${r.severity}] was marked **${e}**`+(n?` by ${n}`:"")+`.${t?` Reason: ${t}`:""}
|
|
487
|
-
`+(e==="false-positive"?"Do not raise this class of finding here again unless the code meaningfully changes.":"Known and accepted
|
|
488
|
-
${r.trim()}`}function
|
|
489
|
-
`)){let s=n.trim();!s||s.startsWith("#")||e.push(s)}return e.slice(0,10)}async function
|
|
490
|
-
[killed: timed out]`},s);c.on("close",
|
|
488
|
+
`+(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 fl(r,e){return`## ${new Date().toISOString().slice(0,10)} \xB7 taught${e?` by ${e}`:""}
|
|
489
|
+
${r.trim()}`}function pl(r){let e=[];for(let t of ul.AuditRole.options)for(let n of cl(t,r))e.push({role:t,...n});return e}function ml(r,e,t,n,s,i){if(!/^[a-zA-Z0-9._-]+\.md$/.test(s))throw new Error("file name must be a simple .md name");let o=t==="org"?Ye.default.join(vo(e),s):n==="lessons"?_o(r,e):ll(r,e);ge.default.mkdirSync(Ye.default.dirname(o),{recursive:!0}),ge.default.writeFileSync(o,i,{mode:t==="org"?384:420})}var wo=()=>new Date().toISOString(),g={info:r=>console.log(`${wo()} [info] ${r}`),warn:r=>console.warn(`${wo()} [warn] ${r}`),error:r=>console.error(`${wo()} [error] ${r}`)};var gl=require("node:child_process"),yl=$(require("node:fs"),1),vl=$(require("node:path"),1);function _l(r){for(let e of["TEST.md","TESTING.md","docs/TEST.md"]){let t=vl.default.join(r,e);if(yl.default.existsSync(t))return t}return null}function bl(r){let e=[];for(let t of r.matchAll(/```(?:bash|sh|shell)?\s*\n([\s\S]*?)```/g))for(let n of t[1].split(`
|
|
490
|
+
`)){let s=n.trim();!s||s.startsWith("#")||e.push(s)}return e.slice(0,10)}async function wl(r,e,t={}){let n=[],s=t.perCommandTimeoutMs??6e5;for(let i of e){t.onProgress?.(`running: ${i}`);let o=Date.now(),a=await new Promise(l=>{let c=(0,gl.spawn)("bash",["-lc",i],{cwd:r,env:{...process.env,CI:"1",FORCE_COLOR:"0"}}),h="",p=b=>{h+=b.toString(),h.length>2e5&&(h=h.slice(-1e5))};c.stdout.on("data",p),c.stderr.on("data",p);let _=setTimeout(()=>{c.kill("SIGKILL"),h+=`
|
|
491
|
+
[killed: timed out]`},s);c.on("close",b=>{clearTimeout(_),l({command:i,exitCode:b??-1,durationMs:Date.now()-o,tail:h.slice(-4e3)})}),c.on("error",b=>{clearTimeout(_),l({command:i,exitCode:-1,durationMs:Date.now()-o,tail:String(b)})})});t.onProgress?.(`exit ${a.exitCode} in ${Math.round(a.durationMs/1e3)}s: ${i}`),n.push(a)}return n}async function on(r){let{packs:e,lessons:t}=dl(r.role,r.repoPath);if(!e.length)return{ok:!1,error:`no knowledge packs found for the ${r.role} role - add markdown files under ~/.config/ticketpilot/knowledge/${r.role}/ on the runner`};let n="";if(r.scope.kind==="ticket"&&r.scope.ref){let p=r.scope.ref,_="";try{let x=await r.jira.getIssue(p);_=`Ticket ${p}: ${x.summary}
|
|
491
492
|
|
|
492
|
-
${
|
|
493
|
+
${x.description}`.slice(0,4e3)}catch{_=`Ticket ${p} (could not fetch its text from Jira).`}let b=await ro(r.repoPath,p).catch(()=>null);if(b){let{base:x,stat:C,diff:S}=await Os(r.repoPath,b).catch(()=>({base:"",stat:"",diff:""}));n=`${_}
|
|
493
494
|
|
|
494
|
-
Its implementation branch \`${
|
|
495
|
+
Its implementation branch \`${b}\` vs \`${x}\`:
|
|
495
496
|
\`\`\`
|
|
496
|
-
${
|
|
497
|
+
${C}\`\`\`
|
|
497
498
|
\`\`\`diff
|
|
498
|
-
${
|
|
499
|
-
\`\`\``}else n=`${
|
|
499
|
+
${S}
|
|
500
|
+
\`\`\``}else n=`${_}
|
|
500
501
|
|
|
501
|
-
No implementation branch found for ${
|
|
502
|
+
No implementation branch found for ${p} - audit the parts of the codebase this ticket touches or would touch.`}else if(r.scope.kind==="branch"&&r.scope.ref){let{base:p,stat:_,diff:b}=await Os(r.repoPath,r.scope.ref);n=`The diff of \`${r.scope.ref}\` vs \`${p}\`:
|
|
502
503
|
\`\`\`
|
|
503
|
-
${
|
|
504
|
+
${_}\`\`\`
|
|
504
505
|
\`\`\`diff
|
|
505
|
-
${
|
|
506
|
-
\`\`\``}let s,i;if(r.role==="testing"){let
|
|
507
|
-
(exit ${
|
|
508
|
-
${
|
|
506
|
+
${b}
|
|
507
|
+
\`\`\``}let s,i;if(r.role==="testing"){let p=_l(r.repoPath),_=p?bl(kl.default.readFileSync(p,"utf8")):[];_.length&&(g.info(`Audit (testing): executing ${_.length} TEST.md command(s)`),i=await wl(r.repoPath,_,{onProgress:b=>g.info(`[test-run] ${b}`)}),s=i.map(b=>`$ ${b.command}
|
|
508
|
+
(exit ${b.exitCode}, ${Math.round(b.durationMs/1e3)}s)
|
|
509
|
+
${b.tail.slice(-2e3)}`).join(`
|
|
509
510
|
|
|
510
511
|
---
|
|
511
512
|
|
|
512
|
-
`))}let o=r.model||"claude-fable-5",a=await Ne.run({repoPath:r.repoPath,prompt:
|
|
513
|
-
`,{mode:384}),ye.default.renameSync(t,r),ye.default.chmodSync(r,384)}function
|
|
513
|
+
`))}let o=r.model||"claude-fable-5",a=await Ne.run({repoPath:r.repoPath,prompt:Ju(r.role,e,t,{scopeNote:n,testResults:s}),timeoutSeconds:480,bin:r.claudeBin,mode:"read_only",maxTurns:120,sessionId:(0,ko.randomUUID)(),model:o,onLog:(p,_)=>{p==="agent"&&g.info(`[audit:${r.role}] ${_.slice(0,160)}`)}}),l=Yu(a.resultText);if("error"in l)return{ok:!1,error:l.error};let c=Xu(r.repoPath,l.findings);for(let p of c.droppedFindings)g.warn(`[audit:${r.role}] dropped "${p.title}" - cited files do not exist: `+p.files.join(", "));let h={id:(0,ko.randomUUID)(),role:r.role,createdAt:new Date().toISOString(),model:a.model||o,summary:l.summary,packNames:e.map(p=>p.name),findings:c.findings,costUsd:a.costUsd??0,ticketed:{},verdicts:{},lessonsWritten:[],scope:r.scope,...i?{testRun:i}:{}};return rl(r.projectId,h),g.info(`Audit (${r.role}${r.scope.kind!=="repo"?` \xB7 ${r.scope.kind}:${r.scope.ref}`:""}) done: ${c.findings.length} finding(s)`+(l.dropped?`, ${l.dropped} malformed`:"")+(c.droppedFindings.length?`, ${c.droppedFindings.length} dropped for citing files that do not exist`:"")+(c.correctedLines?`, ${c.correctedLines} bad line number(s) stripped`:"")),{ok:!0,audit:h}}var Cr=$(Te(),1);var jl=$(require("node:path"),1),Zs=require("node:crypto"),Ce=$(Te(),1);var Un=$(Te(),1);var Sl=require("node:child_process"),xl=$(require("node:readline"),1),Tl=$(Te(),1);async function em(r){if(r.mode!=="read_only")return{ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,error:"the codex adapter only supports read-only runs - its write sandbox cannot exclude shell, and Allwright never weakens a guarantee silently"};if(r.resume)return{ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,error:"the codex adapter cannot resume sessions"};let e=["exec","--json","--sandbox","read-only","--skip-git-repo-check","--cd",r.repoPath,...r.model?["--model",r.model]:[],"-"];return new Promise(t=>{let n=(0,Sl.spawn)(r.bin,e,{cwd:r.repoPath,env:process.env,stdio:["pipe","pipe","pipe"]}),s={ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0},i="",o=!1,a=()=>{o||(o=!0,clearTimeout(l),t(s))},l=setTimeout(()=>{s.timedOut=!0,s.error=`run exceeded ${r.timeoutSeconds}s wall-clock limit`,r.onLog("error",s.error),n.kill("SIGTERM"),setTimeout(()=>n.kill("SIGKILL"),5e3).unref()},r.timeoutSeconds*1e3);n.stdin.write(r.prompt),n.stdin.end(),xl.default.createInterface({input:n.stdout}).on("line",p=>{if(!p.trim())return;let _;try{_=JSON.parse(p)}catch{r.onLog("agent",p.slice(0,1e3));return}let b=_.item??_.msg??_,x=b?.type??_.type,C=b?.text??b?.message??"";x==="agent_message"&&typeof C=="string"&&C.trim()?(i=C,r.onLog("agent",C.trim().slice(0,4e3))):x==="command_execution"||x==="exec_command_begin"?r.onLog("info",`tool ${String(b?.command??"").slice(0,300)}`):x==="error"&&typeof C=="string"&&C&&r.onLog("error",C.slice(0,1e3))});let h="";n.stderr.on("data",p=>{h=(h+p.toString()).slice(-2e3)}),n.on("error",p=>{s.error=`failed to start ${r.bin}: ${p.message} - is the Codex CLI installed and logged in?`,r.onLog("error",s.error),a()}),n.on("close",p=>{p===0&&i.trim()?(s.ok=!0,s.resultText=i):s.error||(s.error=`codex exited with code ${p}`+(i?"":" and produced no answer")+(h?`: ${h.slice(-500)}`:"")),a()})})}var So={id:"codex",displayName:"OpenAI Codex CLI (experimental)",capabilities:Tl.REGISTERED_AGENTS.find(r=>r.id==="codex").capabilities,run:em};var tm={[Ne.id]:Ne,[So.id]:So};function wr(r){return tm[r||Un.DEFAULT_AGENT_ID]??null}function an(r,e){return!e||e===Ne.id?r.claudeBin:r.agents[e]?.bin??e}function Ds(r,e){let t=wr(r);if(!t)return`no agent adapter named "${r}" on this runner - update the runner, or set the rule's agent to "${Un.DEFAULT_AGENT_ID}"`;let n=(0,Un.missingAgentCapabilities)(t.id,e);return n&&n.length?`agent "${t.displayName}" cannot run ${e} rules: it cannot guarantee ${n.join(", ")}. Allwright refuses rather than weakening the isolation silently.`:null}function Pt(r,e){return r.replace(/\{\{(\w+)\}\}/g,(t,n)=>n in e?e[n]:t)}ct();_r();var ye=$(require("node:fs"),1),ln=$(require("node:path"),1);var nm=k.object({runId:k.string(),issueKey:k.string(),repoName:k.string(),owner:k.string(),repo:k.string(),prNumber:k.number().int(),prUrl:k.string(),branch:k.string(),headSha:k.string(),doneLabel:k.string(),failedLabel:k.string(),jiraTransition:k.string().optional(),changesRequestedNotified:k.boolean().optional(),conflictNotified:k.boolean().optional()}),sm=k.record(nm),im=k.object({runId:k.string(),issueKey:k.string(),issueSummary:k.string().default(""),projectId:k.string(),repoName:k.string(),environmentName:k.string(),requestedBy:k.string().default(""),createdAt:k.string()}),om=k.record(im),am=k.object({runId:k.string(),issueKey:k.string(),kind:k.enum(["plan","implement"]),repoPath:k.string(),sessionId:k.string(),doneLabel:k.string(),failedLabel:k.string(),timeoutSeconds:k.number(),createdAt:k.string(),questionsPostedAt:k.string(),rounds:k.number().int().default(1),nextLogSeq:k.number().int().nonnegative().default(0),baseRepoPath:k.string().optional(),repoName:k.string().optional(),branch:k.string().optional(),baseBranch:k.string().optional(),jiraTransition:k.string().optional(),jiraTransitionOnMerge:k.string().optional(),requireApproval:k.boolean().optional(),maxTurns:k.number().int().optional(),issueSummary:k.string().default(""),claudeConfigDir:k.string().optional(),agent:k.string().optional(),model:k.string().optional(),actorEmail:k.string().optional()}),um=k.object({runId:k.string(),issueKey:k.string(),issueSummary:k.string().default(""),repoName:k.string(),baseRepoPath:k.string(),branch:k.string(),baseBranch:k.string(),headSha:k.string(),requireApproval:k.boolean(),doneLabel:k.string(),failedLabel:k.string(),jiraTransition:k.string().optional(),jiraTransitionOnMerge:k.string().optional(),actorEmail:k.string().optional(),resultSummary:k.string().default(""),costUsd:k.number().default(0),nextLogSeq:k.number().int().default(1e5),createdAt:k.string()}),lm=k.record(um),cm=k.object({runId:k.string(),issueKey:k.string(),repoName:k.string(),owner:k.string(),repo:k.string(),prNumber:k.number().int(),prUrl:k.string(),jiraTransitionOnMerge:k.string().default(""),createdAt:k.string()}),dm=k.record(cm),hm=k.record(am);function Cl(){return ln.default.join(Q(),"pending-runs.json")}function xo(){return ln.default.join(Q(),"pending-deploys.json")}function To(){return ln.default.join(Q(),"pending-inputs.json")}function Co(){return ln.default.join(Q(),"merge-watch.json")}function Eo(){return ln.default.join(Q(),"pending-pushes.json")}function Io(){let r=Eo();if(!ye.default.existsSync(r))return{};try{return lm.parse(JSON.parse(ye.default.readFileSync(r,"utf8")))}catch{return{}}}function Ao(r){let e=Io();e[r.runId]=r,dt(Eo(),e)}function Us(r){return Io()[r]??null}function Ro(r){let e=Io();r in e&&(delete e[r],dt(Eo(),e))}function qs(){let r=Co();if(!ye.default.existsSync(r))return{};try{return dm.parse(JSON.parse(ye.default.readFileSync(r,"utf8")))}catch{return{}}}function El(r){let e=qs();e[r.runId]=r,dt(Co(),e)}function qn(r){let e=qs();r in e&&(delete e[r],dt(Co(),e))}function Fn(){let r=Cl();if(!ye.default.existsSync(r))return{};try{return sm.parse(JSON.parse(ye.default.readFileSync(r,"utf8")))}catch{return{}}}function dt(r,e){ye.default.mkdirSync(Q(),{recursive:!0,mode:448});let t=r+".tmp";ye.default.writeFileSync(t,JSON.stringify(e,null,2)+`
|
|
514
|
+
`,{mode:384}),ye.default.renameSync(t,r),ye.default.chmodSync(r,384)}function Il(r){dt(Cl(),r)}function cn(r){let e=Fn();e[r.runId]=r,Il(e)}function $o(r){return Fn()[r]??null}function kr(r){let e=Fn();r in e&&(delete e[r],Il(e))}function Po(){let r=xo();if(!ye.default.existsSync(r))return{};try{return om.parse(JSON.parse(ye.default.readFileSync(r,"utf8")))}catch{return{}}}function Al(r){let e=Po();e[r.runId]=r,dt(xo(),e)}function Fs(r){return Po()[r]??null}function Bs(r){let e=Po();r in e&&(delete e[r],dt(xo(),e))}function dn(){let r=To();if(!ye.default.existsSync(r))return{};try{return hm.parse(JSON.parse(ye.default.readFileSync(r,"utf8")))}catch{return{}}}function Rl(r){let e=dn();e[r.runId]=r,dt(To(),e)}function Xe(r){let e=dn();r in e&&(delete e[r],dt(To(),e))}var Ol=5,$l=2,fm=8,Pl=2,pm="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 Zn(r,e,t,n){let s=Date.now(),i="";n&&(i=await n().catch(()=>""));let o=await r.run(e),a=0,l="",c=n?fm:$l;for(;!o.ok&&o.turnLimitHit&&r.capabilities.sessionResume;){if(a>=c){l=`resume cap (${c}) reached`;break}if(n&&a>=$l){let p=await n().catch(()=>""),_=p!==""&&p!==i;if(i=p,!_){l="the last resume produced no new work";break}if(Date.now()-s>e.timeoutSeconds*Pl*1e3){l=`wall-clock budget (${Pl}x the rule's timeout) exhausted`;break}}a++,t("info",`Turn limit hit mid-work - auto-resuming the same session (resume ${a}, cap ${c})`);let h=await r.run({...e,prompt:pm,resume:!0});h.costUsd+=o.costUsd,h.inputTokens+=o.inputTokens,h.outputTokens+=o.outputTokens,o=h}return!o.ok&&o.turnLimitHit&&r.capabilities.sessionResume&&(o.error=`${o.error??"hit the turn limit"} - even after ${a} automatic same-session resume(s)${l?` (stopped: ${l})`:""}. The ticket is probably too large for one run: raise the rule's max turns, or split the ticket.`),o}function Sr(r,e,t=0){let n=t;return{emit:(o,a)=>{e.send({type:"run.log",runId:r,seq:n++,ts:new Date().toISOString(),level:o,message:a}),o!=="agent"&&g.info(`[run ${r}] ${a}`)},setStatus:(o,a={})=>{e.send({type:"run.status",runId:r,status:o,...a})},nextSeq:()=>n}}async function Ks(r){return r.rule.action.type==="implement"?ym(r):r.rule.action.type==="respond"?gm(r):mm(r)}async function mm(r){let{emit:e,setStatus:t,nextSeq:n}=Sr(r.runId,r.transport),{trigger:s}=r.rule,i=r.rule.action;if(i.type!=="plan_only")return;let o=Ds(i.agent,i.type);if(o){e("error",o),await hn(r,o),t("failed",{error:o});return}let a=(0,Zs.randomUUID)();try{t("running"),e("info",`Run started for ${r.issueKey} (rule "${r.rule.name}", plan-only)`),e("info",`Fetching ${r.issueKey} from Jira`);let l=await r.jira.getIssue(r.issueKey),c=Pt(i.promptTemplate,{issueKey:l.key,summary:l.summary,description:l.description||"(no description)",comments:Vn(l.comments)})+await Zr(r.jira,l.attachments,r.repoPath,e);e("info",`Starting Claude Code in ${r.repoPath} - read-only tools, path-jailed to the repo, timeout ${i.timeoutSeconds}s`);let h=await Zn(wr(i.agent),{repoPath:r.repoPath,prompt:c,timeoutSeconds:i.timeoutSeconds,bin:an(r.cfg,i.agent),configDir:r.claudeConfigDir,mode:"read_only",model:i.model||void 0,sessionId:a,onLog:(b,x)=>e(b,x)},e),p={costUsd:h.costUsd,inputTokens:h.inputTokens,outputTokens:h.outputTokens,billingMode:h.billingMode,model:h.model};if(!h.ok||!h.resultText.trim()){let b=h.error??"Claude Code produced no output";e("error",`Run failed: ${b}`),await hn(r,b),t(h.timedOut?"timed_out":"failed",{error:b,...p});return}let _=Vs(h.resultText);if(_){await Gs({kind:"plan",runId:r.runId,issueKey:r.issueKey,repoPath:r.repoPath,sessionId:a,doneLabel:s.doneLabel,failedLabel:s.failedLabel,timeoutSeconds:i.timeoutSeconds,jira:r.jira,nextLogSeq:n(),rounds:1,claudeConfigDir:r.claudeConfigDir,agent:i.agent,model:i.model},_,e,t,p);return}await Ml({runId:r.runId,issueKey:r.issueKey,doneLabel:s.doneLabel,jira:r.jira,resultText:h.resultText,costFields:p,emit:e,setStatus:t})}catch(l){let c=l instanceof Error?l.message:String(l);e("error",`Run failed: ${c}`),await hn(r,c),t("failed",{error:c})}finally{Tt(r.repoPath)}}async function Nl(r,e,t,n){let{emit:s,setStatus:i,nextSeq:o}=Sr(r.runId,n.transport,r.nextLogSeq);try{i("running"),s("info",`Reply received on ${r.issueKey} - continuing run \`${r.runId}\``);let a=Gl(e)+await Zr(n.jiraFor(r.repoName??""),t,r.repoPath,s),l=await Zn(wr(r.agent),{repoPath:r.repoPath,prompt:a,timeoutSeconds:r.timeoutSeconds,bin:an(n.cfg,r.agent??""),configDir:r.claudeConfigDir,mode:"read_only",model:r.model||void 0,sessionId:r.sessionId,resume:!0,onLog:(p,_)=>s(p,_)},s),c={costUsd:l.costUsd,inputTokens:l.inputTokens,outputTokens:l.outputTokens,billingMode:l.billingMode,model:l.model};if(!l.ok||!l.resultText.trim()){let p=l.error??"Claude Code produced no output";s("error",`Run failed: ${p}`),await ht(n.jiraFor(r.repoName??""),r.issueKey,r.runId,r.failedLabel,p),Xe(r.runId),i(l.timedOut?"timed_out":"failed",{error:p,...c});return}let h=Vs(l.resultText);if(h){if(r.rounds>=Ol){await Hl(n.jiraFor(r.repoName??""),r,s,i,c);return}await Gs({kind:"plan",runId:r.runId,issueKey:r.issueKey,repoPath:r.repoPath,sessionId:r.sessionId,doneLabel:r.doneLabel,failedLabel:r.failedLabel,timeoutSeconds:r.timeoutSeconds,jira:n.jiraFor(r.repoName??""),nextLogSeq:o(),rounds:r.rounds+1,createdAt:r.createdAt,claudeConfigDir:r.claudeConfigDir,actorEmail:r.actorEmail,agent:r.agent,model:r.model},h,s,i,c);return}await Ml({runId:r.runId,issueKey:r.issueKey,doneLabel:r.doneLabel,jira:n.jiraFor(r.repoName??""),resultText:l.resultText,costFields:c,emit:s,setStatus:i}),Xe(r.runId)}catch(a){let l=a instanceof Error?a.message:String(a);s("error",`Run failed: ${l}`),await ht(n.jiraFor(r.repoName??""),r.issueKey,r.runId,r.failedLabel,l),Xe(r.runId),i("failed",{error:l})}finally{Tt(r.repoPath)}}async function Ml(r){let{runId:e,issueKey:t,doneLabel:n,jira:s,resultText:i,costFields:o,emit:a,setStatus:l}=r;l("posting",o),a("info",`Posting plan to ${t} (${i.length} chars)`);let c=`
|
|
514
515
|
|
|
515
516
|
---
|
|
516
|
-
_Allwright plan-only run \`${e}\` \xB7 cost $${o.costUsd.toFixed(4)} \xB7 no code was written._`;await s.addComment(t,i+c),await s.editLabels(t,{add:[n],remove:[Ce.NEEDS_INPUT_LABEL]}),a("info",`Labeled ${t} with "${n}"`),l("succeeded",{...o,resultSummary:
|
|
517
|
+
_Allwright plan-only run \`${e}\` \xB7 cost $${o.costUsd.toFixed(4)} \xB7 no code was written._`;await s.addComment(t,i+c),await s.editLabels(t,{add:[n],remove:[Ce.NEEDS_INPUT_LABEL]}),a("info",`Labeled ${t} with "${n}"`),l("succeeded",{...o,resultSummary:Bn(i)}),a("info",`Run succeeded \xB7 $${o.costUsd.toFixed(4)}`)}async function gm(r){let{emit:e,setStatus:t}=Sr(r.runId,r.transport),n=r.rule.action;if(n.type!=="respond")return;let s=Ds(n.agent,n.type);if(s){e("error",s),await r.jira.addComment(r.issueKey,`**Allwright could not answer this question.**
|
|
517
518
|
|
|
518
|
-
${s}`).catch(()=>{}),t("failed",{error:s});return}try{t("running"),e("info",`Run started for ${r.issueKey} (rule "${r.rule.name}", respond`+(r.question?`, question from ${r.question.author}`:"")+")"),e("info",`Fetching ${r.issueKey} from Jira`);let i=await r.jira.getIssue(r.issueKey),o=Pt(n.promptTemplate,{issueKey:i.key,summary:i.summary,description:i.description||"(no description)",comments:Vn(i.comments),question:r.question?.body??"(see the latest comment on the ticket)",questionAuthor:r.question?.author??"the commenter"})+await Zr(r.jira,i.attachments,r.repoPath,e);e("info",`Starting Claude Code in ${r.repoPath}
|
|
519
|
+
${s}`).catch(()=>{}),t("failed",{error:s});return}try{t("running"),e("info",`Run started for ${r.issueKey} (rule "${r.rule.name}", respond`+(r.question?`, question from ${r.question.author}`:"")+")"),e("info",`Fetching ${r.issueKey} from Jira`);let i=await r.jira.getIssue(r.issueKey),o=Pt(n.promptTemplate,{issueKey:i.key,summary:i.summary,description:i.description||"(no description)",comments:Vn(i.comments),question:r.question?.body??"(see the latest comment on the ticket)",questionAuthor:r.question?.author??"the commenter"})+await Zr(r.jira,i.attachments,r.repoPath,e);e("info",`Starting Claude Code in ${r.repoPath} - read-only tools, path-jailed, timeout ${n.timeoutSeconds}s`);let a=await Zn(wr(n.agent),{repoPath:r.repoPath,prompt:o,timeoutSeconds:n.timeoutSeconds,bin:an(r.cfg,n.agent),configDir:r.claudeConfigDir,mode:"read_only",model:n.model||void 0,sessionId:(0,Zs.randomUUID)(),onLog:(c,h)=>e(c,h)},e),l={costUsd:a.costUsd,inputTokens:a.inputTokens,outputTokens:a.outputTokens,billingMode:a.billingMode,model:a.model};if(!a.ok||!a.resultText.trim()){let c=a.error??"Claude Code produced no answer";e("error",`Run failed: ${c}`),await r.jira.addComment(r.issueKey,`**Allwright could not answer this question.**
|
|
519
520
|
|
|
520
521
|
Error: ${c.slice(0,800)}
|
|
521
522
|
|
|
522
|
-
Ask again in a new comment to retry. (run \`${r.runId}\`)`).catch(
|
|
523
|
+
Ask again in a new comment to retry. (run \`${r.runId}\`)`).catch(h=>g.error(`could not post answer failure to ${r.issueKey}: ${h}`)),t(a.timedOut?"timed_out":"failed",{error:c,...l});return}t("posting",l),e("info",`Posting answer to ${r.issueKey} (${a.resultText.length} chars)`),await r.jira.addComment(r.issueKey,a.resultText),t("succeeded",{...l,resultSummary:Bn(a.resultText)}),e("info",`Run succeeded \xB7 $${a.costUsd.toFixed(4)}`)}catch(i){let o=i instanceof Error?i.message:String(i);e("error",`Run failed: ${o}`),t("failed",{error:o})}finally{Tt(r.repoPath)}}async function zl(r,e,t,n){let s=`${e}-wip`;try{return Tt(r),await Ps(r,`WIP: turn limit exhausted (Allwright run ${t})`),await Wi(r,s),n("info",`Partial work preserved on branch "${s}"`),s}catch(i){return n("warn",`could not preserve partial work: ${i instanceof Error?i.message:i}`),null}}function Ll(r){return`
|
|
523
524
|
|
|
524
|
-
Partial work from this run is saved on branch \`${r}\`
|
|
525
|
+
Partial work from this run is saved on branch \`${r}\` - 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 ym(r){let{emit:e,setStatus:t,nextSeq:n}=Sr(r.runId,r.transport),{trigger:s}=r.rule,i=r.rule.action;if(i.type!=="implement")return;let o=Ds(i.agent,i.type);if(o){e("error",o),await hn(r,o),t("failed",{error:o});return}let a=jl.default.join(Mn(),r.runId),l=Pt(i.branchTemplate,{issueKey:r.issueKey}),c=(0,Zs.randomUUID)(),h=!1,p=!1;try{if(!Ns(ce()??r.cfg,r.project.repoName,r.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(l===i.baseBranch)throw new Error(`rendered branch "${l}" equals the base branch - refusing (check the rule's branch template)`);if(t("running"),e("info",`Run started for ${r.issueKey} (rule "${r.rule.name}", implement)`),i.jiraTransitionOnStart)try{await r.jira.transitionByName(r.issueKey,i.jiraTransitionOnStart)?e("info",`Jira transition "${i.jiraTransitionOnStart}" applied at run start`):e("warn",`no transition named "${i.jiraTransitionOnStart}" is available from this ticket's current status - continuing anyway`)}catch(q){e("warn",`Jira start transition failed: ${q instanceof Error?q.message:q} - continuing anyway`)}let _=await yr(r.repoPath);if(e("info",`Repo origin: ${_}`),!vr(_))throw new Error(`origin "${_}" is not a GitHub remote - implement mode supports GitHub only`);e("info",`Fetching ${r.issueKey} from Jira`);let b=await r.jira.getIssue(r.issueKey);e("info",`Preparing worktree on branch "${l}" from origin/${i.baseBranch}`),await tn(r.repoPath,i.baseBranch),await Yi(r.repoPath,l),await Xi(r.repoPath,a,l,i.baseBranch),h=!0;let x=Pt(i.promptTemplate,{issueKey:b.key,summary:b.summary,description:b.description||"(no description)",comments:Vn(b.comments)})+await Zr(r.jira,b.attachments,a,e)+(i.updateMemory?Ce.MEMORY_UPDATE_PROMPT:"");e("info",`Starting Claude Code in the worktree - edit tools enabled, path-jailed, no shell, timeout ${i.timeoutSeconds}s`);let C=await Zn(wr(i.agent),{repoPath:a,prompt:x,timeoutSeconds:i.timeoutSeconds,bin:an(r.cfg,i.agent),configDir:r.claudeConfigDir,mode:"edit_no_shell",model:i.model||void 0,maxTurns:i.maxTurns,sessionId:c,onLog:(q,f)=>e(q,f)},e,()=>$s(a)),S={costUsd:C.costUsd,inputTokens:C.inputTokens,outputTokens:C.outputTokens,billingMode:C.billingMode,model:C.model};if(!C.ok){let q=C.error??"Claude Code failed";e("error",`Run failed: ${q}`);let f=q;if(C.turnLimitHit){let m=await zl(a,l,r.runId,e);m&&(f+=Ll(m))}await hn(r,f),t(C.timedOut?"timed_out":"failed",{error:q,...S});return}let F=Vs(C.resultText);if(F){p=!0,await Gs({kind:"implement",runId:r.runId,issueKey:r.issueKey,repoPath:a,sessionId:c,doneLabel:s.doneLabel,failedLabel:s.failedLabel,timeoutSeconds:i.timeoutSeconds,jira:r.jira,nextLogSeq:n(),rounds:1,claudeConfigDir:r.claudeConfigDir,agent:i.agent,model:i.model,actorEmail:r.actorEmail,baseRepoPath:r.repoPath,repoName:r.project.repoName,branch:l,baseBranch:i.baseBranch,jiraTransition:i.jiraTransition,jiraTransitionOnMerge:i.jiraTransitionOnMerge,requireApproval:i.requireApproval,maxTurns:i.maxTurns,issueSummary:b.summary},F,e,t,S);return}Tt(a),await Ul({runId:r.runId,issueKey:r.issueKey,issueSummary:b.summary,worktreePath:a,baseRepoPath:r.repoPath,branch:l,baseBranch:i.baseBranch,jiraTransition:i.jiraTransition,jiraTransitionOnMerge:i.jiraTransitionOnMerge,requireApproval:i.requireApproval,doneLabel:s.doneLabel,failedLabel:s.failedLabel,repoName:r.project.repoName,jira:r.jira,cfg:r.cfg,actorEmail:r.actorEmail,resultText:C.resultText,costFields:S,emit:e,setStatus:t})}catch(_){let b=_ instanceof Error?_.message:String(_);e("error",`Run failed: ${b}`),await hn(r,b),t("failed",{error:b})}finally{h&&!p&&await rn(r.repoPath,a).catch(()=>{})}}async function Dl(r,e,t,n){let{emit:s,setStatus:i,nextSeq:o}=Sr(r.runId,n.transport,r.nextLogSeq),a=r.repoPath,l=!1;try{if(!Ns(ce()??n.cfg,r.repoName??"",r.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 ${r.issueKey} - continuing run \`${r.runId}\``);let c=Gl(e)+await Zr(n.jiraFor(r.repoName??""),t,a,s),h=await Zn(wr(r.agent),{repoPath:a,prompt:c,timeoutSeconds:r.timeoutSeconds,bin:an(n.cfg,r.agent??""),configDir:r.claudeConfigDir,mode:"edit_no_shell",model:r.model||void 0,maxTurns:r.maxTurns??120,sessionId:r.sessionId,resume:!0,onLog:(b,x)=>s(b,x)},s,()=>$s(a)),p={costUsd:h.costUsd,inputTokens:h.inputTokens,outputTokens:h.outputTokens,billingMode:h.billingMode,model:h.model};if(!h.ok){let b=h.error??"Claude Code failed";s("error",`Run failed: ${b}`);let x=b;if(h.turnLimitHit&&r.branch){let C=await zl(a,r.branch,r.runId,s);C&&(x+=Ll(C))}await ht(n.jiraFor(r.repoName??""),r.issueKey,r.runId,r.failedLabel,x),Xe(r.runId),i(h.timedOut?"timed_out":"failed",{error:b,...p});return}let _=Vs(h.resultText);if(_){if(r.rounds>=Ol){await Hl(n.jiraFor(r.repoName??""),r,s,i,p);return}l=!0,await Gs({kind:"implement",runId:r.runId,issueKey:r.issueKey,repoPath:a,sessionId:r.sessionId,doneLabel:r.doneLabel,failedLabel:r.failedLabel,timeoutSeconds:r.timeoutSeconds,jira:n.jiraFor(r.repoName??""),nextLogSeq:o(),rounds:r.rounds+1,createdAt:r.createdAt,claudeConfigDir:r.claudeConfigDir,actorEmail:r.actorEmail,agent:r.agent,model:r.model,baseRepoPath:r.baseRepoPath,repoName:r.repoName,branch:r.branch,baseBranch:r.baseBranch,jiraTransition:r.jiraTransition,jiraTransitionOnMerge:r.jiraTransitionOnMerge,requireApproval:r.requireApproval,maxTurns:r.maxTurns,issueSummary:r.issueSummary},_,s,i,p);return}Tt(a),await Ul({runId:r.runId,issueKey:r.issueKey,issueSummary:r.issueSummary,worktreePath:a,baseRepoPath:r.baseRepoPath??a,branch:r.branch,baseBranch:r.baseBranch,jiraTransition:r.jiraTransition,requireApproval:r.requireApproval??!0,doneLabel:r.doneLabel,failedLabel:r.failedLabel,repoName:r.repoName,jira:n.jiraFor(r.repoName??""),cfg:n.cfg,actorEmail:r.actorEmail,resultText:h.resultText,costFields:p,emit:s,setStatus:i}),Xe(r.runId)}catch(c){let h=c instanceof Error?c.message:String(c);s("error",`Run failed: ${h}`),await ht(n.jiraFor(r.repoName??""),r.issueKey,r.runId,r.failedLabel,h),Xe(r.runId),i("failed",{error:h})}finally{l||await rn(r.baseRepoPath??a,a).catch(()=>{})}}async function Ul(r){let{runId:e,issueKey:t,issueSummary:n,worktreePath:s,baseRepoPath:i,branch:o,baseBranch:a,jiraTransition:l,jiraTransitionOnMerge:c,requireApproval:h,doneLabel:p,failedLabel:_,repoName:b,jira:x,cfg:C,actorEmail:S,resultText:F,costFields:q,emit:f,setStatus:m}=r,w=await Hi(s);w.deleted.length&&f("info",`Deleted ${w.deleted.length} file(s) listed in ${en}: `+w.deleted.slice(0,10).join(", ")+(w.deleted.length>10?", \u2026":""));for(let M of w.refused)f("warn",`${en} entry refused: ${M}`);f("info","Committing changes"),await Ps(s,`${t}: ${n}
|
|
525
526
|
|
|
526
|
-
Allwright run ${e}`);let A=await
|
|
527
|
+
Allwright run ${e}`);let A=await Qi(s,a);if(!A.ok){let M=A.forbidden.length?`refusing to push: changes touch protected paths (${A.forbidden.slice(0,5).join(", ")}) - CI/workflow files can exfiltrate repo secrets and are never pushed by the agent`:`refusing to push: change is too large (${A.files} files, ${A.insertions+A.deletions} lines; limits ${As}/${Rs})`;f("error",M),await ht(x,t,e,_,M),m("failed",{error:M,...q});return}f("info",`Diff: ${A.files} file(s), +${A.insertions}/-${A.deletions}`);let N=await yr(s),B=vr(N);if(!B){let M=`origin "${N}" is not a GitHub remote - implement mode supports GitHub only`;f("error",M),await ht(x,t,e,_,M),m("failed",{error:M,...q});return}let z=await zn(s),re=vm(F);try{await ql({gitDir:s,ownerRepo:B,runId:e,issueKey:t,issueSummary:n,branch:o,baseBranch:a,jiraTransition:l,jiraTransitionOnMerge:c,requireApproval:h,doneLabel:p,failedLabel:_,repoName:b,jira:x,cfg:C,actorEmail:S,summary:re,cost:q,emit:f,setStatus:m})}catch(M){let J=M instanceof Error?M.message:String(M);Ao({runId:e,issueKey:t,issueSummary:n,repoName:b,baseRepoPath:i,branch:o,baseBranch:a,headSha:z,requireApproval:h,doneLabel:p,failedLabel:_,jiraTransition:l,jiraTransitionOnMerge:c,actorEmail:S,resultSummary:re,costUsd:q.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),f("error",`Run failed: ${J}`),f("info",`The commit itself survived on the runner (branch ${o}) - fix the cause, then use "Retry push" on this run's dashboard page.`),await ht(x,t,e,_,`${J}
|
|
527
528
|
|
|
528
|
-
The agent's commit survived on the runner
|
|
529
|
+
The agent's commit survived on the runner - "Retry push" on the dashboard's run page re-pushes it without a new agent run.`),m("failed",{error:J,retryAvailable:!0,...q})}}async function ql(r){let{gitDir:e,ownerRepo:t,runId:n,issueKey:s,issueSummary:i,branch:o,baseBranch:a,jiraTransition:l,jiraTransitionOnMerge:c,requireApproval:h,doneLabel:p,failedLabel:_,repoName:b,jira:x,cfg:C,actorEmail:S,summary:F,cost:q,emit:f,setStatus:m}=r;f("info",`Pushing ${o} to origin`),await eo(e,o);let w=await js(e,o),A=`${F}
|
|
529
530
|
|
|
530
531
|
---
|
|
531
532
|
Jira: ${new URL(`/browse/${s}`,C.jira?.baseUrl??"").toString()}
|
|
532
|
-
_Allwright implement run \`${n}\` \xB7 cost $${q.costUsd.toFixed(4)}. The agent could not run tests
|
|
533
|
+
_Allwright implement run \`${n}\` \xB7 cost $${q.costUsd.toFixed(4)}. The agent could not run tests - review accordingly._`;f("info","Opening pull request");let N=Ns(ce()??C,b,S);N.source==="user"&&f("info",`PR will be authored with ${S}'s own GitHub token`);let z=await new Me(N.token).createPullRequest(t.owner,t.repo,{title:`${s}: ${i}`.slice(0,250),head:o,base:a,body:A});f("info",`PR ready: ${z.url}`),El({runId:n,issueKey:s,repoName:b,owner:t.owner,repo:t.repo,prNumber:z.number,prUrl:z.url,jiraTransitionOnMerge:c??"",createdAt:new Date().toISOString()}),m("posting",q);let re={runId:n,issueKey:s,repoName:b,owner:t.owner,repo:t.repo,prNumber:z.number,prUrl:z.url,branch:o,headSha:w,doneLabel:p,failedLabel:_,jiraTransition:l};h?(cn(re),await x.addComment(s,`**Allwright opened a pull request for review.**
|
|
533
534
|
|
|
534
|
-
PR: ${
|
|
535
|
+
PR: ${z.url}
|
|
535
536
|
|
|
536
|
-
Approve the PR on GitHub OR on the Allwright dashboard
|
|
537
|
+
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 \`${n}\`)`),m("awaiting_approval",{...q,prUrl:z.url,headSha:w,resultSummary:Bn(F),retryAvailable:!1}),f("info",`Awaiting approval on the dashboard \xB7 $${q.costUsd.toFixed(4)}`)):(await Fl({jira:x,issueKey:s},re,f),m("succeeded",{...q,prUrl:z.url,headSha:w,resultSummary:Bn(F),retryAvailable:!1}),f("info",`Run succeeded \xB7 ${z.url} \xB7 $${q.costUsd.toFixed(4)}`))}async function Fl(r,e,t){let n=null;if(e.jiraTransition)try{await r.jira.transitionByName(e.issueKey,e.jiraTransition)?t("info",`Jira transition "${e.jiraTransition}" applied`):(n=`no transition named "${e.jiraTransition}" is available from this ticket's current status - the PR is fine, but move the ticket manually`,t("warn",n))}catch(s){n=`Jira transition failed: ${s instanceof Error?s.message:s}`,t("warn",n)}return await r.jira.addComment(e.issueKey,`**Allwright: implementation complete.**
|
|
537
538
|
|
|
538
539
|
PR: ${e.prUrl}`+(n?`
|
|
539
540
|
|
|
540
541
|
Note: ${n}`:"")+`
|
|
541
542
|
|
|
542
|
-
(run \`${e.runId}\`)`),await r.jira.editLabels(e.issueKey,{add:[e.doneLabel],remove:[Ce.NEEDS_INPUT_LABEL]}),n}async function Kn(r,e,t){let n
|
|
543
|
+
(run \`${e.runId}\`)`),await r.jira.editLabels(e.issueKey,{add:[e.doneLabel],remove:[Ce.NEEDS_INPUT_LABEL]}),n}async function Kn(r,e,t){let n=$o(e);if(!n){g.warn(`run.approved for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:s,setStatus:i}=Kl(r,e);try{let o=$t(ce()??r.cfg,n.repoName);if(!o)throw new Error("GitHub token missing on this runner");let a=new Me(o);s("info",`Approval received for ${n.issueKey} - verifying PR state`);let l=await a.getPullRequest(n.owner,n.repo,n.prNumber);if(!l)throw new Error(`PR #${n.prNumber} no longer exists on GitHub`);if(l.state==="closed"&&!l.merged)throw new Error(`PR #${n.prNumber} was closed on GitHub without merging`);let c=t??n.headSha;if(l.state==="open"&&l.headSha!==c){let h=`PR #${n.prNumber} changed since review started (${c.slice(0,7)} \u2192 ${l.headSha.slice(0,7)}) - approval not applied. Re-review the PR and approve again.`;s("warn",h),await r.jiraFor(n.repoName??"").addComment(n.issueKey,`**Allwright:** ${h}`),i("awaiting_approval",{prUrl:n.prUrl,headSha:l.headSha,resultSummary:h});return}await Fl({jira:r.jiraFor(n.repoName??""),issueKey:n.issueKey},n,s),i("succeeded",{prUrl:n.prUrl}),s("info","Run completed after approval"),kr(e)}catch(o){let a=o instanceof Error?o.message:String(o);s("error",`Approval handling failed: ${a}`),await Vl(r,n,a),i("failed",{error:a}),kr(e)}}async function Bl(r,e){let t=$o(e);if(!t){g.warn(`run.rejected for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:n,setStatus:s}=Kl(r,e);try{let i=$t(ce()??r.cfg,t.repoName);if(!i)throw new Error("GitHub token missing on this runner");let o=new Me(i);n("info",`Rejection received for ${t.issueKey} - closing PR #${t.prNumber}`);let a=await o.getPullRequest(t.owner,t.repo,t.prNumber);a&&a.state==="open"&&await o.closePullRequest(t.owner,t.repo,t.prNumber),a?.merged||await o.deleteBranch(t.owner,t.repo,t.branch),await r.jiraFor(t.repoName??"").addComment(t.issueKey,`**Allwright: changes rejected.**
|
|
543
544
|
|
|
544
|
-
The pull request was closed and the branch deleted. This ticket is labeled \`${t.failedLabel}\`; remove the label to try again. (run \`${t.runId}\`)`),await r.jiraFor(t.repoName??"").editLabels(t.issueKey,{add:[t.failedLabel]}),s("failed",{error:"rejected by user"}),n("info","PR closed, branch deleted, ticket labeled"),kr(e)}catch(i){let o=i instanceof Error?i.message:String(i);n("error",`Rejection handling failed: ${o}`),await
|
|
545
|
+
The pull request was closed and the branch deleted. This ticket is labeled \`${t.failedLabel}\`; remove the label to try again. (run \`${t.runId}\`)`),await r.jiraFor(t.repoName??"").editLabels(t.issueKey,{add:[t.failedLabel]}),s("failed",{error:"rejected by user"}),n("info","PR closed, branch deleted, ticket labeled"),kr(e)}catch(i){let o=i instanceof Error?i.message:String(i);n("error",`Rejection handling failed: ${o}`),await Vl(r,t,o),s("failed",{error:o}),kr(e)}}async function Zl(r,e){let t=Us(e);if(!t){g.warn(`run.retryPush for ${e}: no retry record (already pushed, or invalidated?)`);let{emit:o,setStatus:a}=Sr(e,r.transport,1e5);o("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."),a("failed",{retryAvailable:!1});return}let{emit:n,setStatus:s,nextSeq:i}=Sr(e,r.transport,t.nextLogSeq);try{let o=await js(t.baseRepoPath,t.branch);if(o!==t.headSha){n("error",`Retry push aborted: branch ${t.branch} no longer holds the commit this run produced (expected ${t.headSha.slice(0,7)}, ${o?`found ${o.slice(0,7)}`:"the branch is gone"}) - a newer run has likely reused the branch. Re-run the ticket instead.`),Ro(e),s("failed",{retryAvailable:!1});return}let a=await yr(t.baseRepoPath),l=vr(a);if(!l)throw new Error(`origin "${a}" is not a GitHub remote`);n("info",`Retry push for ${t.issueKey}: branch ${t.branch} at ${t.headSha.slice(0,7)}`);let c=r.jiraFor(t.repoName);await ql({gitDir:t.baseRepoPath,ownerRepo:l,runId:t.runId,issueKey:t.issueKey,issueSummary:t.issueSummary,branch:t.branch,baseBranch:t.baseBranch,jiraTransition:t.jiraTransition,jiraTransitionOnMerge:t.jiraTransitionOnMerge,requireApproval:t.requireApproval,doneLabel:t.doneLabel,failedLabel:t.failedLabel,repoName:t.repoName,jira:c,cfg:ce()??r.cfg,actorEmail:t.actorEmail,summary:t.resultSummary,cost:{costUsd:t.costUsd},emit:n,setStatus:s}),Ro(e),await c.editLabels(t.issueKey,{remove:[t.failedLabel]}).catch(()=>{})}catch(o){let a=o instanceof Error?o.message:String(o);n("error",`Retry push failed: ${a}`),Ao({...t,nextLogSeq:i()}),s("failed",{error:a,retryAvailable:!0})}}function Kl(r,e){let t=1e5;return{emit:(i,o)=>{r.transport.send({type:"run.log",runId:e,seq:t++,ts:new Date().toISOString(),level:i,message:o}),i!=="agent"&&g.info(`[run ${e}] ${o}`)},setStatus:(i,o={})=>{r.transport.send({type:"run.status",runId:e,status:i,...o})}}}async function Vl(r,e,t){try{await r.jiraFor(e.repoName??"").addComment(e.issueKey,`**Allwright could not complete the approval decision.**
|
|
545
546
|
|
|
546
547
|
Error: ${t.slice(0,800)}
|
|
547
548
|
|
|
@@ -549,47 +550,47 @@ PR: ${e.prUrl}
|
|
|
549
550
|
(run \`${e.runId}\`)`),await r.jiraFor(e.repoName??"").editLabels(e.issueKey,{add:[e.failedLabel]})}catch(n){g.error(`could not post decision failure to ${e.issueKey}: ${n}`)}}function Vn(r){if(!r.length)return"(no comments)";let e=6e4,t=r.map(i=>`${i.author} (${i.created}):
|
|
550
551
|
${i.body}`),n=[],s=0;for(let i=t.length-1;i>=0;i--){if(s+=t[i].length+6,s>e){n.unshift(`(\u2026 ${i+1} earlier comment(s) omitted for length \u2026)`);break}n.unshift(t[i])}return n.join(`
|
|
551
552
|
---
|
|
552
|
-
`)}function
|
|
553
|
+
`)}function Gl(r){return`The ticket author replied:
|
|
553
554
|
|
|
554
555
|
${r}
|
|
555
556
|
|
|
556
|
-
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 ${Ce.NEEDS_INPUT_MARKER} marker).`}function
|
|
557
|
+
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 ${Ce.NEEDS_INPUT_MARKER} marker).`}function Vs(r){let e=r.trim(),t=e.split(`
|
|
557
558
|
`,1)[0].trim(),n=o=>o.replace(/[^a-z]/gi,"").toUpperCase();if(n(t)!==n(Ce.NEEDS_INPUT_MARKER))return null;let s=e.indexOf(`
|
|
558
|
-
`);return s<0?null:e.slice(s+1).trim()||null}async function
|
|
559
|
+
`);return s<0?null:e.slice(s+1).trim()||null}async function Gs(r,e,t,n,s){t("info",`Claude needs more information - posting questions to ${r.issueKey}`),await r.jira.addComment(r.issueKey,`**${Ce.NEEDS_INPUT_COMMENT_MARKER} before it can continue.**
|
|
559
560
|
|
|
560
561
|
${e}
|
|
561
562
|
|
|
562
|
-
Reply with your answers in a comment on this ticket
|
|
563
|
+
Reply with your answers in a comment on this ticket - this run will pick up right where it left off, automatically, once you do. (run \`${r.runId}\`)`);let i=new Date().toISOString();await r.jira.editLabels(r.issueKey,{add:[Ce.NEEDS_INPUT_LABEL]}),Rl({runId:r.runId,issueKey:r.issueKey,kind:r.kind,repoPath:r.repoPath,sessionId:r.sessionId,doneLabel:r.doneLabel,failedLabel:r.failedLabel,timeoutSeconds:r.timeoutSeconds,createdAt:r.createdAt??i,questionsPostedAt:i,rounds:r.rounds,nextLogSeq:r.nextLogSeq,baseRepoPath:r.baseRepoPath,repoName:r.repoName,branch:r.branch,baseBranch:r.baseBranch,jiraTransition:r.jiraTransition,jiraTransitionOnMerge:r.jiraTransitionOnMerge,requireApproval:r.requireApproval,maxTurns:r.maxTurns,issueSummary:r.issueSummary??"",claudeConfigDir:r.claudeConfigDir,agent:r.agent,model:r.model,actorEmail:r.actorEmail}),n("needs_input",{...s,resultSummary:Bn(e)}),t("info",`Waiting for a reply on ${r.issueKey} (label "${Ce.NEEDS_INPUT_LABEL}")`)}async function Hl(r,e,t,n,s){let i=`Claude asked for clarification ${e.rounds} times without reaching a result - giving up. Answer more completely and re-trigger manually if you want another attempt.`;t("error",i),await ht(r,e.issueKey,e.runId,e.failedLabel,i),Xe(e.runId),n("failed",{error:i,...s})}async function hn(r,e){await ht(r.jira,r.issueKey,r.runId,r.rule.trigger.failedLabel,e)}async function ht(r,e,t,n,s){try{await r.addComment(e,`**Allwright run failed.**
|
|
563
564
|
|
|
564
565
|
Error: ${s.slice(0,800)}
|
|
565
566
|
|
|
566
|
-
This ticket has been labeled \`${n}\` and will not be retried automatically. To retry, fix the cause and remove the \`${n}\` label. (run \`${t}\`)`),await r.editLabels(e,{add:[n],remove:[Ce.NEEDS_INPUT_LABEL]})}catch(i){g.error(`could not post failure comment to ${e}: ${i}`)}}function
|
|
567
|
-
`)){let t=e.replace(/^#+\s*/,"").trim();if(t.length>10)return t.slice(0,200)}return r.slice(0,200)}var
|
|
567
|
+
This ticket has been labeled \`${n}\` and will not be retried automatically. To retry, fix the cause and remove the \`${n}\` label. (run \`${t}\`)`),await r.editLabels(e,{add:[n],remove:[Ce.NEEDS_INPUT_LABEL]})}catch(i){g.error(`could not post failure comment to ${e}: ${i}`)}}function vm(r){let e=/##\s*Summary of changes\s*\n([\s\S]*)$/i.exec(r);return(e?e[1]:r).trim().slice(0,8e3)||"(no summary provided)"}function Bn(r){for(let e of r.split(`
|
|
568
|
+
`)){let t=e.replace(/^#+\s*/,"").trim();if(t.length>10)return t.slice(0,200)}return r.slice(0,200)}var fn=$(require("node:fs"),1),xr=$(require("node:path"),1),Hs=require("node:child_process"),Oo=$(require("node:readline"),1),ec=require("node:crypto"),Tr=$(Te(),1);_r();ct();var Wl=4e3,_m=4e3;function No(r){let e=0;return{emit:(s,i)=>{r.transport.send({type:"run.log",runId:r.runId,seq:e++,ts:new Date().toISOString(),level:s,message:i.slice(0,_m)}),s!=="agent"&&g.info(`[deploy ${r.runId}] ${i}`)},setStatus:(s,i={})=>{r.transport.send({type:"run.status",runId:r.runId,status:s,...i})}}}async function Ws(r){let{emit:e,setStatus:t}=No(r),n=r.environment;try{let s=bm(r);if(s){e("error",s),await Fe(r,`**Allwright could not deploy to \`${n.name}\`.**
|
|
568
569
|
|
|
569
|
-
${s}`),t("failed",{error:s});return}if(n.requireApproval){
|
|
570
|
+
${s}`),t("failed",{error:s});return}if(n.requireApproval){Al({runId:r.runId,issueKey:r.issueKey,issueSummary:r.issueSummary,projectId:r.project.id,repoName:r.project.repoName,environmentName:n.name,requestedBy:r.requestedBy,createdAt:new Date().toISOString()}),e("info",`Deploy to "${n.name}" is waiting for approval on the dashboard - no step has run yet`),await Fe(r,`**Allwright: deploy to \`${n.name}\` needs approval.**
|
|
570
571
|
|
|
571
|
-
${r.requestedBy?`Requested by ${r.requestedBy}. `:""}Nothing has been executed yet. Approve it on the Allwright dashboard to run the ${n.steps.length} deploy step(s), or reject to cancel. (run \`${r.runId}\`)`),t("awaiting_approval",{resultSummary:`Awaiting approval to deploy ${r.issueKey} to ${n.name}`});return}await
|
|
572
|
+
${r.requestedBy?`Requested by ${r.requestedBy}. `:""}Nothing has been executed yet. Approve it on the Allwright dashboard to run the ${n.steps.length} deploy step(s), or reject to cancel. (run \`${r.runId}\`)`),t("awaiting_approval",{resultSummary:`Awaiting approval to deploy ${r.issueKey} to ${n.name}`});return}await tc(r,e,t)}catch(s){let i=s instanceof Error?s.message:String(s);e("error",`Deploy failed: ${i}`),await Fe(r,`**Allwright deploy to \`${n.name}\` failed.**
|
|
572
573
|
|
|
573
574
|
${i.slice(0,800)}
|
|
574
575
|
|
|
575
|
-
(run \`${r.runId}\`)`),t("failed",{error:i})}}function
|
|
576
|
+
(run \`${r.runId}\`)`),t("failed",{error:i})}}function bm(r){let e=r.environment;if(!r.cfg.deploy.enabled)return"deployments are turned off on this runner. Deploy steps are shell commands, so they stay disabled until someone with access to this machine runs `allwright deploy enable`.";if(!e.steps.length)return`environment "${e.name}" has no deploy steps configured - add them in the dashboard first`;if(e.promotionMode==="merge_and_deploy"&&!e.branch)return`environment "${e.name}" is set to merge-and-deploy but has no branch configured`;if(e.useDedicatedCheckout&&!e.branch)return`environment "${e.name}" wants a dedicated checkout but has no branch configured`;let t=Qt(r.cfg,r.project.repoName,e.name),n=e.requiredSecrets.filter(s=>!t[s]&&!process.env[s]);return n.length?`missing deploy secret(s) on this runner: ${n.join(", ")}. Set them with: allwright env set "${r.project.repoName}" "${e.name}" ${n[0]}=...`:null}async function tc(r,e,t){let n=r.environment,s=Qt(r.cfg,r.project.repoName,n.name),i=Tm(Object.values(s)),o=Date.now();if(t("running"),e("info",`Deploying ${r.issueKey} to "${n.name}"`+(r.requestedBy?` (requested by ${r.requestedBy})`:"")+` - ${n.steps.length} step(s), ${n.timeoutSeconds}s budget`),n.auditBeforeDeploy){e("info",`Pre-deploy ${n.auditBeforeDeploy} audit starting (advisory - will not block)`);try{let S=await on({projectId:r.project.id,repoPath:r.repoPath,role:n.auditBeforeDeploy,scope:{kind:"repo",ref:""},model:"",claudeBin:r.cfg.claudeBin,jira:r.jira});if(!S.ok)e("warn",`Pre-deploy audit could not run: ${S.error} - deploying anyway (advisory)`);else if(!S.audit.findings.length)e("info","Pre-deploy audit: no findings \u2713");else{let F={};for(let q of S.audit.findings)F[q.severity]=(F[q.severity]??0)+1;e("warn",`Pre-deploy audit: ${S.audit.findings.length} finding(s) (`+Object.entries(F).map(([q,f])=>`${f} ${q}`).join(", ")+") - full report on the Audits page. Deploying anyway (advisory).");for(let q of S.audit.findings.slice(0,5))e("warn",` [${q.severity}] ${q.title} - ${q.evidence[0]?.file??""}`)}}catch(S){e("warn",`Pre-deploy audit crashed: ${S instanceof Error?S.message:String(S)} - deploying anyway`)}}if(n.requireSyncCheck){if(!n.previousEnvBranch||!n.branch){let F=n.branch?`"${n.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 "${n.name}" moved to the top?), or turn the check off.`:`"${n.name}" requires a branch sync check but has no branch set - set it, or turn the check off`;e("error",F),await Fe(r,`**Allwright refused to deploy to \`${n.name}\`.**
|
|
576
577
|
|
|
577
|
-
${
|
|
578
|
+
${F}
|
|
578
579
|
|
|
579
|
-
(run \`${r.runId}\`)`),t("failed",{error:
|
|
580
|
+
(run \`${r.runId}\`)`),t("failed",{error:F,errorKind:"guard"});return}let S=await km(r,e);if(S){await Fe(r,S.comment),t("failed",{error:S.error,...S.guard?{errorKind:"guard"}:{}});return}}let a=r.repoPath;if(n.useDedicatedCheckout||n.promotionMode==="merge_and_deploy"?(e("info",`Preparing ${n.name} checkout at origin/${n.branch}`),a=await no({repoPath:r.repoPath,repoName:r.project.repoName,envName:n.name,branch:n.branch,attached:n.promotionMode==="merge_and_deploy"})):e("info",`No dedicated checkout for "${n.name}" - running the steps in the mapped checkout as it is`),n.promotionMode==="merge_and_deploy"){let S=Pt(n.ticketBranchTemplate,{issueKey:r.issueKey});e("info",`Merging "${S}" into "${n.branch}"`);let F=await so(a,S,`Deploy ${r.issueKey} to ${n.name}
|
|
580
581
|
|
|
581
|
-
Allwright run ${r.runId}`);if(!
|
|
582
|
+
Allwright run ${r.runId}`);if(!F.ok){e("error",F.reason??"merge failed"),await Fe(r,`**Allwright deploy to \`${n.name}\` failed before running anything.**
|
|
582
583
|
|
|
583
|
-
${
|
|
584
|
+
${F.reason}`),t("failed",{error:F.reason});return}F.alreadyMerged?e("info",`"${S}" is already in "${n.branch}" - nothing to merge`):(e("info",`Pushing "${n.branch}" to origin`),await io(a,n.branch))}let c=await zn(a).catch(()=>"");c&&e("info",`Deploying commit ${c.slice(0,10)}`);let h=Sm(a,n.workdir),p={...process.env,...s,ALLWRIGHT_ENVIRONMENT:n.name,ALLWRIGHT_ISSUE_KEY:r.issueKey,ALLWRIGHT_RUN_ID:r.runId,ALLWRIGHT_DEPLOY_REF:c,ALLWRIGHT_BRANCH:n.branch,TICKETPILOT_ENVIRONMENT:n.name,TICKETPILOT_ISSUE_KEY:r.issueKey,TICKETPILOT_RUN_ID:r.runId,TICKETPILOT_DEPLOY_REF:c,TICKETPILOT_BRANCH:n.branch},_=0,b=n.timeoutSeconds*1e3;for(let[S,F]of n.steps.entries()){let q=b-(Date.now()-o);if(q<=0){let m=`deploy exceeded its ${n.timeoutSeconds}s budget before step ${S+1}`;e("error",m),await Fe(r,`**Allwright deploy to \`${n.name}\` timed out.**
|
|
584
585
|
|
|
585
|
-
${m}`),t("timed_out",{error:m,deployedRef:c});return}e("info",`\u25B6 step ${
|
|
586
|
+
${m}`),t("timed_out",{error:m,deployedRef:c});return}e("info",`\u25B6 step ${S+1}/${n.steps.length}: ${F.name}`);let f=await xm({command:F.run,cwd:h,env:p,timeoutMs:q,onLine:(m,w)=>{_++,_===Wl&&e("warn","(output truncated - deploy log limit reached)"),!(_>=Wl)&&e(m,i(w))}});if(f.timedOut){let m=`step "${F.name}" hit the ${n.timeoutSeconds}s deploy budget and was killed`;e("error",m),await Fe(r,`**Allwright deploy to \`${n.name}\` timed out.**
|
|
586
587
|
|
|
587
|
-
${m}`),t("timed_out",{error:m,deployedRef:c});return}if(f.code!==0){if(
|
|
588
|
+
${m}`),t("timed_out",{error:m,deployedRef:c});return}if(f.code!==0){if(F.continueOnError){e("warn",`step "${F.name}" exited ${f.code} - continuing (marked continue-on-error)`);continue}let m="";try{m=i(await Ji(a))}catch{}let w=`step ${S+1} "${F.name}" failed with exit code ${f.code}`+(f.tail?`: ${i(f.tail)}`:"")+(m?`
|
|
588
589
|
|
|
589
590
|
Checkout at failure:
|
|
590
|
-
${m}`:"");e("error",
|
|
591
|
+
${m}`:"");e("error",w),await Fe(r,`**Allwright deploy to \`${n.name}\` failed.**
|
|
591
592
|
|
|
592
|
-
Step ${
|
|
593
|
+
Step ${S+1} \`${F.name}\` exited ${f.code}.
|
|
593
594
|
|
|
594
595
|
`+(f.tail?`\`\`\`
|
|
595
596
|
${i(f.tail).slice(0,1200)}
|
|
@@ -600,96 +601,96 @@ ${i(f.tail).slice(0,1200)}
|
|
|
600
601
|
${m.slice(0,800)}
|
|
601
602
|
\`\`\`
|
|
602
603
|
|
|
603
|
-
`:"")+`Nothing after it ran. Full log is on the Allwright dashboard. (run \`${r.runId}\`)`),t("failed",{error:
|
|
604
|
+
`:"")+`Nothing after it ran. Full log is on the Allwright dashboard. (run \`${r.runId}\`)`),t("failed",{error:w.slice(0,1600),deployedRef:c});return}e("info",`\u2713 step ${S+1}/${n.steps.length}: ${F.name}`)}t("posting");let x=Math.round((Date.now()-o)/1e3);r.issueKey!==Tr.BRANCH_DEPLOY_ISSUE_KEY&&await Fe(r,`**Allwright deployed \`${r.issueKey}\` to \`${n.name}\`.**
|
|
604
605
|
|
|
605
606
|
`+(c?`Commit: \`${c.slice(0,10)}\`${n.branch?` on \`${n.branch}\``:""}
|
|
606
|
-
`:"")+`${n.steps.length} step(s) in ${
|
|
607
|
+
`:"")+`${n.steps.length} step(s) in ${x}s.`+(r.requestedBy?` Requested by ${r.requestedBy}.`:"")+`
|
|
607
608
|
|
|
608
|
-
(run \`${r.runId}\`)`);let C=await
|
|
609
|
+
(run \`${r.runId}\`)`);let C=await wm(r,e,c);t("succeeded",{resultSummary:`Deployed to ${n.name}${c?` at ${c.slice(0,10)}`:""} in ${x}s`+(C!==null?` \xB7 ${C} ticket(s) moved to "${n.deployToColumn}"`:""),deployedRef:c}),e("info",`Deploy to "${n.name}" succeeded in ${x}s`)}async function wm(r,e,t){let n=r.environment;if(!n.deployFromColumn||!n.deployToColumn)return null;let s=new Date().toISOString().slice(0,10),i;try{i=await r.jira.search(`project = "${r.project.jiraProjectKey}" AND status = "${n.deployFromColumn}" ORDER BY updated ASC`,50)}catch(a){return e("warn",`deploy succeeded, but listing tickets in "${n.deployFromColumn}" failed: ${a instanceof Error?a.message:a} - move them by hand`),null}if(!i.length)return e("info",`No tickets in "${n.deployFromColumn}" to move`),0;e("info",`Moving ${i.length} ticket(s) from "${n.deployFromColumn}" to "${n.deployToColumn}"`);let o=0;for(let a of i)try{if(await r.jira.addComment(a.key,`**Allwright: deployed to \`${n.name}\` on ${s}.**
|
|
609
610
|
|
|
610
611
|
`+(t?`Commit: \`${t.slice(0,10)}\`${n.branch?` on \`${n.branch}\``:""}
|
|
611
|
-
`:"")+(r.requestedBy?`Requested by ${r.requestedBy}. `:"")+`(run \`${r.runId}\`)`),!await r.jira.transitionByName(a.key,n.deployToColumn)){e("warn",`${a.key}: no workflow transition to "${n.deployToColumn}" from its current status
|
|
612
|
+
`:"")+(r.requestedBy?`Requested by ${r.requestedBy}. `:"")+`(run \`${r.runId}\`)`),!await r.jira.transitionByName(a.key,n.deployToColumn)){e("warn",`${a.key}: no workflow transition to "${n.deployToColumn}" from its current status - left in place`),await r.jira.addComment(a.key,`**Allwright could not move this ticket to \`${n.deployToColumn}\`** - no such transition from its current status. The deploy itself succeeded; move it by hand. (run \`${r.runId}\`)`).catch(()=>{});continue}o++,e("info",`\u2713 ${a.key} \u2192 "${n.deployToColumn}"`)}catch(l){e("warn",`${a.key}: sweep failed (${l instanceof Error?l.message:l}) - left in "${n.deployFromColumn}"`)}return e("info",`Moved ${o}/${i.length} ticket(s) to "${n.deployToColumn}"`),o}async function km(r,e){let t=r.environment,n=t.previousEnvBranch,s=(a,l=!1)=>({error:a,guard:l,comment:`**Allwright could not deploy \`${r.issueKey}\` to \`${t.name}\`.**
|
|
612
613
|
|
|
613
614
|
${a}
|
|
614
615
|
|
|
615
|
-
(run \`${r.runId}\`)`});e("info",`Checking "${t.branch}" is in sync with "${n}" before deploying`);try{await tn(r.repoPath,n),await tn(r.repoPath,t.branch)}catch(a){return s(`sync check could not fetch branches: ${a instanceof Error?a.message:String(a)}`)}let i;try{i=await
|
|
616
|
+
(run \`${r.runId}\`)`});e("info",`Checking "${t.branch}" is in sync with "${n}" before deploying`);try{await tn(r.repoPath,n),await tn(r.repoPath,t.branch)}catch(a){return s(`sync check could not fetch branches: ${a instanceof Error?a.message:String(a)}`)}let i;try{i=await oo(r.repoPath,`origin/${n}`,`origin/${t.branch}`)}catch(a){return s(`sync check failed: ${a instanceof Error?a.message:String(a)}`)}if(!i)return e("info",`"${t.branch}" already matches "${n}" - continuing`),null;e("warn",`"${t.branch}" and "${n}" have diverged - opening a PR instead of deploying`);let o=$t(ce()??r.cfg,r.project.repoName);if(!o)return s(`"${t.branch}" and "${n}" 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 a=await yr(r.repoPath),l=vr(a);if(!l)throw new Error(`could not parse a GitHub owner/repo from origin "${a}"`);let h=await new Me(o).createPullRequest(l.owner,l.repo,{title:`Sync ${t.name} (${t.branch}) with ${n}`,head:n,base:t.branch,body:`Allwright opened this automatically while trying to deploy \`${r.issueKey}\` to \`${t.name}\`: \`${t.branch}\` doesn't have everything that's on \`${n}\` yet, so deploying now would ship different code than what was validated there. Merge this PR, then retry the deploy.
|
|
616
617
|
|
|
617
|
-
(run \`${r.runId}\`)`});return s(`"${t.branch}" is not in sync with "${n}"
|
|
618
|
-
`)}))},l=setTimeout(()=>{o=!0,
|
|
618
|
+
(run \`${r.runId}\`)`});return s(`"${t.branch}" is not in sync with "${n}" - opened ${h.url} to catch it up. Merge that, then retry the deploy.`,!0)}catch(a){return s(`could not open a sync PR: ${a instanceof Error?a.message:String(a)}`)}}function Sm(r,e){if(!e.trim())return r;let t=xr.default.resolve(r,e),n=xr.default.relative(r,t);if(n.startsWith("..")||xr.default.isAbsolute(n))throw new Error(`working directory "${e}" is outside the repository checkout`);return t}function xm(r){return new Promise(e=>{let t=(0,Hs.spawn)("bash",["-lc",r.command],{cwd:r.cwd,env:r.env,detached:!0,stdio:["ignore","pipe","pipe"]}),n=[],s=c=>{n.push(c),n.length>20&&n.shift()},i=!1,o=!1,a=c=>{i||(i=!0,clearTimeout(l),e({code:c,timedOut:o,tail:n.join(`
|
|
619
|
+
`)}))},l=setTimeout(()=>{o=!0,Jl(t.pid,"SIGTERM"),setTimeout(()=>Jl(t.pid,"SIGKILL"),1e4).unref()},r.timeoutMs);Oo.default.createInterface({input:t.stdout}).on("line",c=>{s(c),r.onLine("info",c)}),Oo.default.createInterface({input:t.stderr}).on("line",c=>{s(c),r.onLine("warn",c)}),t.on("error",c=>{s(`failed to start: ${c.message}`),a(127)}),t.on("close",c=>a(c??1))})}function Jl(r,e){if(r)try{process.kill(-r,e)}catch{try{process.kill(r,e)}catch{}}}function Tm(r){let e=r.filter(t=>t&&t.length>=6).sort((t,n)=>n.length-t.length);return e.length?t=>{let n=t;for(let s of e)n=n.split(s).join("***");return n}:t=>t}async function Fe(r,e){if(r.issueKey!==Tr.BRANCH_DEPLOY_ISSUE_KEY)try{await r.jira.addComment(r.issueKey,e)}catch(t){g.error(`could not post deploy comment to ${r.issueKey}: ${t}`)}}function Mo(r){return Fs(r)!==null}async function rc(r,e){let t=Fs(e);if(!t)return;let{emit:n,setStatus:s}=No({runId:e,transport:r.transport}),i=r.lookup(t.projectId,t.environmentName);if(!i){let a=`approved, but environment "${t.environmentName}" is no longer in this runner's config (deleted or renamed?) - nothing was deployed`;n("error",a),s("failed",{error:a}),Bs(e);return}Bs(e);let o={runId:e,project:i.project,environment:i.environment,issueKey:t.issueKey,issueSummary:t.issueSummary,repoPath:i.repoPath,cfg:r.cfg,jira:r.jiraFor(i.project.repoName),transport:r.transport,requestedBy:t.requestedBy};n("info",`Approved - running the ${i.environment.steps.length} deploy step(s) now`);try{await tc(o,n,s)}catch(a){let l=a instanceof Error?a.message:String(a);n("error",`Deploy failed: ${l}`),await Fe(o,`**Allwright deploy failed.**
|
|
619
620
|
|
|
620
|
-
${l.slice(0,800)}`),s("failed",{error:l})}}async function
|
|
621
|
+
${l.slice(0,800)}`),s("failed",{error:l})}}async function nc(r,e){let t=Fs(e);if(!t)return;let{emit:n,setStatus:s}=No({runId:e,transport:r.transport});Bs(e),n("info",`Deploy to "${t.environmentName}" was rejected - nothing ran`);let i=r.lookup(t.projectId,t.environmentName);try{await r.jiraFor(i?.project.repoName??"").addComment(t.issueKey,`**Allwright: deploy to \`${t.environmentName}\` was rejected.**
|
|
621
622
|
|
|
622
|
-
No deploy step was executed. (run \`${e}\`)`)}catch(o){g.error(`could not post rejection comment to ${t.issueKey}: ${o}`)}s("failed",{error:"deploy rejected by a reviewer"})}var
|
|
623
|
+
No deploy step was executed. (run \`${e}\`)`)}catch(o){g.error(`could not post rejection comment to ${t.issueKey}: ${o}`)}s("failed",{error:"deploy rejected by a reviewer"})}var Cm=k.object({steps:k.array(Tr.DeployStep).max(50).default([]),requiredSecrets:k.array(k.string()).max(50).default([]),notes:k.string().default("")}),Em=[".ticketpilot/deploy.md","DEPLOY.md","DEPLOYMENT.md","docs/DEPLOY.md","docs/deploy.md","docs/deployment.md"],Yl=24e3;function zo(r){for(let e of Em){let t=xr.default.join(r,e);try{if(!fn.default.existsSync(t))continue;let n=fn.default.readFileSync(t,"utf8");if(!n.trim())continue;return{path:e,content:n.length>Yl?n.slice(0,Yl)+`
|
|
623
624
|
|
|
624
|
-
[\u2026document truncated\u2026]`:n}}catch{continue}}return null}var
|
|
625
|
+
[\u2026document truncated\u2026]`:n}}catch{continue}}return null}var Xl=["docker","docker-compose","pm2","systemctl","node","pnpm","npm","yarn","make","python3","pip","rsync","ssh","caddy","nginx"];function sc(r){return ic("bash",["-lc",`command -v ${JSON.stringify(r)}`]).trim().length>0}function ic(r,e){try{let t=(0,Hs.spawnSync)(r,e,{encoding:"utf8",timeout:5e3});return t.status===0?t.stdout??"":""}catch{return""}}async function Im(r,e){let t;try{t=new URL(r)}catch{e.push({name:"public-url",ok:!1,detail:`not a valid URL: ${r}`});return}try{let{lookup:n}=await import("node:dns/promises"),s=await n(t.hostname);e.push({name:"public-url-dns",ok:!0,detail:`${t.hostname} \u2192 ${s.address}`})}catch{e.push({name:"public-url-dns",ok:!1,detail:`${t.hostname} does not resolve - add an A/CNAME record for it at your DNS provider (changes can take a few minutes to propagate)`});return}if(t.protocol==="https:"){let n=await import("node:tls");await new Promise(s=>{let i=n.connect({host:t.hostname,port:Number(t.port||443),servername:t.hostname,timeout:8e3},()=>{let o=i.getPeerCertificate(),a=o?.valid_to?Math.round((new Date(o.valid_to).getTime()-Date.now())/864e5):NaN;e.push(Number.isFinite(a)&&a>0?{name:"public-url-tls",ok:a>14,detail:`certificate valid, expires in ${a} day(s)${a<=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 n=await fetch(t.toString(),{method:"GET",redirect:"manual",signal:AbortSignal.timeout(1e4)});e.push({name:"public-url-reachable",ok:n.status<500,detail:`HTTP ${n.status}${n.status>=300&&n.status<400?` \u2192 ${n.headers.get("location")??""}`:""}`})}catch(n){e.push({name:"public-url-reachable",ok:!1,detail:`not reachable from the runner: ${n instanceof Error?n.message:String(n)}`})}}function Am(r){let e=r.match(/\/(?:var|home|opt|srv)\/[\w./-]+/g)??[],t=[...new Set(e.map(s=>s.replace(/[.,;:)\]'"`]+$/,"")))].slice(0,12);return t.length?`
|
|
625
626
|
- absolute paths the document mentions, checked on THIS machine:
|
|
626
|
-
${t.map(s=>` - ${s}: ${
|
|
627
|
-
`)}`:""}function
|
|
627
|
+
${t.map(s=>` - ${s}: ${fn.default.existsSync(s)?"EXISTS on this machine":"not found on this machine"}`).join(`
|
|
628
|
+
`)}`:""}function Rm(r,e,t,n=""){let s=Xl.filter(a=>sc(a)),i=Xl.filter(a=>!s.includes(a)),o=Object.keys(Qt(r,e,t));return`About the machine these steps will run on (gathered by the runner, trust it):
|
|
628
629
|
- available tools: ${s.join(", ")||"(none of the common ones)"}
|
|
629
630
|
- NOT installed: ${i.join(", ")||"(none missing)"}
|
|
630
|
-
- secrets already stored for this environment (names only): ${o.join(", ")||"(none yet)"}`+
|
|
631
|
-
`+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
|
|
632
|
-
`)[0].trim()||`Step ${e+1}`).slice(0,120)}_r();ct();function
|
|
631
|
+
- secrets already stored for this environment (names only): ${o.join(", ")||"(none yet)"}`+Am(n)}async function oc(r){let e=[];if(r.publicUrl?.trim()&&await Im(r.publicUrl.trim(),e),e.push(fn.default.existsSync(r.repoPath)?{name:"repo-path",ok:!0,detail:r.repoPath}:{name:"repo-path",ok:!1,detail:`checkout missing: ${r.repoPath}`}),e.push({name:"deploys-enabled",ok:r.cfg.deploy.enabled,detail:r.cfg.deploy.enabled?"enabled on this runner":"disabled - run: allwright deploy enable (then restart the runner)"}),r.workdir){let a=xr.default.isAbsolute(r.workdir)?r.workdir:xr.default.join(r.repoPath,r.workdir);e.push(fn.default.existsSync(a)?{name:"workdir",ok:!0,detail:a}:{name:"workdir",ok:!1,detail:`does not exist: ${a}`})}if(r.branch){let a=ic("git",["-C",r.repoPath,"ls-remote","--heads","origin",r.branch]);e.push(a.trim()?{name:"branch",ok:!0,detail:`origin/${r.branch} exists`}:{name:"branch",ok:!1,detail:`origin has no branch "${r.branch}" (or the remote is unreachable)`})}let t=Qt(r.cfg,r.repoName,r.environmentName),n=new Set(r.requiredSecrets);for(let a of r.steps)for(let l of a.run.matchAll(/\$\{?([A-Z][A-Z0-9_]{2,})\}?/g))n.add(l[1]);let s=[...n].filter(a=>!t[a]&&!process.env[a]);e.push({name:"secrets",ok:s.length===0,detail:s.length?`missing: ${s.join(", ")} - set with: allwright env set "${r.repoName}" "${r.environmentName}" ${s[0]}=...`:`${n.size} present`});let i=new Set;for(let a of r.steps)for(let l of a.run.split(/&&|\|\||;|\|/)){let c=l.trim().split(/\s+/),h=c.shift();for(;h&&(/^[A-Za-z_][A-Za-z0-9_]*=/.test(h)||h==="sudo"||h==="env"||h==="nohup");)h=c.shift();!h||h.startsWith("$")||h.startsWith("#")||h.startsWith("(")||i.add(h)}let o=[...i].filter(a=>!sc(a));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(a=>a.ok),checks:e}}async function ac(r){let e=zo(r.repoPath);if(!e)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:'this repo has no deploy document. Create DEPLOY.md at the repo root (or .ticketpilot/deploy.md) describing how this project actually deploys - the same commands you run by hand. "Ask Claude for steps" translates that document; it does not guess.'};let t=Rm(r.cfg,r.repoName,r.environmentName,e.content),n=Pt(Tr.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE,{envName:r.environmentName,docPath:e.path,docContent:e.content,notes:r.notes.trim()||"(nothing specified)",machineContext:t}),s=await Ne.run({repoPath:r.repoPath,prompt:n,timeoutSeconds:r.timeoutSeconds,bin:r.cfg.claudeBin,mode:"read_only",maxTurns:30,sessionId:(0,ec.randomUUID)(),onLog:()=>{}});if(!s.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:s.error??"Claude Code produced no output"};let i=$m(s.resultText);return i?{ok:!0,...i}:(g.warn(`deploy step suggestion could not be parsed. Claude's raw answer follows:
|
|
632
|
+
`+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 $m(r){for(let e of Pm(r)){let t;try{t=JSON.parse(e)}catch{continue}let n=Cm.safeParse(jm(t));if(n.success&&n.data.steps.length||n.success&&n.data.notes.trim())return n.data}return null}function Pm(r){let e=[];for(let s of r.matchAll(/```[a-zA-Z0-9_-]*[ \t]*\r?\n([\s\S]*?)```/g))s[1].trim()&&e.push(s[1]);let t=r.indexOf("{"),n=r.lastIndexOf("}");return t>=0&&n>t&&e.push(r.slice(t,n+1)),e}function jm(r){if(!r||typeof r!="object")return r;let e=r,n=(Array.isArray(r)?r:Array.isArray(e.steps)?e.steps:Array.isArray(e.deploy_steps)?e.deploy_steps:Array.isArray(e.deploySteps)?e.deploySteps:[]).map((o,a)=>{if(typeof o=="string")return o.trim()?{name:Ql(o,a),run:o.trim()}:null;if(!o||typeof o!="object")return null;let l=o,c=jo(l.run,l.command,l.cmd,l.script,l.shell);return c?{name:(jo(l.name,l.title,l.description)??Ql(c,a)).slice(0,120),run:c,continueOnError:l.continueOnError===!0||l.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:n.slice(0,50),requiredSecrets:i.slice(0,50),notes:jo(e.notes,e.note,e.explanation)??""}}function jo(...r){for(let e of r)if(typeof e=="string"&&e.trim())return e.trim()}function Ql(r,e){return(r.split(`
|
|
633
|
+
`)[0].trim()||`Step ${e+1}`).slice(0,120)}_r();ct();function Js(r,e){if(!r.componentRoutes.length)return{project:r};let t=e.filter(Boolean);if(!t.length)return{error:`no Jira component set - project "${r.name}" routes by component (${r.componentRoutes.map(i=>i.component).join(", ")}); set one on the ticket`};let n=r.componentRoutes.filter(i=>t.includes(i.component));if(!n.length)return{error:`component(s) [${t.join(", ")}] not mapped - known: `+r.componentRoutes.map(i=>`${i.component}\u2192${i.repoName}`).join(", ")};let s=new Set(n.map(i=>i.repoName));return s.size>1?{error:`components map to DIFFERENT repos (${[...s].join(", ")}) - ambiguous, refusing`}:{project:{...r,repoName:n[0].repoName}}}var uc=24*3600*1e3,Ys=14,Om=Ys*24*3600*1e3,Nm=new Set(["to","on","this","the","a","an","env","environment","please","now","it"]),Xs=class{constructor(e,t,n){this.cfg=e;this.jiraFor=t;this.transport=n}cfg;jiraFor;transport;projects=[];rules=[];environments=[];inFlight=new Set;autopilotPausedUntil=0;get busyCount(){return this.inFlight.size}repoQueues=new Map;envQueues=new Map;timer=null;ticking=!1;paused=!1;jiraOf(e){return this.jiraFor(e.repoName)}routingWarned=new Set;warnRoutingOnce(e,t){this.routingWarned.has(e)||(this.routingWarned.add(e),g.warn(`Component routing refused - ${t}`))}resolveClaudeProfile(e,t){if(!t)return;let n=this.cfg.claudeProfiles[t]?.configDir;return!n&&e&&(this.transport.send({type:"run.log",runId:e,seq:99e3,ts:new Date().toISOString(),level:"warn",message:`Claude profile "${t}" is not set up on this runner (allwright claude login "${t}") - using the runner's own login instead.`}),g.warn(`run ${e}: claude profile "${t}" missing locally - using default login`)),n}setConfig(e,t,n=!1,s=[]){this.projects=e,this.rules=t,this.environments=s;let i=t.filter(o=>o.enabled).length;g.info(`config synced: ${e.length} project(s), ${t.length} rule(s) (${i} enabled), ${s.length} environment(s)`),n!==this.paused&&(g.info(n?"polling paused from the dashboard":"polling resumed from the dashboard"),this.paused=n)}start(){let e=this.cfg.pollIntervalSeconds*1e3;this.timer=setInterval(()=>{this.tick()},e),this.tick(),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 t=this.projects.find(s=>s.repoName===e.repoName);if(!t)continue;let n=il(t.id,e.role);if(!(n&&Date.now()-new Date(n).getTime()<e.intervalHours*36e5)){this.auditInFlight=!0;try{g.info(`Scheduled ${e.role} audit of ${e.repoName} starting (every ${e.intervalHours}h)`);let s=await on({projectId:t.id,repoPath:this.cfg.repos[e.repoName]?.path??"",role:e.role,scope:{kind:"repo",ref:""},model:"",claudeBin:this.cfg.claudeBin,jira:this.jiraFor(e.repoName)});if(s.ok){let i=s.audit.findings.length;g.info(`Scheduled audit done: ${i} finding(s) - drift visible on the Audits page`)}else g.warn(`Scheduled audit failed: ${s.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)){this.ticking=!0;try{await this.runScheduledAudits(),await this.sweepMergedPRs(),await this.sweepGitHubApprovals();let e=new Set;for(let t of this.rules){if(!t.enabled)continue;let n=this.projects.find(i=>i.id===t.projectId);if(!n)continue;let s=this.cfg.repos[n.repoName];if(!s){g.warn(`rule "${t.name}": no local path for repo "${n.repoName}" - run: allwright repo add "${n.repoName}" /path/to/checkout`);continue}t.action.type==="deploy"?await this.pollDeployRule(t,n,s.path):t.action.type==="respond"?await this.pollRespondRule(t,n,s.path):(e.has(n.id)||(e.add(n.id),await this.sweepNeedsInput(n)),t.trigger.type==="comment_keyword"&&await this.sweepRevisions(t,n),await this.pollRule(t,n,s.path))}await this.pullAutopilotWork()}catch(e){g.warn(`poll tick failed: ${e instanceof Error?e.message:e}`)}finally{this.ticking=!1}}}async pullAutopilotWork(){if(this.inFlight.size>0||this.autopilotPausedUntil>Date.now())return;let e=await this.transport.requestAutopilotNext();if(!e?.ok)return;if(e.pausedUntil){let b=Date.parse(e.pausedUntil);Number.isFinite(b)&&(this.autopilotPausedUntil=b);return}let t=e.item;if(!t)return;let n=this.rules.find(b=>b.id===t.ruleId&&b.enabled),s=this.projects.find(b=>b.id===t.projectId);if(!n||!s){this.transport.sendAutopilotReport({itemId:t.id,outcome:"failed",error:"the rule or project this item was queued against no longer exists"});return}let i=Js(s,[]),o="project"in i?i.project:s,a=this.cfg.repos[o.repoName];if(!a){this.transport.sendAutopilotReport({itemId:t.id,outcome:"failed",error:`no local checkout mapped for "${o.repoName}" on this machine`});return}g.info(`autopilot: taking ${t.issueKey} (${n.name})`);let l=this.jiraOf(o),c="";try{c=(await l.getIssue(t.issueKey))?.summary??""}catch(b){this.transport.sendAutopilotReport({itemId:t.id,outcome:"failed",error:`could not read ${t.issueKey} from Jira: ${b instanceof Error?b.message:String(b)}`});return}let h=await this.transport.claimRun({ruleId:n.id,issueKey:t.issueKey,issueSummary:c,triggerFingerprint:`autopilot:${t.id}`,dedupKey:`autopilot:${t.id}`});if(!h.accepted||!h.runId){this.transport.sendAutopilotReport({itemId:t.id,outcome:"failed",error:h.reason??"the control plane refused the run"});return}this.transport.sendAutopilotReport({itemId:t.id,outcome:"claimed",runId:h.runId});let p=`${n.id}:${t.issueKey}`;this.inFlight.add(p);let _=this.resolveClaudeProfile(h.runId,h.claudeProfile);this.enqueueForRepo(a.path,async()=>{try{await Ks({runId:h.runId,rule:n,project:o,issueKey:t.issueKey,repoPath:a.path,cfg:this.cfg,jira:l,transport:this.transport,claudeConfigDir:_,actorEmail:h.actorEmail})}finally{this.inFlight.delete(p)}})}async sweepGitHubApprovals(){let e=Object.values(Fn());if(!e.length)return;let t=ce()??this.cfg,n=new Map,s=i=>{let o=$t(t,i);if(!o)return null;let a=n.get(o);return a||n.set(o,a=new Me(o)),a};for(let i of e.slice(0,10)){let o=s(i.repoName);if(!o)continue;let a=`gh-approve:${i.runId}`;if(this.inFlight.has(a))continue;let l,c;try{[l,c]=await Promise.all([o.getReviews(i.owner,i.repo,i.prNumber),o.getPullRequest(i.owner,i.repo,i.prNumber)])}catch(b){g.warn(`review check failed for ${i.owner}/${i.repo}#${i.prNumber}: ${b instanceof Error?b.message:b}`);continue}if(!c)continue;let h={cfg:this.cfg,jiraFor:this.jiraFor,transport:this.transport};if(c.merged){g.info(`PR #${i.prNumber} for ${i.issueKey} was merged on GitHub - completing the run`),this.inFlight.add(a);try{await Kn(h,i.runId,c.headSha)}finally{this.inFlight.delete(a)}continue}if(c.state==="closed"){g.info(`PR #${i.prNumber} for ${i.issueKey} was closed unmerged on GitHub - failing the run`);let b=this.jiraFor(i.repoName),x=`PR #${i.prNumber} was closed on GitHub without merging`;await b.addComment(i.issueKey,`**Allwright: the pull request for this ticket was closed on GitHub without merging.**
|
|
633
634
|
|
|
634
635
|
PR: ${i.prUrl}
|
|
635
636
|
|
|
636
|
-
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
|
|
637
|
+
The run is marked failed. Remove the \`${i.failedLabel}\` label (or hit Retry on the Allwright board) to implement again. (run \`${i.runId}\`)`).catch(()=>{}),await b.editLabels(i.issueKey,{add:[i.failedLabel]}).catch(()=>{}),this.transport.send({type:"run.status",runId:i.runId,status:"failed",error:x}),kr(i.runId);continue}c.mergeableState==="dirty"?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.
|
|
637
638
|
|
|
638
639
|
PR: ${i.prUrl}
|
|
639
640
|
|
|
640
|
-
To fix: Reject this run on the Allwright dashboard (that closes the conflicted PR), then post the implement trigger comment again
|
|
641
|
+
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,cn(i),g.info(`merge conflicts on PR #${i.prNumber} for ${i.issueKey} - ticket notified`)):i.conflictNotified&&c.mergeableState!==null&&c.mergeableState!=="unknown"&&(i.conflictNotified=!1,cn(i));let p=l.filter(b=>b.state==="APPROVED"||b.state==="CHANGES_REQUESTED").sort((b,x)=>b.submittedAt.localeCompare(x.submittedAt)),_=p[p.length-1];if(_){if(_.state==="CHANGES_REQUESTED"){i.changesRequestedNotified||(await this.jiraFor(i.repoName).addComment(i.issueKey,`**Allwright: changes were requested on the pull request** (by ${_.user}).
|
|
641
642
|
|
|
642
643
|
PR: ${i.prUrl}
|
|
643
644
|
|
|
644
|
-
Reply to the review on GitHub, or reject the run on the Allwright dashboard and re-trigger with new instructions. (run \`${i.runId}\`)`).catch(()=>{}),
|
|
645
|
+
Reply to the review on GitHub, or reject the run on the Allwright dashboard and re-trigger with new instructions. (run \`${i.runId}\`)`).catch(()=>{}),cn({...i,changesRequestedNotified:!0}),g.info(`changes requested on PR #${i.prNumber} for ${i.issueKey} - ticket notified`));continue}if(_.commitId===c.headSha){g.info(`PR #${i.prNumber} for ${i.issueKey} approved on GitHub by ${_.user} - completing the run`),this.inFlight.add(a);try{await Kn(h,i.runId,_.commitId)}catch(b){g.warn(`github-approval completion failed for ${i.runId}: ${b instanceof Error?b.message:b}`)}finally{this.inFlight.delete(a)}}}}}async sweepMergedPRs(){let e=Object.values(qs());if(!e.length)return;let t=ce()??this.cfg,n=new Map,s=a=>{let l=$t(t,a);if(!l)return null;let c=n.get(l);return c||n.set(l,c=new Me(l)),c},i=20,o=720*3600*1e3;for(let a of e.slice(0,i)){let l=s(a.repoName);if(!l)continue;if(Date.now()-new Date(a.createdAt).getTime()>o){g.warn(`merge watch for ${a.issueKey} PR #${a.prNumber} is over 30 days old - dropping`),qn(a.runId);continue}let c;try{c=await l.getPullRequest(a.owner,a.repo,a.prNumber)}catch(_){g.warn(`merge check failed for ${a.owner}/${a.repo}#${a.prNumber}: ${_ instanceof Error?_.message:_}`);continue}if(!c){qn(a.runId);continue}if(c.state==="open")continue;if(!c.merged){qn(a.runId);continue}let h=this.jiraFor(a.repoName),p="";if(a.jiraTransitionOnMerge)try{p=await h.transitionByName(a.issueKey,a.jiraTransitionOnMerge)?`
|
|
645
646
|
|
|
646
647
|
Ticket moved to **${a.jiraTransitionOnMerge}**.`:`
|
|
647
648
|
|
|
648
|
-
Note: no transition named "${a.jiraTransitionOnMerge}" is available from this ticket's current status
|
|
649
|
+
Note: no transition named "${a.jiraTransitionOnMerge}" is available from this ticket's current status - move it manually.`}catch(_){p=`
|
|
649
650
|
|
|
650
|
-
Note: the "${a.jiraTransitionOnMerge}" transition failed: ${_ instanceof Error?_.message:_}`}try{await
|
|
651
|
+
Note: the "${a.jiraTransitionOnMerge}" transition failed: ${_ instanceof Error?_.message:_}`}try{await h.addComment(a.issueKey,`**Allwright: the pull request for this ticket was merged.**
|
|
651
652
|
|
|
652
653
|
PR: ${a.prUrl} (merged at \`${c.headSha.slice(0,10)}\`)${p}
|
|
653
654
|
|
|
654
|
-
(run \`${a.runId}\`)`)}catch(_){g.warn(`could not post merge comment to ${a.issueKey}: ${_ instanceof Error?_.message:_}`);continue}g.info(`PR #${a.prNumber} for ${a.issueKey} merged
|
|
655
|
+
(run \`${a.runId}\`)`)}catch(_){g.warn(`could not post merge comment to ${a.issueKey}: ${_ instanceof Error?_.message:_}`);continue}g.info(`PR #${a.prNumber} for ${a.issueKey} merged - ticket updated`),qn(a.runId)}}async sweepNeedsInput(e){let t;try{t=await this.jiraOf(e).search(`project = "${e.jiraProjectKey}" AND labels = "${Cr.NEEDS_INPUT_LABEL}"`,10)}catch(s){g.warn(`needs-input sweep failed for ${e.jiraProjectKey}: ${s instanceof Error?s.message:s}`);return}if(!t.length)return;let n=dn();for(let s of t){let i=Object.values(n).filter(a=>a.issueKey===s.key);if(!i.length){await this.jiraOf(e).editLabels(s.key,{remove:[Cr.NEEDS_INPUT_LABEL]}).catch(()=>{}),g.warn(`${s.key}: needs-input label with no local pending record - removed`);continue}let o=null;for(let a of i){let l=`resume:${a.runId}`;if(this.inFlight.has(l))continue;if(Date.now()-new Date(a.createdAt).getTime()>Om){this.inFlight.add(l),this.abandonStaleInput(a,e).finally(()=>this.inFlight.delete(l));continue}try{o=o??await this.jiraOf(e).getIssue(s.key)}catch(x){g.warn(`needs-input check failed for ${s.key}: ${x instanceof Error?x.message:x}`);continue}let c=new Date(a.questionsPostedAt).getTime(),h=o.comments.filter(x=>!Je(x.body)&&new Date(x.created).getTime()>c);if(!h.length)continue;let p=Vn(h),_=o.attachments;this.inFlight.add(l),g.info(`reply received on ${s.key} - resuming run ${a.runId}`),await this.jiraOf(e).editLabels(s.key,{remove:[Cr.NEEDS_INPUT_LABEL]}).catch(x=>{g.warn(`could not remove needs-input label on ${s.key}: ${x}`)});let b={jiraFor:this.jiraFor,transport:this.transport,cfg:this.cfg};a.kind==="implement"?this.enqueueForRepo(a.baseRepoPath??a.repoPath,async()=>{try{await Dl(a,p,_,b)}finally{this.inFlight.delete(l)}}):this.enqueueForRepo(a.repoPath,async()=>{try{await Nl(a,p,_,b)}finally{this.inFlight.delete(l)}})}}}async abandonStaleInput(e,t){g.warn(`${e.issueKey}: needs-input unanswered for over ${Ys}d - abandoning run ${e.runId}`);try{await this.jiraOf(t).addComment(e.issueKey,`**Allwright gave up waiting for an answer.**
|
|
655
656
|
|
|
656
|
-
No reply arrived within ${
|
|
657
|
+
No reply arrived within ${Ys} days of the question above. This ticket has been labeled \`${e.failedLabel}\`; remove it and re-trigger to try again. (run \`${e.runId}\`)`),await this.jiraOf(t).editLabels(e.issueKey,{add:[e.failedLabel],remove:[Cr.NEEDS_INPUT_LABEL]})}catch(n){g.warn(`could not post staleness notice for ${e.issueKey}: ${n}`)}e.kind==="implement"&&await rn(e.baseRepoPath??e.repoPath,e.repoPath).catch(()=>{}),Xe(e.runId),this.transport.send({type:"run.status",runId:e.runId,status:"failed",error:`no reply within ${Ys} days`})}async pollRule(e,t,n){let s=e.trigger.type==="label_added"?await this.matchLabelTrigger(e,t):await this.matchCommentTrigger(e,t);for(let i of s){let o=`${e.id}:${i.issueKey}`;if(this.inFlight.has(o))continue;let a=Js(t,i.components??[]);if("error"in a){this.warnRoutingOnce(`${e.id}:${i.issueKey}`,`${i.issueKey}: ${a.error}`);continue}let l=a.project,c=l.repoName===t.repoName?n:this.cfg.repos[l.repoName]?.path;if(!c){this.warnRoutingOnce(`${e.id}:${i.issueKey}:path`,`${i.issueKey}: routed to repo "${l.repoName}" but it has no local checkout - run: allwright repo add "${l.repoName}" /path/to/checkout`);continue}let h=await this.transport.claimRun({ruleId:e.id,issueKey:i.issueKey,issueSummary:i.summary,triggerFingerprint:i.fingerprint,triggeredByAccountId:i.triggeredByAccountId});if(!h.accepted||!h.runId){h.reason!=="duplicate"&&g.warn(`claim rejected for ${i.issueKey}: ${h.reason??"unknown"}`);continue}this.inFlight.add(o),g.info(`claimed run ${h.runId} for ${i.issueKey}`+(l.repoName!==t.repoName?` (routed \u2192 ${l.repoName})`:"")+(h.claudeProfile?` (claude profile "${h.claudeProfile}")`:""));let p=this.resolveClaudeProfile(h.runId,h.claudeProfile);this.enqueueForRepo(c,async()=>{try{await Ks({runId:h.runId,rule:e,project:l,issueKey:i.issueKey,repoPath:c,cfg:this.cfg,jira:this.jiraOf(l),transport:this.transport,claudeConfigDir:p,actorEmail:h.actorEmail})}finally{this.inFlight.delete(o)}})}}async pollRespondRule(e,t,n){let s=e.trigger;if(s.type!=="comment_keyword"||e.action.type!=="respond")return;let i=await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=s.keyword.toLowerCase(),a=Date.now()-uc;for(let l of i){let c=await this.jiraOf(t).getIssue(l.key);for(let h of c.comments){if(!h.body.toLowerCase().includes(o)||Je(h.body)||new Date(h.created).getTime()<a||!h.id)continue;let p=`respond:${h.id}`;if(this.inFlight.has(p))continue;let _=Js(t,l.components??[]);if("error"in _){this.warnRoutingOnce(`${e.id}:${l.key}`,`${l.key}: ${_.error}`);continue}let b=_.project,x=b.repoName===t.repoName?n:this.cfg.repos[b.repoName]?.path;if(!x){this.warnRoutingOnce(`${e.id}:${l.key}:path`,`${l.key}: routed to repo "${b.repoName}" but it has no local checkout - run: allwright repo add "${b.repoName}" /path/to/checkout`);continue}let C=await this.transport.claimRun({ruleId:e.id,issueKey:l.key,issueSummary:l.summary,triggerFingerprint:`question by ${h.author} at ${h.created}`,dedupKey:`respond:comment:${h.id}`,triggeredByAccountId:h.authorAccountId??void 0});if(!C.accepted||!C.runId){C.reason!=="duplicate"&&g.warn(`respond claim rejected for ${l.key}: ${C.reason??"unknown"}`);continue}this.inFlight.add(p),g.info(`claimed respond run ${C.runId}: ${l.key} (comment ${h.id})`+(b.repoName!==t.repoName?` (routed \u2192 ${b.repoName})`:"")+(C.claudeProfile?` (claude profile "${C.claudeProfile}")`:""));let S={author:h.author,body:h.body},F=this.resolveClaudeProfile(C.runId,C.claudeProfile);this.enqueueForRepo(x,async()=>{try{await Ks({runId:C.runId,rule:e,project:b,issueKey:l.key,repoPath:x,cfg:this.cfg,jira:this.jiraOf(b),transport:this.transport,question:S,claudeConfigDir:F,actorEmail:C.actorEmail})}finally{this.inFlight.delete(p)}})}}}async sweepRevisions(e,t){let n=e.trigger;if(n.type!=="comment_keyword")return;let s;try{s=await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND labels = "${n.doneLabel}" AND updated >= "-2d"`,10)}catch(o){g.warn(`revision sweep failed for ${t.jiraProjectKey}: ${o instanceof Error?o.message:o}`);return}let i=n.keyword.toLowerCase();for(let o of s)try{let a=await this.jiraOf(t).getIssue(o.key),l=null;for(let h of a.comments)Je(h.body)&&(l=Math.max(l??0,new Date(h.created).getTime()));if(l===null||!a.comments.some(h=>!Je(h.body)&&h.body.toLowerCase().includes(i)&&new Date(h.created).getTime()>l))continue;await this.jiraOf(t).editLabels(o.key,{remove:[n.doneLabel]}),g.info(`revision requested on ${o.key} (new "${n.keyword}" after completion) - done label removed, rule will re-fire`)}catch(a){g.warn(`revision check failed for ${o.key}: ${a instanceof Error?a.message:a}`)}}async pollDeployRule(e,t,n){if(e.action.type!=="deploy")return;let s=e.trigger.type==="status_changed"?await this.matchStatusDeploys(e,t):await this.matchCommentDeploys(e,t);for(let i of s){let o=`deploy:${i.dedupKey}`;if(this.inFlight.has(o))continue;let a=await this.transport.claimDeploy({projectId:t.id,ruleId:e.id,issueKey:i.issueKey,issueSummary:i.summary,environmentName:i.environmentName,requestedByAccountId:i.requestedByAccountId,requestedByDisplayName:i.requestedByDisplayName,dedupKey:i.dedupKey,triggerFingerprint:i.fingerprint});if(!a.accepted||!a.runId||!a.environment){if(a.code==="duplicate")continue;a.reason&&a.runId?(await this.jiraOf(t).addComment(i.issueKey,`**Allwright did not deploy this ticket.**
|
|
657
658
|
|
|
658
659
|
${a.reason}`+(i.requestedByAccountId?`
|
|
659
660
|
|
|
660
661
|
Jira account id: \`${i.requestedByAccountId}\``:"")+`
|
|
661
662
|
|
|
662
|
-
(run \`${a.runId}\`)`).catch(c=>g.warn(`could not post refusal to ${i.issueKey}: ${c}`)),g.warn(`deploy refused for ${i.issueKey}: ${a.reason}`)):a.reason&&g.warn(`deploy claim rejected for ${i.issueKey}: ${a.reason}`);continue}let l=a.environment;this.inFlight.add(o),g.info(`claimed deploy ${a.runId}: ${i.issueKey} \u2192 ${l.name}`),this.enqueue(this.envQueues,l.id,async()=>{try{await
|
|
663
|
-
`,{mode:384}),Er.default.renameSync(t,e),Er.default.chmodSync(e,384)}function uc(r,e,t,n){let s=No(),o=s[e]??{sessionId:e,projectId:r,title:t.slice(0,80),updatedAt:new Date().toISOString(),messages:[]};o.messages.push({role:"user",text:t.slice(0,ic)},{role:"agent",text:n.slice(0,ic)}),o.messages=o.messages.slice(-Mm),o.updatedAt=new Date().toISOString(),s[e]=o;let a=Object.values(s).filter(l=>l.projectId===o.projectId).sort((l,c)=>c.updatedAt.localeCompare(l.updatedAt));for(let l of a.slice(Nm))delete s[l.sessionId];Lm(s)}function lc(r){return Object.values(No()).filter(e=>e.projectId===r).sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt)).map(e=>({sessionId:e.sessionId,title:e.title,updatedAt:e.updatedAt,messageCount:e.messages.length}))}function Mo(r){return No()[r]??null}var sy=P(sd(),1),iy=P(ni(),1),oy=P(mn(),1),ay=P(Go(),1),uy=P(Jo(),1),ly=P(ra(),1),fd=P(ai(),1),cy=P(hd(),1);var sa=fd.default;var oa=P(require("node:crypto"),1),et=P(xe(),1);function dy(r){let e=r&&typeof r=="object"&&"name"in r?String(r.name):null;return e?`"${e}"`:"(unnamed)"}function ia(r,e,t,n){r.push(`dropped ${e} ${t} \u2014 this runner is out of date and does not understand it yet (${n}). Update the runner (npm install -g @ticketpilot/runner) to pick it up.`)}function hy(r){if(!r||typeof r!="object"||r.type!=="config")return null;let e=r,t=[],n=[];for(let a of Array.isArray(e.projects)?e.projects:[]){let l=et.ProjectConfig.safeParse(a);l.success?n.push(l.data):ia(t,"project","",l.error.issues[0]?.message??"invalid shape")}let s=[];for(let a of Array.isArray(e.rules)?e.rules:[]){let l=et.RuleConfig.safeParse(a);l.success?s.push(l.data):ia(t,"rule",dy(a),l.error.issues[0]?.message??"invalid shape")}let i=[];for(let a of Array.isArray(e.environments)?e.environments:[]){let l=et.EnvironmentConfig.safeParse(a);l.success?i.push(l.data):ia(t,"environment","",l.error.issues[0]?.message??"invalid shape")}return{msg:{type:"config",projects:n,rules:s,environments:i,pollingPaused:typeof e.pollingPaused=="boolean"?e.pollingPaused:!1},warnings:t}}var fy=2e4,py=6e4,my=5e3,li=class{constructor(e,t,n,s){this.wsUrl=e;this.runnerToken=t;this.meta=n;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===sa.OPEN}connect(){if(this.closed)return;g.info(`connecting to control plane at ${this.wsUrl}`);let e=new sa(this.wsUrl,{headers:{authorization:`Bearer ${this.runnerToken}`}});this.ws=e,e.on("open",()=>{this.backoffMs=1e3,this.sendNow({type:"hello",protocolVersion:et.PROTOCOL_VERSION,runnerVersion:this.meta.runnerVersion,platform:`${process.platform}/${process.arch} node${process.versions.node}`,justBooted:!this.bootAnnounced});let t=this.queue.splice(0,this.queue.length);for(let n of t)this.sendNow(n);this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=setInterval(()=>{this.send({type:"heartbeat",ts:new Date().toISOString()})},fy)}),e.on("message",t=>{let n;try{n=JSON.parse(t.toString())}catch(i){g.warn(`ignoring malformed server message (bad JSON): ${i}`);return}let s;try{s=(0,et.parseServerMsg)(n)}catch(i){let o=hy(n);if(!o){g.warn(`ignoring malformed server message: ${i}`);return}for(let a of o.warnings)g.warn(a);g.warn(`config push had ${o.warnings.length} ${o.warnings.length===1?"entry":"entries"} this runner doesn't understand \u2014 applied everything else instead of dropping the whole config`),s=o.msg}this.handle(s)}),e.on("close",t=>{if(this.heartbeat&&clearInterval(this.heartbeat),t===4001)g.error("control plane rejected this runner version (protocol mismatch). Update with: npm install -g @ticketpilot/runner");else if(t===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 n=Math.random()*.3+.85,s=Math.round(this.backoffMs*n);g.warn(`disconnected (code ${t}); reconnecting in ${Math.round(s/1e3)}s`),setTimeout(()=>this.connect(),s),this.backoffMs=Math.min(this.backoffMs*2,py)}),e.on("error",t=>{g.warn(`websocket error: ${t.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"){let t=this.pending.get(e.requestId);t&&(clearTimeout(t.timer),this.pending.delete(e.requestId),t.resolve(e));return}if(e.type==="config")return this.events.onConfig(e);if(e.type==="project.test")return this.events.onProjectTest(e);if(e.type==="rule.diagnose")return this.events.onRuleDiagnose(e);if(e.type==="run.cancel")return this.events.onCancel(e.runId);if(e.type==="run.approved")return this.events.onApproved(e.runId,e.headSha);if(e.type==="run.rejected")return this.events.onRejected(e.runId);if(e.type==="run.retryPush")return this.events.onRetryPush(e.runId);if(e.type==="deploy.start")return this.events.onDeployStart(e);if(e.type==="deploy.suggest")return this.events.onDeploySuggest(e);if(e.type==="env.preflight")return this.events.onEnvPreflight(e);if(e.type==="chat.turn")return this.events.onChatTurn(e);if(e.type==="chat.create.ticket")return this.events.onChatCreateTicket(e);if(e.type==="chat.list")return this.events.onChatList(e);if(e.type==="chat.load")return this.events.onChatLoad(e);if(e.type==="board.fetch")return this.events.onBoardFetch(e);if(e.type==="board.trigger")return this.events.onBoardTrigger(e);if(e.type==="audit.start")return this.events.onAuditStart(e);if(e.type==="audit.list")return this.events.onAuditList(e);if(e.type==="audit.get")return this.events.onAuditGet(e);if(e.type==="audit.review")return this.events.onAuditReview(e);if(e.type==="knowledge.list")return this.events.onKnowledgeList(e);if(e.type==="knowledge.save")return this.events.onKnowledgeSave(e);if(e.type==="epic.list")return this.events.onEpicList(e);if(e.type==="epic.suggest")return this.events.onEpicSuggest(e);if(e.type==="team.creds")return this.events.onTeamCreds(e);if(e.type==="jira.users")return this.events.onJiraUsers(e);if(e.type==="setup.status")return this.events.onSetupStatus(e);if(e.type==="setup.claudemd.generate")return this.events.onSetupClaudeMdGenerate(e);if(e.type==="setup.claudemd.save")return this.events.onSetupClaudeMdSave(e);if(e.type==="runner.update")return this.events.onRunnerUpdate(e)}sendNow(e){this.ws?.send(JSON.stringify(e))}send(e){if(this.connected){this.sendNow(e);return}if(this.queue.length>=my){let t=this.queue.findIndex(n=>n.type==="run.log");t>=0?this.queue.splice(t,1):this.queue.shift()}this.queue.push(e)}async claimRun(e){if(!this.connected)return{accepted:!1,reason:"control plane offline"};let t=oa.default.randomUUID(),n=await new Promise(s=>{let i=setTimeout(()=>{this.pending.delete(t),s(null)},15e3);this.pending.set(t,{resolve:s,timer:i}),this.sendNow({type:"run.claim",requestId:t,...e})});return!n||n.type!=="run.claim.result"?{accepted:!1,reason:"claim timed out"}:{accepted:n.accepted,runId:n.runId,reason:n.reason,claudeProfile:n.claudeProfile,actorEmail:n.actorEmail}}async claimDeploy(e){if(!this.connected)return{accepted:!1,reason:"control plane offline"};let t=oa.default.randomUUID(),n=await new Promise(s=>{let i=setTimeout(()=>{this.pending.delete(t),s(null)},15e3);this.pending.set(t,{resolve:s,timer:i}),this.sendNow({type:"deploy.claim",requestId:t,...e})});return!n||n.type!=="deploy.claim.result"?{accepted:!1,reason:"deploy authorization timed out"}:{accepted:n.accepted,runId:n.runId,environment:n.environment,reason:n.reason,code:n.code}}sendDeploySuggestResult(e,t){this.send({type:"deploy.suggest.result",requestId:e,...t})}sendChatTurnResult(e,t){this.send({type:"chat.turn.result",requestId:e,...t})}sendChatCreateTicketResult(e,t){this.send({type:"chat.create.ticket.result",requestId:e,...t,childKeys:t.childKeys??[]})}sendChatListResult(e,t){this.send({type:"chat.list.result",requestId:e,sessions:t})}sendChatLoadResult(e,t){this.send({type:"chat.load.result",requestId:e,...t})}sendBoardFetchResult(e,t){this.send({type:"board.fetch.result",requestId:e,...t,browseBaseUrl:t.browseBaseUrl??""})}sendAuditStartResult(e,t){this.send({type:"audit.start.result",requestId:e,...t})}sendAuditListResult(e,t){this.send({type:"audit.list.result",requestId:e,ok:t.ok,error:t.error,audits:t.audits??[]})}sendAuditGetResult(e,t){this.send({type:"audit.get.result",requestId:e,...t})}sendAuditReviewResult(e,t){this.send({type:"audit.review.result",requestId:e,...t})}sendKnowledgeListResult(e,t){this.send({type:"knowledge.list.result",requestId:e,ok:t.ok,error:t.error,files:t.files??[]})}sendKnowledgeSaveResult(e,t){this.send({type:"knowledge.save.result",requestId:e,...t})}sendEpicListResult(e,t){this.send({type:"epic.list.result",requestId:e,ok:t.ok,error:t.error,epics:t.epics??[],children:t.children??[]})}sendEpicSuggestResult(e,t){this.send({type:"epic.suggest.result",requestId:e,ok:t.ok,error:t.error,issueKey:t.issueKey??"",reason:t.reason??"",considered:t.considered??0})}sendTeamCredsResult(e,t){this.send({type:"team.creds.result",requestId:e,ok:t.ok,error:t.error,githubShared:t.githubShared??!1,sharedGithubLogin:t.sharedGithubLogin??"",entries:t.entries??[]})}sendBoardTriggerResult(e,t){this.send({type:"board.trigger.result",requestId:e,...t})}sendRunnerUpdateResult(e,t){this.send({type:"runner.update.result",requestId:e,ok:t.ok,error:t.error,note:t.note??""})}sendSetupClaudeMdGenerateResult(e,t){this.send({type:"setup.claudemd.generate.result",requestId:e,ok:t.ok,error:t.error,content:t.content??""})}sendSetupClaudeMdSaveResult(e,t){this.send({type:"setup.claudemd.save.result",requestId:e,ok:t.ok,error:t.error,note:t.note??""})}sendSetupStatusResult(e,t){this.send({type:"setup.status.result",requestId:e,ok:t.ok,error:t.error,jiraConfigured:t.jiraConfigured??!1,jiraEmail:t.jiraEmail??"",claude:t.claude,githubTokenSet:t.githubTokenSet??!1,githubLogin:t.githubLogin??"",deploysEnabled:t.deploysEnabled??!1,jiraUserCount:t.jiraUserCount??0,repos:t.repos??[]})}sendEnvPreflightResult(e,t){this.send({type:"env.preflight.result",requestId:e,...t})}sendJiraUsersResult(e,t){this.send({type:"jira.users.result",requestId:e,...t})}sendProjectTestResult(e,t,n){this.send({type:"project.test.result",requestId:e,ok:t,checks:n})}sendRuleDiagnoseResult(e,t){this.send({type:"rule.diagnose.result",requestId:e,...t})}};var wn=P(require("node:fs"),1),aa=P(require("node:path"),1),md=require("node:child_process"),gd=require("node:util");var pd=(0,gd.promisify)(md.execFile);async function ci(r,e,t=[]){let n=[],s=r.repos[e.repoName]?.jira??r.jira;if(!s)n.push({name:"jira-credentials",ok:!1,detail:"no Jira credentials configured on this runner"});else{let o=new qe(s);try{let a=await o.myself();n.push({name:"jira-auth",ok:!0,detail:`authenticated as ${a.displayName}`});try{await o.search(`project = "${e.jiraProjectKey}" ORDER BY created DESC`,1),n.push({name:"jira-project",ok:!0,detail:`project ${e.jiraProjectKey} is readable`})}catch(l){n.push({name:"jira-project",ok:!1,detail:`cannot read project ${e.jiraProjectKey}: ${es(l)}`})}}catch(a){n.push({name:"jira-auth",ok:!1,detail:`Jira auth failed: ${es(a)}`})}}let i=r.repos[e.repoName];if(i&&wn.default.existsSync(i.path)){let o=aa.default.join(i.path,"CLAUDE.md"),a=wn.default.existsSync(o)&&wn.default.readFileSync(o,"utf8").trim().length>0;n.push({name:"memory-file",ok:a,detail:a?"CLAUDE.md present \u2014 the agent has project memory":"MISSING: CLAUDE.md at the repo root. Rules can't be enabled until the project has a memory file \u2014 it is what makes every run smarter than the last."});let l=jo(i.path);n.push({name:"deploy-doc",ok:l!==null,detail:l?`${l.path} present \u2014 deploy suggestions will follow it`:"MISSING: DEPLOY.md (or .ticketpilot/deploy.md). Environments can't be created until the repo documents how it deploys."})}if(!i)n.push({name:"repo-path",ok:!1,detail:`no local path mapped for repo "${e.repoName}" \u2014 run: allwright repo add "${e.repoName}" /path/to/checkout`});else if(!wn.default.existsSync(i.path))n.push({name:"repo-path",ok:!1,detail:`path does not exist: ${i.path}`});else{let o=wn.default.existsSync(aa.default.join(i.path,".git"));n.push({name:"repo-path",ok:!0,detail:`${i.path}${o?" (git checkout)":" (warning: not a git checkout)"}`})}try{let{stdout:o}=await pd(r.claudeBin,["--version"],{timeout:15e3});n.push({name:"claude-code",ok:!0,detail:o.trim().slice(0,100)})}catch(o){n.push({name:"claude-code",ok:!1,detail:`cannot run "${r.claudeBin}": ${es(o)}`})}try{let{stdout:o}=await pd("git",["--version"],{timeout:15e3});n.push({name:"git",ok:!0,detail:o.trim().slice(0,100)})}catch(o){n.push({name:"git",ok:!1,detail:`cannot run git: ${es(o)}`})}if(r.github?.token)try{let{GitHubClient:o}=await Promise.resolve().then(()=>(ct(),an)),a=await new o(r.github.token).whoami();n.push({name:"github-token",ok:!0,detail:`authenticated as ${a}`})}catch(o){n.push({name:"github-token",ok:!1,detail:es(o)})}else n.push({name:"github-token",ok:!0,detail:"not set \u2014 needed only for implement rules (allwright github set-token)"});if(t.length){r.deploy.enabled?n.push({name:"deploy",ok:!0,detail:"deployments enabled on this runner"}):n.push({name:"deploy",ok:!1,detail:"deployments are disabled on this runner \u2014 run `allwright deploy enable` to allow it to execute your saved deploy steps"});for(let o of t){let a=Qt(r,e.repoName,o.name),l=o.requiredSecrets.filter(c=>!a[c]&&!process.env[c]);n.push({name:`env:${o.name}`,ok:l.length===0,detail:l.length?`missing secret(s): ${l.join(", ")} \u2014 allwright env set "${e.repoName}" "${o.name}" ${l[0]}=...`:`${o.steps.length} step(s), ${o.requiredSecrets.length} secret(s) present`+(o.branch?`, deploys origin/${o.branch}`:"")})}}return n}function es(r){return(r instanceof Error?r.message:String(r)).slice(0,300)}var ue=new Ea;ue.name("allwright").description("Allwright runner \u2014 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(Es);ue.command("init").description("Interactive setup: enroll this runner and store credentials locally").option("--cp-url <url>","control plane URL").option("--enroll-token <token>","enrolment token from the Allwright UI").option("--name <name>","runner name",Sd.default.hostname()).option("--jira-url <url>","Jira base URL, e.g. https://yourorg.atlassian.net").option("--jira-email <email>","Jira account email").option("--jira-token <token>","Jira API token (stored locally only)").action(async r=>{let e=Or.default.createInterface({input:process.stdin,output:process.stdout}),t=async(n,s,i=!1)=>{if(s)return s;let o=await e.question(`${n}: `);if(!o.trim())throw new Error(`${n} is required`);return o.trim()};try{let n=await t("Control plane URL",r.cpUrl),s=await t("Enrolment token (from the web UI)",r.enrollToken),i=await t("Jira base URL (https://yourorg.atlassian.net)",r.jiraUrl),o=await t("Jira account email",r.jiraEmail),a=await t("Jira API token (create at id.atlassian.com/manage-profile/security/api-tokens)",r.jiraToken,!0),l=Pi.parse({controlPlaneUrl:n,runnerName:r.name,jira:{baseUrl:i,email:o,apiToken:a}}),c=await new qe(l.jira).myself();g.info(`Jira credential OK \u2014 authenticated as ${c.displayName}`),l=await bu(l,s),g.info(`Enrolled as runner "${l.runnerName}" (${l.runnerId})`),g.info(`Credentials saved to ${St()} (mode 600, this machine only)`),g.info("Next: map your repo with `allwright repo add <repoName> <localPath>`, then `allwright start`")}finally{e.close()}});var ua=ue.command("repo").description("Map control-plane repo names to local checkouts");ua.command("add <repoName> <localPath>").description("Map a repo name (as configured in the web UI) to a local checkout path").action(async(r,e)=>{let t=ee();t.repos[r]={path:e},oe(t),g.info(`mapped repo "${r}" -> ${e}`);try{let{originUrl:n}=await Promise.resolve().then(()=>(_r(),Ru));g.info(` origin remote: ${await n(e)} \u2014 make sure this is the repo you meant`)}catch{g.warn(` could not read an origin remote at ${e} \u2014 is it a git checkout?`)}});ua.command("list").description("Show configured repo mappings").action(()=>{let r=ee(),e=Object.entries(r.repos);if(!e.length)return g.info("no repos mapped yet");for(let[t,n]of e)g.info(`${t} -> ${n.path}`)});var Td=ue.command("claude").description("Per-user Claude login profiles \u2014 each teammate's runs bill their OWN Claude account");Td.command("login <profileName>").description("Create (or re-login) a named Claude profile. Opens Claude Code interactively with its own config directory \u2014 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 r=>{if(!/^[a-zA-Z0-9._-]+$/.test(r))throw new Error("profile name: letters, digits, dots, dashes and underscores only");let e=ee(),t=e.claudeProfiles[r]?.configDir??`${St().replace(/runner\.json$/,"")}claude-profiles/${r}`;yt.default.mkdirSync(t,{recursive:!0,mode:448}),e.claudeProfiles[r]={configDir:t},oe(e),g.info(`profile "${r}" -> ${t}`),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 n=(0,Mt.spawn)(e.claudeBin,[],{env:{...process.env,CLAUDE_CONFIG_DIR:t},stdio:"inherit"});await new Promise(s=>n.on("exit",()=>s())),g.info(`Done. Assign it on the dashboard: Team -> the user -> Claude profile = "${r}".`),g.info("Restart the background runner for this to take effect: allwright stop && allwright start")});Td.command("list").description("Show configured Claude profiles and whether each looks logged in").action(()=>{let r=ee(),e=Object.entries(r.claudeProfiles);if(g.info("default: this OS user's own Claude login (no profile)"),!e.length)return g.info("no named profiles yet \u2014 allwright claude login <name>");for(let[t,n]of e){let s=yt.default.existsSync(n.configDir)&&yt.default.readdirSync(n.configDir).length>0;g.info(`${t} -> ${n.configDir} ${s?"(logged in)":"(NOT logged in yet)"}`)}});ua.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 \u2014 delete the project on the dashboard separately.").action(r=>{let e=ee();if(!e.repos[r]){let i=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${r}" \u2014 mapped repos: ${i}`)}let t=e.repos[r].path;delete e.repos[r];let n=Object.keys(e.environments).filter(i=>i.startsWith(`${r}:`));for(let i of n)delete e.environments[i];let s=e.auditSchedules.length;e.auditSchedules=e.auditSchedules.filter(i=>i.repoName!==r),oe(e),g.info(`Removed "${r}" (was ${t})`),n.length&&g.info(`Also removed ${n.length} environment secret set(s): ${n.join(", ")}`),e.auditSchedules.length!==s&&g.info("Also removed its audit schedule(s)"),g.info("The checkout on disk was NOT touched \u2014 remove it yourself if you want it gone."),g.info("Restart the runner to apply. Dashboard project (if any) is deleted separately there.")});var la=ue.command("service").description("Run the runner as a system service (starts on boot, restarts on crash)");la.command("install").description("Install + start the systemd service \u2014 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(r=>{if(r.print){g.info(`
|
|
664
|
-
`+uo(ao()));return}Lu(g)});la.command("uninstall").description("Stop and remove the systemd service (config/credentials untouched)").action(()=>Du(g));la.command("status").description("systemctl status for the runner service").action(()=>{(0,Mt.spawn)("systemctl",["status","allwright","--no-pager"],{stdio:"inherit"}).on("exit",e=>process.exit(e??0))});ue.command("update").description("Update the runner to the latest published version (npm install -g allwright@latest). Restart the runner afterwards \u2014 and only when no runs are active.").action(async()=>{g.info("Updating: npm install -g allwright@latest");let r=(0,Mt.spawn)("npm",["install","-g","allwright@latest"],{stdio:"inherit"});await new Promise((e,t)=>{r.on("exit",n=>n===0?e():t(new Error(`npm exited with code ${n}`))),r.on("error",t)}),g.info("Updated. Restart the runner service to load the new version (check active runs first).")});var rs=ue.command("jira").description("Per-repo Jira site overrides \u2014 for projects living on a different Atlassian site");rs.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 r=>{let e=ee();if(!e.repos[r]){let n=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${r}" \u2014 mapped repos: ${n}. Run \`allwright repo add\` first.`)}let t=Or.default.createInterface({input:process.stdin,output:process.stdout});try{let n=(await t.question("Jira base URL for this repo (https://yourorg.atlassian.net): ")).trim(),s=(await t.question("Jira account email: ")).trim(),i=(await t.question("Jira API token (id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!n||!s||!i)throw new Error("all three values are required");let o={baseUrl:n,email:s,apiToken:i},a=await new qe(o).myself();g.info(`Jira credential OK \u2014 authenticated as ${a.displayName} on ${n}`),e.repos[r].jira=o,oe(e),g.info(`Saved: repo "${r}" now polls ${n} (other repos keep the runner-wide credential)`),g.info("Restart the background runner for this to take effect: allwright stop && allwright start")}finally{t.close()}});rs.command("show").description("Show which Jira site each repo uses (never prints tokens)").action(()=>{let r=ee();g.info(`runner-wide: ${r.jira?`${r.jira.baseUrl} (${r.jira.email})`:"(not configured)"}`);for(let[e,t]of Object.entries(r.repos))g.info(`${e} -> ${t.jira?`${t.jira.baseUrl} (${t.jira.email})`:"(runner-wide credential)"}`)});rs.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 \u2014 no restart needed.").action(async r=>{let e=ee(),t=r.trim().toLowerCase();if(!t.includes("@"))throw new Error(`"${r}" doesn't look like an email`);let n=Or.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await n.question(`Their ATLASSIAN account email [${t}]: `)).trim()||t,i=(await n.question("Their Jira API token (they create it at id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!i)throw new Error("API token is required");let o=[e.jira,...Object.values(e.repos).map(c=>c.jira)].filter(c=>!!c),a=new Set,l=!1;for(let c of o)if(!a.has(c.baseUrl)){a.add(c.baseUrl);try{let d=await new qe({baseUrl:c.baseUrl,email:s,apiToken:i}).myself();g.info(`${c.baseUrl}: OK \u2014 authenticated as ${d.displayName}`),l=!0}catch{g.warn(`${c.baseUrl}: this credential does NOT work there (fine if they don't use that site)`)}}if(!l)throw new Error("credential failed on every configured Jira site \u2014 nothing saved");e.jiraUsers[t]={email:s,apiToken:i},oe(e),g.info(`Saved. Dashboard actions by ${t} now post to Jira as ${s}. No restart needed.`)}finally{n.close()}});rs.command("user-list").description("Show which Allwright users have their own Jira credential here (never prints tokens)").action(()=>{let r=ee(),e=Object.entries(r.jiraUsers);if(!e.length)return g.info("none yet \u2014 everyone's dashboard clicks require one: allwright jira user-add <their-ticketpilot-email>");for(let[t,n]of e)g.info(`${t} -> posts to Jira as ${n.email}`)});rs.command("user-remove <ticketpilotEmail>").description("Delete a person's stored Jira credential").action(r=>{let e=ee(),t=r.trim().toLowerCase();if(!e.jiraUsers[t])throw new Error(`no credential stored for ${t}`);delete e.jiraUsers[t],oe(e),g.info(`Removed. Dashboard actions by ${t} will now be refused until a new credential is added.`)});var Sn=ue.command("github").description("GitHub credential for implement-mode rules");Sn.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 r=>{let e=Or.default.createInterface({input:process.stdin,output:process.stdout});try{let t=r.token??(await e.question("GitHub token (fine-grained PAT recommended): ")).trim();if(!t)throw new Error("token is required");let{GitHubClient:n}=await Promise.resolve().then(()=>(ct(),an)),s=await new n(t).whoami(),i=ee();i.github={token:t,login:s},oe(i),g.info(`GitHub token OK \u2014 authenticated as ${s}`),g.info(`Saved to ${St()} (mode 600, this machine only)`)}finally{e.close()}});Sn.command("set <repoName>").description("Store a GitHub token for ONE repo only \u2014 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 r=>{let e=ee();if(!e.repos[r]){let n=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${r}" \u2014 mapped repos: ${n}. Run \`allwright repo add\` first.`)}let t=Or.default.createInterface({input:process.stdin,output:process.stdout});try{let n=(await t.question(`GitHub token for "${r}" (fine-grained PAT scoped to just this repo): `)).trim();if(!n)throw new Error("token is required");let{GitHubClient:s}=await Promise.resolve().then(()=>(ct(),an)),i=await new s(n).whoami();e.repos[r].github={token:n,login:i},oe(e),g.info(`GitHub token OK \u2014 authenticated as ${i}`),g.info(`Saved: repo "${r}" now uses its own token (other repos keep the runner-wide one)`)}finally{t.close()}});Sn.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 \u2014 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 r=>{let e=ee(),t=r.trim().toLowerCase();if(!t.includes("@"))throw new Error(`"${r}" doesn't look like an email`);let n=Or.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await n.question(`GitHub token for ${t}: `)).trim();if(!s)throw new Error("token is required");let{GitHubClient:i}=await Promise.resolve().then(()=>(ct(),an)),o=await new i(s).whoami();e.githubUsers[t]={token:s,login:o},oe(e),g.info(`GitHub token OK \u2014 authenticated as ${o}`),g.info(`Saved. Implement runs triggered by ${t} now open PRs as ${o}. No restart needed.`)}finally{n.close()}});Sn.command("user-list").description("Show which Allwright users have their own GitHub token here (never prints tokens)").action(()=>{let r=ee(),e=Object.entries(r.githubUsers);if(!e.length)return g.info("no per-user GitHub tokens \u2014 everyone's PRs use the repo/runner-wide token");for(let[t]of e)g.info(`${t} -> own GitHub token stored`)});Sn.command("user-remove <ticketpilotEmail>").description("Delete a person's stored GitHub token (their runs fall back to the shared token)").action(r=>{let e=ee(),t=r.trim().toLowerCase();if(!e.githubUsers[t])throw new Error(`no GitHub token stored for ${t}`);delete e.githubUsers[t],oe(e),g.info(`Removed. ${t}'s runs use the repo/runner-wide token again.`)});Sn.command("show").description("Show which GitHub token each repo and person would use (never prints tokens)").action(()=>{let r=ee();g.info(`runner-wide: ${r.github?.token?"token set":"(not configured)"}`);for(let[t,n]of Object.entries(r.repos))g.info(`${t} -> ${n.github?.token?"own repo token":"runner-wide token"}`);let e=Object.keys(r.githubUsers);g.info(e.length?`per-user tokens: ${e.join(", ")}`:"per-user tokens: (none)")});var ca=ue.command("audit").description("Recurring specialist audits on this runner");ca.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 \u2014 nothing blocks.").action((r,e,t)=>{let n=ee();if(!n.repos[r]){let i=Object.keys(n.repos).join(", ")||"(none)";throw new Error(`unknown repo "${r}" \u2014 mapped repos: ${i}`)}if(e!=="security"&&e!=="testing")throw new Error('role must be "security" or "testing"');let s=parseInt(t,10);if(!Number.isInteger(s)||s<6||s>720)throw new Error("intervalHours must be 6-720");n.auditSchedules=[...n.auditSchedules.filter(i=>!(i.repoName===r&&i.role===e)),{repoName:r,role:e,intervalHours:s}],oe(n),g.info(`Scheduled: ${e} audit of "${r}" every ${s}h. Restart the runner to apply.`)});ca.command("schedules").description("List scheduled audits").action(()=>{let r=ee();if(!r.auditSchedules.length)return g.info("no scheduled audits \u2014 allwright audit schedule <repo> <role> <hours>");for(let e of r.auditSchedules)g.info(`${e.repoName} \xB7 ${e.role} \xB7 every ${e.intervalHours}h`)});ca.command("unschedule <repoName> <role>").description("Remove a scheduled audit").action((r,e)=>{let t=ee(),n=t.auditSchedules.length;if(t.auditSchedules=t.auditSchedules.filter(s=>!(s.repoName===r&&s.role===e)),t.auditSchedules.length===n)throw new Error("no such schedule");oe(t),g.info("Removed. Restart the runner to apply.")});var da=ue.command("deploy").description("Deployment settings for this machine");da.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 \u2014 so this switch lives on the machine, not in the web UI, and only someone with shell access can flip it.").action(()=>{let r=ee();r.deploy={enabled:!0},oe(r),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."),g.info("Restart the background runner for this to take effect: allwright stop && allwright start")});da.command("disable").description("Stop this runner from executing any deploy steps").action(()=>{let r=ee();r.deploy={enabled:!1},oe(r),g.info("deployments DISABLED on this runner"),g.info("Restart the background runner for this to take effect: allwright stop && allwright start")});da.command("status").description("Show whether deployments are enabled here, and which env secrets are stored").action(()=>{let r=ee();g.info(`deployments: ${r.deploy.enabled?"enabled":"disabled"}`);let e=Object.entries(r.environments);if(!e.length)return g.info("no environment secrets stored");for(let[t,n]of e){let s=Object.keys(n.secrets);g.info(`${t}: ${s.length?s.join(", "):"(no secrets)"}`)}});var ha=ue.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((r,e,t)=>{let n=ee(),s=fs(r,e),i=n.environments[s]??{secrets:{}},o=[];for(let a of t){let l=a.indexOf("=");if(l<=0)throw new Error(`expected KEY=VALUE, got "${a}"`);let c=a.slice(0,l).trim();i.secrets[c]=a.slice(l+1),o.push(c)}n.environments[s]=i,oe(n),g.info(`stored ${o.length} secret(s) for ${s}: ${o.join(", ")}`),g.info(`Saved to ${St()} (mode 600, this machine only)`),g.info("Restart the background runner to pick these up: allwright stop && allwright start")});ha.command("unset <repoName> <envName> <names...>").description("Remove stored secrets for an environment").action((r,e,t)=>{let n=ee(),s=fs(r,e),i=n.environments[s];if(!i)return g.info(`nothing stored for ${s}`);for(let o of t)delete i.secrets[o];n.environments[s]=i,oe(n),g.info(`removed ${t.join(", ")} from ${s}`)});ha.command("list").description("Show which environments have secrets stored here (names only, never values)").action(()=>{let r=ee(),e=Object.entries(r.environments);if(!e.length)return g.info("no environment secrets stored");for(let[t,n]of e)g.info(`${t}: ${Object.keys(n.secrets).join(", ")||"(none)"}`)});ue.command("export [file]").description("Back up ALL runner state (config+secrets, knowledge, audits, chats) to one tarball").action(r=>{try{let e=Ua(r);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 \u2014 anyone holding it can act as this runner."),g.info(`Restore on any machine with: allwright import ${kn.default.basename(e.file)}`)}catch(e){g.error(e instanceof Error?e.message:String(e)),process.exitCode=1}});ue.command("import <file>").description("Restore runner state from an `export` tarball (existing config is kept as a .bak dir)").action(r=>{let e=Kr();if(e&&Vr(e)){g.error("the runner is running \u2014 stop it first (systemctl stop allwright, or `allwright stop` for a pid-file daemon), then import."),process.exitCode=1;return}try{let t=qa(r);g.info(`Restored ${t.restored.length} entries into ${Q()}`),t.previousDir&&g.info(`Previous config kept at ${t.previousDir}`),g.info("Start the runner and it will reconnect with the restored identity.")}catch(t){g.error(t instanceof Error?t.message:String(t)),process.exitCode=1}});ue.command("test").description("Check local setup: Jira auth, repo mappings, Claude Code binary").action(async()=>{let r=ee(),e=Object.keys(r.repos);if(!r.jira){g.error("no Jira credentials configured \u2014 run `allwright init`"),process.exitCode=1;return}let t=e.length?e.map(s=>({jiraProjectKey:"*",repoName:s})):[{jiraProjectKey:"*",repoName:"(none mapped)"}],n=!0;for(let s of t){let i=await ci(r,s);for(let o of i){if(s.jiraProjectKey==="*"&&o.name==="jira-project")continue;let a=o.ok?"PASS":"FAIL";(o.ok?g.info:g.error)(`[${a}] ${o.name}: ${o.detail}`),n&&=o.ok}}n||(process.exitCode=1)});function vy(r){if(!r.runnerToken)throw new Error("runner not enrolled \u2014 run `allwright init`");if(!r.jira)throw new Error("no Jira credentials \u2014 run `allwright init`");let e=Ha();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",Ni);let t=new qe(r.jira),n=new Map,s=f=>{let m=r.repos[f]?.jira;if(!m)return t;let b=n.get(f);return b||(b=new qe(m),n.set(f,b)),b},i=new Map,o=(f,m)=>{let b=ju(ce()??r,f,m);switch(b.kind){case"legacy":return{jira:s(f),authored:!1};case"self":return{jira:s(f),authored:!0};case"missing":return{error:b.error};case"user":{let A=`${b.creds.baseUrl}:${b.creds.email}:${b.creds.apiToken.slice(-6)}`,N=i.get(A);return N||(N=new qe(b.creds),i.set(A,N)),{jira:N,authored:!0}}}},a=new URL("/api/runner/ws",r.controlPlaneUrl);a.protocol=a.protocol==="https:"?"wss:":"ws:";let l=[],c=[],d=[],p,_={cfg:r,jiraFor:s,transport:null},S=new Set,T=f=>{let m=l.find(A=>A.id===f),b=m&&r.repos[m.repoName];return m&&b?{project:m,repoPath:b.path}:null},C={cfg:r,jiraFor:s,get transport(){return _.transport},lookup:(f,m)=>{let b=T(f),A=d.find(N=>N.projectId===f&&N.name===m);return b&&A?{...b,environment:A}:null}},k=new li(a.toString(),r.runnerToken,{runnerVersion:Es},{onConfig:f=>{l=f.projects,c=f.rules,d=f.environments,p.setConfig(f.projects,f.rules,f.pollingPaused,f.environments)},onProjectTest:async f=>{let m=l.find(A=>A.id===f.projectId);if(!m){k.sendProjectTestResult(f.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 b=await ci(r,m,d.filter(A=>A.projectId===m.id));k.sendProjectTestResult(f.requestId,b.every(A=>A.ok),b)},onRuleDiagnose:async f=>{let m=c.find(M=>M.id===f.ruleId),b=m&&l.find(M=>M.id===m.projectId);if(!m||!b){k.sendRuleDiagnoseResult(f.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 A=await ci(r,b,m.action.type==="deploy"?d.filter(M=>M.projectId===b.id):[]),N=m.action.type==="implement"?A:A.filter(M=>M.name!=="github-token"),{matchedCount:F,excludedCount:L,excludedSample:re}=await p.diagnoseRule(m,b);k.sendRuleDiagnoseResult(f.requestId,{checks:N,matchedCount:F,excludedCount:L,excludedSample:re})},onCancel:f=>{g.warn(`cancel requested for run ${f} \u2014 not supported in this version, run will finish or time out`)},onApproved:(f,m)=>{if(Po(f)){Xl(C,f).catch(b=>g.error(`deploy approval crashed for ${f}: ${b instanceof Error?b.stack:b}`));return}Kn(_,f,m).catch(b=>g.error(`approval handling crashed for ${f}: ${b instanceof Error?b.stack:b}`))},onRetryPush:f=>{let m=Ds(f),b=()=>Ul(_,f).catch(A=>g.error(`retry push crashed for ${f}: ${A instanceof Error?A.stack:A}`));m?p.runOnRepoQueue(m.baseRepoPath,b):b()},onRejected:f=>{if(Po(f)){Ql(C,f).catch(m=>g.error(`deploy rejection crashed for ${f}: ${m instanceof Error?m.stack:m}`));return}zl(_,f).catch(m=>g.error(`rejection handling crashed for ${f}: ${m instanceof Error?m.stack:m}`))},onDeployStart:f=>{let m=`${f.runId}#${f.attempt}`;if(S.has(m))return;S.add(m);let b=T(f.projectId);if(!b){let A="this runner has no local checkout mapped for that project \u2014 run: allwright repo add <repoName> /path/to/checkout";g.error(`deploy ${f.runId}: ${A}`),k.send({type:"run.status",runId:f.runId,status:"failed",error:A});return}g.info(`deploy ${f.runId} requested from the dashboard: ${f.issueKey} \u2192 ${f.environment.name}`),p.runOnEnvironmentQueue(f.environment.id,()=>Vs({runId:f.runId,project:b.project,environment:f.environment,issueKey:f.issueKey,issueSummary:f.issueSummary,repoPath:b.repoPath,cfg:r,jira:s(b.project.repoName),transport:k,requestedBy:f.requestedBy}).catch(A=>g.error(`deploy crashed for ${f.runId}: ${A instanceof Error?A.stack:A}`)))},onDeploySuggest:async f=>{let m=T(f.projectId);if(!m){k.sendDeploySuggestResult(f.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:"this runner has no local checkout mapped for that project"});return}g.info(`asking Claude Code for "${f.environmentName}" deploy steps in ${m.repoPath}`);let b=await nc({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:f.environmentName,notes:f.notes,timeoutSeconds:f.timeoutSeconds,cfg:r});k.sendDeploySuggestResult(f.requestId,b)},onEnvPreflight:async f=>{let m=T(f.projectId);if(!m){k.sendEnvPreflightResult(f.requestId,{ok:!1,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project"}]});return}let b=await rc({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:f.environmentName,steps:f.steps,requiredSecrets:f.requiredSecrets,workdir:f.workdir,branch:f.branch,publicUrl:f.publicUrl,cfg:r});k.sendEnvPreflightResult(f.requestId,b)},onChatTurn:async f=>{let m=T(f.projectId);if(!m){k.sendChatTurnResult(f.requestId,{ok:!1,sessionId:f.sessionId??"",reply:"",error:"this runner has no local checkout mapped for that project"});return}let b=f.sessionId||(0,di.randomUUID)(),A=!f.sessionId;if((A?0:Mo(b)?.messages.length??0)>=44){k.sendChatTurnResult(f.requestId,{ok:!1,sessionId:b,reply:"",error:"this chat has hit its length limit \u2014 every turn re-reads the whole conversation, so long chats get slow and expensive. Start a new chat (it keeps the repo knowledge; only the conversation resets)."});return}let F=f.files.length?Za(m.repoPath,f.requestId,f.files):null,L="```",re=A?`You are the project assistant for "${m.project.name}" \u2014 this working directory is its repository, and you have read-only access.
|
|
663
|
+
(run \`${a.runId}\`)`).catch(c=>g.warn(`could not post refusal to ${i.issueKey}: ${c}`)),g.warn(`deploy refused for ${i.issueKey}: ${a.reason}`)):a.reason&&g.warn(`deploy claim rejected for ${i.issueKey}: ${a.reason}`);continue}let l=a.environment;this.inFlight.add(o),g.info(`claimed deploy ${a.runId}: ${i.issueKey} \u2192 ${l.name}`),this.enqueue(this.envQueues,l.id,async()=>{try{await Ws({runId:a.runId,project:t,environment:l,issueKey:i.issueKey,issueSummary:i.summary,repoPath:n,cfg:this.cfg,jira:this.jiraOf(t),transport:this.transport,requestedBy:i.requestedByDisplayName})}finally{this.inFlight.delete(o)}})}}async matchCommentDeploys(e,t){let n=e.trigger,s=e.action;if(n.type!=="comment_keyword"||s.type!=="deploy")return[];let i=await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=n.keyword.toLowerCase(),a=Date.now()-uc,l=this.environments.filter(p=>p.projectId===t.id).map(p=>p.name),c=this.fixedEnvironmentName(s.environmentId),h=[];for(let p of i){let _=await this.jiraOf(t).getIssue(p.key);if(!(s.requireStatus&&_.status.toLowerCase()!==s.requireStatus.toLowerCase()))for(let b of _.comments){if(!b.body.toLowerCase().includes(o)||Je(b.body)||new Date(b.created).getTime()<a||!b.id)continue;let x=s.envSelection==="fixed"?c:Mm(b.body,n.keyword,l);h.push({issueKey:p.key,summary:p.summary,environmentName:x,requestedByAccountId:b.authorAccountId??void 0,requestedByDisplayName:b.author,dedupKey:`deploy:comment:${b.id}`,fingerprint:`comment "${n.keyword}" by ${b.author} at ${b.created}`+(x?` \u2192 ${x}`:"")})}}return h}async matchStatusDeploys(e,t){let n=e.trigger,s=e.action;if(n.type!=="status_changed"||s.type!=="deploy")return[];let i=await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND status = "${n.status}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=this.fixedEnvironmentName(s.environmentId),a=[];for(let l of i){let c=await this.jiraOf(t).lastEnteredStatus(l.key,n.status);c&&a.push({issueKey:l.key,summary:l.summary,environmentName:o,requestedByAccountId:c.authorAccountId??void 0,requestedByDisplayName:c.author,dedupKey:`deploy:status:${e.id}:${l.key}:${c.at}`,fingerprint:`moved to "${n.status}" by ${c.author} at ${c.at}`})}return a}fixedEnvironmentName(e){return e?this.environments.find(t=>t.id===e)?.name??"":""}async matchLabelTrigger(e,t){let n=e.trigger;if(n.type!=="label_added")return[];let s=`project = "${t.jiraProjectKey}" AND labels = "${n.label}" AND labels not in ("${n.doneLabel}", "${n.failedLabel}", "${Cr.NEEDS_INPUT_LABEL}") ORDER BY updated ASC`;return(await this.jiraOf(t).search(s,10)).map(o=>({issueKey:o.key,summary:o.summary,components:o.components,fingerprint:`label "${n.label}" matched at ${new Date().toISOString()}`}))}async matchCommentTrigger(e,t){let n=e.trigger;if(n.type!=="comment_keyword")return[];let s=`project = "${t.jiraProjectKey}" AND updated >= "-2d" AND (labels IS EMPTY OR labels not in ("${n.doneLabel}", "${n.failedLabel}", "${Cr.NEEDS_INPUT_LABEL}")) ORDER BY updated DESC`,i=await this.jiraOf(t).search(s,10),o=n.keyword.toLowerCase(),a=[];for(let l of i){let h=(await this.jiraOf(t).getIssue(l.key)).comments.find(p=>p.body.toLowerCase().includes(o)&&!Je(p.body));h&&a.push({issueKey:l.key,components:l.components,summary:l.summary,fingerprint:`comment keyword "${n.keyword}" by ${h.author} at ${h.created}`,triggeredByAccountId:h.authorAccountId??void 0})}return a}async diagnoseRule(e,t){let n=e.trigger;if(e.action.type==="deploy"){let l=n.type==="status_changed"?await this.matchStatusDeploys(e,t):await this.matchCommentDeploys(e,t),c=l.filter(h=>h.environmentName);return{matchedCount:c.length,excludedCount:l.length-c.length,excludedSample:l.filter(h=>!h.environmentName).slice(0,5).map(h=>h.issueKey)}}if(n.type==="status_changed")return{matchedCount:(await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND status = "${n.status}"`,50)).length,excludedCount:0,excludedSample:[]};if(n.type==="label_added"){let[l,c]=await Promise.all([this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND labels = "${n.label}" AND labels not in ("${n.doneLabel}", "${n.failedLabel}")`,50),this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND labels = "${n.label}" AND labels in ("${n.doneLabel}", "${n.failedLabel}")`,50)]);return{matchedCount:l.length,excludedCount:c.length,excludedSample:c.slice(0,5).map(h=>h.key)}}let s=n.keyword.toLowerCase(),[i,o]=await Promise.all([this.matchCommentTrigger(e,t),this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND updated >= "-2d" AND labels in ("${n.doneLabel}", "${n.failedLabel}")`,50)]),a=[];for(let l of o)(await this.jiraOf(t).getIssue(l.key)).comments.some(h=>h.body.toLowerCase().includes(s))&&a.push(l.key);return{matchedCount:i.length,excludedCount:a.length,excludedSample:a.slice(0,5)}}enqueueForRepo(e,t){this.enqueue(this.repoQueues,e,t)}runOnRepoQueue(e,t){this.enqueue(this.repoQueues,e,t)}runOnEnvironmentQueue(e,t){this.enqueue(this.envQueues,e,t)}enqueue(e,t,n){let i=(e.get(t)??Promise.resolve()).then(n).catch(o=>{g.error(`run crashed: ${o instanceof Error?o.stack:o}`)});e.set(t,i)}};function Mm(r,e,t){let n=r.toLowerCase().indexOf(e.toLowerCase());if(n<0)return"";let i=r.slice(n+e.length).split(/[^\w.-]+/).filter(Boolean);for(let o of i){let a=t.find(l=>l.toLowerCase()===o.toLowerCase());if(a)return a}for(let o of i)if(!Nm.has(o.toLowerCase()))return o;return""}var Er=$(require("node:fs"),1),cc=$(require("node:path"),1);var zm=k.object({role:k.enum(["user","agent"]),text:k.string()}),Lm=k.object({sessionId:k.string(),projectId:k.string(),title:k.string().default(""),updatedAt:k.string(),messages:k.array(zm).default([])}),Dm=k.record(Lm),Um=10,qm=200,lc=2e4;function dc(){return cc.default.join(Q(),"chat-sessions.json")}function Lo(){let r=dc();if(!Er.default.existsSync(r))return{};try{return Dm.parse(JSON.parse(Er.default.readFileSync(r,"utf8")))}catch{return{}}}function Fm(r){Er.default.mkdirSync(Q(),{recursive:!0,mode:448});let e=dc(),t=e+".tmp";Er.default.writeFileSync(t,JSON.stringify(r,null,2)+`
|
|
664
|
+
`,{mode:384}),Er.default.renameSync(t,e),Er.default.chmodSync(e,384)}function hc(r,e,t,n){let s=Lo(),o=s[e]??{sessionId:e,projectId:r,title:t.slice(0,80),updatedAt:new Date().toISOString(),messages:[]};o.messages.push({role:"user",text:t.slice(0,lc)},{role:"agent",text:n.slice(0,lc)}),o.messages=o.messages.slice(-qm),o.updatedAt=new Date().toISOString(),s[e]=o;let a=Object.values(s).filter(l=>l.projectId===o.projectId).sort((l,c)=>c.updatedAt.localeCompare(l.updatedAt));for(let l of a.slice(Um))delete s[l.sessionId];Fm(s)}function fc(r){return Object.values(Lo()).filter(e=>e.projectId===r).sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt)).map(e=>({sessionId:e.sessionId,title:e.title,updatedAt:e.updatedAt,messageCount:e.messages.length}))}function Do(r){return Lo()[r]??null}var ly=$(ud(),1),cy=$(ai(),1),dy=$(gn(),1),hy=$(Jo(),1),fy=$(Qo(),1),py=$(ia(),1),yd=$(di(),1),my=$(gd(),1);var aa=yd.default;var es=$(require("node:crypto"),1),et=$(Te(),1);function gy(r){let e=r&&typeof r=="object"&&"name"in r?String(r.name):null;return e?`"${e}"`:"(unnamed)"}function ua(r,e,t,n){r.push(`dropped ${e} ${t} - this runner is out of date and does not understand it yet (${n}). Update the runner (npm install -g @ticketpilot/runner) to pick it up.`)}function yy(r){if(!r||typeof r!="object"||r.type!=="config")return null;let e=r,t=[],n=[];for(let a of Array.isArray(e.projects)?e.projects:[]){let l=et.ProjectConfig.safeParse(a);l.success?n.push(l.data):ua(t,"project","",l.error.issues[0]?.message??"invalid shape")}let s=[];for(let a of Array.isArray(e.rules)?e.rules:[]){let l=et.RuleConfig.safeParse(a);l.success?s.push(l.data):ua(t,"rule",gy(a),l.error.issues[0]?.message??"invalid shape")}let i=[];for(let a of Array.isArray(e.environments)?e.environments:[]){let l=et.EnvironmentConfig.safeParse(a);l.success?i.push(l.data):ua(t,"environment","",l.error.issues[0]?.message??"invalid shape")}return{msg:{type:"config",projects:n,rules:s,environments:i,pollingPaused:typeof e.pollingPaused=="boolean"?e.pollingPaused:!1},warnings:t}}var vy=2e4,_y=6e4,by=5e3,fi=class{constructor(e,t,n,s){this.wsUrl=e;this.runnerToken=t;this.meta=n;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===aa.OPEN}connect(){if(this.closed)return;g.info(`connecting to control plane at ${this.wsUrl}`);let e=new aa(this.wsUrl,{headers:{authorization:`Bearer ${this.runnerToken}`}});this.ws=e,e.on("open",()=>{this.backoffMs=1e3,this.sendNow({type:"hello",protocolVersion:et.PROTOCOL_VERSION,runnerVersion:this.meta.runnerVersion,platform:`${process.platform}/${process.arch} node${process.versions.node}`,justBooted:!this.bootAnnounced});let t=this.queue.splice(0,this.queue.length);for(let n of t)this.sendNow(n);this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=setInterval(()=>{this.send({type:"heartbeat",ts:new Date().toISOString()})},vy)}),e.on("message",t=>{let n;try{n=JSON.parse(t.toString())}catch(i){g.warn(`ignoring malformed server message (bad JSON): ${i}`);return}let s;try{s=(0,et.parseServerMsg)(n)}catch(i){let o=yy(n);if(!o){g.warn(`ignoring malformed server message: ${i}`);return}for(let a of o.warnings)g.warn(a);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",t=>{if(this.heartbeat&&clearInterval(this.heartbeat),t===4001)g.error("control plane rejected this runner version (protocol mismatch). Update with: npm install -g @ticketpilot/runner");else if(t===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 n=Math.random()*.3+.85,s=Math.round(this.backoffMs*n);g.warn(`disconnected (code ${t}); reconnecting in ${Math.round(s/1e3)}s`),setTimeout(()=>this.connect(),s),this.backoffMs=Math.min(this.backoffMs*2,_y)}),e.on("error",t=>{g.warn(`websocket error: ${t.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 t=this.pending.get(e.requestId);t&&(clearTimeout(t.timer),this.pending.delete(e.requestId),t.resolve(e));return}if(e.type==="config")return this.events.onConfig(e);if(e.type==="project.test")return this.events.onProjectTest(e);if(e.type==="rule.diagnose")return this.events.onRuleDiagnose(e);if(e.type==="run.cancel")return this.events.onCancel(e.runId);if(e.type==="run.approved")return this.events.onApproved(e.runId,e.headSha);if(e.type==="run.rejected")return this.events.onRejected(e.runId);if(e.type==="run.retryPush")return this.events.onRetryPush(e.runId);if(e.type==="deploy.start")return this.events.onDeployStart(e);if(e.type==="deploy.suggest")return this.events.onDeploySuggest(e);if(e.type==="env.preflight")return this.events.onEnvPreflight(e);if(e.type==="chat.turn")return this.events.onChatTurn(e);if(e.type==="chat.create.ticket")return this.events.onChatCreateTicket(e);if(e.type==="chat.list")return this.events.onChatList(e);if(e.type==="chat.load")return this.events.onChatLoad(e);if(e.type==="board.fetch")return this.events.onBoardFetch(e);if(e.type==="board.trigger")return this.events.onBoardTrigger(e);if(e.type==="audit.start")return this.events.onAuditStart(e);if(e.type==="audit.list")return this.events.onAuditList(e);if(e.type==="audit.get")return this.events.onAuditGet(e);if(e.type==="audit.review")return this.events.onAuditReview(e);if(e.type==="knowledge.list")return this.events.onKnowledgeList(e);if(e.type==="knowledge.save")return this.events.onKnowledgeSave(e);if(e.type==="epic.list")return this.events.onEpicList(e);if(e.type==="epic.suggest")return this.events.onEpicSuggest(e);if(e.type==="team.creds")return this.events.onTeamCreds(e);if(e.type==="jira.users")return this.events.onJiraUsers(e);if(e.type==="setup.status")return this.events.onSetupStatus(e);if(e.type==="setup.claudemd.generate")return this.events.onSetupClaudeMdGenerate(e);if(e.type==="setup.claudemd.save")return this.events.onSetupClaudeMdSave(e);if(e.type==="runner.update")return this.events.onRunnerUpdate(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>=by){let t=this.queue.findIndex(n=>n.type==="run.log");t>=0?this.queue.splice(t,1):this.queue.shift()}this.queue.push(e)}async claimRun(e){if(!this.connected)return{accepted:!1,reason:"control plane offline"};let t=es.default.randomUUID(),n=await new Promise(s=>{let i=setTimeout(()=>{this.pending.delete(t),s(null)},15e3);this.pending.set(t,{resolve:s,timer:i}),this.sendNow({type:"run.claim",requestId:t,...e})});return!n||n.type!=="run.claim.result"?{accepted:!1,reason:"claim timed out"}:{accepted:n.accepted,runId:n.runId,reason:n.reason,claudeProfile:n.claudeProfile,actorEmail:n.actorEmail}}async requestAutopilotNext(){if(!this.connected)return null;let e=es.default.randomUUID(),t=await new Promise(n=>{let s=setTimeout(()=>{this.pending.delete(e),n(null)},15e3);this.pending.set(e,{resolve:n,timer:s}),this.sendNow({type:"autopilot.next",requestId:e})});return!t||t.type!=="autopilot.next.result"?null:{ok:t.ok,item:t.item,pausedUntil:t.pausedUntil}}sendAutopilotReport(e){this.send({type:"autopilot.report",requestId:es.default.randomUUID(),itemId:e.itemId,outcome:e.outcome,runId:e.runId??"",error:e.error??""})}async claimDeploy(e){if(!this.connected)return{accepted:!1,reason:"control plane offline"};let t=es.default.randomUUID(),n=await new Promise(s=>{let i=setTimeout(()=>{this.pending.delete(t),s(null)},15e3);this.pending.set(t,{resolve:s,timer:i}),this.sendNow({type:"deploy.claim",requestId:t,...e})});return!n||n.type!=="deploy.claim.result"?{accepted:!1,reason:"deploy authorization timed out"}:{accepted:n.accepted,runId:n.runId,environment:n.environment,reason:n.reason,code:n.code}}sendDeploySuggestResult(e,t){this.send({type:"deploy.suggest.result",requestId:e,...t})}sendChatTurnResult(e,t){this.send({type:"chat.turn.result",requestId:e,...t})}sendChatCreateTicketResult(e,t){this.send({type:"chat.create.ticket.result",requestId:e,...t,childKeys:t.childKeys??[]})}sendChatListResult(e,t){this.send({type:"chat.list.result",requestId:e,sessions:t})}sendChatLoadResult(e,t){this.send({type:"chat.load.result",requestId:e,...t})}sendBoardFetchResult(e,t){this.send({type:"board.fetch.result",requestId:e,...t,browseBaseUrl:t.browseBaseUrl??""})}sendAuditStartResult(e,t){this.send({type:"audit.start.result",requestId:e,...t})}sendAuditListResult(e,t){this.send({type:"audit.list.result",requestId:e,ok:t.ok,error:t.error,audits:t.audits??[]})}sendAuditGetResult(e,t){this.send({type:"audit.get.result",requestId:e,...t})}sendAuditReviewResult(e,t){this.send({type:"audit.review.result",requestId:e,...t})}sendKnowledgeListResult(e,t){this.send({type:"knowledge.list.result",requestId:e,ok:t.ok,error:t.error,files:t.files??[]})}sendKnowledgeSaveResult(e,t){this.send({type:"knowledge.save.result",requestId:e,...t})}sendEpicListResult(e,t){this.send({type:"epic.list.result",requestId:e,ok:t.ok,error:t.error,epics:t.epics??[],children:t.children??[]})}sendEpicSuggestResult(e,t){this.send({type:"epic.suggest.result",requestId:e,ok:t.ok,error:t.error,issueKey:t.issueKey??"",reason:t.reason??"",considered:t.considered??0})}sendTeamCredsResult(e,t){this.send({type:"team.creds.result",requestId:e,ok:t.ok,error:t.error,githubShared:t.githubShared??!1,sharedGithubLogin:t.sharedGithubLogin??"",entries:t.entries??[]})}sendBoardTriggerResult(e,t){this.send({type:"board.trigger.result",requestId:e,...t})}sendAuditStatsResult(e,t){this.send({type:"audit.stats.result",requestId:e,ok:t.ok,error:t.error,byProject:t.byProject??{}})}sendRunnerUpdateResult(e,t){this.send({type:"runner.update.result",requestId:e,ok:t.ok,error:t.error,note:t.note??""})}sendSetupClaudeMdGenerateResult(e,t){this.send({type:"setup.claudemd.generate.result",requestId:e,ok:t.ok,error:t.error,content:t.content??""})}sendSetupClaudeMdSaveResult(e,t){this.send({type:"setup.claudemd.save.result",requestId:e,ok:t.ok,error:t.error,note:t.note??""})}sendSetupStatusResult(e,t){this.send({type:"setup.status.result",requestId:e,ok:t.ok,error:t.error,jiraConfigured:t.jiraConfigured??!1,jiraEmail:t.jiraEmail??"",claude:t.claude,githubTokenSet:t.githubTokenSet??!1,githubLogin:t.githubLogin??"",deploysEnabled:t.deploysEnabled??!1,jiraUserCount:t.jiraUserCount??0,repos:t.repos??[]})}sendEnvPreflightResult(e,t){this.send({type:"env.preflight.result",requestId:e,...t})}sendJiraUsersResult(e,t){this.send({type:"jira.users.result",requestId:e,...t})}sendProjectTestResult(e,t,n){this.send({type:"project.test.result",requestId:e,ok:t,checks:n})}sendRuleDiagnoseResult(e,t){this.send({type:"rule.diagnose.result",requestId:e,...t})}};var kn=$(require("node:fs"),1),la=$(require("node:path"),1),_d=require("node:child_process"),bd=require("node:util");var vd=(0,bd.promisify)(_d.execFile);async function pi(r,e,t=[]){let n=[],s=r.repos[e.repoName]?.jira??r.jira;if(!s)n.push({name:"jira-credentials",ok:!1,detail:"no Jira credentials configured on this runner"});else{let o=new qe(s);try{let a=await o.myself();n.push({name:"jira-auth",ok:!0,detail:`authenticated as ${a.displayName}`});try{await o.search(`project = "${e.jiraProjectKey}" ORDER BY created DESC`,1),n.push({name:"jira-project",ok:!0,detail:`project ${e.jiraProjectKey} is readable`})}catch(l){n.push({name:"jira-project",ok:!1,detail:`cannot read project ${e.jiraProjectKey}: ${ts(l)}`})}}catch(a){n.push({name:"jira-auth",ok:!1,detail:`Jira auth failed: ${ts(a)}`})}}let i=r.repos[e.repoName];if(i&&kn.default.existsSync(i.path)){let o=la.default.join(i.path,"CLAUDE.md"),a=kn.default.existsSync(o)&&kn.default.readFileSync(o,"utf8").trim().length>0;n.push({name:"memory-file",ok:a,detail:a?"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."});let l=zo(i.path);n.push({name:"deploy-doc",ok:l!==null,detail:l?`${l.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."})}if(!i)n.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(!kn.default.existsSync(i.path))n.push({name:"repo-path",ok:!1,detail:`path does not exist: ${i.path}`});else{let o=kn.default.existsSync(la.default.join(i.path,".git"));n.push({name:"repo-path",ok:!0,detail:`${i.path}${o?" (git checkout)":" (warning: not a git checkout)"}`})}try{let{stdout:o}=await vd(r.claudeBin,["--version"],{timeout:15e3});n.push({name:"claude-code",ok:!0,detail:o.trim().slice(0,100)})}catch(o){n.push({name:"claude-code",ok:!1,detail:`cannot run "${r.claudeBin}": ${ts(o)}`})}try{let{stdout:o}=await vd("git",["--version"],{timeout:15e3});n.push({name:"git",ok:!0,detail:o.trim().slice(0,100)})}catch(o){n.push({name:"git",ok:!1,detail:`cannot run git: ${ts(o)}`})}if(r.github?.token)try{let{GitHubClient:o}=await Promise.resolve().then(()=>(ct(),un)),a=await new o(r.github.token).whoami();n.push({name:"github-token",ok:!0,detail:`authenticated as ${a}`})}catch(o){n.push({name:"github-token",ok:!1,detail:ts(o)})}else n.push({name:"github-token",ok:!0,detail:"not set - needed only for implement rules (allwright github set-token)"});if(t.length){r.deploy.enabled?n.push({name:"deploy",ok:!0,detail:"deployments enabled on this runner"}):n.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 o of t){let a=Qt(r,e.repoName,o.name),l=o.requiredSecrets.filter(c=>!a[c]&&!process.env[c]);n.push({name:`env:${o.name}`,ok:l.length===0,detail:l.length?`missing secret(s): ${l.join(", ")} - allwright env set "${e.repoName}" "${o.name}" ${l[0]}=...`:`${o.steps.length} step(s), ${o.requiredSecrets.length} secret(s) present`+(o.branch?`, deploys origin/${o.branch}`:"")})}}return n}function ts(r){return(r instanceof Error?r.message:String(r)).slice(0,300)}var ue=new Aa;ue.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(Is);ue.command("init").description("Interactive setup: enroll this runner and store credentials locally").option("--cp-url <url>","control plane URL").option("--enroll-token <token>","enrolment token from the Allwright UI").option("--name <name>","runner name",Ed.default.hostname()).option("--jira-url <url>","Jira base URL, e.g. https://yourorg.atlassian.net").option("--jira-email <email>","Jira account email").option("--jira-token <token>","Jira API token (stored locally only)").action(async r=>{let e=Or.default.createInterface({input:process.stdin,output:process.stdout}),t=async(n,s,i=!1)=>{if(s)return s;let o=await e.question(`${n}: `);if(!o.trim())throw new Error(`${n} is required`);return o.trim()};try{let n=await t("Control plane URL",r.cpUrl),s=await t("Enrolment token (from the web UI)",r.enrollToken),i=await t("Jira base URL (https://yourorg.atlassian.net)",r.jiraUrl),o=await t("Jira account email",r.jiraEmail),a=await t("Jira API token (create at id.atlassian.com/manage-profile/security/api-tokens)",r.jiraToken,!0),l=Mi.parse({controlPlaneUrl:n,runnerName:r.name,jira:{baseUrl:i,email:o,apiToken:a}}),c=await new qe(l.jira).myself();g.info(`Jira credential OK - authenticated as ${c.displayName}`),l=await ku(l,s),g.info(`Enrolled as runner "${l.runnerName}" (${l.runnerId})`),g.info(`Credentials saved to ${St()} (mode 600, this machine only)`),g.info("Next: map your repo with `allwright repo add <repoName> <localPath>`, then `allwright start`")}finally{e.close()}});var ca=ue.command("repo").description("Map control-plane repo names to local checkouts");ca.command("add <repoName> <localPath>").description("Map a repo name (as configured in the web UI) to a local checkout path").action(async(r,e)=>{let t=ee();t.repos[r]={path:e},oe(t),g.info(`mapped repo "${r}" -> ${e}`);try{let{originUrl:n}=await Promise.resolve().then(()=>(_r(),Pu));g.info(` origin remote: ${await n(e)} - make sure this is the repo you meant`)}catch{g.warn(` could not read an origin remote at ${e} - is it a git checkout?`)}});ca.command("list").description("Show configured repo mappings").action(()=>{let r=ee(),e=Object.entries(r.repos);if(!e.length)return g.info("no repos mapped yet");for(let[t,n]of e)g.info(`${t} -> ${n.path}`)});var Id=ue.command("claude").description("Per-user Claude login profiles - each teammate's runs bill their OWN Claude account");Id.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 r=>{if(!/^[a-zA-Z0-9._-]+$/.test(r))throw new Error("profile name: letters, digits, dots, dashes and underscores only");let e=ee(),t=e.claudeProfiles[r]?.configDir??`${St().replace(/runner\.json$/,"")}claude-profiles/${r}`;yt.default.mkdirSync(t,{recursive:!0,mode:448}),e.claudeProfiles[r]={configDir:t},oe(e),g.info(`profile "${r}" -> ${t}`),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 n=(0,Mt.spawn)(e.claudeBin,[],{env:{...process.env,CLAUDE_CONFIG_DIR:t},stdio:"inherit"});await new Promise(s=>n.on("exit",()=>s())),g.info(`Done. Assign it on the dashboard: Team -> the user -> Claude profile = "${r}".`),g.info("Restart the background runner for this to take effect: allwright stop && allwright start")});Id.command("list").description("Show configured Claude profiles and whether each looks logged in").action(()=>{let r=ee(),e=Object.entries(r.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[t,n]of e){let s=yt.default.existsSync(n.configDir)&&yt.default.readdirSync(n.configDir).length>0;g.info(`${t} -> ${n.configDir} ${s?"(logged in)":"(NOT logged in yet)"}`)}});ca.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(r=>{let e=ee();if(!e.repos[r]){let i=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${r}" - mapped repos: ${i}`)}let t=e.repos[r].path;delete e.repos[r];let n=Object.keys(e.environments).filter(i=>i.startsWith(`${r}:`));for(let i of n)delete e.environments[i];let s=e.auditSchedules.length;e.auditSchedules=e.auditSchedules.filter(i=>i.repoName!==r),oe(e),g.info(`Removed "${r}" (was ${t})`),n.length&&g.info(`Also removed ${n.length} environment secret set(s): ${n.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 da=ue.command("service").description("Run the runner as a system service (starts on boot, restarts on crash)");da.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(r=>{if(r.print){g.info(`
|
|
665
|
+
`+fo(ho()));return}Du(g)});da.command("uninstall").description("Stop and remove the systemd service (config/credentials untouched)").action(()=>Uu(g));da.command("status").description("systemctl status for the runner service").action(()=>{(0,Mt.spawn)("systemctl",["status","allwright","--no-pager"],{stdio:"inherit"}).on("exit",e=>process.exit(e??0))});ue.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 r=(0,Mt.spawn)("npm",["install","-g","allwright@latest"],{stdio:"inherit"});await new Promise((e,t)=>{r.on("exit",n=>n===0?e():t(new Error(`npm exited with code ${n}`))),r.on("error",t)}),g.info("Updated. Restart the runner service to load the new version (check active runs first).")});var ns=ue.command("jira").description("Per-repo Jira site overrides - for projects living on a different Atlassian site");ns.command("set <repoName>").description("Store Jira credentials for ONE repo's project (e.g. a project on a different *.atlassian.net site than the runner's main credential). Prompts on stdin; stored locally only, like every other credential.").action(async r=>{let e=ee();if(!e.repos[r]){let n=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${r}" - mapped repos: ${n}. Run \`allwright repo add\` first.`)}let t=Or.default.createInterface({input:process.stdin,output:process.stdout});try{let n=(await t.question("Jira base URL for this repo (https://yourorg.atlassian.net): ")).trim(),s=(await t.question("Jira account email: ")).trim(),i=(await t.question("Jira API token (id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!n||!s||!i)throw new Error("all three values are required");let o={baseUrl:n,email:s,apiToken:i},a=await new qe(o).myself();g.info(`Jira credential OK - authenticated as ${a.displayName} on ${n}`),e.repos[r].jira=o,oe(e),g.info(`Saved: repo "${r}" now polls ${n} (other repos keep the runner-wide credential)`),g.info("Restart the background runner for this to take effect: allwright stop && allwright start")}finally{t.close()}});ns.command("show").description("Show which Jira site each repo uses (never prints tokens)").action(()=>{let r=ee();g.info(`runner-wide: ${r.jira?`${r.jira.baseUrl} (${r.jira.email})`:"(not configured)"}`);for(let[e,t]of Object.entries(r.repos))g.info(`${e} -> ${t.jira?`${t.jira.baseUrl} (${t.jira.email})`:"(runner-wide credential)"}`)});ns.command("user-add <ticketpilotEmail>").description("Store a PERSON's own Jira credential, so board buttons and Compose tickets they click post to Jira under THEIR Atlassian identity instead of the runner's account. Keyed by their Allwright login email. Prompts on stdin; stored locally only. Picked up on the next click - no restart needed.").action(async r=>{let e=ee(),t=r.trim().toLowerCase();if(!t.includes("@"))throw new Error(`"${r}" doesn't look like an email`);let n=Or.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await n.question(`Their ATLASSIAN account email [${t}]: `)).trim()||t,i=(await n.question("Their Jira API token (they create it at id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!i)throw new Error("API token is required");let o=[e.jira,...Object.values(e.repos).map(c=>c.jira)].filter(c=>!!c),a=new Set,l=!1;for(let c of o)if(!a.has(c.baseUrl)){a.add(c.baseUrl);try{let h=await new qe({baseUrl:c.baseUrl,email:s,apiToken:i}).myself();g.info(`${c.baseUrl}: OK - authenticated as ${h.displayName}`),l=!0}catch{g.warn(`${c.baseUrl}: this credential does NOT work there (fine if they don't use that site)`)}}if(!l)throw new Error("credential failed on every configured Jira site - nothing saved");e.jiraUsers[t]={email:s,apiToken:i},oe(e),g.info(`Saved. Dashboard actions by ${t} now post to Jira as ${s}. No restart needed.`)}finally{n.close()}});ns.command("user-list").description("Show which Allwright users have their own Jira credential here (never prints tokens)").action(()=>{let r=ee(),e=Object.entries(r.jiraUsers);if(!e.length)return g.info("none yet - everyone's dashboard clicks require one: allwright jira user-add <their-ticketpilot-email>");for(let[t,n]of e)g.info(`${t} -> posts to Jira as ${n.email}`)});ns.command("user-remove <ticketpilotEmail>").description("Delete a person's stored Jira credential").action(r=>{let e=ee(),t=r.trim().toLowerCase();if(!e.jiraUsers[t])throw new Error(`no credential stored for ${t}`);delete e.jiraUsers[t],oe(e),g.info(`Removed. Dashboard actions by ${t} will now be refused until a new credential is added.`)});var xn=ue.command("github").description("GitHub credential for implement-mode rules");xn.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 r=>{let e=Or.default.createInterface({input:process.stdin,output:process.stdout});try{let t=r.token??(await e.question("GitHub token (fine-grained PAT recommended): ")).trim();if(!t)throw new Error("token is required");let{GitHubClient:n}=await Promise.resolve().then(()=>(ct(),un)),s=await new n(t).whoami(),i=ee();i.github={token:t,login:s},oe(i),g.info(`GitHub token OK - authenticated as ${s}`),g.info(`Saved to ${St()} (mode 600, this machine only)`)}finally{e.close()}});xn.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 r=>{let e=ee();if(!e.repos[r]){let n=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${r}" - mapped repos: ${n}. Run \`allwright repo add\` first.`)}let t=Or.default.createInterface({input:process.stdin,output:process.stdout});try{let n=(await t.question(`GitHub token for "${r}" (fine-grained PAT scoped to just this repo): `)).trim();if(!n)throw new Error("token is required");let{GitHubClient:s}=await Promise.resolve().then(()=>(ct(),un)),i=await new s(n).whoami();e.repos[r].github={token:n,login:i},oe(e),g.info(`GitHub token OK - authenticated as ${i}`),g.info(`Saved: repo "${r}" now uses its own token (other repos keep the runner-wide one)`)}finally{t.close()}});xn.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 r=>{let e=ee(),t=r.trim().toLowerCase();if(!t.includes("@"))throw new Error(`"${r}" doesn't look like an email`);let n=Or.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await n.question(`GitHub token for ${t}: `)).trim();if(!s)throw new Error("token is required");let{GitHubClient:i}=await Promise.resolve().then(()=>(ct(),un)),o=await new i(s).whoami();e.githubUsers[t]={token:s,login:o},oe(e),g.info(`GitHub token OK - authenticated as ${o}`),g.info(`Saved. Implement runs triggered by ${t} now open PRs as ${o}. No restart needed.`)}finally{n.close()}});xn.command("user-list").description("Show which Allwright users have their own GitHub token here (never prints tokens)").action(()=>{let r=ee(),e=Object.entries(r.githubUsers);if(!e.length)return g.info("no per-user GitHub tokens - everyone's PRs use the repo/runner-wide token");for(let[t]of e)g.info(`${t} -> own GitHub token stored`)});xn.command("user-remove <ticketpilotEmail>").description("Delete a person's stored GitHub token (their runs fall back to the shared token)").action(r=>{let e=ee(),t=r.trim().toLowerCase();if(!e.githubUsers[t])throw new Error(`no GitHub token stored for ${t}`);delete e.githubUsers[t],oe(e),g.info(`Removed. ${t}'s runs use the repo/runner-wide token again.`)});xn.command("show").description("Show which GitHub token each repo and person would use (never prints tokens)").action(()=>{let r=ee();g.info(`runner-wide: ${r.github?.token?"token set":"(not configured)"}`);for(let[t,n]of Object.entries(r.repos))g.info(`${t} -> ${n.github?.token?"own repo token":"runner-wide token"}`);let e=Object.keys(r.githubUsers);g.info(e.length?`per-user tokens: ${e.join(", ")}`:"per-user tokens: (none)")});var ha=ue.command("audit").description("Recurring specialist audits on this runner");ha.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((r,e,t)=>{let n=ee();if(!n.repos[r]){let i=Object.keys(n.repos).join(", ")||"(none)";throw new Error(`unknown repo "${r}" - mapped repos: ${i}`)}if(e!=="security"&&e!=="testing")throw new Error('role must be "security" or "testing"');let s=parseInt(t,10);if(!Number.isInteger(s)||s<6||s>720)throw new Error("intervalHours must be 6-720");n.auditSchedules=[...n.auditSchedules.filter(i=>!(i.repoName===r&&i.role===e)),{repoName:r,role:e,intervalHours:s}],oe(n),g.info(`Scheduled: ${e} audit of "${r}" every ${s}h. Restart the runner to apply.`)});ha.command("schedules").description("List scheduled audits").action(()=>{let r=ee();if(!r.auditSchedules.length)return g.info("no scheduled audits - allwright audit schedule <repo> <role> <hours>");for(let e of r.auditSchedules)g.info(`${e.repoName} \xB7 ${e.role} \xB7 every ${e.intervalHours}h`)});ha.command("unschedule <repoName> <role>").description("Remove a scheduled audit").action((r,e)=>{let t=ee(),n=t.auditSchedules.length;if(t.auditSchedules=t.auditSchedules.filter(s=>!(s.repoName===r&&s.role===e)),t.auditSchedules.length===n)throw new Error("no such schedule");oe(t),g.info("Removed. Restart the runner to apply.")});var fa=ue.command("deploy").description("Deployment settings for this machine");fa.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 r=ee();r.deploy={enabled:!0},oe(r),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."),g.info("Restart the background runner for this to take effect: allwright stop && allwright start")});fa.command("disable").description("Stop this runner from executing any deploy steps").action(()=>{let r=ee();r.deploy={enabled:!1},oe(r),g.info("deployments DISABLED on this runner"),g.info("Restart the background runner for this to take effect: allwright stop && allwright start")});fa.command("status").description("Show whether deployments are enabled here, and which env secrets are stored").action(()=>{let r=ee();g.info(`deployments: ${r.deploy.enabled?"enabled":"disabled"}`);let e=Object.entries(r.environments);if(!e.length)return g.info("no environment secrets stored");for(let[t,n]of e){let s=Object.keys(n.secrets);g.info(`${t}: ${s.length?s.join(", "):"(no secrets)"}`)}});var pa=ue.command("env").description("Per-environment deploy secrets. Values stay on this machine, like your Jira token.");pa.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((r,e,t)=>{let n=ee(),s=ps(r,e),i=n.environments[s]??{secrets:{}},o=[];for(let a of t){let l=a.indexOf("=");if(l<=0)throw new Error(`expected KEY=VALUE, got "${a}"`);let c=a.slice(0,l).trim();i.secrets[c]=a.slice(l+1),o.push(c)}n.environments[s]=i,oe(n),g.info(`stored ${o.length} secret(s) for ${s}: ${o.join(", ")}`),g.info(`Saved to ${St()} (mode 600, this machine only)`),g.info("Restart the background runner to pick these up: allwright stop && allwright start")});pa.command("unset <repoName> <envName> <names...>").description("Remove stored secrets for an environment").action((r,e,t)=>{let n=ee(),s=ps(r,e),i=n.environments[s];if(!i)return g.info(`nothing stored for ${s}`);for(let o of t)delete i.secrets[o];n.environments[s]=i,oe(n),g.info(`removed ${t.join(", ")} from ${s}`)});pa.command("list").description("Show which environments have secrets stored here (names only, never values)").action(()=>{let r=ee(),e=Object.entries(r.environments);if(!e.length)return g.info("no environment secrets stored");for(let[t,n]of e)g.info(`${t}: ${Object.keys(n.secrets).join(", ")||"(none)"}`)});ue.command("export [file]").description("Back up ALL runner state (config+secrets, knowledge, audits, chats) to one tarball").action(r=>{try{let e=Fa(r);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 ${Sn.default.basename(e.file)}`)}catch(e){g.error(e instanceof Error?e.message:String(e)),process.exitCode=1}});ue.command("import <file>").description("Restore runner state from an `export` tarball (existing config is kept as a .bak dir)").action(r=>{let e=Kr();if(e&&Vr(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 t=Ba(r);g.info(`Restored ${t.restored.length} entries into ${Q()}`),t.previousDir&&g.info(`Previous config kept at ${t.previousDir}`),g.info("Start the runner and it will reconnect with the restored identity.")}catch(t){g.error(t instanceof Error?t.message:String(t)),process.exitCode=1}});ue.command("test").description("Check local setup: Jira auth, repo mappings, Claude Code binary").action(async()=>{let r=ee(),e=Object.keys(r.repos);if(!r.jira){g.error("no Jira credentials configured - run `allwright init`"),process.exitCode=1;return}let t=e.length?e.map(s=>({jiraProjectKey:"*",repoName:s})):[{jiraProjectKey:"*",repoName:"(none mapped)"}],n=!0;for(let s of t){let i=await pi(r,s);for(let o of i){if(s.jiraProjectKey==="*"&&o.name==="jira-project")continue;let a=o.ok?"PASS":"FAIL";(o.ok?g.info:g.error)(`[${a}] ${o.name}: ${o.detail}`),n&&=o.ok}}n||(process.exitCode=1)});function Sy(r){if(!r.runnerToken)throw new Error("runner not enrolled - run `allwright init`");if(!r.jira)throw new Error("no Jira credentials - run `allwright init`");let e=Ja();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",Di);let t=new qe(r.jira),n=new Map,s=f=>{let m=r.repos[f]?.jira;if(!m)return t;let w=n.get(f);return w||(w=new qe(m),n.set(f,w)),w},i=new Map,o=(f,m)=>{let w=Nu(ce()??r,f,m);switch(w.kind){case"legacy":return{jira:s(f),authored:!1};case"self":return{jira:s(f),authored:!0};case"missing":return{error:w.error};case"user":{let A=`${w.creds.baseUrl}:${w.creds.email}:${w.creds.apiToken.slice(-6)}`,N=i.get(A);return N||(N=new qe(w.creds),i.set(A,N)),{jira:N,authored:!0}}}},a=new URL("/api/runner/ws",r.controlPlaneUrl);a.protocol=a.protocol==="https:"?"wss:":"ws:";let l=[],c=[],h=[],p,_={cfg:r,jiraFor:s,transport:null},b=new Set,x=f=>{let m=l.find(A=>A.id===f),w=m&&r.repos[m.repoName];return m&&w?{project:m,repoPath:w.path}:null},C={cfg:r,jiraFor:s,get transport(){return _.transport},lookup:(f,m)=>{let w=x(f),A=h.find(N=>N.projectId===f&&N.name===m);return w&&A?{...w,environment:A}:null}},S=new fi(a.toString(),r.runnerToken,{runnerVersion:Is},{onConfig:f=>{l=f.projects,c=f.rules,h=f.environments,p.setConfig(f.projects,f.rules,f.pollingPaused,f.environments)},onProjectTest:async f=>{let m=l.find(A=>A.id===f.projectId);if(!m){S.sendProjectTestResult(f.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 w=await pi(r,m,h.filter(A=>A.projectId===m.id));S.sendProjectTestResult(f.requestId,w.every(A=>A.ok),w)},onRuleDiagnose:async f=>{let m=c.find(M=>M.id===f.ruleId),w=m&&l.find(M=>M.id===m.projectId);if(!m||!w){S.sendRuleDiagnoseResult(f.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 A=await pi(r,w,m.action.type==="deploy"?h.filter(M=>M.projectId===w.id):[]),N=m.action.type==="implement"?A:A.filter(M=>M.name!=="github-token"),{matchedCount:B,excludedCount:z,excludedSample:re}=await p.diagnoseRule(m,w);S.sendRuleDiagnoseResult(f.requestId,{checks:N,matchedCount:B,excludedCount:z,excludedSample:re})},onCancel:f=>{g.warn(`cancel requested for run ${f} - not supported in this version, run will finish or time out`)},onApproved:(f,m)=>{if(Mo(f)){rc(C,f).catch(w=>g.error(`deploy approval crashed for ${f}: ${w instanceof Error?w.stack:w}`));return}Kn(_,f,m).catch(w=>g.error(`approval handling crashed for ${f}: ${w instanceof Error?w.stack:w}`))},onRetryPush:f=>{let m=Us(f),w=()=>Zl(_,f).catch(A=>g.error(`retry push crashed for ${f}: ${A instanceof Error?A.stack:A}`));m?p.runOnRepoQueue(m.baseRepoPath,w):w()},onRejected:f=>{if(Mo(f)){nc(C,f).catch(m=>g.error(`deploy rejection crashed for ${f}: ${m instanceof Error?m.stack:m}`));return}Bl(_,f).catch(m=>g.error(`rejection handling crashed for ${f}: ${m instanceof Error?m.stack:m}`))},onDeployStart:f=>{let m=`${f.runId}#${f.attempt}`;if(b.has(m))return;b.add(m);let w=x(f.projectId);if(!w){let A="this runner has no local checkout mapped for that project - run: allwright repo add <repoName> /path/to/checkout";g.error(`deploy ${f.runId}: ${A}`),S.send({type:"run.status",runId:f.runId,status:"failed",error:A});return}g.info(`deploy ${f.runId} requested from the dashboard: ${f.issueKey} \u2192 ${f.environment.name}`),p.runOnEnvironmentQueue(f.environment.id,()=>Ws({runId:f.runId,project:w.project,environment:f.environment,issueKey:f.issueKey,issueSummary:f.issueSummary,repoPath:w.repoPath,cfg:r,jira:s(w.project.repoName),transport:S,requestedBy:f.requestedBy}).catch(A=>g.error(`deploy crashed for ${f.runId}: ${A instanceof Error?A.stack:A}`)))},onDeploySuggest:async f=>{let m=x(f.projectId);if(!m){S.sendDeploySuggestResult(f.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:"this runner has no local checkout mapped for that project"});return}g.info(`asking Claude Code for "${f.environmentName}" deploy steps in ${m.repoPath}`);let w=await ac({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:f.environmentName,notes:f.notes,timeoutSeconds:f.timeoutSeconds,cfg:r});S.sendDeploySuggestResult(f.requestId,w)},onEnvPreflight:async f=>{let m=x(f.projectId);if(!m){S.sendEnvPreflightResult(f.requestId,{ok:!1,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project"}]});return}let w=await oc({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:f.environmentName,steps:f.steps,requiredSecrets:f.requiredSecrets,workdir:f.workdir,branch:f.branch,publicUrl:f.publicUrl,cfg:r});S.sendEnvPreflightResult(f.requestId,w)},onChatTurn:async f=>{let m=x(f.projectId);if(!m){S.sendChatTurnResult(f.requestId,{ok:!1,sessionId:f.sessionId??"",reply:"",error:"this runner has no local checkout mapped for that project"});return}let w=f.sessionId||(0,mi.randomUUID)(),A=!f.sessionId;if((A?0:Do(w)?.messages.length??0)>=44){S.sendChatTurnResult(f.requestId,{ok:!1,sessionId:w,reply:"",error:"this chat has hit its length limit - every turn re-reads the whole conversation, so long chats get slow and expensive. Start a new chat (it keeps the repo knowledge; only the conversation resets)."});return}let B=f.files.length?Va(m.repoPath,f.requestId,f.files):null,z="```",re=A?`You are the project assistant for "${m.project.name}" - this working directory is its repository, and you have read-only access.
|
|
665
666
|
|
|
666
|
-
DEFAULT MODE IS DISCUSSION. Answer questions, explain code, weigh approaches, review ideas
|
|
667
|
+
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.
|
|
667
668
|
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.
|
|
668
669
|
|
|
669
670
|
ONLY when the user explicitly asks for a ticket, propose it by ending your reply with EXACTLY one fenced block in this shape:
|
|
670
|
-
${
|
|
671
|
+
${z}ticket
|
|
671
672
|
{"summary": "\u2026", "description": "\u2026"}
|
|
672
|
-
${
|
|
673
|
-
Before drafting, re-read this ENTIRE conversation from its first message and fold in every decision, constraint, and correction agreed along the way
|
|
673
|
+
${z}
|
|
674
|
+
Before drafting, re-read this ENTIRE conversation from its first message and fold in every decision, constraint, and correction agreed along the way - the ticket reflects the final state of the whole discussion, not just the last message.
|
|
674
675
|
Write the description in plain human language, structured with these Markdown section headings in this order:
|
|
675
|
-
Story:
|
|
676
|
-
Description:
|
|
677
|
-
Expected Flow:
|
|
678
|
-
Current Flow:
|
|
679
|
-
Acceptance Criteria:
|
|
680
|
-
Include a section only when it carries real content, and add extra sections (Out of Scope, Notes, \u2026) when the work genuinely needs them. Use as many bullets as the work needs
|
|
681
|
-
EXCEPTION
|
|
682
|
-
EXCEPTION
|
|
676
|
+
Story: - one or two sentences: who needs this and why.
|
|
677
|
+
Description: - what to build and where in the codebase, as bullet points.
|
|
678
|
+
Expected Flow: - the flow once this ticket is done, as numbered steps.
|
|
679
|
+
Current Flow: - how it behaves today; include ONLY when current behavior exists.
|
|
680
|
+
Acceptance Criteria: - testable bullet points a reviewer can check off one by one.
|
|
681
|
+
Include a section only when it carries real content, and add extra sections (Out of Scope, Notes, \u2026) when the work genuinely needs them. Use as many bullets as the work needs - no artificial length cap, but no padding either. It must stay concrete enough that a developer (or an agent) can implement it without asking questions. NEVER paste the conversation into the description; distill it. Refine the draft over further turns if the user asks.
|
|
682
|
+
EXCEPTION - verbatim payloads: when the user supplies literal content that must land in the ticket exactly (file contents, error logs, specs, commands), include it in the description IN FULL inside a fenced code block - the word budget applies to your own prose around it, never to the user's payload. Never summarize such content and never replace it with a placeholder like "[insert content here]": a placeholder makes the ticket unimplementable, because the implementing agent only ever sees the ticket. Inside the ${z}ticket JSON, fence such payloads with ~~~ (tildes), NEVER with triple backticks - a nested ${z} would end the outer block early and corrupt the draft.
|
|
683
|
+
EXCEPTION - big requirements: when the user asks for an epic with sub-tickets, or asks to ticket something clearly too large for one ticket, break it down instead and emit this shape in the \`\`\`ticket block:
|
|
683
684
|
{"epic": {"summary": "\u2026", "description": "\u2026"}, "tickets": [{"summary": "\u2026", "description": "\u2026"}, \u2026]}
|
|
684
685
|
3-8 tickets, each independently implementable and structured with the same section headings as above, ordered so foundations come first; the epic description is the overall goal in under 100 words.
|
|
685
686
|
|
|
686
|
-
${f.userName||"The user"} says: ${f.message}`+(
|
|
687
|
+
${f.userName||"The user"} says: ${f.message}`+(B?.section??""):`${f.userName||"The user"} says: ${f.message}`+(B?.section??""),M=0,J;try{J=await Ne.run({repoPath:m.repoPath,prompt:re,timeoutSeconds:180,bin:r.claudeBin,mode:"read_only",maxTurns:25,model:f.model||"claude-sonnet-5",sessionId:w,resume:!A,onLog:(Ze,ve)=>{Ze==="agent"&&S.send({type:"chat.stream",requestId:f.requestId,seq:M++,text:ve.slice(0,8e3)})}})}finally{B&&yt.default.rmSync(B.dir,{recursive:!0,force:!0})}J.ok&&hc(f.projectId,w,f.message,J.resultText),S.sendChatTurnResult(f.requestId,{ok:J.ok,sessionId:w,reply:J.resultText,error:J.ok?void 0:J.error??"the agent produced no reply"})},onChatList:f=>{S.sendChatListResult(f.requestId,fc(f.projectId))},onChatLoad:f=>{let m=Do(f.sessionId);S.sendChatLoadResult(f.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 f=>{let m=x(f.projectId);if(!m){S.sendBoardFetchResult(f.requestId,{ok:!1,columns:[],error:"this runner has no local checkout mapped for that project"});return}try{let w=s(m.project.repoName),A;try{A=await w.searchBoard(`project = "${m.project.jiraProjectKey}" ORDER BY Rank ASC`,100)}catch{A=await w.searchBoard(`project = "${m.project.jiraProjectKey}" ORDER BY updated DESC`,100)}let N=await w.boardColumns(m.project.jiraProjectKey),B;if(N){B=N.map(M=>({name:M.name,issues:[]}));let re=new Map;for(let M of A){let J=N.findIndex(ve=>ve.statusIds.includes(M.statusId)),Ze={key:M.key,summary:M.summary,labels:M.labels};if(J>=0)B[J].issues.push(Ze);else{let ve=re.get(M.status)??[];ve.push(Ze),re.set(M.status,ve)}}for(let[M,J]of re)B.push({name:M,issues:J})}else{let re=he=>he.trim().toLowerCase(),M=new Map,J=new Map;for(let he of A){let vt=re(he.status);M.has(vt)||M.set(vt,he.status.trim());let ma=J.get(vt)??[];ma.push({key:he.key,summary:he.summary,labels:he.labels}),J.set(vt,ma)}let Ze=[];try{Ze=await w.projectStatuses(m.project.jiraProjectKey)}catch{}let ve=[];for(let he of Ze){let vt=re(he);!ve.includes(vt)&&J.has(vt)&&ve.push(vt)}for(let he of J.keys())ve.includes(he)||ve.push(he);B=ve.map(he=>({name:M.get(he)??he,issues:J.get(he)??[]}))}let z=r.repos[m.project.repoName]?.jira??r.jira;S.sendBoardFetchResult(f.requestId,{ok:!0,browseBaseUrl:(z?.baseUrl??"").replace(/\/+$/,""),columns:B})}catch(w){S.sendBoardFetchResult(f.requestId,{ok:!1,columns:[],error:w instanceof Error?w.message:String(w)})}},onBoardTrigger:async f=>{let m=x(f.projectId);if(!m){S.sendBoardTriggerResult(f.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{let w=s(m.project.repoName),A=f.comment.trim()?o(m.project.repoName,f.requestedByEmail):{jira:w,authored:!1};if(A.error!==void 0){S.sendBoardTriggerResult(f.requestId,{ok:!1,error:A.error});return}if(f.reimplement){let N=await w.getIssue(f.issueKey),B=N.comments.filter(M=>Je(M.body)),z=B.length?Math.max(...B.map(M=>new Date(M.created).getTime())):0;if(!N.comments.some(M=>!Je(M.body)&&new Date(M.created).getTime()>z)){S.sendBoardTriggerResult(f.requestId,{ok:!1,error:`${f.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 w.editLabels(f.issueKey,{remove:["agent-implemented"]})}f.removeLabel.trim()&&await w.editLabels(f.issueKey,{remove:[f.removeLabel.trim()]}),f.comment.trim()&&await A.jira.addTriggerComment(f.issueKey,`${f.comment.trim()}`+(!A.authored&&f.requestedBy?`
|
|
687
688
|
|
|
688
|
-
_(requested by ${f.requestedBy} via Allwright)_`:"")),g.info(`Board action on ${f.issueKey}`+(f.comment?` comment "${f.comment.trim()}"`:"")+(f.removeLabel?` -label ${f.removeLabel}`:"")+(f.requestedBy?` by ${f.requestedBy}`:"")),
|
|
689
|
+
_(requested by ${f.requestedBy} via Allwright)_`:"")),g.info(`Board action on ${f.issueKey}`+(f.comment?` comment "${f.comment.trim()}"`:"")+(f.removeLabel?` -label ${f.removeLabel}`:"")+(f.requestedBy?` by ${f.requestedBy}`:"")),S.sendBoardTriggerResult(f.requestId,{ok:!0})}catch(w){S.sendBoardTriggerResult(f.requestId,{ok:!1,error:w instanceof Error?w.message:String(w)})}},onChatCreateTicket:async f=>{let m=x(f.projectId);if(!m){S.sendChatCreateTicketResult(f.requestId,{ok:!1,issueKey:"",error:"this runner has no local checkout mapped for that project"});return}try{let w=o(m.project.repoName,f.requestedByEmail);if(w.error!==void 0){S.sendChatCreateTicketResult(f.requestId,{ok:!1,issueKey:"",error:w.error});return}let A=`
|
|
689
690
|
|
|
690
691
|
---
|
|
691
|
-
_Created via Allwright Compose`+(!
|
|
692
|
+
_Created via Allwright Compose`+(!w.authored&&f.requestedBy?` by ${f.requestedBy}`:"")+", drafted with the project agent._",{key:N}=await w.jira.createIssue(m.project.jiraProjectKey,f.summary,(f.description||"(no description)")+A,f.asEpic?"Epic":"Task");f.files.length&&await w.jira.addAttachments(N,f.files.map(z=>({name:z.name,content:Buffer.from(z.contentBase64,"base64")}))).then(()=>g.info(`Compose attached ${f.files.length} file(s) to ${N}`)).catch(z=>g.warn(`Compose could not attach files to ${N}: ${z instanceof Error?z.message:z}`));let B=[];if(f.asEpic){for(let z of f.children){let re=await w.jira.createIssue(m.project.jiraProjectKey,z.summary,z.description||"(no description)","Task",N);B.push(re.key)}g.info(`Compose created epic ${N} with ${B.length} child ticket(s)`),S.sendChatCreateTicketResult(f.requestId,{ok:!0,issueKey:N,childKeys:B});return}f.triggerComment.trim()&&await w.jira.addTriggerComment(N,`${f.triggerComment.trim()}`+(!w.authored&&f.requestedBy?`
|
|
692
693
|
|
|
693
|
-
_(requested by ${f.requestedBy} via Allwright)_`:"")),g.info(`Compose created ${N}`+(f.requestedBy?` for ${f.requestedBy}`:"")+(f.triggerComment?` with trigger "${f.triggerComment.trim()}"`:"")),
|
|
694
|
+
_(requested by ${f.requestedBy} via Allwright)_`:"")),g.info(`Compose created ${N}`+(f.requestedBy?` for ${f.requestedBy}`:"")+(f.triggerComment?` with trigger "${f.triggerComment.trim()}"`:"")),S.sendChatCreateTicketResult(f.requestId,{ok:!0,issueKey:N})}catch(w){S.sendChatCreateTicketResult(f.requestId,{ok:!1,issueKey:"",error:w instanceof Error?w.message:String(w)})}},onAuditStart:async f=>{let m=x(f.projectId);if(!m){S.sendAuditStartResult(f.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{g.info(`Audit (${f.role}) starting on ${m.project.repoName}`+(f.scope.kind!=="repo"?` scoped to ${f.scope.kind}:${f.scope.ref}`:""));let w=await on({projectId:f.projectId,repoPath:m.repoPath,role:f.role,scope:f.scope,model:f.model,claudeBin:r.claudeBin,jira:s(m.project.repoName)});if(!w.ok){S.sendAuditStartResult(f.requestId,{ok:!1,error:w.error});return}S.sendAuditStartResult(f.requestId,{ok:!0,audit:w.audit})}catch(w){S.sendAuditStartResult(f.requestId,{ok:!1,error:w instanceof Error?w.message:String(w)})}},onAuditList:async f=>{try{S.sendAuditListResult(f.requestId,{ok:!0,audits:nl(f.projectId)})}catch(m){S.sendAuditListResult(f.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditGet:async f=>{try{let m=ol(f.projectId,f.auditId);if(!m){S.sendAuditGetResult(f.requestId,{ok:!1,error:"audit not found on this runner"});return}S.sendAuditGetResult(f.requestId,{ok:!0,audit:m})}catch(m){S.sendAuditGetResult(f.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditReview:async f=>{try{let m=yo(f.projectId,f.auditId,{selected:f.selected,ticketed:f.ticketed,verdicts:f.verdicts,verdictBy:f.verdictBy});if(!m){S.sendAuditReviewResult(f.requestId,{ok:!1,error:"audit not found on this runner"});return}let w=x(f.projectId);if(w&&f.verdicts.length){let A=[];for(let N of f.verdicts){if(N.verdict==="valid"||m.lessonsWritten.includes(N.findingId))continue;let B=m.findings.find(z=>z.id===N.findingId);B&&(bo(w.repoPath,m.role,hl(B,N.verdict,N.note,f.verdictBy)),A.push(N.findingId),g.info(`Lesson written (${m.role}): ${N.verdict} - ${B.title.slice(0,60)}`))}A.length&&(m=yo(f.projectId,f.auditId,{markLessonsWritten:A})??m)}S.sendAuditReviewResult(f.requestId,{ok:!0,audit:m})}catch(m){S.sendAuditReviewResult(f.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onKnowledgeList:async f=>{let m=x(f.projectId);if(!m){S.sendKnowledgeListResult(f.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{S.sendKnowledgeListResult(f.requestId,{ok:!0,files:pl(m.repoPath)})}catch(w){S.sendKnowledgeListResult(f.requestId,{ok:!1,error:w instanceof Error?w.message:String(w)})}},onKnowledgeSave:async f=>{let m=x(f.projectId);if(!m){S.sendKnowledgeSaveResult(f.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{f.append?bo(m.repoPath,f.role,fl(f.content,f.by),f.level):ml(m.repoPath,f.role,f.level,f.source,f.name,f.content),g.info(`Knowledge ${f.append?"taught":"saved"}: ${f.role}/${f.level}/${f.name}`),S.sendKnowledgeSaveResult(f.requestId,{ok:!0})}catch(w){S.sendKnowledgeSaveResult(f.requestId,{ok:!1,error:w instanceof Error?w.message:String(w)})}},onEpicList:async f=>{let m=x(f.projectId);if(!m){S.sendEpicListResult(f.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{let w=s(m.project.repoName);if(f.epicKey){let A=await w.epicChildren(f.epicKey);S.sendEpicListResult(f.requestId,{ok:!0,children:A})}else{let A=await w.searchEpics(m.project.jiraProjectKey);S.sendEpicListResult(f.requestId,{ok:!0,epics:A})}}catch(w){S.sendEpicListResult(f.requestId,{ok:!1,error:w instanceof Error?w.message:String(w)})}},onEpicSuggest:async f=>{let m=x(f.projectId);if(!m){S.sendEpicSuggestResult(f.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{let w=s(m.project.repoName),A=await w.epicChildren(f.epicKey),N=Fu(A);if(!N.length){S.sendEpicSuggestResult(f.requestId,{ok:!1,error:`every child of ${f.epicKey} is already done or in an agent's hands - nothing to sequence`});return}if(N.length===1){S.sendEpicSuggestResult(f.requestId,{ok:!0,issueKey:N[0].key,reason:"It's the only pending ticket left in this epic.",considered:1});return}let B=await Promise.all(N.slice(0,12).map(async J=>{try{let Ze=await w.getIssue(J.key);return{...J,description:Ze.description}}catch{return{...J,description:""}}})),z=(await w.getIssue(f.epicKey).catch(()=>null))?.summary??"";g.info(`Epic suggest: weighing ${B.length} pending children of ${f.epicKey}`);let re=await Ne.run({repoPath:m.repoPath,prompt:Bu(f.epicKey,z,B),timeoutSeconds:150,bin:r.claudeBin,mode:"read_only",maxTurns:20,sessionId:(0,mi.randomUUID)(),model:f.model||"claude-sonnet-5",onLog:()=>{}}),M=Zu(re.resultText,B.map(J=>J.key));if("error"in M){S.sendEpicSuggestResult(f.requestId,{ok:!1,error:M.error});return}g.info(`Epic suggest: ${f.epicKey} -> do ${M.issueKey} first`),S.sendEpicSuggestResult(f.requestId,{ok:!0,issueKey:M.issueKey,reason:M.reason,considered:B.length})}catch(w){S.sendEpicSuggestResult(f.requestId,{ok:!1,error:w instanceof Error?w.message:String(w)})}},onTeamCreds:async f=>{try{let m=ce()??r;if(m.github?.token&&!m.github.login)try{let{GitHubClient:A}=await Promise.resolve().then(()=>(ct(),un));m.github.login=await new A(m.github.token).whoami(),oe(m)}catch{}let w=Mu(m,f.emails);S.sendTeamCredsResult(f.requestId,{ok:!0,...w})}catch(m){S.sendTeamCredsResult(f.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupStatus:async f=>{try{let m=ce()??r,{buildSetupReport:w}=await Promise.resolve().then(()=>(Cd(),Td)),A=await w(m,f.repoNames);S.sendSetupStatusResult(f.requestId,{ok:!0,...A})}catch(m){S.sendSetupStatusResult(f.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdGenerate:async f=>{try{let m=x(f.projectId);if(!m){S.sendSetupClaudeMdGenerateResult(f.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let w=f.kind==="deploy"?"DEPLOY.md":"CLAUDE.md";g.info(`Setup: drafting ${w} for ${m.project.repoName}`);let z=(await Ne.run({repoPath:m.repoPath,prompt:f.kind==="deploy"?'Inspect this repository (deploy scripts, CI files, server configs, package scripts) and draft the content of a DEPLOY.md deploy contract for its repo root. An automation tool will follow it LITERALLY, so only write what you can verify from the repo. IMPORTANT: you are running ON the machine where deploys will execute - commands are plain local commands, no ssh wrapper, unless the repo clearly documents a different target machine. For each environment that VERIFIABLY exists: name, branch, exact deploy commands, secrets as $NAMES only (never values), pre/post checks (post-restart checks must wait and retry - services report active before their port binds). Where you cannot verify something (hosts, service names, ports), write it with a clear "VERIFY:" marker so the human fills it in during review, instead of guessing. State explicitly which environments do NOT exist. Reply with ONLY the file content - no preamble, no fences around the whole thing.':"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.",timeoutSeconds:240,bin:r.claudeBin,mode:"read_only",maxTurns:40,sessionId:(0,mi.randomUUID)(),onLog:()=>{}})).resultText.trim();if(!z){S.sendSetupClaudeMdGenerateResult(f.requestId,{ok:!1,error:"the agent returned no content - try again"});return}S.sendSetupClaudeMdGenerateResult(f.requestId,{ok:!0,content:z})}catch(m){S.sendSetupClaudeMdGenerateResult(f.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdSave:async f=>{try{let m=x(f.projectId);if(!m){S.sendSetupClaudeMdSaveResult(f.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let w=f.kind==="deploy"?"DEPLOY.md":"CLAUDE.md",A=Sn.default.join(m.repoPath,w);if(yt.default.existsSync(A)&&!f.overwrite){S.sendSetupClaudeMdSaveResult(f.requestId,{ok:!1,error:`${w} already exists in this checkout`});return}yt.default.writeFileSync(A,f.content.endsWith(`
|
|
694
695
|
`)?f.content:f.content+`
|
|
695
|
-
`),g.info(`Setup: wrote human-approved CLAUDE.md to ${A}`);let N="",
|
|
696
|
+
`),g.info(`Setup: wrote human-approved CLAUDE.md to ${A}`);let N="",B=z=>new Promise((re,M)=>{(0,Mt.execFile)("git",["-C",m.repoPath,...z],{timeout:12e4},(J,Ze,ve)=>J?M(new Error(ve||J.message)):re())});try{await B(["add",w]),await B(["-c","user.name=Allwright","-c","user.email=runner@allwright.local","commit","-m",`Add ${w} (agent-drafted, human-approved via Allwright)`]);try{await B(["push"]),N="committed and pushed to the repo"}catch(z){N="committed locally, but push failed: "+(z instanceof Error?z.message.slice(0,200):"unknown")+" - push it from the server when convenient"}}catch(z){N="file written, but commit failed: "+(z instanceof Error?z.message.slice(0,200):"unknown")+" - commit it from the server when convenient"}S.sendSetupClaudeMdSaveResult(f.requestId,{ok:!0,note:N})}catch(m){S.sendSetupClaudeMdSaveResult(f.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditStats:f=>{try{S.sendAuditStatsResult(f.requestId,{ok:!0,byProject:sl(f.projectIds,f.since)})}catch(m){S.sendAuditStatsResult(f.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRunnerUpdate:async f=>{if(!process.env.INVOCATION_ID){S.sendRunnerUpdateResult(f.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}if(p&&p.busyCount>0){S.sendRunnerUpdateResult(f.requestId,{ok:!1,error:`a run is executing on this machine right now (${p.busyCount} active) - try again when it finishes`});return}g.info("Update requested from the dashboard - installing allwright@latest");let m=Sn.default.dirname(process.execPath),w=yt.default.existsSync(Sn.default.join(m,"npm"))?Sn.default.join(m,"npm"):"npm";(0,Mt.execFile)(w,["install","-g","allwright@latest"],{timeout:18e4,env:{...process.env,PATH:`${m}:${process.env.PATH??""}`}},(A,N,B)=>{if(A){S.sendRunnerUpdateResult(f.requestId,{ok:!1,error:`npm install failed: ${(B||A.message).slice(0,300)} - on the machine run: allwright update && sudo systemctl restart allwright`});return}S.sendRunnerUpdateResult(f.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)})},onJiraUsers:async f=>{try{let m=await t.searchUsers(f.query);S.sendJiraUsersResult(f.requestId,{ok:!0,users:m})}catch(m){S.sendJiraUsersResult(f.requestId,{ok:!1,users:[],error:m instanceof Error?m.message:String(m)})}}});_.transport=S,p=new Xs(r,s,S);let F=Object.values(dn()).filter(f=>f.kind==="implement").map(f=>f.repoPath);to(Object.values(r.repos).map(f=>f.path),F).catch(()=>{}),S.start(),p.start();let q=()=>{g.info("shutting down"),p.stop(),S.stop(),Wa(process.pid),Di(),process.exit(0)};process.on("SIGINT",q),process.on("SIGTERM",q)}ue.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 r=>{let e=ee();if(r.foreground){Sy(e);return}let t=Kr();if(t&&Vr(t)){g.info(`already running in the background (pid ${t}). Use \`allwright status\` or \`stop\`.`);return}let n=Rn();if(n){g.info(`a runner is already running on this machine (pid ${n}) - most likely the systemd service. One machine runs ONE runner; nothing to do. (Service controls: sudo systemctl status|stop|restart allwright)`);return}let s=Ga(),i=(0,Mt.spawn)(process.execPath,[process.argv[1],"start","--foreground"],{detached:!0,stdio:["ignore",s,s]});i.unref(),Ha(i.pid),g.info(`Runner started in the background (pid ${i.pid}).`),g.info(`Logs: ${vs()}`),g.info("It will keep polling Jira until you run `allwright stop` - closing this terminal is fine.")});ue.command("stop").description("Stop the background runner started by `start`").action(()=>{let r=Kr();if(!r||!Vr(r)){g.info("no background runner is running"),r&&yt.default.rmSync(An(),{force:!0});return}process.kill(r,"SIGTERM"),g.info(`stop signal sent (pid ${r})`)});ue.command("status").description("Check whether the background runner is running").action(()=>{let r=Kr();r&&Vr(r)?g.info(`running in the background (pid ${r})`):g.info("not running")});ue.parseAsync().catch(r=>{g.error(r instanceof Error?r.message:String(r)),process.exit(1)});
|