allwright 1.30.0 → 1.31.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/allwright.js +60 -55
- package/package.json +1 -1
package/bin/allwright.js
CHANGED
|
@@ -1,26 +1,26 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var pf=Object.create;var po=Object.defineProperty;var mf=Object.getOwnPropertyDescriptor;var gf=Object.getOwnPropertyNames;var yf=Object.getPrototypeOf,bf=Object.prototype.hasOwnProperty;var Zs=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var re=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}},Gs=(t,e)=>{for(var n in e)po(t,n,{get:e[n],enumerable:!0})},vf=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of gf(e))!bf.call(t,s)&&s!==n&&po(t,s,{get:()=>e[s],enumerable:!(r=mf(e,s))||r.enumerable});return t};var I=(t,e,n)=>(n=t!=null?pf(yf(t)):{},vf(e||!t||!t.__esModule?po(n,"default",{value:t,enumerable:!0}):n,t));var ps=re(go=>{var Vs=class extends Error{constructor(e,n,r){super(r),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=n,this.exitCode=e,this.nestedError=void 0}},mo=class extends Vs{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};go.CommanderError=Vs;go.InvalidArgumentError=mo});var Ws=re(bo=>{var{InvalidArgumentError:wf}=ps(),yo=class{constructor(e,n){switch(this.description=n||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,n){return n===this.defaultValue||!Array.isArray(n)?[e]:n.concat(e)}default(e,n){return this.defaultValue=e,this.defaultValueDescription=n,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(n,r)=>{if(!this.argChoices.includes(n))throw new wf(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(n,r):n},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function _f(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}bo.Argument=yo;bo.humanReadableArgName=_f});var wo=re(Cl=>{var{humanReadableArgName:kf}=Ws(),vo=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let n=e.commands.filter(s=>!s._hidden),r=e._getHelpCommand();return r&&!r._hidden&&n.push(r),this.sortSubcommands&&n.sort((s,i)=>s.name().localeCompare(i.name())),n}compareOptions(e,n){let r=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return r(e).localeCompare(r(n))}visibleOptions(e){let n=e.options.filter(s=>!s.hidden),r=e._getHelpOption();if(r&&!r.hidden){let s=r.short&&e._findOption(r.short),i=r.long&&e._findOption(r.long);!s&&!i?n.push(r):r.long&&!i?n.push(e.createOption(r.long,r.description)):r.short&&!s&&n.push(e.createOption(r.short,r.description))}return this.sortOptions&&n.sort(this.compareOptions),n}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let n=[];for(let r=e.parent;r;r=r.parent){let s=r.options.filter(i=>!i.hidden);n.push(...s)}return this.sortOptions&&n.sort(this.compareOptions),n}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(n=>{n.description=n.description||e._argsDescription[n.name()]||""}),e.registeredArguments.find(n=>n.description)?e.registeredArguments:[]}subcommandTerm(e){let n=e.registeredArguments.map(r=>kf(r)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(n?" "+n:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,n){return n.visibleCommands(e).reduce((r,s)=>Math.max(r,n.subcommandTerm(s).length),0)}longestOptionTermLength(e,n){return n.visibleOptions(e).reduce((r,s)=>Math.max(r,n.optionTerm(s).length),0)}longestGlobalOptionTermLength(e,n){return n.visibleGlobalOptions(e).reduce((r,s)=>Math.max(r,n.optionTerm(s).length),0)}longestArgumentTermLength(e,n){return n.visibleArguments(e).reduce((r,s)=>Math.max(r,n.argumentTerm(s).length),0)}commandUsage(e){let n=e._name;e._aliases[0]&&(n=n+"|"+e._aliases[0]);let r="";for(let s=e.parent;s;s=s.parent)r=s.name()+" "+r;return r+n+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let n=[];return e.argChoices&&n.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&n.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&n.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&n.push(`env: ${e.envVar}`),n.length>0?`${e.description} (${n.join(", ")})`:e.description}argumentDescription(e){let n=[];if(e.argChoices&&n.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&n.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),n.length>0){let r=`(${n.join(", ")})`;return e.description?`${e.description} ${r}`:r}return e.description}formatHelp(e,n){let r=n.padWidth(e,n),s=n.helpWidth||80,i=2,o=2;function l(S,x){if(x){let
|
|
2
|
+
"use strict";var pf=Object.create;var po=Object.defineProperty;var mf=Object.getOwnPropertyDescriptor;var gf=Object.getOwnPropertyNames;var yf=Object.getPrototypeOf,bf=Object.prototype.hasOwnProperty;var Zs=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var re=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}},Gs=(t,e)=>{for(var n in e)po(t,n,{get:e[n],enumerable:!0})},vf=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of gf(e))!bf.call(t,s)&&s!==n&&po(t,s,{get:()=>e[s],enumerable:!(r=mf(e,s))||r.enumerable});return t};var I=(t,e,n)=>(n=t!=null?pf(yf(t)):{},vf(e||!t||!t.__esModule?po(n,"default",{value:t,enumerable:!0}):n,t));var ps=re(go=>{var Vs=class extends Error{constructor(e,n,r){super(r),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=n,this.exitCode=e,this.nestedError=void 0}},mo=class extends Vs{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};go.CommanderError=Vs;go.InvalidArgumentError=mo});var Ws=re(bo=>{var{InvalidArgumentError:wf}=ps(),yo=class{constructor(e,n){switch(this.description=n||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,n){return n===this.defaultValue||!Array.isArray(n)?[e]:n.concat(e)}default(e,n){return this.defaultValue=e,this.defaultValueDescription=n,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(n,r)=>{if(!this.argChoices.includes(n))throw new wf(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(n,r):n},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function _f(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}bo.Argument=yo;bo.humanReadableArgName=_f});var wo=re(Cl=>{var{humanReadableArgName:kf}=Ws(),vo=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let n=e.commands.filter(s=>!s._hidden),r=e._getHelpCommand();return r&&!r._hidden&&n.push(r),this.sortSubcommands&&n.sort((s,i)=>s.name().localeCompare(i.name())),n}compareOptions(e,n){let r=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return r(e).localeCompare(r(n))}visibleOptions(e){let n=e.options.filter(s=>!s.hidden),r=e._getHelpOption();if(r&&!r.hidden){let s=r.short&&e._findOption(r.short),i=r.long&&e._findOption(r.long);!s&&!i?n.push(r):r.long&&!i?n.push(e.createOption(r.long,r.description)):r.short&&!s&&n.push(e.createOption(r.short,r.description))}return this.sortOptions&&n.sort(this.compareOptions),n}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let n=[];for(let r=e.parent;r;r=r.parent){let s=r.options.filter(i=>!i.hidden);n.push(...s)}return this.sortOptions&&n.sort(this.compareOptions),n}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(n=>{n.description=n.description||e._argsDescription[n.name()]||""}),e.registeredArguments.find(n=>n.description)?e.registeredArguments:[]}subcommandTerm(e){let n=e.registeredArguments.map(r=>kf(r)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(n?" "+n:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,n){return n.visibleCommands(e).reduce((r,s)=>Math.max(r,n.subcommandTerm(s).length),0)}longestOptionTermLength(e,n){return n.visibleOptions(e).reduce((r,s)=>Math.max(r,n.optionTerm(s).length),0)}longestGlobalOptionTermLength(e,n){return n.visibleGlobalOptions(e).reduce((r,s)=>Math.max(r,n.optionTerm(s).length),0)}longestArgumentTermLength(e,n){return n.visibleArguments(e).reduce((r,s)=>Math.max(r,n.argumentTerm(s).length),0)}commandUsage(e){let n=e._name;e._aliases[0]&&(n=n+"|"+e._aliases[0]);let r="";for(let s=e.parent;s;s=s.parent)r=s.name()+" "+r;return r+n+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let n=[];return e.argChoices&&n.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&n.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&n.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&n.push(`env: ${e.envVar}`),n.length>0?`${e.description} (${n.join(", ")})`:e.description}argumentDescription(e){let n=[];if(e.argChoices&&n.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&n.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),n.length>0){let r=`(${n.join(", ")})`;return e.description?`${e.description} ${r}`:r}return e.description}formatHelp(e,n){let r=n.padWidth(e,n),s=n.helpWidth||80,i=2,o=2;function l(S,x){if(x){let A=`${S.padEnd(r+o)}${x}`;return n.wrap(A,s-i,r+o)}return S}function u(S){return S.join(`
|
|
3
3
|
`).replace(/^/gm," ".repeat(i))}let c=[`Usage: ${n.commandUsage(e)}`,""],f=n.commandDescription(e);f.length>0&&(c=c.concat([n.wrap(f,s,0),""]));let p=n.visibleArguments(e).map(S=>l(n.argumentTerm(S),n.argumentDescription(S)));p.length>0&&(c=c.concat(["Arguments:",u(p),""]));let b=n.visibleOptions(e).map(S=>l(n.optionTerm(S),n.optionDescription(S)));if(b.length>0&&(c=c.concat(["Options:",u(b),""])),this.showGlobalOptions){let S=n.visibleGlobalOptions(e).map(x=>l(n.optionTerm(x),n.optionDescription(x)));S.length>0&&(c=c.concat(["Global Options:",u(S),""]))}let w=n.visibleCommands(e).map(S=>l(n.subcommandTerm(S),n.subcommandDescription(S)));return w.length>0&&(c=c.concat(["Commands:",u(w),""])),c.join(`
|
|
4
4
|
`)}padWidth(e,n){return Math.max(n.longestOptionTermLength(e,n),n.longestGlobalOptionTermLength(e,n),n.longestSubcommandTermLength(e,n),n.longestArgumentTermLength(e,n))}wrap(e,n,r,s=40){let i=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",o=new RegExp(`[\\n][${i}]+`);if(e.match(o))return e;let l=n-r;if(l<s)return e;let u=e.slice(0,r),c=e.slice(r).replace(`\r
|
|
5
5
|
`,`
|
|
6
6
|
`),f=" ".repeat(r),b="\\s\u200B",w=new RegExp(`
|
|
7
|
-
|.{1,${l-1}}([${b}]|$)|[^${b}]+?([${b}]|$)`,"g"),S=c.match(w)||[];return u+S.map((x,
|
|
8
|
-
`?"":(
|
|
7
|
+
|.{1,${l-1}}([${b}]|$)|[^${b}]+?([${b}]|$)`,"g"),S=c.match(w)||[];return u+S.map((x,A)=>x===`
|
|
8
|
+
`?"":(A>0?f:"")+x.trimEnd()).join(`
|
|
9
9
|
`)}};Cl.Help=vo});var To=re(So=>{var{InvalidArgumentError:Sf}=ps(),_o=class{constructor(e,n){this.flags=e,this.description=n||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let r=xf(e);this.short=r.shortFlag,this.long=r.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,n){return this.defaultValue=e,this.defaultValueDescription=n,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let n=e;return typeof e=="string"&&(n={[e]:!0}),this.implied=Object.assign(this.implied||{},n),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,n){return n===this.defaultValue||!Array.isArray(n)?[e]:n.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(n,r)=>{if(!this.argChoices.includes(n))throw new Sf(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(n,r):n},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return Tf(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},ko=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(n=>{n.negate?this.negativeOptions.set(n.attributeName(),n):this.positiveOptions.set(n.attributeName(),n)}),this.negativeOptions.forEach((n,r)=>{this.positiveOptions.has(r)&&this.dualOptions.add(r)})}valueFromOption(e,n){let r=n.attributeName();if(!this.dualOptions.has(r))return!0;let s=this.negativeOptions.get(r).presetArg,i=s!==void 0?s:!1;return n.negate===(i===e)}};function Tf(t){return t.split("-").reduce((e,n)=>e+n[0].toUpperCase()+n.slice(1))}function xf(t){let e,n,r=t.split(/[ |,]+/);return r.length>1&&!/^[[<]/.test(r[1])&&(e=r.shift()),n=r.shift(),!e&&/^-[^-]$/.test(n)&&(e=n,n=void 0),{shortFlag:e,longFlag:n}}So.Option=_o;So.DualOptions=ko});var Rl=re(Il=>{function Cf(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);let n=[];for(let r=0;r<=t.length;r++)n[r]=[r];for(let r=0;r<=e.length;r++)n[0][r]=r;for(let r=1;r<=e.length;r++)for(let s=1;s<=t.length;s++){let i=1;t[s-1]===e[r-1]?i=0:i=1,n[s][r]=Math.min(n[s-1][r]+1,n[s][r-1]+1,n[s-1][r-1]+i),s>1&&r>1&&t[s-1]===e[r-2]&&t[s-2]===e[r-1]&&(n[s][r]=Math.min(n[s][r],n[s-2][r-2]+1))}return n[t.length][e.length]}function If(t,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let n=t.startsWith("--");n&&(t=t.slice(2),e=e.map(o=>o.slice(2)));let r=[],s=3,i=.4;return e.forEach(o=>{if(o.length<=1)return;let l=Cf(t,o),u=Math.max(t.length,o.length);(u-l)/u>i&&(l<s?(s=l,r=[o]):l===s&&r.push(o))}),r.sort((o,l)=>o.localeCompare(l)),n&&(r=r.map(o=>`--${o}`)),r.length>1?`
|
|
10
10
|
(Did you mean one of ${r.join(", ")}?)`:r.length===1?`
|
|
11
|
-
(Did you mean ${r[0]}?)`:""}Il.suggestSimilar=If});var jl=re(Pl=>{var Rf=require("node:events").EventEmitter,xo=require("node:child_process"),It=require("node:path"),Co=require("node:fs"),me=require("node:process"),{Argument:
|
|
12
|
-
- specify the name in Command constructor or using .name()`);return n=n||{},n.isDefault&&(this._defaultCommandName=e._name),(n.noHelp||n.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,n){return new
|
|
13
|
-
Expecting one of '${r.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(n):this._lifeCycleHooks[e]=[n],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=n=>{if(n.code!=="commander.executeSubCommandAsync")throw n},this}_exit(e,n,r){this._exitCallback&&this._exitCallback(new Io(e,n,r)),me.exit(e)}action(e){let n=r=>{let s=this.registeredArguments.length,i=r.slice(0,s);return this._storeOptionsAsProperties?i[s]=this:i[s]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=n,this}createOption(e,n){return new
|
|
14
|
-
- already used by option '${n.flags}'`)}this.options.push(e)}_registerCommand(e){let n=s=>[s.name()].concat(s.aliases()),r=n(e).find(s=>this._findCommand(s));if(r){let s=n(this._findCommand(r)).join("|"),i=n(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let n=e.name(),r=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(r,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(r,e.defaultValue,"default");let s=(i,o,l)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let u=this.getOptionValue(r);i!==null&&e.parseArg?i=this._callParseArg(e,i,u,o):i!==null&&e.variadic&&(i=e._concatValue(i,u)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(r,i,l)};return this.on("option:"+n,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;s(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+n,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;s(i,o,"env")}),this}_optionEx(e,n,r,s,i){if(typeof n=="object"&&n instanceof
|
|
11
|
+
(Did you mean ${r[0]}?)`:""}Il.suggestSimilar=If});var jl=re(Pl=>{var Rf=require("node:events").EventEmitter,xo=require("node:child_process"),It=require("node:path"),Co=require("node:fs"),me=require("node:process"),{Argument:Ef,humanReadableArgName:Af}=Ws(),{CommanderError:Io}=ps(),{Help:$f}=wo(),{Option:El,DualOptions:Pf}=To(),{suggestSimilar:Al}=Rl(),Ro=class t extends Rf{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:n=>me.stdout.write(n),writeErr:n=>me.stderr.write(n),getOutHelpWidth:()=>me.stdout.isTTY?me.stdout.columns:void 0,getErrHelpWidth:()=>me.stderr.isTTY?me.stderr.columns:void 0,outputError:(n,r)=>r(n)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let n=this;n;n=n.parent)e.push(n);return e}command(e,n,r){let s=n,i=r;typeof s=="object"&&s!==null&&(i=s,s=null),i=i||{};let[,o,l]=e.match(/([^ ]+) *(.*)/),u=this.createCommand(o);return s&&(u.description(s),u._executableHandler=!0),i.isDefault&&(this._defaultCommandName=u._name),u._hidden=!!(i.noHelp||i.hidden),u._executableFile=i.executableFile||null,l&&u.arguments(l),this._registerCommand(u),u.parent=this,u.copyInheritedSettings(this),s?this:u}createCommand(e){return new t(e)}createHelp(){return Object.assign(new $f,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,n){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
12
|
+
- specify the name in Command constructor or using .name()`);return n=n||{},n.isDefault&&(this._defaultCommandName=e._name),(n.noHelp||n.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,n){return new Ef(e,n)}argument(e,n,r,s){let i=this.createArgument(e,n);return typeof r=="function"?i.default(s).argParser(r):i.default(r),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(n=>{this.argument(n)}),this}addArgument(e){let n=this.registeredArguments.slice(-1)[0];if(n&&n.variadic)throw new Error(`only the last argument can be variadic '${n.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,n){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,r,s]=e.match(/([^ ]+) *(.*)/),i=n??"display help for command",o=this.createCommand(r);return o.helpOption(!1),s&&o.arguments(s),i&&o.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(e,n){return typeof e!="object"?(this.helpCommand(e,n),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,n){let r=["preSubcommand","preAction","postAction"];if(!r.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
13
|
+
Expecting one of '${r.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(n):this._lifeCycleHooks[e]=[n],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=n=>{if(n.code!=="commander.executeSubCommandAsync")throw n},this}_exit(e,n,r){this._exitCallback&&this._exitCallback(new Io(e,n,r)),me.exit(e)}action(e){let n=r=>{let s=this.registeredArguments.length,i=r.slice(0,s);return this._storeOptionsAsProperties?i[s]=this:i[s]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=n,this}createOption(e,n){return new El(e,n)}_callParseArg(e,n,r,s){try{return e.parseArg(n,r)}catch(i){if(i.code==="commander.invalidArgument"){let o=`${s} ${i.message}`;this.error(o,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){let n=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(n){let r=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${r}'
|
|
14
|
+
- already used by option '${n.flags}'`)}this.options.push(e)}_registerCommand(e){let n=s=>[s.name()].concat(s.aliases()),r=n(e).find(s=>this._findCommand(s));if(r){let s=n(this._findCommand(r)).join("|"),i=n(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let n=e.name(),r=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(r,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(r,e.defaultValue,"default");let s=(i,o,l)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let u=this.getOptionValue(r);i!==null&&e.parseArg?i=this._callParseArg(e,i,u,o):i!==null&&e.variadic&&(i=e._concatValue(i,u)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(r,i,l)};return this.on("option:"+n,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;s(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+n,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;s(i,o,"env")}),this}_optionEx(e,n,r,s,i){if(typeof n=="object"&&n instanceof El)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(n,r);if(o.makeOptionMandatory(!!e.mandatory),typeof s=="function")o.default(i).argParser(s);else if(s instanceof RegExp){let l=s;s=(u,c)=>{let f=l.exec(u);return f?f[0]:c},o.default(i).argParser(s)}else o.default(s);return this.addOption(o)}option(e,n,r,s){return this._optionEx({},e,n,r,s)}requiredOption(e,n,r,s){return this._optionEx({mandatory:!0},e,n,r,s)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,n){return this.setOptionValueWithSource(e,n,void 0)}setOptionValueWithSource(e,n,r){return this._storeOptionsAsProperties?this[e]=n:this._optionValues[e]=n,this._optionValueSources[e]=r,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let n;return this._getCommandAndAncestors().forEach(r=>{r.getOptionValueSource(e)!==void 0&&(n=r.getOptionValueSource(e))}),n}_prepareUserArgs(e,n){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(n=n||{},e===void 0&&n.from===void 0){me.versions?.electron&&(n.from="electron");let s=me.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(n.from="eval")}e===void 0&&(e=me.argv),this.rawArgs=e.slice();let r;switch(n.from){case void 0:case"node":this._scriptPath=e[1],r=e.slice(2);break;case"electron":me.defaultApp?(this._scriptPath=e[1],r=e.slice(2)):r=e.slice(1);break;case"user":r=e.slice(0);break;case"eval":r=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${n.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",r}parse(e,n){let r=this._prepareUserArgs(e,n);return this._parseCommand([],r),this}async parseAsync(e,n){let r=this._prepareUserArgs(e,n);return await this._parseCommand([],r),this}_executeSubCommand(e,n){n=n.slice();let r=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function i(f,p){let b=It.resolve(f,p);if(Co.existsSync(b))return b;if(s.includes(It.extname(p)))return;let w=s.find(S=>Co.existsSync(`${b}${S}`));if(w)return`${b}${w}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,l=this._executableDir||"";if(this._scriptPath){let f;try{f=Co.realpathSync(this._scriptPath)}catch{f=this._scriptPath}l=It.resolve(It.dirname(f),l)}if(l){let f=i(l,o);if(!f&&!e._executableFile&&this._scriptPath){let p=It.basename(this._scriptPath,It.extname(this._scriptPath));p!==this._name&&(f=i(l,`${p}-${e._name}`))}o=f||o}r=s.includes(It.extname(o));let u;me.platform!=="win32"?r?(n.unshift(o),n=$l(me.execArgv).concat(n),u=xo.spawn(me.argv[0],n,{stdio:"inherit"})):u=xo.spawn(o,n,{stdio:"inherit"}):(n.unshift(o),n=$l(me.execArgv).concat(n),u=xo.spawn(me.execPath,n,{stdio:"inherit"})),u.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(p=>{me.on(p,()=>{u.killed===!1&&u.exitCode===null&&u.kill(p)})});let c=this._exitCallback;u.on("close",f=>{f=f??1,c?c(new Io(f,"commander.executeSubCommandAsync","(close)")):me.exit(f)}),u.on("error",f=>{if(f.code==="ENOENT"){let p=l?`searched for local subcommand relative to directory '${l}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",b=`'${o}' does not exist
|
|
15
15
|
- if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
16
16
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
17
17
|
- ${p}`;throw new Error(b)}else if(f.code==="EACCES")throw new Error(`'${o}' not executable`);if(!c)me.exit(1);else{let p=new Io(1,"commander.executeSubCommandAsync","(error)");p.nestedError=f,c(p)}}),this.runningCommand=u}_dispatchSubcommand(e,n,r){let s=this._findCommand(e);s||this.help({error:!0});let i;return i=this._chainOrCallSubCommandHook(i,s,"preSubcommand"),i=this._chainOrCall(i,()=>{if(s._executableHandler)this._executeSubCommand(s,n.concat(r));else return s._parseCommand(n,r)}),i}_dispatchHelpCommand(e){e||this.help();let n=this._findCommand(e);return n&&!n._executableHandler&&n.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,n)=>{e.required&&this.args[n]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(r,s,i)=>{let o=s;if(s!==null&&r.parseArg){let l=`error: command-argument value '${s}' is invalid for argument '${r.name()}'.`;o=this._callParseArg(r,s,i,l)}return o};this._checkNumberOfArguments();let n=[];this.registeredArguments.forEach((r,s)=>{let i=r.defaultValue;r.variadic?s<this.args.length?(i=this.args.slice(s),r.parseArg&&(i=i.reduce((o,l)=>e(r,l,o),r.defaultValue))):i===void 0&&(i=[]):s<this.args.length&&(i=this.args[s],r.parseArg&&(i=e(r,i,r.defaultValue))),n[s]=i}),this.processedArgs=n}_chainOrCall(e,n){return e&&e.then&&typeof e.then=="function"?e.then(()=>n()):n()}_chainOrCallHooks(e,n){let r=e,s=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[n]!==void 0).forEach(i=>{i._lifeCycleHooks[n].forEach(o=>{s.push({hookedCommand:i,callback:o})})}),n==="postAction"&&s.reverse(),s.forEach(i=>{r=this._chainOrCall(r,()=>i.callback(i.hookedCommand,this))}),r}_chainOrCallSubCommandHook(e,n,r){let s=e;return this._lifeCycleHooks[r]!==void 0&&this._lifeCycleHooks[r].forEach(i=>{s=this._chainOrCall(s,()=>i(this,n))}),s}_parseCommand(e,n){let r=this.parseOptions(n);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(r.operands),n=r.unknown,this.args=e.concat(n),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),n);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(n),this._dispatchSubcommand(this._defaultCommandName,e,n);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(r.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{r.unknown.length>0&&this.unknownOption(r.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){s(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(i,e,n)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(i))s(),this._processArguments(),this.parent.emit(i,e,n);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,n);this.listenerCount("command:*")?this.emit("command:*",e,n):this.commands.length?this.unknownCommand():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(n=>n._name===e||n._aliases.includes(e))}_findOption(e){return this.options.find(n=>n.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(n=>{n.mandatory&&e.getOptionValue(n.attributeName())===void 0&&e.missingMandatoryOptionValue(n)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(r=>{let s=r.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});e.filter(r=>r.conflictsWith.length>0).forEach(r=>{let s=e.find(i=>r.conflictsWith.includes(i.attributeName()));s&&this._conflictingOption(r,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let n=[],r=[],s=n,i=e.slice();function o(u){return u.length>1&&u[0]==="-"}let l=null;for(;i.length;){let u=i.shift();if(u==="--"){s===r&&s.push(u),s.push(...i);break}if(l&&!o(u)){this.emit(`option:${l.name()}`,u);continue}if(l=null,o(u)){let c=this._findOption(u);if(c){if(c.required){let f=i.shift();f===void 0&&this.optionMissingArgument(c),this.emit(`option:${c.name()}`,f)}else if(c.optional){let f=null;i.length>0&&!o(i[0])&&(f=i.shift()),this.emit(`option:${c.name()}`,f)}else this.emit(`option:${c.name()}`);l=c.variadic?c:null;continue}}if(u.length>2&&u[0]==="-"&&u[1]!=="-"){let c=this._findOption(`-${u[1]}`);if(c){c.required||c.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${c.name()}`,u.slice(2)):(this.emit(`option:${c.name()}`),i.unshift(`-${u.slice(2)}`));continue}}if(/^--[^=]+=/.test(u)){let c=u.indexOf("="),f=this._findOption(u.slice(0,c));if(f&&(f.required||f.optional)){this.emit(`option:${f.name()}`,u.slice(c+1));continue}}if(o(u)&&(s=r),(this._enablePositionalOptions||this._passThroughOptions)&&n.length===0&&r.length===0){if(this._findCommand(u)){n.push(u),i.length>0&&r.push(...i);break}else if(this._getHelpCommand()&&u===this._getHelpCommand().name()){n.push(u),i.length>0&&n.push(...i);break}else if(this._defaultCommandName){r.push(u),i.length>0&&r.push(...i);break}}if(this._passThroughOptions){s.push(u),i.length>0&&s.push(...i);break}s.push(u)}return{operands:n,unknown:r}}opts(){if(this._storeOptionsAsProperties){let e={},n=this.options.length;for(let r=0;r<n;r++){let s=this.options[r].attributeName();e[s]=s===this._versionOptionName?this._version:this[s]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,n)=>Object.assign(e,n.opts()),{})}error(e,n){this._outputConfiguration.outputError(`${e}
|
|
18
18
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
19
19
|
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
20
|
-
`),this.outputHelp({error:!0}));let r=n||{},s=r.exitCode||1,i=r.code||"commander.error";this._exit(s,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in me.env){let n=e.attributeName();(this.getOptionValue(n)===void 0||["default","config","env"].includes(this.getOptionValueSource(n)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,me.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Pf(this.options),n=r=>this.getOptionValue(r)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(r));this.options.filter(r=>r.implied!==void 0&&n(r.attributeName())&&e.valueFromOption(this.getOptionValue(r.attributeName()),r)).forEach(r=>{Object.keys(r.implied).filter(s=>!n(s)).forEach(s=>{this.setOptionValueWithSource(s,r.implied[s],"implied")})})}missingArgument(e){let n=`error: missing required argument '${e}'`;this.error(n,{code:"commander.missingArgument"})}optionMissingArgument(e){let n=`error: option '${e.flags}' argument missing`;this.error(n,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let n=`error: required option '${e.flags}' not specified`;this.error(n,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,n){let r=o=>{let l=o.attributeName(),u=this.getOptionValue(l),c=this.options.find(p=>p.negate&&l===p.attributeName()),f=this.options.find(p=>!p.negate&&l===p.attributeName());return c&&(c.presetArg===void 0&&u===!1||c.presetArg!==void 0&&u===c.presetArg)?c:f||o},s=o=>{let l=r(o),u=l.attributeName();return this.getOptionValueSource(u)==="env"?`environment variable '${l.envVar}'`:`option '${l.flags}'`},i=`error: ${s(e)} cannot be used with ${s(n)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let n="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],i=this;do{let o=i.createHelp().visibleOptions(i).filter(l=>l.long).map(l=>l.long);s=s.concat(o),i=i.parent}while(i&&!i._enablePositionalOptions);n=
|
|
21
|
-
`),this._exit(0,"commander.version",e)}),this}description(e,n){return e===void 0&&n===void 0?this._description:(this._description=e,n&&(this._argsDescription=n),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let n=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(n=this.commands[this.commands.length-1]),e===n._name)throw new Error("Command alias can't be the same as its name");let r=this.parent?._findCommand(e);if(r){let s=[r.name()].concat(r.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return n._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(n=>this.alias(n)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let n=this.registeredArguments.map(r=>
|
|
20
|
+
`),this.outputHelp({error:!0}));let r=n||{},s=r.exitCode||1,i=r.code||"commander.error";this._exit(s,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in me.env){let n=e.attributeName();(this.getOptionValue(n)===void 0||["default","config","env"].includes(this.getOptionValueSource(n)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,me.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Pf(this.options),n=r=>this.getOptionValue(r)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(r));this.options.filter(r=>r.implied!==void 0&&n(r.attributeName())&&e.valueFromOption(this.getOptionValue(r.attributeName()),r)).forEach(r=>{Object.keys(r.implied).filter(s=>!n(s)).forEach(s=>{this.setOptionValueWithSource(s,r.implied[s],"implied")})})}missingArgument(e){let n=`error: missing required argument '${e}'`;this.error(n,{code:"commander.missingArgument"})}optionMissingArgument(e){let n=`error: option '${e.flags}' argument missing`;this.error(n,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let n=`error: required option '${e.flags}' not specified`;this.error(n,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,n){let r=o=>{let l=o.attributeName(),u=this.getOptionValue(l),c=this.options.find(p=>p.negate&&l===p.attributeName()),f=this.options.find(p=>!p.negate&&l===p.attributeName());return c&&(c.presetArg===void 0&&u===!1||c.presetArg!==void 0&&u===c.presetArg)?c:f||o},s=o=>{let l=r(o),u=l.attributeName();return this.getOptionValueSource(u)==="env"?`environment variable '${l.envVar}'`:`option '${l.flags}'`},i=`error: ${s(e)} cannot be used with ${s(n)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let n="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],i=this;do{let o=i.createHelp().visibleOptions(i).filter(l=>l.long).map(l=>l.long);s=s.concat(o),i=i.parent}while(i&&!i._enablePositionalOptions);n=Al(e,s)}let r=`error: unknown option '${e}'${n}`;this.error(r,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let n=this.registeredArguments.length,r=n===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${n} argument${r} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],n="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(i=>{s.push(i.name()),i.alias()&&s.push(i.alias())}),n=Al(e,s)}let r=`error: unknown command '${e}'${n}`;this.error(r,{code:"commander.unknownCommand"})}version(e,n,r){if(e===void 0)return this._version;this._version=e,n=n||"-V, --version",r=r||"output the version number";let s=this.createOption(n,r);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
21
|
+
`),this._exit(0,"commander.version",e)}),this}description(e,n){return e===void 0&&n===void 0?this._description:(this._description=e,n&&(this._argsDescription=n),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let n=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(n=this.commands[this.commands.length-1]),e===n._name)throw new Error("Command alias can't be the same as its name");let r=this.parent?._findCommand(e);if(r){let s=[r.name()].concat(r.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return n._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(n=>this.alias(n)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let n=this.registeredArguments.map(r=>Af(r));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?n:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=It.basename(e,It.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let n=this.createHelp();return n.helpWidth===void 0&&(n.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),n.formatHelp(this,n)}_getHelpContext(e){e=e||{};let n={error:!!e.error},r;return n.error?r=s=>this._outputConfiguration.writeErr(s):r=s=>this._outputConfiguration.writeOut(s),n.write=e.write||r,n.command=this,n}outputHelp(e){let n;typeof e=="function"&&(n=e,e=void 0);let r=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",r)),this.emit("beforeHelp",r);let s=this.helpInformation(r);if(n&&(s=n(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");r.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",r),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",r))}helpOption(e,n){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",n=n??"display help for command",this._helpOption=this.createOption(e,n),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let n=me.exitCode||0;n===0&&e&&typeof e!="function"&&e.error&&(n=1),this._exit(n,"commander.help","(outputHelp)")}addHelpText(e,n){let r=["beforeAll","before","after","afterAll"];if(!r.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
22
22
|
Expecting one of '${r.join("', '")}'`);let s=`${e}Help`;return this.on(s,i=>{let o;typeof n=="function"?o=n({error:i.error,command:i.command}):o=n,o&&i.write(`${o}
|
|
23
|
-
`)}),this}_outputHelpIfRequested(e){let n=this._getHelpOption();n&&e.find(s=>n.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function $l(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let n,r="127.0.0.1",s="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?n=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(n=i[1],/^\d+$/.test(i[3])?s=i[3]:r=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(n=i[1],r=i[3],s=i[4]),n&&s!=="0"?`${n}=${r}:${parseInt(s)+1}`:e})}Pl.Command=Ro});var zl=re(Ve=>{var{Argument:Ol}=Ws(),{Command:Ao}=jl(),{CommanderError:jf,InvalidArgumentError:Nl}=ps(),{Help:Of}=wo(),{Option:Ml}=To();Ve.program=new Ao;Ve.createCommand=t=>new Ao(t);Ve.createOption=(t,e)=>new Ml(t,e);Ve.createArgument=(t,e)=>new Ol(t,e);Ve.Command=Ao;Ve.Option=Ml;Ve.Argument=Ol;Ve.Help=Of;Ve.CommanderError=jf;Ve.InvalidArgumentError=Nl;Ve.InvalidOptionArgumentError=Nl});var vs=re(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.getParsedType=le.ZodParsedType=le.objectUtil=le.util=void 0;var zo;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function n(s){throw new Error}t.assertNever=n,t.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},t.getValidEnumValues=s=>{let i=t.objectKeys(s).filter(l=>typeof s[s[l]]!="number"),o={};for(let l of i)o[l]=s[l];return t.objectValues(o)},t.objectValues=s=>t.objectKeys(s).map(function(i){return s[i]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},t.find=(s,i)=>{for(let o of s)if(i(o))return o},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(zo||(le.util=zo={}));var lu;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(lu||(le.objectUtil=lu={}));le.ZodParsedType=zo.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var Xp=t=>{switch(typeof t){case"undefined":return le.ZodParsedType.undefined;case"string":return le.ZodParsedType.string;case"number":return Number.isNaN(t)?le.ZodParsedType.nan:le.ZodParsedType.number;case"boolean":return le.ZodParsedType.boolean;case"function":return le.ZodParsedType.function;case"bigint":return le.ZodParsedType.bigint;case"symbol":return le.ZodParsedType.symbol;case"object":return Array.isArray(t)?le.ZodParsedType.array:t===null?le.ZodParsedType.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?le.ZodParsedType.promise:typeof Map<"u"&&t instanceof Map?le.ZodParsedType.map:typeof Set<"u"&&t instanceof Set?le.ZodParsedType.set:typeof Date<"u"&&t instanceof Date?le.ZodParsedType.date:le.ZodParsedType.object;default:return le.ZodParsedType.unknown}};le.getParsedType=Xp});var ui=re(en=>{"use strict";Object.defineProperty(en,"__esModule",{value:!0});en.ZodError=en.quotelessJson=en.ZodIssueCode=void 0;var uu=vs();en.ZodIssueCode=uu.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 Qp=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");en.quotelessJson=Qp;var ws=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(i){return i.message},r={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)r._errors.push(n(o));else{let l=r,u=0;for(;u<o.path.length;){let c=o.path[u];u===o.path.length-1?(l[c]=l[c]||{_errors:[]},l[c]._errors.push(n(o))):l[c]=l[c]||{_errors:[]},l=l[c],u++}}};return s(this),r}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,uu.util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];n[i]=n[i]||[],n[i].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};en.ZodError=ws;ws.create=t=>new ws(t)});var Lo=re(Do=>{"use strict";Object.defineProperty(Do,"__esModule",{value:!0});var Ae=ui(),Mn=vs(),em=(t,e)=>{let n;switch(t.code){case Ae.ZodIssueCode.invalid_type:t.received===Mn.ZodParsedType.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case Ae.ZodIssueCode.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,Mn.util.jsonStringifyReplacer)}`;break;case Ae.ZodIssueCode.unrecognized_keys:n=`Unrecognized key(s) in object: ${Mn.util.joinValues(t.keys,", ")}`;break;case Ae.ZodIssueCode.invalid_union:n="Invalid input";break;case Ae.ZodIssueCode.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Mn.util.joinValues(t.options)}`;break;case Ae.ZodIssueCode.invalid_enum_value:n=`Invalid enum value. Expected ${Mn.util.joinValues(t.options)}, received '${t.received}'`;break;case Ae.ZodIssueCode.invalid_arguments:n="Invalid function arguments";break;case Ae.ZodIssueCode.invalid_return_type:n="Invalid function return type";break;case Ae.ZodIssueCode.invalid_date:n="Invalid date";break;case Ae.ZodIssueCode.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:Mn.util.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case Ae.ZodIssueCode.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case Ae.ZodIssueCode.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case Ae.ZodIssueCode.custom:n="Invalid input";break;case Ae.ZodIssueCode.invalid_intersection_types:n="Intersection results could not be merged";break;case Ae.ZodIssueCode.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case Ae.ZodIssueCode.not_finite:n="Number must be finite";break;default:n=e.defaultError,Mn.util.assertNever(t)}return{message:n}};Do.default=em});var ci=re(tn=>{"use strict";var tm=tn&&tn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(tn,"__esModule",{value:!0});tn.defaultErrorMap=void 0;tn.setErrorMap=nm;tn.getErrorMap=rm;var cu=tm(Lo());tn.defaultErrorMap=cu.default;var du=cu.default;function nm(t){du=t}function rm(){return du}});var qo=re(oe=>{"use strict";var sm=oe&&oe.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(oe,"__esModule",{value:!0});oe.isAsync=oe.isValid=oe.isDirty=oe.isAborted=oe.OK=oe.DIRTY=oe.INVALID=oe.ParseStatus=oe.EMPTY_PATH=oe.makeIssue=void 0;oe.addIssueToContext=am;var im=ci(),hu=sm(Lo()),om=t=>{let{data:e,path:n,errorMaps:r,issueData:s}=t,i=[...n,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let l="",u=r.filter(c=>!!c).slice().reverse();for(let c of u)l=c(o,{data:e,defaultError:l}).message;return{...s,path:i,message:l}};oe.makeIssue=om;oe.EMPTY_PATH=[];function am(t,e){let n=(0,im.getErrorMap)(),r=(0,oe.makeIssue)({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===hu.default?void 0:hu.default].filter(s=>!!s)});t.common.issues.push(r)}var Uo=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let s of n){if(s.status==="aborted")return oe.INVALID;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let s of n){let i=await s.key,o=await s.value;r.push({key:i,value:o})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let s of n){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return oe.INVALID;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(r[i.value]=o.value)}return{status:e.value,value:r}}};oe.ParseStatus=Uo;oe.INVALID=Object.freeze({status:"aborted"});var lm=t=>({status:"dirty",value:t});oe.DIRTY=lm;var um=t=>({status:"valid",value:t});oe.OK=um;var cm=t=>t.status==="aborted";oe.isAborted=cm;var dm=t=>t.status==="dirty";oe.isDirty=dm;var hm=t=>t.status==="valid";oe.isValid=hm;var fm=t=>typeof Promise<"u"&&t instanceof Promise;oe.isAsync=fm});var pu=re(fu=>{"use strict";Object.defineProperty(fu,"__esModule",{value:!0})});var gu=re(di=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});di.errorUtil=void 0;var mu;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(mu||(di.errorUtil=mu={}))});var Ru=re(k=>{"use strict";Object.defineProperty(k,"__esModule",{value:!0});k.discriminatedUnion=k.date=k.boolean=k.bigint=k.array=k.any=k.coerce=k.ZodFirstPartyTypeKind=k.late=k.ZodSchema=k.Schema=k.ZodReadonly=k.ZodPipeline=k.ZodBranded=k.BRAND=k.ZodNaN=k.ZodCatch=k.ZodDefault=k.ZodNullable=k.ZodOptional=k.ZodTransformer=k.ZodEffects=k.ZodPromise=k.ZodNativeEnum=k.ZodEnum=k.ZodLiteral=k.ZodLazy=k.ZodFunction=k.ZodSet=k.ZodMap=k.ZodRecord=k.ZodTuple=k.ZodIntersection=k.ZodDiscriminatedUnion=k.ZodUnion=k.ZodObject=k.ZodArray=k.ZodVoid=k.ZodNever=k.ZodUnknown=k.ZodAny=k.ZodNull=k.ZodUndefined=k.ZodSymbol=k.ZodDate=k.ZodBoolean=k.ZodBigInt=k.ZodNumber=k.ZodString=k.ZodType=void 0;k.NEVER=k.void=k.unknown=k.union=k.undefined=k.tuple=k.transformer=k.symbol=k.string=k.strictObject=k.set=k.record=k.promise=k.preprocess=k.pipeline=k.ostring=k.optional=k.onumber=k.oboolean=k.object=k.number=k.nullable=k.null=k.never=k.nativeEnum=k.nan=k.map=k.literal=k.lazy=k.intersection=k.instanceof=k.function=k.enum=k.effect=void 0;k.datetimeRegex=_u;k.custom=Su;var A=ui(),hi=ci(),q=gu(),T=qo(),$=vs(),Qe=class{constructor(e,n,r,s){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},yu=(t,e)=>{if((0,T.isValid)(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new A.ZodError(t.common.issues);return this._error=n,this._error}}};function Y(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:s}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,l)=>{let{message:u}=t;return o.code==="invalid_enum_value"?{message:u??l.defaultError}:typeof l.data>"u"?{message:u??r??l.defaultError}:o.code!=="invalid_type"?{message:l.defaultError}:{message:u??n??l.defaultError}},description:s}}var X=class{get description(){return this._def.description}_getType(e){return(0,$.getParsedType)(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:(0,$.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new T.ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:(0,$.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if((0,T.isAsync)(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,$.getParsedType)(e)},s=this._parseSync({data:e,path:r.path,parent:r});return yu(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,$.getParsedType)(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return(0,T.isValid)(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>(0,T.isValid)(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,$.getParsedType)(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await((0,T.isAsync)(s)?s:Promise.resolve(s));return yu(r,i)}refine(e,n){let r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,i)=>{let o=e(s),l=()=>i.addIssue({code:A.ZodIssueCode.custom,...r(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(u=>u?!0:(l(),!1)):o?!0:(l(),!1)})}refinement(e,n){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(e){return new Fe({schema:this,typeName:G.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Xe.create(this,this._def)}nullable(){return bt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return zt.create(this)}promise(){return sn.create(this,this._def)}or(e){return Bn.create([this,e],this._def)}and(e){return Kn.create(this,e,this._def)}transform(e){return new Fe({...Y(this._def),schema:this,typeName:G.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new Wn({...Y(this._def),innerType:this,defaultValue:n,typeName:G.ZodDefault})}brand(){return new _s({typeName:G.ZodBranded,type:this,...Y(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Jn({...Y(this._def),innerType:this,catchValue:n,typeName:G.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return ks.create(this,e)}readonly(){return Yn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};k.ZodType=X;k.Schema=X;k.ZodSchema=X;var pm=/^c[^\s-]{8,}$/i,mm=/^[0-9a-z]+$/,gm=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ym=/^[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,bm=/^[a-z0-9_-]{21}$/i,vm=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,wm=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,_m=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,km="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Fo,Sm=/^(?:(?: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])$/,Tm=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,xm=/^(([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]))$/,Cm=/^(([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])$/,Im=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Rm=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,vu="((\\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])))",Am=new RegExp(`^${vu}$`);function wu(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function Em(t){return new RegExp(`^${wu(t)}$`)}function _u(t){let e=`${vu}T${wu(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function $m(t,e){return!!((e==="v4"||!e)&&Sm.test(t)||(e==="v6"||!e)&&xm.test(t))}function Pm(t,e){if(!vm.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function jm(t,e){return!!((e==="v4"||!e)&&Tm.test(t)||(e==="v6"||!e)&&Cm.test(t))}var nn=class t extends X{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==$.ZodParsedType.string){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.string,received:i.parsedType}),T.INVALID}let r=new T.ParseStatus,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:A.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:A.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,l=e.data.length<i.value;(o||l)&&(s=this._getOrReturnCtx(e,s),o?(0,T.addIssueToContext)(s,{code:A.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):l&&(0,T.addIssueToContext)(s,{code:A.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")_m.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"email",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Fo||(Fo=new RegExp(km,"u")),Fo.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"emoji",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")ym.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"uuid",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")bm.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"nanoid",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")pm.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"cuid",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")mm.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"cuid2",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")gm.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"ulid",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"url",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"regex",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:A.ZodIssueCode.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:A.ZodIssueCode.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:A.ZodIssueCode.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?_u(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:A.ZodIssueCode.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?Am.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:A.ZodIssueCode.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Em(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:A.ZodIssueCode.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?wm.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"duration",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?$m(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"ip",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?Pm(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"jwt",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?jm(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"cidr",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?Im.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"base64",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?Rm.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"base64url",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):$.util.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:A.ZodIssueCode.invalid_string,...q.errorUtil.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...q.errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...q.errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...q.errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...q.errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...q.errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...q.errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...q.errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...q.errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...q.errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...q.errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...q.errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...q.errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...q.errorUtil.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...q.errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...q.errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...q.errorUtil.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...q.errorUtil.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...q.errorUtil.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...q.errorUtil.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...q.errorUtil.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...q.errorUtil.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...q.errorUtil.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...q.errorUtil.errToObj(n)})}nonempty(e){return this.min(1,q.errorUtil.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};k.ZodString=nn;nn.create=t=>new nn({checks:[],typeName:G.ZodString,coerce:t?.coerce??!1,...Y(t)});function Om(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,i=Number.parseInt(t.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var zn=class t extends X{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)!==$.ZodParsedType.number){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.number,received:i.parsedType}),T.INVALID}let r,s=new T.ParseStatus;for(let i of this._def.checks)i.kind==="int"?$.util.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Om(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.not_finite,message:i.message}),s.dirty()):$.util.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,q.errorUtil.toString(n))}gt(e,n){return this.setLimit("min",e,!1,q.errorUtil.toString(n))}lte(e,n){return this.setLimit("max",e,!0,q.errorUtil.toString(n))}lt(e,n){return this.setLimit("max",e,!1,q.errorUtil.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:q.errorUtil.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:q.errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:q.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:q.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:q.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:q.errorUtil.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:q.errorUtil.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:q.errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:q.errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:q.errorUtil.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&$.util.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};k.ZodNumber=zn;zn.create=t=>new zn({checks:[],typeName:G.ZodNumber,coerce:t?.coerce||!1,...Y(t)});var Dn=class t extends X{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)!==$.ZodParsedType.bigint)return this._getInvalidInput(e);let r,s=new T.ParseStatus;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):$.util.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(n,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.bigint,received:n.parsedType}),T.INVALID}gte(e,n){return this.setLimit("min",e,!0,q.errorUtil.toString(n))}gt(e,n){return this.setLimit("min",e,!1,q.errorUtil.toString(n))}lte(e,n){return this.setLimit("max",e,!0,q.errorUtil.toString(n))}lt(e,n){return this.setLimit("max",e,!1,q.errorUtil.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:q.errorUtil.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:q.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:q.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:q.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:q.errorUtil.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:q.errorUtil.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};k.ZodBigInt=Dn;Dn.create=t=>new Dn({checks:[],typeName:G.ZodBigInt,coerce:t?.coerce??!1,...Y(t)});var Ln=class extends X{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==$.ZodParsedType.boolean){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.boolean,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};k.ZodBoolean=Ln;Ln.create=t=>new Ln({typeName:G.ZodBoolean,coerce:t?.coerce||!1,...Y(t)});var Un=class t extends X{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==$.ZodParsedType.date){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.date,received:i.parsedType}),T.INVALID}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:A.ZodIssueCode.invalid_date}),T.INVALID}let r=new T.ParseStatus,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:A.ZodIssueCode.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:A.ZodIssueCode.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):$.util.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:q.errorUtil.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:q.errorUtil.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};k.ZodDate=Un;Un.create=t=>new Un({checks:[],coerce:t?.coerce||!1,typeName:G.ZodDate,...Y(t)});var Lr=class extends X{_parse(e){if(this._getType(e)!==$.ZodParsedType.symbol){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.symbol,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};k.ZodSymbol=Lr;Lr.create=t=>new Lr({typeName:G.ZodSymbol,...Y(t)});var qn=class extends X{_parse(e){if(this._getType(e)!==$.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.undefined,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};k.ZodUndefined=qn;qn.create=t=>new qn({typeName:G.ZodUndefined,...Y(t)});var Fn=class extends X{_parse(e){if(this._getType(e)!==$.ZodParsedType.null){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.null,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};k.ZodNull=Fn;Fn.create=t=>new Fn({typeName:G.ZodNull,...Y(t)});var rn=class extends X{constructor(){super(...arguments),this._any=!0}_parse(e){return(0,T.OK)(e.data)}};k.ZodAny=rn;rn.create=t=>new rn({typeName:G.ZodAny,...Y(t)});var Mt=class extends X{constructor(){super(...arguments),this._unknown=!0}_parse(e){return(0,T.OK)(e.data)}};k.ZodUnknown=Mt;Mt.create=t=>new Mt({typeName:G.ZodUnknown,...Y(t)});var ot=class extends X{_parse(e){let n=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(n,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.never,received:n.parsedType}),T.INVALID}};k.ZodNever=ot;ot.create=t=>new ot({typeName:G.ZodNever,...Y(t)});var Ur=class extends X{_parse(e){if(this._getType(e)!==$.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.void,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};k.ZodVoid=Ur;Ur.create=t=>new Ur({typeName:G.ZodVoid,...Y(t)});var zt=class t extends X{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==$.ZodParsedType.array)return(0,T.addIssueToContext)(n,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.array,received:n.parsedType}),T.INVALID;if(s.exactLength!==null){let o=n.data.length>s.exactLength.value,l=n.data.length<s.exactLength.value;(o||l)&&((0,T.addIssueToContext)(n,{code:o?A.ZodIssueCode.too_big:A.ZodIssueCode.too_small,minimum:l?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&((0,T.addIssueToContext)(n,{code:A.ZodIssueCode.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&((0,T.addIssueToContext)(n,{code:A.ZodIssueCode.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((o,l)=>s.type._parseAsync(new Qe(n,o,n.path,l)))).then(o=>T.ParseStatus.mergeArray(r,o));let i=[...n.data].map((o,l)=>s.type._parseSync(new Qe(n,o,n.path,l)));return T.ParseStatus.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:q.errorUtil.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:q.errorUtil.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:q.errorUtil.toString(n)}})}nonempty(e){return this.min(1,e)}};k.ZodArray=zt;zt.create=(t,e)=>new zt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:G.ZodArray,...Y(e)});function Dr(t){if(t instanceof De){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=Xe.create(Dr(r))}return new De({...t._def,shape:()=>e})}else return t instanceof zt?new zt({...t._def,type:Dr(t.element)}):t instanceof Xe?Xe.create(Dr(t.unwrap())):t instanceof bt?bt.create(Dr(t.unwrap())):t instanceof yt?yt.create(t.items.map(e=>Dr(e))):t}var De=class t extends X{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),n=$.util.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==$.ZodParsedType.object){let c=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(c,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.object,received:c.parsedType}),T.INVALID}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),l=[];if(!(this._def.catchall instanceof ot&&this._def.unknownKeys==="strip"))for(let c in s.data)o.includes(c)||l.push(c);let u=[];for(let c of o){let f=i[c],p=s.data[c];u.push({key:{status:"valid",value:c},value:f._parse(new Qe(s,p,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof ot){let c=this._def.unknownKeys;if(c==="passthrough")for(let f of l)u.push({key:{status:"valid",value:f},value:{status:"valid",value:s.data[f]}});else if(c==="strict")l.length>0&&((0,T.addIssueToContext)(s,{code:A.ZodIssueCode.unrecognized_keys,keys:l}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let f of l){let p=s.data[f];u.push({key:{status:"valid",value:f},value:c._parse(new Qe(s,p,s.path,f)),alwaysSet:f in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let c=[];for(let f of u){let p=await f.key,b=await f.value;c.push({key:p,value:b,alwaysSet:f.alwaysSet})}return c}).then(c=>T.ParseStatus.mergeObjectSync(r,c)):T.ParseStatus.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(e){return q.errorUtil.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:q.errorUtil.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:G.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of $.util.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of $.util.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return Dr(this)}partial(e){let n={};for(let r of $.util.objectKeys(this.shape)){let s=this.shape[r];e&&!e[r]?n[r]=s:n[r]=s.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of $.util.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Xe;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return ku($.util.objectKeys(this.shape))}};k.ZodObject=De;De.create=(t,e)=>new De({shape:()=>t,unknownKeys:"strip",catchall:ot.create(),typeName:G.ZodObject,...Y(e)});De.strictCreate=(t,e)=>new De({shape:()=>t,unknownKeys:"strict",catchall:ot.create(),typeName:G.ZodObject,...Y(e)});De.lazycreate=(t,e)=>new De({shape:t,unknownKeys:"strip",catchall:ot.create(),typeName:G.ZodObject,...Y(e)});var Bn=class extends X{_parse(e){let{ctx:n}=this._processInputParams(e),r=this._def.options;function s(i){for(let l of i)if(l.result.status==="valid")return l.result;for(let l of i)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;let o=i.map(l=>new A.ZodError(l.ctx.common.issues));return(0,T.addIssueToContext)(n,{code:A.ZodIssueCode.invalid_union,unionErrors:o}),T.INVALID}if(n.common.async)return Promise.all(r.map(async i=>{let o={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let u of r){let c={...n,common:{...n.common,issues:[]},parent:null},f=u._parseSync({data:n.data,path:n.path,parent:c});if(f.status==="valid")return f;f.status==="dirty"&&!i&&(i={result:f,ctx:c}),c.common.issues.length&&o.push(c.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let l=o.map(u=>new A.ZodError(u));return(0,T.addIssueToContext)(n,{code:A.ZodIssueCode.invalid_union,unionErrors:l}),T.INVALID}}get options(){return this._def.options}};k.ZodUnion=Bn;Bn.create=(t,e)=>new Bn({options:t,typeName:G.ZodUnion,...Y(e)});var Nt=t=>t instanceof Hn?Nt(t.schema):t instanceof Fe?Nt(t.innerType()):t instanceof Zn?[t.value]:t instanceof Gn?t.options:t instanceof Vn?$.util.objectValues(t.enum):t instanceof Wn?Nt(t._def.innerType):t instanceof qn?[void 0]:t instanceof Fn?[null]:t instanceof Xe?[void 0,...Nt(t.unwrap())]:t instanceof bt?[null,...Nt(t.unwrap())]:t instanceof _s||t instanceof Yn?Nt(t.unwrap()):t instanceof Jn?Nt(t._def.innerType):[],fi=class t extends X{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==$.ZodParsedType.object)return(0,T.addIssueToContext)(n,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.object,received:n.parsedType}),T.INVALID;let r=this.discriminator,s=n.data[r],i=this.optionsMap.get(s);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):((0,T.addIssueToContext)(n,{code:A.ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),T.INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let s=new Map;for(let i of n){let o=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 l of o){if(s.has(l))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(l)}`);s.set(l,i)}}return new t({typeName:G.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...Y(r)})}};k.ZodDiscriminatedUnion=fi;function Bo(t,e){let n=(0,$.getParsedType)(t),r=(0,$.getParsedType)(e);if(t===e)return{valid:!0,data:t};if(n===$.ZodParsedType.object&&r===$.ZodParsedType.object){let s=$.util.objectKeys(e),i=$.util.objectKeys(t).filter(l=>s.indexOf(l)!==-1),o={...t,...e};for(let l of i){let u=Bo(t[l],e[l]);if(!u.valid)return{valid:!1};o[l]=u.data}return{valid:!0,data:o}}else if(n===$.ZodParsedType.array&&r===$.ZodParsedType.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<t.length;i++){let o=t[i],l=e[i],u=Bo(o,l);if(!u.valid)return{valid:!1};s.push(u.data)}return{valid:!0,data:s}}else return n===$.ZodParsedType.date&&r===$.ZodParsedType.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Kn=class extends X{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=(i,o)=>{if((0,T.isAborted)(i)||(0,T.isAborted)(o))return T.INVALID;let l=Bo(i.value,o.value);return l.valid?(((0,T.isDirty)(i)||(0,T.isDirty)(o))&&n.dirty(),{status:n.value,value:l.data}):((0,T.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_intersection_types}),T.INVALID)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};k.ZodIntersection=Kn;Kn.create=(t,e,n)=>new Kn({left:t,right:e,typeName:G.ZodIntersection,...Y(n)});var yt=class t extends X{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==$.ZodParsedType.array)return(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.array,received:r.parsedType}),T.INVALID;if(r.data.length<this._def.items.length)return(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),T.INVALID;!this._def.rest&&r.data.length>this._def.items.length&&((0,T.addIssueToContext)(r,{code:A.ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let i=[...r.data].map((o,l)=>{let u=this._def.items[l]||this._def.rest;return u?u._parse(new Qe(r,o,r.path,l)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>T.ParseStatus.mergeArray(n,o)):T.ParseStatus.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};k.ZodTuple=yt;yt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new yt({items:t,typeName:G.ZodTuple,rest:null,...Y(e)})};var pi=class t extends X{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==$.ZodParsedType.object)return(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.object,received:r.parsedType}),T.INVALID;let s=[],i=this._def.keyType,o=this._def.valueType;for(let l in r.data)s.push({key:i._parse(new Qe(r,l,r.path,l)),value:o._parse(new Qe(r,r.data[l],r.path,l)),alwaysSet:l in r.data});return r.common.async?T.ParseStatus.mergeObjectAsync(n,s):T.ParseStatus.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof X?new t({keyType:e,valueType:n,typeName:G.ZodRecord,...Y(r)}):new t({keyType:nn.create(),valueType:e,typeName:G.ZodRecord,...Y(n)})}};k.ZodRecord=pi;var qr=class extends X{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==$.ZodParsedType.map)return(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.map,received:r.parsedType}),T.INVALID;let s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([l,u],c)=>({key:s._parse(new Qe(r,l,r.path,[c,"key"])),value:i._parse(new Qe(r,u,r.path,[c,"value"]))}));if(r.common.async){let l=new Map;return Promise.resolve().then(async()=>{for(let u of o){let c=await u.key,f=await u.value;if(c.status==="aborted"||f.status==="aborted")return T.INVALID;(c.status==="dirty"||f.status==="dirty")&&n.dirty(),l.set(c.value,f.value)}return{status:n.value,value:l}})}else{let l=new Map;for(let u of o){let c=u.key,f=u.value;if(c.status==="aborted"||f.status==="aborted")return T.INVALID;(c.status==="dirty"||f.status==="dirty")&&n.dirty(),l.set(c.value,f.value)}return{status:n.value,value:l}}}};k.ZodMap=qr;qr.create=(t,e,n)=>new qr({valueType:e,keyType:t,typeName:G.ZodMap,...Y(n)});var Fr=class t extends X{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==$.ZodParsedType.set)return(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.set,received:r.parsedType}),T.INVALID;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&((0,T.addIssueToContext)(r,{code:A.ZodIssueCode.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&((0,T.addIssueToContext)(r,{code:A.ZodIssueCode.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let i=this._def.valueType;function o(u){let c=new Set;for(let f of u){if(f.status==="aborted")return T.INVALID;f.status==="dirty"&&n.dirty(),c.add(f.value)}return{status:n.value,value:c}}let l=[...r.data.values()].map((u,c)=>i._parse(new Qe(r,u,r.path,c)));return r.common.async?Promise.all(l).then(u=>o(u)):o(l)}min(e,n){return new t({...this._def,minSize:{value:e,message:q.errorUtil.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:q.errorUtil.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};k.ZodSet=Fr;Fr.create=(t,e)=>new Fr({valueType:t,minSize:null,maxSize:null,typeName:G.ZodSet,...Y(e)});var mi=class t extends X{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==$.ZodParsedType.function)return(0,T.addIssueToContext)(n,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.function,received:n.parsedType}),T.INVALID;function r(l,u){return(0,T.makeIssue)({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,(0,hi.getErrorMap)(),hi.defaultErrorMap].filter(c=>!!c),issueData:{code:A.ZodIssueCode.invalid_arguments,argumentsError:u}})}function s(l,u){return(0,T.makeIssue)({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,(0,hi.getErrorMap)(),hi.defaultErrorMap].filter(c=>!!c),issueData:{code:A.ZodIssueCode.invalid_return_type,returnTypeError:u}})}let i={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof sn){let l=this;return(0,T.OK)(async function(...u){let c=new A.ZodError([]),f=await l._def.args.parseAsync(u,i).catch(w=>{throw c.addIssue(r(u,w)),c}),p=await Reflect.apply(o,this,f);return await l._def.returns._def.type.parseAsync(p,i).catch(w=>{throw c.addIssue(s(p,w)),c})})}else{let l=this;return(0,T.OK)(function(...u){let c=l._def.args.safeParse(u,i);if(!c.success)throw new A.ZodError([r(u,c.error)]);let f=Reflect.apply(o,this,c.data),p=l._def.returns.safeParse(f,i);if(!p.success)throw new A.ZodError([s(f,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:yt.create(e).rest(Mt.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new t({args:e||yt.create([]).rest(Mt.create()),returns:n||Mt.create(),typeName:G.ZodFunction,...Y(r)})}};k.ZodFunction=mi;var Hn=class extends X{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};k.ZodLazy=Hn;Hn.create=(t,e)=>new Hn({getter:t,typeName:G.ZodLazy,...Y(e)});var Zn=class extends X{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(n,{received:n.data,code:A.ZodIssueCode.invalid_literal,expected:this._def.value}),T.INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}};k.ZodLiteral=Zn;Zn.create=(t,e)=>new Zn({value:t,typeName:G.ZodLiteral,...Y(e)});function ku(t,e){return new Gn({values:t,typeName:G.ZodEnum,...Y(e)})}var Gn=class t extends X{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return(0,T.addIssueToContext)(n,{expected:$.util.joinValues(r),received:n.parsedType,code:A.ZodIssueCode.invalid_type}),T.INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return(0,T.addIssueToContext)(n,{received:n.data,code:A.ZodIssueCode.invalid_enum_value,options:r}),T.INVALID}return(0,T.OK)(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};k.ZodEnum=Gn;Gn.create=ku;var Vn=class extends X{_parse(e){let n=$.util.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==$.ZodParsedType.string&&r.parsedType!==$.ZodParsedType.number){let s=$.util.objectValues(n);return(0,T.addIssueToContext)(r,{expected:$.util.joinValues(s),received:r.parsedType,code:A.ZodIssueCode.invalid_type}),T.INVALID}if(this._cache||(this._cache=new Set($.util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=$.util.objectValues(n);return(0,T.addIssueToContext)(r,{received:r.data,code:A.ZodIssueCode.invalid_enum_value,options:s}),T.INVALID}return(0,T.OK)(e.data)}get enum(){return this._def.values}};k.ZodNativeEnum=Vn;Vn.create=(t,e)=>new Vn({values:t,typeName:G.ZodNativeEnum,...Y(e)});var sn=class extends X{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==$.ZodParsedType.promise&&n.common.async===!1)return(0,T.addIssueToContext)(n,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.promise,received:n.parsedType}),T.INVALID;let r=n.parsedType===$.ZodParsedType.promise?n.data:Promise.resolve(n.data);return(0,T.OK)(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};k.ZodPromise=sn;sn.create=(t,e)=>new sn({type:t,typeName:G.ZodPromise,...Y(e)});var Fe=class extends X{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===G.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{(0,T.addIssueToContext)(r,o),o.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(r.data,i);if(r.common.async)return Promise.resolve(o).then(async l=>{if(n.value==="aborted")return T.INVALID;let u=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return u.status==="aborted"?T.INVALID:u.status==="dirty"||n.value==="dirty"?(0,T.DIRTY)(u.value):u});{if(n.value==="aborted")return T.INVALID;let l=this._def.schema._parseSync({data:o,path:r.path,parent:r});return l.status==="aborted"?T.INVALID:l.status==="dirty"||n.value==="dirty"?(0,T.DIRTY)(l.value):l}}if(s.type==="refinement"){let o=l=>{let u=s.refinement(l,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){let l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?T.INVALID:(l.status==="dirty"&&n.dirty(),o(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?T.INVALID:(l.status==="dirty"&&n.dirty(),o(l.value).then(()=>({status:n.value,value:l.value}))))}if(s.type==="transform")if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!(0,T.isValid)(o))return T.INVALID;let l=s.transform(o.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>(0,T.isValid)(o)?Promise.resolve(s.transform(o.value,i)).then(l=>({status:n.value,value:l})):T.INVALID);$.util.assertNever(s)}};k.ZodEffects=Fe;k.ZodTransformer=Fe;Fe.create=(t,e,n)=>new Fe({schema:t,typeName:G.ZodEffects,effect:e,...Y(n)});Fe.createWithPreprocess=(t,e,n)=>new Fe({schema:e,effect:{type:"preprocess",transform:t},typeName:G.ZodEffects,...Y(n)});var Xe=class extends X{_parse(e){return this._getType(e)===$.ZodParsedType.undefined?(0,T.OK)(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};k.ZodOptional=Xe;Xe.create=(t,e)=>new Xe({innerType:t,typeName:G.ZodOptional,...Y(e)});var bt=class extends X{_parse(e){return this._getType(e)===$.ZodParsedType.null?(0,T.OK)(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};k.ZodNullable=bt;bt.create=(t,e)=>new bt({innerType:t,typeName:G.ZodNullable,...Y(e)});var Wn=class extends X{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===$.ZodParsedType.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};k.ZodDefault=Wn;Wn.create=(t,e)=>new Wn({innerType:t,typeName:G.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Y(e)});var Jn=class extends X{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return(0,T.isAsync)(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new A.ZodError(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new A.ZodError(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};k.ZodCatch=Jn;Jn.create=(t,e)=>new Jn({innerType:t,typeName:G.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Y(e)});var Br=class extends X{_parse(e){if(this._getType(e)!==$.ZodParsedType.nan){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.nan,received:r.parsedType}),T.INVALID}return{status:"valid",value:e.data}}};k.ZodNaN=Br;Br.create=t=>new Br({typeName:G.ZodNaN,...Y(t)});k.BRAND=Symbol("zod_brand");var _s=class extends X{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}};k.ZodBranded=_s;var ks=class t extends X{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?T.INVALID:i.status==="dirty"?(n.dirty(),(0,T.DIRTY)(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?T.INVALID:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:G.ZodPipeline})}};k.ZodPipeline=ks;var Yn=class extends X{_parse(e){let n=this._def.innerType._parse(e),r=s=>((0,T.isValid)(s)&&(s.value=Object.freeze(s.value)),s);return(0,T.isAsync)(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};k.ZodReadonly=Yn;Yn.create=(t,e)=>new Yn({innerType:t,typeName:G.ZodReadonly,...Y(e)});function bu(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function Su(t,e={},n){return t?rn.create().superRefine((r,s)=>{let i=t(r);if(i instanceof Promise)return i.then(o=>{if(!o){let l=bu(e,r),u=l.fatal??n??!0;s.addIssue({code:"custom",...l,fatal:u})}});if(!i){let o=bu(e,r),l=o.fatal??n??!0;s.addIssue({code:"custom",...o,fatal:l})}}):rn.create()}k.late={object:De.lazycreate};var G;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(G||(k.ZodFirstPartyTypeKind=G={}));var Nm=(t,e={message:`Input not instance of ${t.name}`})=>Su(n=>n instanceof t,e);k.instanceof=Nm;var Tu=nn.create;k.string=Tu;var xu=zn.create;k.number=xu;var Mm=Br.create;k.nan=Mm;var zm=Dn.create;k.bigint=zm;var Cu=Ln.create;k.boolean=Cu;var Dm=Un.create;k.date=Dm;var Lm=Lr.create;k.symbol=Lm;var Um=qn.create;k.undefined=Um;var qm=Fn.create;k.null=qm;var Fm=rn.create;k.any=Fm;var Bm=Mt.create;k.unknown=Bm;var Km=ot.create;k.never=Km;var Hm=Ur.create;k.void=Hm;var Zm=zt.create;k.array=Zm;var Gm=De.create;k.object=Gm;var Vm=De.strictCreate;k.strictObject=Vm;var Wm=Bn.create;k.union=Wm;var Jm=fi.create;k.discriminatedUnion=Jm;var Ym=Kn.create;k.intersection=Ym;var Xm=yt.create;k.tuple=Xm;var Qm=pi.create;k.record=Qm;var eg=qr.create;k.map=eg;var tg=Fr.create;k.set=tg;var ng=mi.create;k.function=ng;var rg=Hn.create;k.lazy=rg;var sg=Zn.create;k.literal=sg;var ig=Gn.create;k.enum=ig;var og=Vn.create;k.nativeEnum=og;var ag=sn.create;k.promise=ag;var Iu=Fe.create;k.effect=Iu;k.transformer=Iu;var lg=Xe.create;k.optional=lg;var ug=bt.create;k.nullable=ug;var cg=Fe.createWithPreprocess;k.preprocess=cg;var dg=ks.create;k.pipeline=dg;var hg=()=>Tu().optional();k.ostring=hg;var fg=()=>xu().optional();k.onumber=fg;var pg=()=>Cu().optional();k.oboolean=pg;k.coerce={string:(t=>nn.create({...t,coerce:!0})),number:(t=>zn.create({...t,coerce:!0})),boolean:(t=>Ln.create({...t,coerce:!0})),bigint:(t=>Dn.create({...t,coerce:!0})),date:(t=>Un.create({...t,coerce:!0}))};k.NEVER=T.INVALID});var Ko=re(et=>{"use strict";var mg=et&&et.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Kr=et&&et.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&mg(e,t,n)};Object.defineProperty(et,"__esModule",{value:!0});Kr(ci(),et);Kr(qo(),et);Kr(pu(),et);Kr(vs(),et);Kr(Ru(),et);Kr(ui(),et)});var $u=re(Le=>{"use strict";var Au=Le&&Le.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),gg=Le&&Le.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),yg=Le&&Le.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&Au(e,t,n);return gg(e,t),e},bg=Le&&Le.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Au(e,t,n)};Object.defineProperty(Le,"__esModule",{value:!0});Le.z=void 0;var Eu=yg(Ko());Le.z=Eu;bg(Ko(),Le);Le.default=Eu});var _e=re(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.ChatLoadResultMsg=h.REPLY_STYLES=h.BUILTIN_REPLY_LANGUAGES=h.ChatLoadMsg=h.ChatListResultMsg=h.ChatListMsg=h.ChatUsageMsg=h.ChatStreamMsg=h.JiraUsersResultMsg=h.DeployClaimResultMsg=h.DeployClaimMsg=h.RuleDiagnoseResultMsg=h.ProjectTestResultMsg=h.RunStatusMsg=h.FailedTest=h.RunUsageMsg=h.RunLogMsg=h.RunClaimMsg=h.HeartbeatMsg=h.HelloMsg=h.RuleConfig=h.ProjectConfig=h.ActionConfig=h.DeployAction=h.EnvironmentConfig=h.PromotionMode=h.DeployStep=h.RespondAction=h.ImplementAction=h.PlanOnlyAction=h.TriggerConfig=h.StatusChangedTrigger=h.CommentKeywordTrigger=h.LabelAddedTrigger=h.ActionType=h.TriggerType=h.ACTIVE_RUN_STATUSES=h.RunStatus=h.needsInputMarkerIn=h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=h.NEEDS_INPUT_COMMENT_MARKER=h.NEEDS_INPUT_LABEL=h.NEEDS_INPUT_ASK_FENCE=h.NEEDS_INPUT_MARKER=h.BRANCH_DEPLOY_ISSUE_KEY=h.REQUIRED_AGENT_CAPABILITIES=h.DEFAULT_AGENT_ID=h.REGISTERED_AGENTS=h.PROTOCOL_VERSION=h.GITHUB_TOKEN_PERMISSIONS=void 0;h.SetupStatusResultMsg=h.SetupStatusMsg=h.DeploySuggestResultMsg=h.SelfMigrationApplyResultMsg=h.SelfMigrationApplyMsg=h.SELF_MIGRATION_DIR=h.EnvPreflightResultMsg=h.EnvPreflightMsg=h.ChatCreateTicketResultMsg=h.ChatCreateTicketMsg=h.ChatTurnResultMsg=h.ChatTurnMsg=h.ChatFile=h.TeamCredsResultMsg=h.TeamCredsMsg=h.KnowledgeSaveResultMsg=h.KnowledgeSaveMsg=h.KnowledgeListResultMsg=h.KnowledgeFile=h.KnowledgeListMsg=h.AuditReviewResultMsg=h.AuditReviewMsg=h.AuditGetResultMsg=h.AuditGetMsg=h.AuditListResultMsg=h.AuditStatsResultMsg=h.AuditStatsMsg=h.AuditListMsg=h.AuditStartResultMsg=h.AuditStartMsg=h.AuditRecord=h.AuditFinding=h.AuditDetailLevel=h.AuditScope=h.AuditSeverity=h.KnowledgeRole=h.AuditRole=h.EpicSuggestResultMsg=h.EpicSuggestMsg=h.EpicListResultMsg=h.EpicChild=h.EpicListMsg=h.BoardTriggerResultMsg=h.BoardTriggerMsg=h.BoardFetchResultMsg=h.BoardFetchMsg=h.RepoDocReadResultMsg=h.RepoDocReadMsg=h.RepoDocsResultMsg=h.RepoDocsMsg=void 0;h.DEFAULT_DEPLOY_SUGGEST_PROMPT_TEMPLATE=h.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE=h.DEPLOY_FIX_PROMPT_TEMPLATE=h.PROMPT_PRESETS=h.DEFAULT_RESPOND_PROMPT_TEMPLATE=h.BUGFIX_IMPLEMENT_PROMPT_TEMPLATE=h.BUG_INVESTIGATION_PROMPT_TEMPLATE=h.TECHNICAL_PLAN_PROMPT_TEMPLATE=h.MEMORY_UPDATE_PROMPT=h.DEFAULT_IMPLEMENT_PROMPT_TEMPLATE=h.WRITE_TESTS_PROMPT=h.NEEDS_INPUT_OPTIONS_PROMPT=h.DEFAULT_PLAN_PROMPT_TEMPLATE=h.EnrollResponse=h.EnrollRequest=h.ServerToRunnerMsg=h.JiraUsersMsg=h.DeploySuggestMsg=h.DeployFixMsg=h.DeployStartMsg=h.RunRetryPushMsg=h.RunRejectedMsg=h.RunApprovedMsg=h.RunCancelMsg=h.RuleDiagnoseMsg=h.ProjectTestMsg=h.RunClaimResultMsg=h.ConfigMsg=h.HelloAckMsg=h.RunnerToServerMsg=h.AutopilotReportMsg=h.AutopilotNextResultMsg=h.AutopilotNextMsg=h.RunnerUpdateResultMsg=h.AgentProfilesResultMsg=h.AgentProfilesMsg=h.RunPrConflictMsg=h.RunResolveConflictResultMsg=h.RunAnswerResultMsg=h.RunAnswerMsg=h.RunTestFixResultMsg=h.RunTestFixMsg=h.RunResolveConflictMsg=h.RunnerUpdateMsg=h.RepoDocSaveResultMsg=h.RepoDocSaveMsg=h.SetupClaudeMdSaveResultMsg=h.SetupClaudeMdSaveMsg=h.SetupClaudeMdGenerateResultMsg=h.SetupClaudeMdGenerateMsg=void 0;h.missingAgentCapabilities=vg;h.replyPreferenceAppendix=_g;h.pendingMigrationsAppendix=kg;h.isSelfMigrationFilename=Sg;h.parseRunnerMsg=Tg;h.parseServerMsg=xg;var a=$u();h.GITHUB_TOKEN_PERMISSIONS={where:"github.com/settings/personal-access-tokens/new (fine-grained token)",steps:["Resource owner: the org or user that OWNS the repo - not your personal account, unless the repo is under it","Repository access: Only select repositories -> pick this repo","Contents: Read and write - pushing the agent's branch","Pull requests: Read and write - opening the PR, and merging it when you approve","Metadata: Read-only - GitHub adds this itself and will not let you remove it","Workflows: Read and write - ONLY if changes may touch .github/workflows; without it GitHub rejects those pushes"],note:"A fine-grained token covers exactly ONE resource owner, so a repo in a different org always needs its own token. A classic token with the `repo` scope also works and is simpler, but it reaches every repository you can see - prefer fine-grained."};h.PROTOCOL_VERSION="1.50";h.REGISTERED_AGENTS=[{id:"claude-code",displayName:"Claude Code",capabilities:{readOnlyJail:!0,editNoShellJail:!0,sessionResume:!0,costReporting:!0,modelSelection:!0,loginProfiles:!0},suggestedModels:["claude-fable-5","claude-opus-5","claude-sonnet-5","claude-haiku-4-5-20251001"],experimental:!1},{id:"codex",displayName:"OpenAI Codex CLI (experimental)",capabilities:{readOnlyJail:!0,editNoShellJail:!1,sessionResume:!1,costReporting:!1,modelSelection:!0,loginProfiles:!1},suggestedModels:[],experimental:!0}];h.DEFAULT_AGENT_ID="claude-code";h.REQUIRED_AGENT_CAPABILITIES={plan_only:["readOnlyJail","sessionResume"],respond:["readOnlyJail"],implement:["editNoShellJail","sessionResume"],deploy:[],chat:["readOnlyJail","sessionResume"],assist:["readOnlyJail"]};function vg(t,e){let n=h.REGISTERED_AGENTS.find(r=>r.id===t);return n?(h.REQUIRED_AGENT_CAPABILITIES[e]??[]).filter(r=>!n.capabilities[r]):null}h.BRANCH_DEPLOY_ISSUE_KEY="(branch deploy)";h.NEEDS_INPUT_MARKER="NEEDS-INPUT";h.NEEDS_INPUT_ASK_FENCE="ask";h.NEEDS_INPUT_LABEL="agent-needs-input";h.NEEDS_INPUT_COMMENT_MARKER="Allwright needs your input";h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=["TicketPilot needs your input"];var wg=t=>t.includes(h.NEEDS_INPUT_COMMENT_MARKER)||h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS.some(e=>t.includes(e));h.needsInputMarkerIn=wg;h.RunStatus=a.z.enum(["queued","running","posting","awaiting_approval","needs_input","succeeded","failed","timed_out"]);h.ACTIVE_RUN_STATUSES=["queued","running","posting","awaiting_approval"];h.TriggerType=a.z.enum(["label_added","comment_keyword","status_changed"]);h.ActionType=a.z.enum(["plan_only","implement","respond","deploy"]);h.LabelAddedTrigger=a.z.object({type:a.z.literal("label_added"),label:a.z.string().min(1),doneLabel:a.z.string().min(1).default("agent-planned"),failedLabel:a.z.string().min(1).default("agent-failed")});h.CommentKeywordTrigger=a.z.object({type:a.z.literal("comment_keyword"),keyword:a.z.string().min(1),doneLabel:a.z.string().min(1).default("agent-implemented"),failedLabel:a.z.string().min(1).default("agent-failed")});h.StatusChangedTrigger=a.z.object({type:a.z.literal("status_changed"),status:a.z.string().min(1),doneLabel:a.z.string().min(1).default("agent-deployed"),failedLabel:a.z.string().min(1).default("agent-failed")});h.TriggerConfig=a.z.discriminatedUnion("type",[h.LabelAddedTrigger,h.CommentKeywordTrigger,h.StatusChangedTrigger]);h.PlanOnlyAction=a.z.object({type:a.z.literal("plan_only"),promptTemplate:a.z.string().min(1),timeoutSeconds:a.z.number().int().positive().max(3600).default(900),agent:a.z.string().default(h.DEFAULT_AGENT_ID),model:a.z.string().default("")});h.ImplementAction=a.z.object({type:a.z.literal("implement"),promptTemplate:a.z.string().min(1),timeoutSeconds:a.z.number().int().positive().max(7200).default(1800),maxTurns:a.z.number().int().positive().max(500).default(120),requireApproval:a.z.boolean().default(!0),branchTemplate:a.z.string().min(1).default("agent/{{issueKey}}").refine(t=>t.includes("{{issueKey}}"),{message:"branchTemplate must contain {{issueKey}}"}),baseBranch:a.z.string().min(1).default("main"),jiraTransition:a.z.string().optional(),jiraTransitionOnStart:a.z.string().optional(),jiraTransitionOnMerge:a.z.string().optional(),agent:a.z.string().default(h.DEFAULT_AGENT_ID),model:a.z.string().default(""),updateMemory:a.z.boolean().default(!1),writeTests:a.z.boolean().default(!0),runTests:a.z.boolean().default(!0),mergeOnApprove:a.z.boolean().default(!0),mergeMethod:a.z.enum(["squash","merge","rebase"]).default("squash"),autoMerge:a.z.boolean().default(!0)});h.RespondAction=a.z.object({type:a.z.literal("respond"),promptTemplate:a.z.string().min(1),timeoutSeconds:a.z.number().int().positive().max(3600).default(600),agent:a.z.string().default(h.DEFAULT_AGENT_ID),model:a.z.string().default("")});h.DeployStep=a.z.object({name:a.z.string().min(1).max(120),run:a.z.string().min(1).max(4e3),continueOnError:a.z.boolean().default(!1)});h.PromotionMode=a.z.enum(["deploy_only","merge_and_deploy"]);h.EnvironmentConfig=a.z.object({id:a.z.string(),projectId:a.z.string(),name:a.z.string(),rank:a.z.number().int().nonnegative(),auditBeforeDeploy:a.z.enum(["","security","testing"]).default(""),branch:a.z.string().default(""),publicUrl:a.z.string().default(""),useDedicatedCheckout:a.z.boolean().default(!1),promotionMode:h.PromotionMode.default("deploy_only"),ticketBranchTemplate:a.z.string().default("agent/{{issueKey}}"),steps:a.z.array(h.DeployStep).default([]),workdir:a.z.string().default(""),timeoutSeconds:a.z.number().int().positive().max(21600).default(1800),requiredSecrets:a.z.array(a.z.string()).default([]),requireApproval:a.z.boolean().default(!1),requireSyncCheck:a.z.boolean().default(!1),previousEnvBranch:a.z.string().optional(),deployFromColumn:a.z.string().default(""),deployToColumn:a.z.string().default("")});h.DeployAction=a.z.object({type:a.z.literal("deploy"),envSelection:a.z.enum(["fixed","from_comment"]).default("from_comment"),environmentId:a.z.string().optional(),requireStatus:a.z.string().optional()});h.ActionConfig=a.z.discriminatedUnion("type",[h.PlanOnlyAction,h.ImplementAction,h.RespondAction,h.DeployAction]);h.ProjectConfig=a.z.object({id:a.z.string(),name:a.z.string(),jiraProjectKey:a.z.string(),goLiveIssueKey:a.z.string().default(""),repoName:a.z.string(),jiraSiteUrl:a.z.string().default(""),defaultAgent:a.z.string().default("claude-code"),componentRoutes:a.z.array(a.z.object({component:a.z.string().min(1),repoName:a.z.string().min(1)})).default([])});h.RuleConfig=a.z.object({id:a.z.string(),projectId:a.z.string(),name:a.z.string(),enabled:a.z.boolean(),trigger:h.TriggerConfig,action:h.ActionConfig});h.HelloMsg=a.z.object({type:a.z.literal("hello"),protocolVersion:a.z.string(),runnerVersion:a.z.string(),platform:a.z.string(),justBooted:a.z.boolean().optional()});h.HeartbeatMsg=a.z.object({type:a.z.literal("heartbeat"),ts:a.z.string()});h.RunClaimMsg=a.z.object({type:a.z.literal("run.claim"),requestId:a.z.string(),ruleId:a.z.string(),issueKey:a.z.string(),issueSummary:a.z.string().default(""),triggerFingerprint:a.z.string(),dedupKey:a.z.string().optional(),triggeredByAccountId:a.z.string().optional()});h.RunLogMsg=a.z.object({type:a.z.literal("run.log"),runId:a.z.string(),seq:a.z.number().int().nonnegative(),ts:a.z.string(),level:a.z.enum(["info","warn","error","agent"]),message:a.z.string().max(16384)});h.RunUsageMsg=a.z.object({type:a.z.literal("run.usage"),runId:a.z.string(),inputTokens:a.z.number().int().nonnegative(),outputTokens:a.z.number().int().nonnegative(),cacheReadTokens:a.z.number().int().nonnegative().optional(),costUsd:a.z.number().nonnegative().optional(),turns:a.z.number().int().nonnegative().optional()});h.FailedTest=a.z.object({command:a.z.string().max(500),exitCode:a.z.number().int(),tail:a.z.string().max(4e3)});h.RunStatusMsg=a.z.object({type:a.z.literal("run.status"),runId:a.z.string(),status:h.RunStatus,error:a.z.string().optional(),errorKind:a.z.enum(["guard"]).optional(),costUsd:a.z.number().nonnegative().optional(),inputTokens:a.z.number().int().nonnegative().optional(),outputTokens:a.z.number().int().nonnegative().optional(),resultSummary:a.z.string().max(2e3).optional(),billingMode:a.z.enum(["subscription","api","unknown"]).optional(),model:a.z.string().max(200).optional(),prUrl:a.z.string().optional(),headSha:a.z.string().optional(),deployedRef:a.z.string().optional(),retryAvailable:a.z.boolean().optional(),failedTests:a.z.array(h.FailedTest).max(20).optional(),testsPassed:a.z.number().int().nonnegative().optional(),testsTotal:a.z.number().int().nonnegative().optional(),manualSteps:a.z.array(a.z.object({command:a.z.string().max(500),why:a.z.string().max(300).default("")})).max(20).optional(),goLiveDraft:a.z.string().max(4e3).optional(),inputQuestions:a.z.string().max(4e3).optional(),inputOptions:a.z.array(a.z.string().max(200)).max(5).optional()});h.ProjectTestResultMsg=a.z.object({type:a.z.literal("project.test.result"),requestId:a.z.string(),ok:a.z.boolean(),checks:a.z.array(a.z.object({name:a.z.string(),ok:a.z.boolean(),detail:a.z.string(),kind:a.z.enum(["connection","content"]).default("connection"),fix:a.z.array(a.z.string()).default([]),fixNote:a.z.string().default("")}))});h.RuleDiagnoseResultMsg=a.z.object({type:a.z.literal("rule.diagnose.result"),requestId:a.z.string(),checks:a.z.array(a.z.object({name:a.z.string(),ok:a.z.boolean(),detail:a.z.string(),kind:a.z.enum(["connection","content"]).default("connection"),fix:a.z.array(a.z.string()).default([]),fixNote:a.z.string().default("")})),matchedCount:a.z.number().int().nonnegative(),excludedCount:a.z.number().int().nonnegative(),excludedSample:a.z.array(a.z.string()).max(5)});h.DeployClaimMsg=a.z.object({type:a.z.literal("deploy.claim"),requestId:a.z.string(),projectId:a.z.string(),ruleId:a.z.string(),issueKey:a.z.string(),issueSummary:a.z.string().default(""),environmentName:a.z.string(),requestedByAccountId:a.z.string().optional(),requestedByDisplayName:a.z.string().default(""),dedupKey:a.z.string(),triggerFingerprint:a.z.string()});h.DeployClaimResultMsg=a.z.object({type:a.z.literal("deploy.claim.result"),requestId:a.z.string(),accepted:a.z.boolean(),runId:a.z.string().optional(),environment:h.EnvironmentConfig.optional(),reason:a.z.string().optional(),code:a.z.enum(["ok","duplicate","unknown_environment","not_permitted","unlinked_jira_account","promotion_order","jira_disabled","rule_disabled","cap"]).optional()});h.JiraUsersResultMsg=a.z.object({type:a.z.literal("jira.users.result"),requestId:a.z.string(),ok:a.z.boolean(),users:a.z.array(a.z.object({accountId:a.z.string(),displayName:a.z.string(),email:a.z.string().default(""),active:a.z.boolean().default(!0)})).default([]),error:a.z.string().optional()});h.ChatStreamMsg=a.z.object({type:a.z.literal("chat.stream"),requestId:a.z.string(),seq:a.z.number().int().nonnegative(),text:a.z.string().max(8e3)});h.ChatUsageMsg=a.z.object({type:a.z.literal("chat.usage"),requestId:a.z.string(),inputTokens:a.z.number().int().nonnegative(),outputTokens:a.z.number().int().nonnegative(),cacheReadTokens:a.z.number().int().nonnegative().optional(),turns:a.z.number().int().nonnegative().optional()});h.ChatListMsg=a.z.object({type:a.z.literal("chat.list"),requestId:a.z.string(),projectId:a.z.string()});h.ChatListResultMsg=a.z.object({type:a.z.literal("chat.list.result"),requestId:a.z.string(),sessions:a.z.array(a.z.object({sessionId:a.z.string(),title:a.z.string().default(""),updatedAt:a.z.string().default(""),messageCount:a.z.number().int().nonnegative().default(0)})).default([])});h.ChatLoadMsg=a.z.object({type:a.z.literal("chat.load"),requestId:a.z.string(),sessionId:a.z.string()});h.BUILTIN_REPLY_LANGUAGES=[{name:"English",instruction:"Write your prose in English."},{name:"Hindi",instruction:"Write your prose in Hindi, in the Devanagari script. Keep technical terms that have no everyday Hindi equivalent in English rather than inventing a translation."},{name:"Hinglish",instruction:"Write your prose in Hinglish: conversational Hindi written in the Latin alphabet, with English technical words left in English - the way an Indian developer talks at work."}];h.REPLY_STYLES=[{id:"technical",label:"Technical",hint:"Full detail - names files, functions and trade-offs",instruction:"Answer at full technical depth: name the files, functions and data structures involved, and state trade-offs precisely. Assume the reader reads code every day."},{id:"balanced",label:"Balanced",hint:"Plain explanation, with the technical detail that matters",instruction:"Explain in plain language first, then add the technical detail that actually matters for the decision. Assume the reader is technical but does not know this codebase."},{id:"simple",label:"Simple",hint:"Everyday words - no jargon unless it is unavoidable",instruction:"Answer in everyday words, as if to someone who does not write code. Avoid jargon; when a technical term is unavoidable, explain it in half a sentence. Prefer short paragraphs and concrete examples over precision about internals."}];function _g(t){let e=[],n=(t.language??"").trim();if(n){let s=h.BUILTIN_REPLY_LANGUAGES.find(i=>i.name.toLowerCase()===n.toLowerCase());e.push((t.languageInstruction??"").trim()||s?.instruction||`Write your prose in ${n}.`),e.push("Code, file paths, identifiers, commands, error text and log output stay exactly as they are - only your own prose changes language."),e.push("The ```ticket block is the exception: its summary and description are ALWAYS written in English, because the ticket is read by other people and by the implementing agent.")}let r=h.REPLY_STYLES.find(s=>s.id===(t.style??"").trim());return r&&e.push(r.instruction),e.length?`
|
|
23
|
+
`)}),this}_outputHelpIfRequested(e){let n=this._getHelpOption();n&&e.find(s=>n.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function $l(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let n,r="127.0.0.1",s="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?n=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(n=i[1],/^\d+$/.test(i[3])?s=i[3]:r=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(n=i[1],r=i[3],s=i[4]),n&&s!=="0"?`${n}=${r}:${parseInt(s)+1}`:e})}Pl.Command=Ro});var zl=re(Ve=>{var{Argument:Ol}=Ws(),{Command:Eo}=jl(),{CommanderError:jf,InvalidArgumentError:Nl}=ps(),{Help:Of}=wo(),{Option:Ml}=To();Ve.program=new Eo;Ve.createCommand=t=>new Eo(t);Ve.createOption=(t,e)=>new Ml(t,e);Ve.createArgument=(t,e)=>new Ol(t,e);Ve.Command=Eo;Ve.Option=Ml;Ve.Argument=Ol;Ve.Help=Of;Ve.CommanderError=jf;Ve.InvalidArgumentError=Nl;Ve.InvalidOptionArgumentError=Nl});var vs=re(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.getParsedType=le.ZodParsedType=le.objectUtil=le.util=void 0;var zo;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function n(s){throw new Error}t.assertNever=n,t.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},t.getValidEnumValues=s=>{let i=t.objectKeys(s).filter(l=>typeof s[s[l]]!="number"),o={};for(let l of i)o[l]=s[l];return t.objectValues(o)},t.objectValues=s=>t.objectKeys(s).map(function(i){return s[i]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},t.find=(s,i)=>{for(let o of s)if(i(o))return o},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(zo||(le.util=zo={}));var lu;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(lu||(le.objectUtil=lu={}));le.ZodParsedType=zo.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var Xp=t=>{switch(typeof t){case"undefined":return le.ZodParsedType.undefined;case"string":return le.ZodParsedType.string;case"number":return Number.isNaN(t)?le.ZodParsedType.nan:le.ZodParsedType.number;case"boolean":return le.ZodParsedType.boolean;case"function":return le.ZodParsedType.function;case"bigint":return le.ZodParsedType.bigint;case"symbol":return le.ZodParsedType.symbol;case"object":return Array.isArray(t)?le.ZodParsedType.array:t===null?le.ZodParsedType.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?le.ZodParsedType.promise:typeof Map<"u"&&t instanceof Map?le.ZodParsedType.map:typeof Set<"u"&&t instanceof Set?le.ZodParsedType.set:typeof Date<"u"&&t instanceof Date?le.ZodParsedType.date:le.ZodParsedType.object;default:return le.ZodParsedType.unknown}};le.getParsedType=Xp});var ui=re(en=>{"use strict";Object.defineProperty(en,"__esModule",{value:!0});en.ZodError=en.quotelessJson=en.ZodIssueCode=void 0;var uu=vs();en.ZodIssueCode=uu.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 Qp=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");en.quotelessJson=Qp;var ws=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(i){return i.message},r={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)r._errors.push(n(o));else{let l=r,u=0;for(;u<o.path.length;){let c=o.path[u];u===o.path.length-1?(l[c]=l[c]||{_errors:[]},l[c]._errors.push(n(o))):l[c]=l[c]||{_errors:[]},l=l[c],u++}}};return s(this),r}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,uu.util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];n[i]=n[i]||[],n[i].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};en.ZodError=ws;ws.create=t=>new ws(t)});var Lo=re(Do=>{"use strict";Object.defineProperty(Do,"__esModule",{value:!0});var Ee=ui(),Mn=vs(),em=(t,e)=>{let n;switch(t.code){case Ee.ZodIssueCode.invalid_type:t.received===Mn.ZodParsedType.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case Ee.ZodIssueCode.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,Mn.util.jsonStringifyReplacer)}`;break;case Ee.ZodIssueCode.unrecognized_keys:n=`Unrecognized key(s) in object: ${Mn.util.joinValues(t.keys,", ")}`;break;case Ee.ZodIssueCode.invalid_union:n="Invalid input";break;case Ee.ZodIssueCode.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Mn.util.joinValues(t.options)}`;break;case Ee.ZodIssueCode.invalid_enum_value:n=`Invalid enum value. Expected ${Mn.util.joinValues(t.options)}, received '${t.received}'`;break;case Ee.ZodIssueCode.invalid_arguments:n="Invalid function arguments";break;case Ee.ZodIssueCode.invalid_return_type:n="Invalid function return type";break;case Ee.ZodIssueCode.invalid_date:n="Invalid date";break;case Ee.ZodIssueCode.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:Mn.util.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case Ee.ZodIssueCode.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case Ee.ZodIssueCode.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case Ee.ZodIssueCode.custom:n="Invalid input";break;case Ee.ZodIssueCode.invalid_intersection_types:n="Intersection results could not be merged";break;case Ee.ZodIssueCode.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case Ee.ZodIssueCode.not_finite:n="Number must be finite";break;default:n=e.defaultError,Mn.util.assertNever(t)}return{message:n}};Do.default=em});var ci=re(tn=>{"use strict";var tm=tn&&tn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(tn,"__esModule",{value:!0});tn.defaultErrorMap=void 0;tn.setErrorMap=nm;tn.getErrorMap=rm;var cu=tm(Lo());tn.defaultErrorMap=cu.default;var du=cu.default;function nm(t){du=t}function rm(){return du}});var qo=re(oe=>{"use strict";var sm=oe&&oe.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(oe,"__esModule",{value:!0});oe.isAsync=oe.isValid=oe.isDirty=oe.isAborted=oe.OK=oe.DIRTY=oe.INVALID=oe.ParseStatus=oe.EMPTY_PATH=oe.makeIssue=void 0;oe.addIssueToContext=am;var im=ci(),hu=sm(Lo()),om=t=>{let{data:e,path:n,errorMaps:r,issueData:s}=t,i=[...n,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let l="",u=r.filter(c=>!!c).slice().reverse();for(let c of u)l=c(o,{data:e,defaultError:l}).message;return{...s,path:i,message:l}};oe.makeIssue=om;oe.EMPTY_PATH=[];function am(t,e){let n=(0,im.getErrorMap)(),r=(0,oe.makeIssue)({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===hu.default?void 0:hu.default].filter(s=>!!s)});t.common.issues.push(r)}var Uo=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let s of n){if(s.status==="aborted")return oe.INVALID;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let s of n){let i=await s.key,o=await s.value;r.push({key:i,value:o})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let s of n){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return oe.INVALID;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(r[i.value]=o.value)}return{status:e.value,value:r}}};oe.ParseStatus=Uo;oe.INVALID=Object.freeze({status:"aborted"});var lm=t=>({status:"dirty",value:t});oe.DIRTY=lm;var um=t=>({status:"valid",value:t});oe.OK=um;var cm=t=>t.status==="aborted";oe.isAborted=cm;var dm=t=>t.status==="dirty";oe.isDirty=dm;var hm=t=>t.status==="valid";oe.isValid=hm;var fm=t=>typeof Promise<"u"&&t instanceof Promise;oe.isAsync=fm});var pu=re(fu=>{"use strict";Object.defineProperty(fu,"__esModule",{value:!0})});var gu=re(di=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});di.errorUtil=void 0;var mu;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(mu||(di.errorUtil=mu={}))});var Ru=re(k=>{"use strict";Object.defineProperty(k,"__esModule",{value:!0});k.discriminatedUnion=k.date=k.boolean=k.bigint=k.array=k.any=k.coerce=k.ZodFirstPartyTypeKind=k.late=k.ZodSchema=k.Schema=k.ZodReadonly=k.ZodPipeline=k.ZodBranded=k.BRAND=k.ZodNaN=k.ZodCatch=k.ZodDefault=k.ZodNullable=k.ZodOptional=k.ZodTransformer=k.ZodEffects=k.ZodPromise=k.ZodNativeEnum=k.ZodEnum=k.ZodLiteral=k.ZodLazy=k.ZodFunction=k.ZodSet=k.ZodMap=k.ZodRecord=k.ZodTuple=k.ZodIntersection=k.ZodDiscriminatedUnion=k.ZodUnion=k.ZodObject=k.ZodArray=k.ZodVoid=k.ZodNever=k.ZodUnknown=k.ZodAny=k.ZodNull=k.ZodUndefined=k.ZodSymbol=k.ZodDate=k.ZodBoolean=k.ZodBigInt=k.ZodNumber=k.ZodString=k.ZodType=void 0;k.NEVER=k.void=k.unknown=k.union=k.undefined=k.tuple=k.transformer=k.symbol=k.string=k.strictObject=k.set=k.record=k.promise=k.preprocess=k.pipeline=k.ostring=k.optional=k.onumber=k.oboolean=k.object=k.number=k.nullable=k.null=k.never=k.nativeEnum=k.nan=k.map=k.literal=k.lazy=k.intersection=k.instanceof=k.function=k.enum=k.effect=void 0;k.datetimeRegex=_u;k.custom=Su;var E=ui(),hi=ci(),q=gu(),T=qo(),$=vs(),Qe=class{constructor(e,n,r,s){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},yu=(t,e)=>{if((0,T.isValid)(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new E.ZodError(t.common.issues);return this._error=n,this._error}}};function Y(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:s}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,l)=>{let{message:u}=t;return o.code==="invalid_enum_value"?{message:u??l.defaultError}:typeof l.data>"u"?{message:u??r??l.defaultError}:o.code!=="invalid_type"?{message:l.defaultError}:{message:u??n??l.defaultError}},description:s}}var X=class{get description(){return this._def.description}_getType(e){return(0,$.getParsedType)(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:(0,$.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new T.ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:(0,$.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if((0,T.isAsync)(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,$.getParsedType)(e)},s=this._parseSync({data:e,path:r.path,parent:r});return yu(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,$.getParsedType)(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return(0,T.isValid)(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>(0,T.isValid)(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,$.getParsedType)(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await((0,T.isAsync)(s)?s:Promise.resolve(s));return yu(r,i)}refine(e,n){let r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,i)=>{let o=e(s),l=()=>i.addIssue({code:E.ZodIssueCode.custom,...r(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(u=>u?!0:(l(),!1)):o?!0:(l(),!1)})}refinement(e,n){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(e){return new Fe({schema:this,typeName:G.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Xe.create(this,this._def)}nullable(){return bt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return zt.create(this)}promise(){return sn.create(this,this._def)}or(e){return Bn.create([this,e],this._def)}and(e){return Kn.create(this,e,this._def)}transform(e){return new Fe({...Y(this._def),schema:this,typeName:G.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new Wn({...Y(this._def),innerType:this,defaultValue:n,typeName:G.ZodDefault})}brand(){return new _s({typeName:G.ZodBranded,type:this,...Y(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Jn({...Y(this._def),innerType:this,catchValue:n,typeName:G.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return ks.create(this,e)}readonly(){return Yn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};k.ZodType=X;k.Schema=X;k.ZodSchema=X;var pm=/^c[^\s-]{8,}$/i,mm=/^[0-9a-z]+$/,gm=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ym=/^[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,bm=/^[a-z0-9_-]{21}$/i,vm=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,wm=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,_m=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,km="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Fo,Sm=/^(?:(?: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])$/,Tm=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,xm=/^(([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]))$/,Cm=/^(([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])$/,Im=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Rm=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,vu="((\\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])))",Em=new RegExp(`^${vu}$`);function wu(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function Am(t){return new RegExp(`^${wu(t)}$`)}function _u(t){let e=`${vu}T${wu(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function $m(t,e){return!!((e==="v4"||!e)&&Sm.test(t)||(e==="v6"||!e)&&xm.test(t))}function Pm(t,e){if(!vm.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function jm(t,e){return!!((e==="v4"||!e)&&Tm.test(t)||(e==="v6"||!e)&&Cm.test(t))}var nn=class t extends X{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==$.ZodParsedType.string){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.string,received:i.parsedType}),T.INVALID}let r=new T.ParseStatus,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:E.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:E.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,l=e.data.length<i.value;(o||l)&&(s=this._getOrReturnCtx(e,s),o?(0,T.addIssueToContext)(s,{code:E.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):l&&(0,T.addIssueToContext)(s,{code:E.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")_m.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"email",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Fo||(Fo=new RegExp(km,"u")),Fo.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"emoji",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")ym.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"uuid",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")bm.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"nanoid",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")pm.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"cuid",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")mm.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"cuid2",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")gm.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"ulid",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"url",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"regex",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:E.ZodIssueCode.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:E.ZodIssueCode.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:E.ZodIssueCode.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?_u(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:E.ZodIssueCode.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?Em.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:E.ZodIssueCode.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Am(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:E.ZodIssueCode.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?wm.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"duration",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?$m(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"ip",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?Pm(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"jwt",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?jm(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"cidr",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?Im.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"base64",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?Rm.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{validation:"base64url",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):$.util.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:E.ZodIssueCode.invalid_string,...q.errorUtil.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...q.errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...q.errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...q.errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...q.errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...q.errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...q.errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...q.errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...q.errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...q.errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...q.errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...q.errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...q.errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...q.errorUtil.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...q.errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...q.errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...q.errorUtil.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...q.errorUtil.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...q.errorUtil.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...q.errorUtil.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...q.errorUtil.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...q.errorUtil.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...q.errorUtil.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...q.errorUtil.errToObj(n)})}nonempty(e){return this.min(1,q.errorUtil.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};k.ZodString=nn;nn.create=t=>new nn({checks:[],typeName:G.ZodString,coerce:t?.coerce??!1,...Y(t)});function Om(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,i=Number.parseInt(t.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var zn=class t extends X{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)!==$.ZodParsedType.number){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.number,received:i.parsedType}),T.INVALID}let r,s=new T.ParseStatus;for(let i of this._def.checks)i.kind==="int"?$.util.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{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)&&(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{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)&&(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:E.ZodIssueCode.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Om(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:E.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:E.ZodIssueCode.not_finite,message:i.message}),s.dirty()):$.util.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,q.errorUtil.toString(n))}gt(e,n){return this.setLimit("min",e,!1,q.errorUtil.toString(n))}lte(e,n){return this.setLimit("max",e,!0,q.errorUtil.toString(n))}lt(e,n){return this.setLimit("max",e,!1,q.errorUtil.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:q.errorUtil.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:q.errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:q.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:q.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:q.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:q.errorUtil.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:q.errorUtil.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:q.errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:q.errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:q.errorUtil.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&$.util.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};k.ZodNumber=zn;zn.create=t=>new zn({checks:[],typeName:G.ZodNumber,coerce:t?.coerce||!1,...Y(t)});var Dn=class t extends X{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)!==$.ZodParsedType.bigint)return this._getInvalidInput(e);let r,s=new T.ParseStatus;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code: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)&&(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{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)&&(r=this._getOrReturnCtx(e,r),(0,T.addIssueToContext)(r,{code:E.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):$.util.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(n,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.bigint,received:n.parsedType}),T.INVALID}gte(e,n){return this.setLimit("min",e,!0,q.errorUtil.toString(n))}gt(e,n){return this.setLimit("min",e,!1,q.errorUtil.toString(n))}lte(e,n){return this.setLimit("max",e,!0,q.errorUtil.toString(n))}lt(e,n){return this.setLimit("max",e,!1,q.errorUtil.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:q.errorUtil.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:q.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:q.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:q.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:q.errorUtil.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:q.errorUtil.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};k.ZodBigInt=Dn;Dn.create=t=>new Dn({checks:[],typeName:G.ZodBigInt,coerce:t?.coerce??!1,...Y(t)});var Ln=class extends X{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==$.ZodParsedType.boolean){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.boolean,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};k.ZodBoolean=Ln;Ln.create=t=>new Ln({typeName:G.ZodBoolean,coerce:t?.coerce||!1,...Y(t)});var Un=class t extends X{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==$.ZodParsedType.date){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.date,received:i.parsedType}),T.INVALID}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(i,{code:E.ZodIssueCode.invalid_date}),T.INVALID}let r=new T.ParseStatus,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:E.ZodIssueCode.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),(0,T.addIssueToContext)(s,{code:E.ZodIssueCode.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):$.util.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:q.errorUtil.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:q.errorUtil.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};k.ZodDate=Un;Un.create=t=>new Un({checks:[],coerce:t?.coerce||!1,typeName:G.ZodDate,...Y(t)});var Lr=class extends X{_parse(e){if(this._getType(e)!==$.ZodParsedType.symbol){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.symbol,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};k.ZodSymbol=Lr;Lr.create=t=>new Lr({typeName:G.ZodSymbol,...Y(t)});var qn=class extends X{_parse(e){if(this._getType(e)!==$.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.undefined,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};k.ZodUndefined=qn;qn.create=t=>new qn({typeName:G.ZodUndefined,...Y(t)});var Fn=class extends X{_parse(e){if(this._getType(e)!==$.ZodParsedType.null){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.null,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};k.ZodNull=Fn;Fn.create=t=>new Fn({typeName:G.ZodNull,...Y(t)});var rn=class extends X{constructor(){super(...arguments),this._any=!0}_parse(e){return(0,T.OK)(e.data)}};k.ZodAny=rn;rn.create=t=>new rn({typeName:G.ZodAny,...Y(t)});var Mt=class extends X{constructor(){super(...arguments),this._unknown=!0}_parse(e){return(0,T.OK)(e.data)}};k.ZodUnknown=Mt;Mt.create=t=>new Mt({typeName:G.ZodUnknown,...Y(t)});var ot=class extends X{_parse(e){let n=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(n,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.never,received:n.parsedType}),T.INVALID}};k.ZodNever=ot;ot.create=t=>new ot({typeName:G.ZodNever,...Y(t)});var Ur=class extends X{_parse(e){if(this._getType(e)!==$.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.void,received:r.parsedType}),T.INVALID}return(0,T.OK)(e.data)}};k.ZodVoid=Ur;Ur.create=t=>new Ur({typeName:G.ZodVoid,...Y(t)});var zt=class t extends X{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==$.ZodParsedType.array)return(0,T.addIssueToContext)(n,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.array,received:n.parsedType}),T.INVALID;if(s.exactLength!==null){let o=n.data.length>s.exactLength.value,l=n.data.length<s.exactLength.value;(o||l)&&((0,T.addIssueToContext)(n,{code:o?E.ZodIssueCode.too_big:E.ZodIssueCode.too_small,minimum:l?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&((0,T.addIssueToContext)(n,{code:E.ZodIssueCode.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&((0,T.addIssueToContext)(n,{code:E.ZodIssueCode.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((o,l)=>s.type._parseAsync(new Qe(n,o,n.path,l)))).then(o=>T.ParseStatus.mergeArray(r,o));let i=[...n.data].map((o,l)=>s.type._parseSync(new Qe(n,o,n.path,l)));return T.ParseStatus.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:q.errorUtil.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:q.errorUtil.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:q.errorUtil.toString(n)}})}nonempty(e){return this.min(1,e)}};k.ZodArray=zt;zt.create=(t,e)=>new zt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:G.ZodArray,...Y(e)});function Dr(t){if(t instanceof De){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=Xe.create(Dr(r))}return new De({...t._def,shape:()=>e})}else return t instanceof zt?new zt({...t._def,type:Dr(t.element)}):t instanceof Xe?Xe.create(Dr(t.unwrap())):t instanceof bt?bt.create(Dr(t.unwrap())):t instanceof yt?yt.create(t.items.map(e=>Dr(e))):t}var De=class t extends X{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),n=$.util.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==$.ZodParsedType.object){let c=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(c,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.object,received:c.parsedType}),T.INVALID}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),l=[];if(!(this._def.catchall instanceof ot&&this._def.unknownKeys==="strip"))for(let c in s.data)o.includes(c)||l.push(c);let u=[];for(let c of o){let f=i[c],p=s.data[c];u.push({key:{status:"valid",value:c},value:f._parse(new Qe(s,p,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof ot){let c=this._def.unknownKeys;if(c==="passthrough")for(let f of l)u.push({key:{status:"valid",value:f},value:{status:"valid",value:s.data[f]}});else if(c==="strict")l.length>0&&((0,T.addIssueToContext)(s,{code:E.ZodIssueCode.unrecognized_keys,keys:l}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let f of l){let p=s.data[f];u.push({key:{status:"valid",value:f},value:c._parse(new Qe(s,p,s.path,f)),alwaysSet:f in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let c=[];for(let f of u){let p=await f.key,b=await f.value;c.push({key:p,value:b,alwaysSet:f.alwaysSet})}return c}).then(c=>T.ParseStatus.mergeObjectSync(r,c)):T.ParseStatus.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(e){return q.errorUtil.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:q.errorUtil.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:G.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of $.util.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of $.util.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return Dr(this)}partial(e){let n={};for(let r of $.util.objectKeys(this.shape)){let s=this.shape[r];e&&!e[r]?n[r]=s:n[r]=s.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of $.util.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Xe;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return ku($.util.objectKeys(this.shape))}};k.ZodObject=De;De.create=(t,e)=>new De({shape:()=>t,unknownKeys:"strip",catchall:ot.create(),typeName:G.ZodObject,...Y(e)});De.strictCreate=(t,e)=>new De({shape:()=>t,unknownKeys:"strict",catchall:ot.create(),typeName:G.ZodObject,...Y(e)});De.lazycreate=(t,e)=>new De({shape:t,unknownKeys:"strip",catchall:ot.create(),typeName:G.ZodObject,...Y(e)});var Bn=class extends X{_parse(e){let{ctx:n}=this._processInputParams(e),r=this._def.options;function s(i){for(let l of i)if(l.result.status==="valid")return l.result;for(let l of i)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;let o=i.map(l=>new E.ZodError(l.ctx.common.issues));return(0,T.addIssueToContext)(n,{code:E.ZodIssueCode.invalid_union,unionErrors:o}),T.INVALID}if(n.common.async)return Promise.all(r.map(async i=>{let o={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let u of r){let c={...n,common:{...n.common,issues:[]},parent:null},f=u._parseSync({data:n.data,path:n.path,parent:c});if(f.status==="valid")return f;f.status==="dirty"&&!i&&(i={result:f,ctx:c}),c.common.issues.length&&o.push(c.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let l=o.map(u=>new E.ZodError(u));return(0,T.addIssueToContext)(n,{code:E.ZodIssueCode.invalid_union,unionErrors:l}),T.INVALID}}get options(){return this._def.options}};k.ZodUnion=Bn;Bn.create=(t,e)=>new Bn({options:t,typeName:G.ZodUnion,...Y(e)});var Nt=t=>t instanceof Hn?Nt(t.schema):t instanceof Fe?Nt(t.innerType()):t instanceof Zn?[t.value]:t instanceof Gn?t.options:t instanceof Vn?$.util.objectValues(t.enum):t instanceof Wn?Nt(t._def.innerType):t instanceof qn?[void 0]:t instanceof Fn?[null]:t instanceof Xe?[void 0,...Nt(t.unwrap())]:t instanceof bt?[null,...Nt(t.unwrap())]:t instanceof _s||t instanceof Yn?Nt(t.unwrap()):t instanceof Jn?Nt(t._def.innerType):[],fi=class t extends X{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==$.ZodParsedType.object)return(0,T.addIssueToContext)(n,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.object,received:n.parsedType}),T.INVALID;let r=this.discriminator,s=n.data[r],i=this.optionsMap.get(s);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):((0,T.addIssueToContext)(n,{code:E.ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),T.INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let s=new Map;for(let i of n){let o=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 l of o){if(s.has(l))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(l)}`);s.set(l,i)}}return new t({typeName:G.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...Y(r)})}};k.ZodDiscriminatedUnion=fi;function Bo(t,e){let n=(0,$.getParsedType)(t),r=(0,$.getParsedType)(e);if(t===e)return{valid:!0,data:t};if(n===$.ZodParsedType.object&&r===$.ZodParsedType.object){let s=$.util.objectKeys(e),i=$.util.objectKeys(t).filter(l=>s.indexOf(l)!==-1),o={...t,...e};for(let l of i){let u=Bo(t[l],e[l]);if(!u.valid)return{valid:!1};o[l]=u.data}return{valid:!0,data:o}}else if(n===$.ZodParsedType.array&&r===$.ZodParsedType.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<t.length;i++){let o=t[i],l=e[i],u=Bo(o,l);if(!u.valid)return{valid:!1};s.push(u.data)}return{valid:!0,data:s}}else return n===$.ZodParsedType.date&&r===$.ZodParsedType.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Kn=class extends X{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=(i,o)=>{if((0,T.isAborted)(i)||(0,T.isAborted)(o))return T.INVALID;let l=Bo(i.value,o.value);return l.valid?(((0,T.isDirty)(i)||(0,T.isDirty)(o))&&n.dirty(),{status:n.value,value:l.data}):((0,T.addIssueToContext)(r,{code:E.ZodIssueCode.invalid_intersection_types}),T.INVALID)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};k.ZodIntersection=Kn;Kn.create=(t,e,n)=>new Kn({left:t,right:e,typeName:G.ZodIntersection,...Y(n)});var yt=class t extends X{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==$.ZodParsedType.array)return(0,T.addIssueToContext)(r,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.array,received:r.parsedType}),T.INVALID;if(r.data.length<this._def.items.length)return(0,T.addIssueToContext)(r,{code:E.ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),T.INVALID;!this._def.rest&&r.data.length>this._def.items.length&&((0,T.addIssueToContext)(r,{code:E.ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let i=[...r.data].map((o,l)=>{let u=this._def.items[l]||this._def.rest;return u?u._parse(new Qe(r,o,r.path,l)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>T.ParseStatus.mergeArray(n,o)):T.ParseStatus.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};k.ZodTuple=yt;yt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new yt({items:t,typeName:G.ZodTuple,rest:null,...Y(e)})};var pi=class t extends X{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==$.ZodParsedType.object)return(0,T.addIssueToContext)(r,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.object,received:r.parsedType}),T.INVALID;let s=[],i=this._def.keyType,o=this._def.valueType;for(let l in r.data)s.push({key:i._parse(new Qe(r,l,r.path,l)),value:o._parse(new Qe(r,r.data[l],r.path,l)),alwaysSet:l in r.data});return r.common.async?T.ParseStatus.mergeObjectAsync(n,s):T.ParseStatus.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof X?new t({keyType:e,valueType:n,typeName:G.ZodRecord,...Y(r)}):new t({keyType:nn.create(),valueType:e,typeName:G.ZodRecord,...Y(n)})}};k.ZodRecord=pi;var qr=class extends X{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==$.ZodParsedType.map)return(0,T.addIssueToContext)(r,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.map,received:r.parsedType}),T.INVALID;let s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([l,u],c)=>({key:s._parse(new Qe(r,l,r.path,[c,"key"])),value:i._parse(new Qe(r,u,r.path,[c,"value"]))}));if(r.common.async){let l=new Map;return Promise.resolve().then(async()=>{for(let u of o){let c=await u.key,f=await u.value;if(c.status==="aborted"||f.status==="aborted")return T.INVALID;(c.status==="dirty"||f.status==="dirty")&&n.dirty(),l.set(c.value,f.value)}return{status:n.value,value:l}})}else{let l=new Map;for(let u of o){let c=u.key,f=u.value;if(c.status==="aborted"||f.status==="aborted")return T.INVALID;(c.status==="dirty"||f.status==="dirty")&&n.dirty(),l.set(c.value,f.value)}return{status:n.value,value:l}}}};k.ZodMap=qr;qr.create=(t,e,n)=>new qr({valueType:e,keyType:t,typeName:G.ZodMap,...Y(n)});var Fr=class t extends X{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==$.ZodParsedType.set)return(0,T.addIssueToContext)(r,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.set,received:r.parsedType}),T.INVALID;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&((0,T.addIssueToContext)(r,{code:E.ZodIssueCode.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&((0,T.addIssueToContext)(r,{code:E.ZodIssueCode.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let i=this._def.valueType;function o(u){let c=new Set;for(let f of u){if(f.status==="aborted")return T.INVALID;f.status==="dirty"&&n.dirty(),c.add(f.value)}return{status:n.value,value:c}}let l=[...r.data.values()].map((u,c)=>i._parse(new Qe(r,u,r.path,c)));return r.common.async?Promise.all(l).then(u=>o(u)):o(l)}min(e,n){return new t({...this._def,minSize:{value:e,message:q.errorUtil.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:q.errorUtil.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};k.ZodSet=Fr;Fr.create=(t,e)=>new Fr({valueType:t,minSize:null,maxSize:null,typeName:G.ZodSet,...Y(e)});var mi=class t extends X{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==$.ZodParsedType.function)return(0,T.addIssueToContext)(n,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.function,received:n.parsedType}),T.INVALID;function r(l,u){return(0,T.makeIssue)({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,(0,hi.getErrorMap)(),hi.defaultErrorMap].filter(c=>!!c),issueData:{code:E.ZodIssueCode.invalid_arguments,argumentsError:u}})}function s(l,u){return(0,T.makeIssue)({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,(0,hi.getErrorMap)(),hi.defaultErrorMap].filter(c=>!!c),issueData:{code:E.ZodIssueCode.invalid_return_type,returnTypeError:u}})}let i={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof sn){let l=this;return(0,T.OK)(async function(...u){let c=new E.ZodError([]),f=await l._def.args.parseAsync(u,i).catch(w=>{throw c.addIssue(r(u,w)),c}),p=await Reflect.apply(o,this,f);return await l._def.returns._def.type.parseAsync(p,i).catch(w=>{throw c.addIssue(s(p,w)),c})})}else{let l=this;return(0,T.OK)(function(...u){let c=l._def.args.safeParse(u,i);if(!c.success)throw new E.ZodError([r(u,c.error)]);let f=Reflect.apply(o,this,c.data),p=l._def.returns.safeParse(f,i);if(!p.success)throw new E.ZodError([s(f,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:yt.create(e).rest(Mt.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new t({args:e||yt.create([]).rest(Mt.create()),returns:n||Mt.create(),typeName:G.ZodFunction,...Y(r)})}};k.ZodFunction=mi;var Hn=class extends X{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};k.ZodLazy=Hn;Hn.create=(t,e)=>new Hn({getter:t,typeName:G.ZodLazy,...Y(e)});var Zn=class extends X{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(n,{received:n.data,code:E.ZodIssueCode.invalid_literal,expected:this._def.value}),T.INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}};k.ZodLiteral=Zn;Zn.create=(t,e)=>new Zn({value:t,typeName:G.ZodLiteral,...Y(e)});function ku(t,e){return new Gn({values:t,typeName:G.ZodEnum,...Y(e)})}var Gn=class t extends X{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return(0,T.addIssueToContext)(n,{expected:$.util.joinValues(r),received:n.parsedType,code:E.ZodIssueCode.invalid_type}),T.INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return(0,T.addIssueToContext)(n,{received:n.data,code:E.ZodIssueCode.invalid_enum_value,options:r}),T.INVALID}return(0,T.OK)(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};k.ZodEnum=Gn;Gn.create=ku;var Vn=class extends X{_parse(e){let n=$.util.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==$.ZodParsedType.string&&r.parsedType!==$.ZodParsedType.number){let s=$.util.objectValues(n);return(0,T.addIssueToContext)(r,{expected:$.util.joinValues(s),received:r.parsedType,code:E.ZodIssueCode.invalid_type}),T.INVALID}if(this._cache||(this._cache=new Set($.util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=$.util.objectValues(n);return(0,T.addIssueToContext)(r,{received:r.data,code:E.ZodIssueCode.invalid_enum_value,options:s}),T.INVALID}return(0,T.OK)(e.data)}get enum(){return this._def.values}};k.ZodNativeEnum=Vn;Vn.create=(t,e)=>new Vn({values:t,typeName:G.ZodNativeEnum,...Y(e)});var sn=class extends X{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==$.ZodParsedType.promise&&n.common.async===!1)return(0,T.addIssueToContext)(n,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.promise,received:n.parsedType}),T.INVALID;let r=n.parsedType===$.ZodParsedType.promise?n.data:Promise.resolve(n.data);return(0,T.OK)(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};k.ZodPromise=sn;sn.create=(t,e)=>new sn({type:t,typeName:G.ZodPromise,...Y(e)});var Fe=class extends X{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===G.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{(0,T.addIssueToContext)(r,o),o.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(r.data,i);if(r.common.async)return Promise.resolve(o).then(async l=>{if(n.value==="aborted")return T.INVALID;let u=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return u.status==="aborted"?T.INVALID:u.status==="dirty"||n.value==="dirty"?(0,T.DIRTY)(u.value):u});{if(n.value==="aborted")return T.INVALID;let l=this._def.schema._parseSync({data:o,path:r.path,parent:r});return l.status==="aborted"?T.INVALID:l.status==="dirty"||n.value==="dirty"?(0,T.DIRTY)(l.value):l}}if(s.type==="refinement"){let o=l=>{let u=s.refinement(l,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){let l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?T.INVALID:(l.status==="dirty"&&n.dirty(),o(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?T.INVALID:(l.status==="dirty"&&n.dirty(),o(l.value).then(()=>({status:n.value,value:l.value}))))}if(s.type==="transform")if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!(0,T.isValid)(o))return T.INVALID;let l=s.transform(o.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>(0,T.isValid)(o)?Promise.resolve(s.transform(o.value,i)).then(l=>({status:n.value,value:l})):T.INVALID);$.util.assertNever(s)}};k.ZodEffects=Fe;k.ZodTransformer=Fe;Fe.create=(t,e,n)=>new Fe({schema:t,typeName:G.ZodEffects,effect:e,...Y(n)});Fe.createWithPreprocess=(t,e,n)=>new Fe({schema:e,effect:{type:"preprocess",transform:t},typeName:G.ZodEffects,...Y(n)});var Xe=class extends X{_parse(e){return this._getType(e)===$.ZodParsedType.undefined?(0,T.OK)(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};k.ZodOptional=Xe;Xe.create=(t,e)=>new Xe({innerType:t,typeName:G.ZodOptional,...Y(e)});var bt=class extends X{_parse(e){return this._getType(e)===$.ZodParsedType.null?(0,T.OK)(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};k.ZodNullable=bt;bt.create=(t,e)=>new bt({innerType:t,typeName:G.ZodNullable,...Y(e)});var Wn=class extends X{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===$.ZodParsedType.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};k.ZodDefault=Wn;Wn.create=(t,e)=>new Wn({innerType:t,typeName:G.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Y(e)});var Jn=class extends X{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return(0,T.isAsync)(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new E.ZodError(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new E.ZodError(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};k.ZodCatch=Jn;Jn.create=(t,e)=>new Jn({innerType:t,typeName:G.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Y(e)});var Br=class extends X{_parse(e){if(this._getType(e)!==$.ZodParsedType.nan){let r=this._getOrReturnCtx(e);return(0,T.addIssueToContext)(r,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.nan,received:r.parsedType}),T.INVALID}return{status:"valid",value:e.data}}};k.ZodNaN=Br;Br.create=t=>new Br({typeName:G.ZodNaN,...Y(t)});k.BRAND=Symbol("zod_brand");var _s=class extends X{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}};k.ZodBranded=_s;var ks=class t extends X{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?T.INVALID:i.status==="dirty"?(n.dirty(),(0,T.DIRTY)(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?T.INVALID:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:G.ZodPipeline})}};k.ZodPipeline=ks;var Yn=class extends X{_parse(e){let n=this._def.innerType._parse(e),r=s=>((0,T.isValid)(s)&&(s.value=Object.freeze(s.value)),s);return(0,T.isAsync)(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};k.ZodReadonly=Yn;Yn.create=(t,e)=>new Yn({innerType:t,typeName:G.ZodReadonly,...Y(e)});function bu(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function Su(t,e={},n){return t?rn.create().superRefine((r,s)=>{let i=t(r);if(i instanceof Promise)return i.then(o=>{if(!o){let l=bu(e,r),u=l.fatal??n??!0;s.addIssue({code:"custom",...l,fatal:u})}});if(!i){let o=bu(e,r),l=o.fatal??n??!0;s.addIssue({code:"custom",...o,fatal:l})}}):rn.create()}k.late={object:De.lazycreate};var G;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(G||(k.ZodFirstPartyTypeKind=G={}));var Nm=(t,e={message:`Input not instance of ${t.name}`})=>Su(n=>n instanceof t,e);k.instanceof=Nm;var Tu=nn.create;k.string=Tu;var xu=zn.create;k.number=xu;var Mm=Br.create;k.nan=Mm;var zm=Dn.create;k.bigint=zm;var Cu=Ln.create;k.boolean=Cu;var Dm=Un.create;k.date=Dm;var Lm=Lr.create;k.symbol=Lm;var Um=qn.create;k.undefined=Um;var qm=Fn.create;k.null=qm;var Fm=rn.create;k.any=Fm;var Bm=Mt.create;k.unknown=Bm;var Km=ot.create;k.never=Km;var Hm=Ur.create;k.void=Hm;var Zm=zt.create;k.array=Zm;var Gm=De.create;k.object=Gm;var Vm=De.strictCreate;k.strictObject=Vm;var Wm=Bn.create;k.union=Wm;var Jm=fi.create;k.discriminatedUnion=Jm;var Ym=Kn.create;k.intersection=Ym;var Xm=yt.create;k.tuple=Xm;var Qm=pi.create;k.record=Qm;var eg=qr.create;k.map=eg;var tg=Fr.create;k.set=tg;var ng=mi.create;k.function=ng;var rg=Hn.create;k.lazy=rg;var sg=Zn.create;k.literal=sg;var ig=Gn.create;k.enum=ig;var og=Vn.create;k.nativeEnum=og;var ag=sn.create;k.promise=ag;var Iu=Fe.create;k.effect=Iu;k.transformer=Iu;var lg=Xe.create;k.optional=lg;var ug=bt.create;k.nullable=ug;var cg=Fe.createWithPreprocess;k.preprocess=cg;var dg=ks.create;k.pipeline=dg;var hg=()=>Tu().optional();k.ostring=hg;var fg=()=>xu().optional();k.onumber=fg;var pg=()=>Cu().optional();k.oboolean=pg;k.coerce={string:(t=>nn.create({...t,coerce:!0})),number:(t=>zn.create({...t,coerce:!0})),boolean:(t=>Ln.create({...t,coerce:!0})),bigint:(t=>Dn.create({...t,coerce:!0})),date:(t=>Un.create({...t,coerce:!0}))};k.NEVER=T.INVALID});var Ko=re(et=>{"use strict";var mg=et&&et.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Kr=et&&et.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&mg(e,t,n)};Object.defineProperty(et,"__esModule",{value:!0});Kr(ci(),et);Kr(qo(),et);Kr(pu(),et);Kr(vs(),et);Kr(Ru(),et);Kr(ui(),et)});var $u=re(Le=>{"use strict";var Eu=Le&&Le.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),gg=Le&&Le.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),yg=Le&&Le.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&Eu(e,t,n);return gg(e,t),e},bg=Le&&Le.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Eu(e,t,n)};Object.defineProperty(Le,"__esModule",{value:!0});Le.z=void 0;var Au=yg(Ko());Le.z=Au;bg(Ko(),Le);Le.default=Au});var _e=re(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.ChatLoadResultMsg=h.REPLY_STYLES=h.BUILTIN_REPLY_LANGUAGES=h.ChatLoadMsg=h.ChatListResultMsg=h.ChatListMsg=h.ChatUsageMsg=h.ChatStreamMsg=h.JiraUsersResultMsg=h.DeployClaimResultMsg=h.DeployClaimMsg=h.RuleDiagnoseResultMsg=h.ProjectTestResultMsg=h.RunStatusMsg=h.FailedTest=h.RunUsageMsg=h.RunLogMsg=h.RunClaimMsg=h.HeartbeatMsg=h.HelloMsg=h.RuleConfig=h.ProjectConfig=h.ActionConfig=h.DeployAction=h.EnvironmentConfig=h.PromotionMode=h.DeployStep=h.RespondAction=h.ImplementAction=h.PlanOnlyAction=h.TriggerConfig=h.StatusChangedTrigger=h.CommentKeywordTrigger=h.LabelAddedTrigger=h.ActionType=h.TriggerType=h.ACTIVE_RUN_STATUSES=h.RunStatus=h.needsInputMarkerIn=h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=h.NEEDS_INPUT_COMMENT_MARKER=h.NEEDS_INPUT_LABEL=h.NEEDS_INPUT_ASK_FENCE=h.NEEDS_INPUT_MARKER=h.BRANCH_DEPLOY_ISSUE_KEY=h.REQUIRED_AGENT_CAPABILITIES=h.DEFAULT_AGENT_ID=h.REGISTERED_AGENTS=h.PROTOCOL_VERSION=h.GITHUB_TOKEN_PERMISSIONS=void 0;h.SetupStatusResultMsg=h.SetupStatusMsg=h.DeploySuggestResultMsg=h.SelfMigrationApplyResultMsg=h.SelfMigrationApplyMsg=h.SELF_MIGRATION_DIR=h.EnvPreflightResultMsg=h.EnvPreflightMsg=h.ChatCreateTicketResultMsg=h.ChatCreateTicketMsg=h.ChatTurnResultMsg=h.ChatTurnMsg=h.ChatFile=h.TeamCredsResultMsg=h.TeamCredsMsg=h.KnowledgeSaveResultMsg=h.KnowledgeSaveMsg=h.KnowledgeListResultMsg=h.KnowledgeFile=h.KnowledgeListMsg=h.AuditReviewResultMsg=h.AuditReviewMsg=h.AuditGetResultMsg=h.AuditGetMsg=h.AuditListResultMsg=h.AuditStatsResultMsg=h.AuditStatsMsg=h.AuditListMsg=h.AuditStartResultMsg=h.AuditStartMsg=h.AuditRecord=h.AuditFinding=h.AuditDetailLevel=h.AuditScope=h.AuditSeverity=h.KnowledgeRole=h.AuditRole=h.EpicSuggestResultMsg=h.EpicSuggestMsg=h.EpicListResultMsg=h.EpicChild=h.EpicListMsg=h.BoardTriggerResultMsg=h.BoardTriggerMsg=h.BoardFetchResultMsg=h.BoardFetchMsg=h.RepoDocReadResultMsg=h.RepoDocReadMsg=h.RepoDocsResultMsg=h.RepoDocsMsg=void 0;h.DEFAULT_DEPLOY_SUGGEST_PROMPT_TEMPLATE=h.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE=h.DEPLOY_FIX_PROMPT_TEMPLATE=h.PROMPT_PRESETS=h.DEFAULT_RESPOND_PROMPT_TEMPLATE=h.BUGFIX_IMPLEMENT_PROMPT_TEMPLATE=h.BUG_INVESTIGATION_PROMPT_TEMPLATE=h.TECHNICAL_PLAN_PROMPT_TEMPLATE=h.MEMORY_UPDATE_PROMPT=h.DEFAULT_IMPLEMENT_PROMPT_TEMPLATE=h.WRITE_TESTS_PROMPT=h.NEEDS_INPUT_OPTIONS_PROMPT=h.DEFAULT_PLAN_PROMPT_TEMPLATE=h.EnrollResponse=h.EnrollRequest=h.ServerToRunnerMsg=h.JiraUsersMsg=h.DeploySuggestMsg=h.DeployFixMsg=h.DeployStartMsg=h.RunRetryPushMsg=h.RunRejectedMsg=h.RunApprovedMsg=h.RunCancelMsg=h.RuleDiagnoseMsg=h.ProjectTestMsg=h.RunClaimResultMsg=h.ConfigMsg=h.HelloAckMsg=h.RunnerToServerMsg=h.AutopilotReportMsg=h.AutopilotNextResultMsg=h.AutopilotNextMsg=h.RunnerUpdateResultMsg=h.AgentProfilesResultMsg=h.AgentProfilesMsg=h.RunPrConflictMsg=h.RunResolveConflictResultMsg=h.RunAnswerResultMsg=h.RunAnswerMsg=h.RunTestFixResultMsg=h.RunTestFixMsg=h.RunResolveConflictMsg=h.RunnerUpdateMsg=h.RepoDocSaveResultMsg=h.RepoDocSaveMsg=h.SetupClaudeMdSaveResultMsg=h.SetupClaudeMdSaveMsg=h.SetupClaudeMdGenerateResultMsg=h.SetupClaudeMdGenerateMsg=void 0;h.missingAgentCapabilities=vg;h.replyPreferenceAppendix=_g;h.pendingMigrationsAppendix=kg;h.isSelfMigrationFilename=Sg;h.parseRunnerMsg=Tg;h.parseServerMsg=xg;var a=$u();h.GITHUB_TOKEN_PERMISSIONS={where:"github.com/settings/personal-access-tokens/new (fine-grained token)",steps:["Resource owner: the org or user that OWNS the repo - not your personal account, unless the repo is under it","Repository access: Only select repositories -> pick this repo","Contents: Read and write - pushing the agent's branch","Pull requests: Read and write - opening the PR, and merging it when you approve","Metadata: Read-only - GitHub adds this itself and will not let you remove it","Workflows: Read and write - ONLY if changes may touch .github/workflows; without it GitHub rejects those pushes"],note:"A fine-grained token covers exactly ONE resource owner, so a repo in a different org always needs its own token. A classic token with the `repo` scope also works and is simpler, but it reaches every repository you can see - prefer fine-grained."};h.PROTOCOL_VERSION="1.51";h.REGISTERED_AGENTS=[{id:"claude-code",displayName:"Claude Code",capabilities:{readOnlyJail:!0,editNoShellJail:!0,sessionResume:!0,costReporting:!0,modelSelection:!0,loginProfiles:!0},suggestedModels:["claude-fable-5","claude-opus-5","claude-sonnet-5","claude-haiku-4-5-20251001"],experimental:!1},{id:"codex",displayName:"OpenAI Codex CLI (experimental)",capabilities:{readOnlyJail:!0,editNoShellJail:!1,sessionResume:!1,costReporting:!1,modelSelection:!0,loginProfiles:!1},suggestedModels:[],experimental:!0}];h.DEFAULT_AGENT_ID="claude-code";h.REQUIRED_AGENT_CAPABILITIES={plan_only:["readOnlyJail","sessionResume"],respond:["readOnlyJail"],implement:["editNoShellJail","sessionResume"],deploy:[],chat:["readOnlyJail","sessionResume"],assist:["readOnlyJail"]};function vg(t,e){let n=h.REGISTERED_AGENTS.find(r=>r.id===t);return n?(h.REQUIRED_AGENT_CAPABILITIES[e]??[]).filter(r=>!n.capabilities[r]):null}h.BRANCH_DEPLOY_ISSUE_KEY="(branch deploy)";h.NEEDS_INPUT_MARKER="NEEDS-INPUT";h.NEEDS_INPUT_ASK_FENCE="ask";h.NEEDS_INPUT_LABEL="agent-needs-input";h.NEEDS_INPUT_COMMENT_MARKER="Allwright needs your input";h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=["TicketPilot needs your input"];var wg=t=>t.includes(h.NEEDS_INPUT_COMMENT_MARKER)||h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS.some(e=>t.includes(e));h.needsInputMarkerIn=wg;h.RunStatus=a.z.enum(["queued","running","posting","awaiting_approval","needs_input","succeeded","failed","timed_out"]);h.ACTIVE_RUN_STATUSES=["queued","running","posting","awaiting_approval"];h.TriggerType=a.z.enum(["label_added","comment_keyword","status_changed"]);h.ActionType=a.z.enum(["plan_only","implement","respond","deploy"]);h.LabelAddedTrigger=a.z.object({type:a.z.literal("label_added"),label:a.z.string().min(1),doneLabel:a.z.string().min(1).default("agent-planned"),failedLabel:a.z.string().min(1).default("agent-failed")});h.CommentKeywordTrigger=a.z.object({type:a.z.literal("comment_keyword"),keyword:a.z.string().min(1),doneLabel:a.z.string().min(1).default("agent-implemented"),failedLabel:a.z.string().min(1).default("agent-failed")});h.StatusChangedTrigger=a.z.object({type:a.z.literal("status_changed"),status:a.z.string().min(1),doneLabel:a.z.string().min(1).default("agent-deployed"),failedLabel:a.z.string().min(1).default("agent-failed")});h.TriggerConfig=a.z.discriminatedUnion("type",[h.LabelAddedTrigger,h.CommentKeywordTrigger,h.StatusChangedTrigger]);h.PlanOnlyAction=a.z.object({type:a.z.literal("plan_only"),promptTemplate:a.z.string().min(1),timeoutSeconds:a.z.number().int().positive().max(3600).default(900),agent:a.z.string().default(h.DEFAULT_AGENT_ID),model:a.z.string().default("")});h.ImplementAction=a.z.object({type:a.z.literal("implement"),promptTemplate:a.z.string().min(1),timeoutSeconds:a.z.number().int().positive().max(7200).default(1800),maxTurns:a.z.number().int().positive().max(500).default(120),requireApproval:a.z.boolean().default(!0),branchTemplate:a.z.string().min(1).default("agent/{{issueKey}}").refine(t=>t.includes("{{issueKey}}"),{message:"branchTemplate must contain {{issueKey}}"}),baseBranch:a.z.string().min(1).default("main"),jiraTransition:a.z.string().optional(),jiraTransitionOnStart:a.z.string().optional(),jiraTransitionOnMerge:a.z.string().optional(),agent:a.z.string().default(h.DEFAULT_AGENT_ID),model:a.z.string().default(""),updateMemory:a.z.boolean().default(!1),writeTests:a.z.boolean().default(!0),runTests:a.z.boolean().default(!0),mergeOnApprove:a.z.boolean().default(!0),mergeMethod:a.z.enum(["squash","merge","rebase"]).default("squash"),autoMerge:a.z.boolean().default(!0)});h.RespondAction=a.z.object({type:a.z.literal("respond"),promptTemplate:a.z.string().min(1),timeoutSeconds:a.z.number().int().positive().max(3600).default(600),agent:a.z.string().default(h.DEFAULT_AGENT_ID),model:a.z.string().default("")});h.DeployStep=a.z.object({name:a.z.string().min(1).max(120),run:a.z.string().min(1).max(4e3),continueOnError:a.z.boolean().default(!1)});h.PromotionMode=a.z.enum(["deploy_only","merge_and_deploy"]);h.EnvironmentConfig=a.z.object({id:a.z.string(),projectId:a.z.string(),name:a.z.string(),rank:a.z.number().int().nonnegative(),auditBeforeDeploy:a.z.enum(["","security","testing"]).default(""),branch:a.z.string().default(""),publicUrl:a.z.string().default(""),useDedicatedCheckout:a.z.boolean().default(!1),promotionMode:h.PromotionMode.default("deploy_only"),ticketBranchTemplate:a.z.string().default("agent/{{issueKey}}"),steps:a.z.array(h.DeployStep).default([]),workdir:a.z.string().default(""),timeoutSeconds:a.z.number().int().positive().max(21600).default(1800),requiredSecrets:a.z.array(a.z.string()).default([]),requireApproval:a.z.boolean().default(!1),requireSyncCheck:a.z.boolean().default(!1),previousEnvBranch:a.z.string().optional(),deployFromColumn:a.z.string().default(""),deployToColumn:a.z.string().default("")});h.DeployAction=a.z.object({type:a.z.literal("deploy"),envSelection:a.z.enum(["fixed","from_comment"]).default("from_comment"),environmentId:a.z.string().optional(),requireStatus:a.z.string().optional()});h.ActionConfig=a.z.discriminatedUnion("type",[h.PlanOnlyAction,h.ImplementAction,h.RespondAction,h.DeployAction]);h.ProjectConfig=a.z.object({id:a.z.string(),name:a.z.string(),jiraProjectKey:a.z.string(),goLiveIssueKey:a.z.string().default(""),repoName:a.z.string(),jiraSiteUrl:a.z.string().default(""),defaultAgent:a.z.string().default("claude-code"),componentRoutes:a.z.array(a.z.object({component:a.z.string().min(1),repoName:a.z.string().min(1)})).default([])});h.RuleConfig=a.z.object({id:a.z.string(),projectId:a.z.string(),name:a.z.string(),enabled:a.z.boolean(),trigger:h.TriggerConfig,action:h.ActionConfig});h.HelloMsg=a.z.object({type:a.z.literal("hello"),protocolVersion:a.z.string(),runnerVersion:a.z.string(),platform:a.z.string(),justBooted:a.z.boolean().optional()});h.HeartbeatMsg=a.z.object({type:a.z.literal("heartbeat"),ts:a.z.string()});h.RunClaimMsg=a.z.object({type:a.z.literal("run.claim"),requestId:a.z.string(),ruleId:a.z.string(),issueKey:a.z.string(),issueSummary:a.z.string().default(""),triggerFingerprint:a.z.string(),dedupKey:a.z.string().optional(),triggeredByAccountId:a.z.string().optional()});h.RunLogMsg=a.z.object({type:a.z.literal("run.log"),runId:a.z.string(),seq:a.z.number().int().nonnegative(),ts:a.z.string(),level:a.z.enum(["info","warn","error","agent"]),message:a.z.string().max(16384)});h.RunUsageMsg=a.z.object({type:a.z.literal("run.usage"),runId:a.z.string(),inputTokens:a.z.number().int().nonnegative(),outputTokens:a.z.number().int().nonnegative(),cacheReadTokens:a.z.number().int().nonnegative().optional(),costUsd:a.z.number().nonnegative().optional(),turns:a.z.number().int().nonnegative().optional()});h.FailedTest=a.z.object({command:a.z.string().max(500),exitCode:a.z.number().int(),tail:a.z.string().max(4e3)});h.RunStatusMsg=a.z.object({type:a.z.literal("run.status"),runId:a.z.string(),status:h.RunStatus,error:a.z.string().optional(),errorKind:a.z.enum(["guard"]).optional(),costUsd:a.z.number().nonnegative().optional(),inputTokens:a.z.number().int().nonnegative().optional(),outputTokens:a.z.number().int().nonnegative().optional(),resultSummary:a.z.string().max(2e3).optional(),billingMode:a.z.enum(["subscription","api","unknown"]).optional(),model:a.z.string().max(200).optional(),prUrl:a.z.string().optional(),headSha:a.z.string().optional(),deployedRef:a.z.string().optional(),retryAvailable:a.z.boolean().optional(),failedTests:a.z.array(h.FailedTest).max(20).optional(),testsPassed:a.z.number().int().nonnegative().optional(),testsTotal:a.z.number().int().nonnegative().optional(),manualSteps:a.z.array(a.z.object({command:a.z.string().max(500),why:a.z.string().max(300).default("")})).max(20).optional(),goLiveDraft:a.z.string().max(4e3).optional(),inputQuestions:a.z.string().max(4e3).optional(),inputOptions:a.z.array(a.z.string().max(200)).max(5).optional()});h.ProjectTestResultMsg=a.z.object({type:a.z.literal("project.test.result"),requestId:a.z.string(),ok:a.z.boolean(),checks:a.z.array(a.z.object({name:a.z.string(),ok:a.z.boolean(),detail:a.z.string(),kind:a.z.enum(["connection","content"]).default("connection"),fix:a.z.array(a.z.string()).default([]),fixNote:a.z.string().default("")}))});h.RuleDiagnoseResultMsg=a.z.object({type:a.z.literal("rule.diagnose.result"),requestId:a.z.string(),checks:a.z.array(a.z.object({name:a.z.string(),ok:a.z.boolean(),detail:a.z.string(),kind:a.z.enum(["connection","content"]).default("connection"),fix:a.z.array(a.z.string()).default([]),fixNote:a.z.string().default("")})),matchedCount:a.z.number().int().nonnegative(),excludedCount:a.z.number().int().nonnegative(),excludedSample:a.z.array(a.z.string()).max(5)});h.DeployClaimMsg=a.z.object({type:a.z.literal("deploy.claim"),requestId:a.z.string(),projectId:a.z.string(),ruleId:a.z.string(),issueKey:a.z.string(),issueSummary:a.z.string().default(""),environmentName:a.z.string(),requestedByAccountId:a.z.string().optional(),requestedByDisplayName:a.z.string().default(""),dedupKey:a.z.string(),triggerFingerprint:a.z.string()});h.DeployClaimResultMsg=a.z.object({type:a.z.literal("deploy.claim.result"),requestId:a.z.string(),accepted:a.z.boolean(),runId:a.z.string().optional(),environment:h.EnvironmentConfig.optional(),reason:a.z.string().optional(),code:a.z.enum(["ok","duplicate","unknown_environment","not_permitted","unlinked_jira_account","promotion_order","jira_disabled","rule_disabled","cap"]).optional()});h.JiraUsersResultMsg=a.z.object({type:a.z.literal("jira.users.result"),requestId:a.z.string(),ok:a.z.boolean(),users:a.z.array(a.z.object({accountId:a.z.string(),displayName:a.z.string(),email:a.z.string().default(""),active:a.z.boolean().default(!0)})).default([]),error:a.z.string().optional()});h.ChatStreamMsg=a.z.object({type:a.z.literal("chat.stream"),requestId:a.z.string(),seq:a.z.number().int().nonnegative(),text:a.z.string().max(8e3)});h.ChatUsageMsg=a.z.object({type:a.z.literal("chat.usage"),requestId:a.z.string(),inputTokens:a.z.number().int().nonnegative(),outputTokens:a.z.number().int().nonnegative(),cacheReadTokens:a.z.number().int().nonnegative().optional(),turns:a.z.number().int().nonnegative().optional()});h.ChatListMsg=a.z.object({type:a.z.literal("chat.list"),requestId:a.z.string(),projectId:a.z.string()});h.ChatListResultMsg=a.z.object({type:a.z.literal("chat.list.result"),requestId:a.z.string(),sessions:a.z.array(a.z.object({sessionId:a.z.string(),title:a.z.string().default(""),updatedAt:a.z.string().default(""),messageCount:a.z.number().int().nonnegative().default(0)})).default([])});h.ChatLoadMsg=a.z.object({type:a.z.literal("chat.load"),requestId:a.z.string(),sessionId:a.z.string()});h.BUILTIN_REPLY_LANGUAGES=[{name:"English",instruction:"Write your prose in English."},{name:"Hindi",instruction:"Write your prose in Hindi, in the Devanagari script. Keep technical terms that have no everyday Hindi equivalent in English rather than inventing a translation."},{name:"Hinglish",instruction:"Write your prose in Hinglish: conversational Hindi written in the Latin alphabet, with English technical words left in English - the way an Indian developer talks at work."}];h.REPLY_STYLES=[{id:"technical",label:"Technical",hint:"Full detail - names files, functions and trade-offs",instruction:"Answer at full technical depth: name the files, functions and data structures involved, and state trade-offs precisely. Assume the reader reads code every day."},{id:"balanced",label:"Balanced",hint:"Plain explanation, with the technical detail that matters",instruction:"Explain in plain language first, then add the technical detail that actually matters for the decision. Assume the reader is technical but does not know this codebase."},{id:"simple",label:"Simple",hint:"Everyday words - no jargon unless it is unavoidable",instruction:"Answer in everyday words, as if to someone who does not write code. Avoid jargon; when a technical term is unavoidable, explain it in half a sentence. Prefer short paragraphs and concrete examples over precision about internals."}];function _g(t){let e=[],n=(t.language??"").trim();if(n){let s=h.BUILTIN_REPLY_LANGUAGES.find(i=>i.name.toLowerCase()===n.toLowerCase());e.push((t.languageInstruction??"").trim()||s?.instruction||`Write your prose in ${n}.`),e.push("Code, file paths, identifiers, commands, error text and log output stay exactly as they are - only your own prose changes language."),e.push("The ```ticket block is the exception: its summary and description are ALWAYS written in English, because the ticket is read by other people and by the implementing agent.")}let r=h.REPLY_STYLES.find(s=>s.id===(t.style??"").trim());return r&&e.push(r.instruction),e.length?`
|
|
24
24
|
|
|
25
25
|
HOW TO WRITE THE REPLY - the person you are answering chose this, so it applies to every reply in this conversation:
|
|
26
26
|
- ${e.join(`
|
|
@@ -34,7 +34,7 @@ These files are checked in but NOT applied to the database this control plane ru
|
|
|
34
34
|
${e}action
|
|
35
35
|
{"type": "apply-migration", "file": "<one filename from the list above>"}
|
|
36
36
|
${e}
|
|
37
|
-
That is the only action block that exists - there is no free-form command form of it. Never mention the block itself in your prose.`}h.ChatLoadResultMsg=a.z.object({type:a.z.literal("chat.load.result"),requestId:a.z.string(),ok:a.z.boolean(),projectId:a.z.string().default(""),messages:a.z.array(a.z.object({role:a.z.enum(["user","agent"]),text:a.z.string(),steps:a.z.array(a.z.string()).default([]),files:a.z.array(a.z.string()).default([])})).default([]),error:a.z.string().optional()});h.RepoDocsMsg=a.z.object({type:a.z.literal("repo.docs"),requestId:a.z.string(),projectId:a.z.string()});h.RepoDocsResultMsg=a.z.object({type:a.z.literal("repo.docs.result"),requestId:a.z.string(),ok:a.z.boolean(),docs:a.z.array(a.z.object({path:a.z.string(),sizeBytes:a.z.number().int().nonnegative().default(0),updatedAt:a.z.string().default("")})).default([]),error:a.z.string().optional()});h.RepoDocReadMsg=a.z.object({type:a.z.literal("repo.doc.read"),requestId:a.z.string(),projectId:a.z.string(),path:a.z.string().max(400)});h.RepoDocReadResultMsg=a.z.object({type:a.z.literal("repo.doc.read.result"),requestId:a.z.string(),ok:a.z.boolean(),path:a.z.string().default(""),content:a.z.string().default(""),truncated:a.z.boolean().default(!1),error:a.z.string().optional()});h.BoardFetchMsg=a.z.object({type:a.z.literal("board.fetch"),requestId:a.z.string(),projectId:a.z.string()});h.BoardFetchResultMsg=a.z.object({type:a.z.literal("board.fetch.result"),requestId:a.z.string(),ok:a.z.boolean(),browseBaseUrl:a.z.string().default(""),columns:a.z.array(a.z.object({name:a.z.string(),issues:a.z.array(a.z.object({key:a.z.string(),summary:a.z.string(),labels:a.z.array(a.z.string()).default([])})).default([])})).default([]),error:a.z.string().optional()});h.BoardTriggerMsg=a.z.object({type:a.z.literal("board.trigger"),requestId:a.z.string(),projectId:a.z.string(),issueKey:a.z.string(),comment:a.z.string().max(2e3).default(""),removeLabel:a.z.string().default(""),requestedBy:a.z.string().default(""),requestedByEmail:a.z.string().default(""),reimplement:a.z.boolean().default(!1)});h.BoardTriggerResultMsg=a.z.object({type:a.z.literal("board.trigger.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional()});h.EpicListMsg=a.z.object({type:a.z.literal("epic.list"),requestId:a.z.string(),projectId:a.z.string(),epicKey:a.z.string().default("")});h.EpicChild=a.z.object({key:a.z.string(),summary:a.z.string(),status:a.z.string(),statusCategory:a.z.string(),labels:a.z.array(a.z.string()).default([])});h.EpicListResultMsg=a.z.object({type:a.z.literal("epic.list.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),epics:a.z.array(a.z.object({key:a.z.string(),summary:a.z.string(),status:a.z.string()})).default([]),children:a.z.array(h.EpicChild).default([])});h.EpicSuggestMsg=a.z.object({type:a.z.literal("epic.suggest"),requestId:a.z.string(),projectId:a.z.string(),epicKey:a.z.string().min(1),model:a.z.string().default("")});h.EpicSuggestResultMsg=a.z.object({type:a.z.literal("epic.suggest.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),issueKey:a.z.string().default(""),reason:a.z.string().default(""),considered:a.z.number().int().default(0)});h.AuditRole=a.z.enum(["security","testing","architecture"]);h.KnowledgeRole=a.z.enum(["security","testing","architecture","implement"]);h.AuditSeverity=a.z.enum(["critical","high","medium","low","info"]);h.AuditScope=a.z.object({kind:a.z.enum(["repo","ticket","branch"]).default("repo"),ref:a.z.string().default("")});h.AuditDetailLevel=a.z.enum(["simple","technical"]);h.AuditFinding=a.z.object({id:a.z.string().min(1),title:a.z.string().min(1),ruleId:a.z.string().max(20).default(""),severity:h.AuditSeverity,area:a.z.string().default(""),evidence:a.z.array(a.z.object({file:a.z.string().min(1),line:a.z.number().int().positive().optional(),note:a.z.string().default("")})).min(1),fix:a.z.string().default("")});h.AuditRecord=a.z.object({id:a.z.string(),role:h.AuditRole,createdAt:a.z.string(),model:a.z.string().default(""),summary:a.z.string().default(""),packNames:a.z.array(a.z.string()).default([]),findings:a.z.array(h.AuditFinding).default([]),costUsd:a.z.number().default(0),review:a.z.object({selected:a.z.array(a.z.string()),updatedAt:a.z.string()}).optional(),verdicts:a.z.record(a.z.object({verdict:a.z.enum(["valid","false-positive","wont-fix"]),note:a.z.string().default(""),by:a.z.string().default(""),at:a.z.string().default("")})).default({}),lessonsWritten:a.z.array(a.z.string()).default([]),ticketed:a.z.record(a.z.string()).default({}),scope:h.AuditScope.default({kind:"repo",ref:""}),detailLevel:h.AuditDetailLevel.default("technical"),testRun:a.z.array(a.z.object({command:a.z.string(),exitCode:a.z.number().int(),durationMs:a.z.number().int().default(0),tail:a.z.string().default("")})).optional()});h.AuditStartMsg=a.z.object({type:a.z.literal("audit.start"),requestId:a.z.string(),projectId:a.z.string(),role:h.AuditRole,model:a.z.string().default(""),scope:h.AuditScope.default({kind:"repo",ref:""}),detailLevel:h.AuditDetailLevel.default("technical")});h.AuditStartResultMsg=a.z.object({type:a.z.literal("audit.start.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),audit:h.AuditRecord.optional()});h.AuditListMsg=a.z.object({type:a.z.literal("audit.list"),requestId:a.z.string(),projectId:a.z.string()});h.AuditStatsMsg=a.z.object({type:a.z.literal("audit.stats"),requestId:a.z.string(),projectIds:a.z.array(a.z.string()).max(200).default([]),since:a.z.string().default("")});h.AuditStatsResultMsg=a.z.object({type:a.z.literal("audit.stats.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),byProject:a.z.record(a.z.object({audits:a.z.number().int().default(0),findings:a.z.number().int().default(0),valid:a.z.number().int().default(0),falsePositive:a.z.number().int().default(0),wontFix:a.z.number().int().default(0),unreviewed:a.z.number().int().default(0)})).default({})});h.AuditListResultMsg=a.z.object({type:a.z.literal("audit.list.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),audits:a.z.array(a.z.object({id:a.z.string(),role:h.AuditRole,createdAt:a.z.string(),findingCount:a.z.number().int(),bySeverity:a.z.record(a.z.number().int()).default({}),detailLevel:h.AuditDetailLevel.default("technical")})).default([])});h.AuditGetMsg=a.z.object({type:a.z.literal("audit.get"),requestId:a.z.string(),projectId:a.z.string(),auditId:a.z.string()});h.AuditGetResultMsg=a.z.object({type:a.z.literal("audit.get.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),audit:h.AuditRecord.optional()});h.AuditReviewMsg=a.z.object({type:a.z.literal("audit.review"),requestId:a.z.string(),projectId:a.z.string(),auditId:a.z.string(),selected:a.z.array(a.z.string()).optional(),ticketed:a.z.array(a.z.object({findingId:a.z.string(),issueKey:a.z.string()})).default([]),verdicts:a.z.array(a.z.object({findingId:a.z.string(),verdict:a.z.enum(["valid","false-positive","wont-fix"]),note:a.z.string().max(2e3).default("")})).default([]),verdictBy:a.z.string().default("")});h.AuditReviewResultMsg=a.z.object({type:a.z.literal("audit.review.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),audit:h.AuditRecord.optional()});h.KnowledgeListMsg=a.z.object({type:a.z.literal("knowledge.list"),requestId:a.z.string(),projectId:a.z.string()});h.KnowledgeFile=a.z.object({role:h.KnowledgeRole,level:a.z.enum(["global","org","project"]),source:a.z.enum(["pack","lessons","memory"]),name:a.z.string(),content:a.z.string(),editable:a.z.boolean().default(!1)});h.KnowledgeListResultMsg=a.z.object({type:a.z.literal("knowledge.list.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),files:a.z.array(h.KnowledgeFile).default([])});h.KnowledgeSaveMsg=a.z.object({type:a.z.literal("knowledge.save"),requestId:a.z.string(),projectId:a.z.string(),role:h.KnowledgeRole,level:a.z.enum(["org","project"]),source:a.z.enum(["pack","lessons"]),name:a.z.string().min(1).max(100),content:a.z.string().max(6e4),append:a.z.boolean().default(!1),by:a.z.string().default("")});h.KnowledgeSaveResultMsg=a.z.object({type:a.z.literal("knowledge.save.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional()});h.TeamCredsMsg=a.z.object({type:a.z.literal("team.creds"),requestId:a.z.string(),emails:a.z.array(a.z.string()).max(200)});h.TeamCredsResultMsg=a.z.object({type:a.z.literal("team.creds.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),githubShared:a.z.boolean().default(!1),sharedGithubLogin:a.z.string().default(""),entries:a.z.array(a.z.object({email:a.z.string(),jira:a.z.enum(["own","runner-account","missing"]),jiraAs:a.z.string().default(""),github:a.z.enum(["own","shared","missing"]),githubAs:a.z.string().default("")})).default([])});h.ChatFile=a.z.object({name:a.z.string().min(1).max(255),contentBase64:a.z.string().min(1).max(6e6)});h.ChatTurnMsg=a.z.object({type:a.z.literal("chat.turn"),requestId:a.z.string(),projectId:a.z.string(),sessionId:a.z.string().optional(),message:a.z.string().min(1).max(2e4),userName:a.z.string().default(""),model:a.z.string().default(""),files:a.z.array(h.ChatFile).max(8).default([]),replyLanguage:a.z.string().max(60).default(""),replyLanguageInstruction:a.z.string().max(600).default(""),replyStyle:a.z.string().max(30).default(""),pendingMigrations:a.z.array(a.z.string().max(200)).max(50).default([])});h.ChatTurnResultMsg=a.z.object({type:a.z.literal("chat.turn.result"),requestId:a.z.string(),ok:a.z.boolean(),sessionId:a.z.string().default(""),reply:a.z.string().default(""),error:a.z.string().optional(),inputTokens:a.z.number().int().nonnegative().default(0),outputTokens:a.z.number().int().nonnegative().default(0),cacheReadTokens:a.z.number().int().nonnegative().default(0),costUsd:a.z.number().nonnegative().default(0),model:a.z.string().max(200).default(""),contextTokens:a.z.number().int().nonnegative().default(0),contextLimit:a.z.number().int().nonnegative().default(0),compacted:a.z.boolean().default(!1),compactedMessages:a.z.number().int().nonnegative().default(0)});h.ChatCreateTicketMsg=a.z.object({type:a.z.literal("chat.create.ticket"),requestId:a.z.string(),projectId:a.z.string(),summary:a.z.string().min(1).max(250),description:a.z.string().default(""),triggerComment:a.z.string().default(""),requestedBy:a.z.string().default(""),requestedByEmail:a.z.string().default(""),asEpic:a.z.boolean().default(!1),children:a.z.array(a.z.object({summary:a.z.string().min(1),description:a.z.string().default("")})).max(20).default([]),createAs:a.z.enum(["epic_with_children","separate_epics","separate_tasks"]).default("epic_with_children"),files:a.z.array(h.ChatFile).max(8).default([])});h.ChatCreateTicketResultMsg=a.z.object({type:a.z.literal("chat.create.ticket.result"),requestId:a.z.string(),ok:a.z.boolean(),issueKey:a.z.string().default(""),error:a.z.string().optional(),childKeys:a.z.array(a.z.string()).default([])});h.EnvPreflightMsg=a.z.object({type:a.z.literal("env.preflight"),requestId:a.z.string(),projectId:a.z.string(),environmentName:a.z.string().default(""),steps:a.z.array(h.DeployStep).default([]),requiredSecrets:a.z.array(a.z.string()).default([]),workdir:a.z.string().default(""),branch:a.z.string().default(""),publicUrl:a.z.string().default("")});h.EnvPreflightResultMsg=a.z.object({type:a.z.literal("env.preflight.result"),requestId:a.z.string(),ok:a.z.boolean(),checks:a.z.array(a.z.object({name:a.z.string(),ok:a.z.boolean(),detail:a.z.string().default(""),kind:a.z.enum(["connection","content"]).default("connection"),fix:a.z.array(a.z.string()).default([]),fixNote:a.z.string().default("")})).default([])});h.SELF_MIGRATION_DIR="apps/api/prisma/manual";function Sg(t){return/^[A-Za-z0-9][A-Za-z0-9._-]*\.sql$/.test(t)&&!t.includes("..")}h.SelfMigrationApplyMsg=a.z.object({type:a.z.literal("selfmigration.apply"),requestId:a.z.string(),projectId:a.z.string(),environmentName:a.z.string().default(""),file:a.z.string(),urlSecret:a.z.string().default("DATABASE_URL")});h.SelfMigrationApplyResultMsg=a.z.object({type:a.z.literal("selfmigration.apply.result"),requestId:a.z.string(),ok:a.z.boolean(),file:a.z.string().default(""),checks:a.z.array(a.z.object({name:a.z.string(),ok:a.z.boolean(),detail:a.z.string().default(""),fix:a.z.array(a.z.string()).default([])})).default([]),output:a.z.string().max(2e4).default(""),error:a.z.string().default("")});h.DeploySuggestResultMsg=a.z.object({type:a.z.literal("deploy.suggest.result"),requestId:a.z.string(),ok:a.z.boolean(),steps:a.z.array(h.DeployStep).default([]),requiredSecrets:a.z.array(a.z.string()).default([]),notes:a.z.string().default(""),error:a.z.string().optional(),docPath:a.z.string().default(""),docContent:a.z.string().max(1e5).default("")});h.SetupStatusMsg=a.z.object({type:a.z.literal("setup.status"),requestId:a.z.string(),repoNames:a.z.array(a.z.string()).max(100).default([])});h.SetupStatusResultMsg=a.z.object({type:a.z.literal("setup.status.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),jiraConfigured:a.z.boolean().default(!1),jiraEmail:a.z.string().default(""),claude:a.z.object({installed:a.z.boolean(),version:a.z.string().default(""),loggedIn:a.z.boolean()}).optional(),githubTokenSet:a.z.boolean().default(!1),githubLogin:a.z.string().default(""),deploysEnabled:a.z.boolean().default(!1),jiraUserCount:a.z.number().int().default(0),repos:a.z.array(a.z.object({repoName:a.z.string(),mapped:a.z.boolean(),pathExists:a.z.boolean().default(!1),isGit:a.z.boolean().default(!1),claudeMd:a.z.boolean().default(!1),deployMd:a.z.boolean().default(!1),testMd:a.z.boolean().default(!1),defaultBranch:a.z.string().default(""),githubToken:a.z.boolean().default(!1),githubTokenOwn:a.z.boolean().default(!1)})).default([])});h.SetupClaudeMdGenerateMsg=a.z.object({type:a.z.literal("setup.claudemd.generate"),requestId:a.z.string(),projectId:a.z.string(),kind:a.z.enum(["claude","deploy","design"]).default("claude"),streamId:a.z.string().default("")});h.SetupClaudeMdGenerateResultMsg=a.z.object({type:a.z.literal("setup.claudemd.generate.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),content:a.z.string().default("")});h.SetupClaudeMdSaveMsg=a.z.object({type:a.z.literal("setup.claudemd.save"),requestId:a.z.string(),projectId:a.z.string(),kind:a.z.enum(["claude","deploy","design"]).default("claude"),overwrite:a.z.boolean().default(!1),content:a.z.string().max(1e5)});h.SetupClaudeMdSaveResultMsg=a.z.object({type:a.z.literal("setup.claudemd.save.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),note:a.z.string().default("")});h.RepoDocSaveMsg=a.z.object({type:a.z.literal("repo.doc.save"),requestId:a.z.string(),projectId:a.z.string(),relPath:a.z.string().min(1).max(200),overwrite:a.z.boolean().default(!1),content:a.z.string().max(2e5)});h.RepoDocSaveResultMsg=a.z.object({type:a.z.literal("repo.doc.save.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),note:a.z.string().default("")});h.RunnerUpdateMsg=a.z.object({type:a.z.literal("runner.update"),requestId:a.z.string()});h.RunResolveConflictMsg=a.z.object({type:a.z.literal("run.resolve.conflict"),requestId:a.z.string(),runId:a.z.string()});h.RunTestFixMsg=a.z.object({type:a.z.literal("run.testfix"),requestId:a.z.string(),runId:a.z.string(),failedTests:a.z.array(h.FailedTest).min(1).max(20)});h.RunTestFixResultMsg=a.z.object({type:a.z.literal("run.testfix.result"),requestId:a.z.string(),ok:a.z.boolean(),note:a.z.string().default(""),headSha:a.z.string().default(""),remaining:a.z.array(h.FailedTest).default([]),costUsd:a.z.number().nonnegative().optional(),inputTokens:a.z.number().int().nonnegative().optional(),outputTokens:a.z.number().int().nonnegative().optional()});h.RunAnswerMsg=a.z.object({type:a.z.literal("run.answer"),requestId:a.z.string(),runId:a.z.string(),text:a.z.string().min(1).max(4e3),answeredBy:a.z.string().default("")});h.RunAnswerResultMsg=a.z.object({type:a.z.literal("run.answer.result"),requestId:a.z.string(),ok:a.z.boolean(),note:a.z.string().default(""),error:a.z.string().optional()});h.RunResolveConflictResultMsg=a.z.object({type:a.z.literal("run.resolve.conflict.result"),requestId:a.z.string(),ok:a.z.boolean(),note:a.z.string().default(""),freeOfCharge:a.z.boolean().default(!1),headSha:a.z.string().default(""),costUsd:a.z.number().nonnegative().optional(),inputTokens:a.z.number().int().nonnegative().optional(),outputTokens:a.z.number().int().nonnegative().optional()});h.RunPrConflictMsg=a.z.object({type:a.z.literal("run.pr.conflict"),runId:a.z.string(),conflicted:a.z.boolean()});h.AgentProfilesMsg=a.z.object({type:a.z.literal("agent.profiles"),requestId:a.z.string()});h.AgentProfilesResultMsg=a.z.object({type:a.z.literal("agent.profiles.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),profiles:a.z.array(a.z.object({agent:a.z.string(),name:a.z.string(),loggedIn:a.z.boolean()})).max(200).default([]),defaultLoggedIn:a.z.boolean().default(!1),agentsWithoutProfiles:a.z.array(a.z.string()).max(20).default([])});h.RunnerUpdateResultMsg=a.z.object({type:a.z.literal("runner.update.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),note:a.z.string().default(""),scheduled:a.z.boolean().default(!1)});h.AutopilotNextMsg=a.z.object({type:a.z.literal("autopilot.next"),requestId:a.z.string()});h.AutopilotNextResultMsg=a.z.object({type:a.z.literal("autopilot.next.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),item:a.z.object({id:a.z.string(),projectId:a.z.string(),issueKey:a.z.string(),ruleId:a.z.string(),baseOverride:a.z.string().default(""),branchOverride:a.z.string().default(""),continueBranch:a.z.boolean().default(!1),autoMerge:a.z.boolean().default(!1)}).nullable().default(null),pausedUntil:a.z.string().default("")});h.AutopilotReportMsg=a.z.object({type:a.z.literal("autopilot.report"),requestId:a.z.string(),itemId:a.z.string(),outcome:a.z.enum(["claimed","failed","paused"]),runId:a.z.string().default(""),error:a.z.string().default("")});h.RunnerToServerMsg=a.z.discriminatedUnion("type",[h.HelloMsg,h.HeartbeatMsg,h.RunClaimMsg,h.RunLogMsg,h.RunUsageMsg,h.RunStatusMsg,h.ProjectTestResultMsg,h.RuleDiagnoseResultMsg,h.DeployClaimMsg,h.DeploySuggestResultMsg,h.EnvPreflightResultMsg,h.SelfMigrationApplyResultMsg,h.ChatTurnResultMsg,h.ChatStreamMsg,h.ChatUsageMsg,h.ChatCreateTicketResultMsg,h.ChatListResultMsg,h.RepoDocsResultMsg,h.RepoDocReadResultMsg,h.ChatLoadResultMsg,h.BoardFetchResultMsg,h.BoardTriggerResultMsg,h.TeamCredsResultMsg,h.AuditStartResultMsg,h.AuditListResultMsg,h.AuditGetResultMsg,h.AuditReviewResultMsg,h.KnowledgeListResultMsg,h.KnowledgeSaveResultMsg,h.EpicListResultMsg,h.EpicSuggestResultMsg,h.JiraUsersResultMsg,h.SetupStatusResultMsg,h.SetupClaudeMdGenerateResultMsg,h.SetupClaudeMdSaveResultMsg,h.RepoDocSaveResultMsg,h.RunnerUpdateResultMsg,h.AgentProfilesResultMsg,h.RunPrConflictMsg,h.RunResolveConflictResultMsg,h.RunTestFixResultMsg,h.RunAnswerResultMsg,h.AuditStatsResultMsg,h.AutopilotNextMsg,h.AutopilotReportMsg]);h.HelloAckMsg=a.z.object({type:a.z.literal("hello.ack"),runnerId:a.z.string(),runnerName:a.z.string(),serverTime:a.z.string()});h.ConfigMsg=a.z.object({type:a.z.literal("config"),projects:a.z.array(h.ProjectConfig),rules:a.z.array(h.RuleConfig),environments:a.z.array(h.EnvironmentConfig).default([]),pollingPaused:a.z.boolean().default(!1)});h.RunClaimResultMsg=a.z.object({type:a.z.literal("run.claim.result"),requestId:a.z.string(),accepted:a.z.boolean(),runId:a.z.string().optional(),reason:a.z.string().optional(),claudeProfile:a.z.string().optional(),actorEmail:a.z.string().optional()});h.ProjectTestMsg=a.z.object({type:a.z.literal("project.test"),requestId:a.z.string(),projectId:a.z.string()});h.RuleDiagnoseMsg=a.z.object({type:a.z.literal("rule.diagnose"),requestId:a.z.string(),ruleId:a.z.string()});h.RunCancelMsg=a.z.object({type:a.z.literal("run.cancel"),runId:a.z.string()});h.RunApprovedMsg=a.z.object({type:a.z.literal("run.approved"),runId:a.z.string(),headSha:a.z.string().optional()});h.RunRejectedMsg=a.z.object({type:a.z.literal("run.rejected"),runId:a.z.string()});h.RunRetryPushMsg=a.z.object({type:a.z.literal("run.retryPush"),runId:a.z.string()});h.DeployStartMsg=a.z.object({type:a.z.literal("deploy.start"),runId:a.z.string(),projectId:a.z.string(),issueKey:a.z.string(),issueSummary:a.z.string().default(""),environment:h.EnvironmentConfig,requestedBy:a.z.string().default(""),attempt:a.z.number().int().positive().default(1)});h.DeployFixMsg=a.z.object({type:a.z.literal("deploy.fix"),requestId:a.z.string(),projectId:a.z.string(),environmentName:a.z.string(),steps:a.z.array(a.z.object({name:a.z.string(),run:a.z.string(),continueOnError:a.z.boolean().default(!1)})),failedStep:a.z.string().default(""),errorText:a.z.string().max(8e3).default("")});h.DeploySuggestMsg=a.z.object({type:a.z.literal("deploy.suggest"),requestId:a.z.string(),projectId:a.z.string(),environmentName:a.z.string(),notes:a.z.string().default(""),timeoutSeconds:a.z.number().int().positive().max(1800).default(300)});h.JiraUsersMsg=a.z.object({type:a.z.literal("jira.users"),requestId:a.z.string(),query:a.z.string().default("")});h.ServerToRunnerMsg=a.z.discriminatedUnion("type",[h.HelloAckMsg,h.ConfigMsg,h.RunClaimResultMsg,h.ProjectTestMsg,h.RuleDiagnoseMsg,h.RunCancelMsg,h.RunApprovedMsg,h.RunRejectedMsg,h.RunRetryPushMsg,h.DeployClaimResultMsg,h.DeployStartMsg,h.DeploySuggestMsg,h.DeployFixMsg,h.EnvPreflightMsg,h.SelfMigrationApplyMsg,h.ChatTurnMsg,h.ChatCreateTicketMsg,h.ChatListMsg,h.RepoDocsMsg,h.RepoDocReadMsg,h.ChatLoadMsg,h.BoardFetchMsg,h.BoardTriggerMsg,h.TeamCredsMsg,h.AuditStartMsg,h.AuditListMsg,h.AuditGetMsg,h.AuditReviewMsg,h.KnowledgeListMsg,h.KnowledgeSaveMsg,h.EpicListMsg,h.EpicSuggestMsg,h.JiraUsersMsg,h.SetupStatusMsg,h.SetupClaudeMdGenerateMsg,h.SetupClaudeMdSaveMsg,h.RepoDocSaveMsg,h.RunnerUpdateMsg,h.AgentProfilesMsg,h.RunResolveConflictMsg,h.RunTestFixMsg,h.RunAnswerMsg,h.AuditStatsMsg,h.AutopilotNextResultMsg]);h.EnrollRequest=a.z.object({enrollToken:a.z.string().min(10),name:a.z.string().min(1).max(100),platform:a.z.string(),runnerVersion:a.z.string()});h.EnrollResponse=a.z.object({runnerId:a.z.string(),runnerToken:a.z.string(),controlPlaneWsUrl:a.z.string()});function Tg(t){return h.RunnerToServerMsg.parse(t)}function xg(t){return h.ServerToRunnerMsg.parse(t)}h.DEFAULT_PLAN_PROMPT_TEMPLATE=`You are a senior engineer asked to assess a Jira ticket. You have read-only access to the repository - do not attempt to modify anything.
|
|
37
|
+
That is the only action block that exists - there is no free-form command form of it. Never mention the block itself in your prose.`}h.ChatLoadResultMsg=a.z.object({type:a.z.literal("chat.load.result"),requestId:a.z.string(),ok:a.z.boolean(),projectId:a.z.string().default(""),messages:a.z.array(a.z.object({role:a.z.enum(["user","agent"]),text:a.z.string(),steps:a.z.array(a.z.string()).default([]),files:a.z.array(a.z.string()).default([])})).default([]),error:a.z.string().optional()});h.RepoDocsMsg=a.z.object({type:a.z.literal("repo.docs"),requestId:a.z.string(),projectId:a.z.string()});h.RepoDocsResultMsg=a.z.object({type:a.z.literal("repo.docs.result"),requestId:a.z.string(),ok:a.z.boolean(),docs:a.z.array(a.z.object({path:a.z.string(),sizeBytes:a.z.number().int().nonnegative().default(0),updatedAt:a.z.string().default("")})).default([]),error:a.z.string().optional()});h.RepoDocReadMsg=a.z.object({type:a.z.literal("repo.doc.read"),requestId:a.z.string(),projectId:a.z.string(),path:a.z.string().max(400)});h.RepoDocReadResultMsg=a.z.object({type:a.z.literal("repo.doc.read.result"),requestId:a.z.string(),ok:a.z.boolean(),path:a.z.string().default(""),content:a.z.string().default(""),truncated:a.z.boolean().default(!1),error:a.z.string().optional()});h.BoardFetchMsg=a.z.object({type:a.z.literal("board.fetch"),requestId:a.z.string(),projectId:a.z.string()});h.BoardFetchResultMsg=a.z.object({type:a.z.literal("board.fetch.result"),requestId:a.z.string(),ok:a.z.boolean(),browseBaseUrl:a.z.string().default(""),columns:a.z.array(a.z.object({name:a.z.string(),issues:a.z.array(a.z.object({key:a.z.string(),summary:a.z.string(),labels:a.z.array(a.z.string()).default([])})).default([])})).default([]),error:a.z.string().optional()});h.BoardTriggerMsg=a.z.object({type:a.z.literal("board.trigger"),requestId:a.z.string(),projectId:a.z.string(),issueKey:a.z.string(),comment:a.z.string().max(2e3).default(""),removeLabel:a.z.string().default(""),requestedBy:a.z.string().default(""),requestedByEmail:a.z.string().default(""),reimplement:a.z.boolean().default(!1)});h.BoardTriggerResultMsg=a.z.object({type:a.z.literal("board.trigger.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional()});h.EpicListMsg=a.z.object({type:a.z.literal("epic.list"),requestId:a.z.string(),projectId:a.z.string(),epicKey:a.z.string().default("")});h.EpicChild=a.z.object({key:a.z.string(),summary:a.z.string(),status:a.z.string(),statusCategory:a.z.string(),labels:a.z.array(a.z.string()).default([])});h.EpicListResultMsg=a.z.object({type:a.z.literal("epic.list.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),epics:a.z.array(a.z.object({key:a.z.string(),summary:a.z.string(),status:a.z.string()})).default([]),children:a.z.array(h.EpicChild).default([])});h.EpicSuggestMsg=a.z.object({type:a.z.literal("epic.suggest"),requestId:a.z.string(),projectId:a.z.string(),epicKey:a.z.string().min(1),model:a.z.string().default("")});h.EpicSuggestResultMsg=a.z.object({type:a.z.literal("epic.suggest.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),issueKey:a.z.string().default(""),reason:a.z.string().default(""),considered:a.z.number().int().default(0)});h.AuditRole=a.z.enum(["security","testing","architecture"]);h.KnowledgeRole=a.z.enum(["security","testing","architecture","implement"]);h.AuditSeverity=a.z.enum(["critical","high","medium","low","info"]);h.AuditScope=a.z.object({kind:a.z.enum(["repo","ticket","branch"]).default("repo"),ref:a.z.string().default("")});h.AuditDetailLevel=a.z.enum(["simple","technical"]);h.AuditFinding=a.z.object({id:a.z.string().min(1),title:a.z.string().min(1),ruleId:a.z.string().max(20).default(""),severity:h.AuditSeverity,area:a.z.string().default(""),evidence:a.z.array(a.z.object({file:a.z.string().min(1),line:a.z.number().int().positive().optional(),note:a.z.string().default("")})).min(1),fix:a.z.string().default("")});h.AuditRecord=a.z.object({id:a.z.string(),role:h.AuditRole,createdAt:a.z.string(),model:a.z.string().default(""),summary:a.z.string().default(""),packNames:a.z.array(a.z.string()).default([]),findings:a.z.array(h.AuditFinding).default([]),costUsd:a.z.number().default(0),review:a.z.object({selected:a.z.array(a.z.string()),updatedAt:a.z.string()}).optional(),verdicts:a.z.record(a.z.object({verdict:a.z.enum(["valid","false-positive","wont-fix"]),note:a.z.string().default(""),by:a.z.string().default(""),at:a.z.string().default("")})).default({}),lessonsWritten:a.z.array(a.z.string()).default([]),ticketed:a.z.record(a.z.string()).default({}),scope:h.AuditScope.default({kind:"repo",ref:""}),detailLevel:h.AuditDetailLevel.default("technical"),testRun:a.z.array(a.z.object({command:a.z.string(),exitCode:a.z.number().int(),durationMs:a.z.number().int().default(0),tail:a.z.string().default("")})).optional()});h.AuditStartMsg=a.z.object({type:a.z.literal("audit.start"),requestId:a.z.string(),projectId:a.z.string(),role:h.AuditRole,model:a.z.string().default(""),scope:h.AuditScope.default({kind:"repo",ref:""}),detailLevel:h.AuditDetailLevel.default("technical")});h.AuditStartResultMsg=a.z.object({type:a.z.literal("audit.start.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),audit:h.AuditRecord.optional()});h.AuditListMsg=a.z.object({type:a.z.literal("audit.list"),requestId:a.z.string(),projectId:a.z.string()});h.AuditStatsMsg=a.z.object({type:a.z.literal("audit.stats"),requestId:a.z.string(),projectIds:a.z.array(a.z.string()).max(200).default([]),since:a.z.string().default("")});h.AuditStatsResultMsg=a.z.object({type:a.z.literal("audit.stats.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),byProject:a.z.record(a.z.object({audits:a.z.number().int().default(0),findings:a.z.number().int().default(0),valid:a.z.number().int().default(0),falsePositive:a.z.number().int().default(0),wontFix:a.z.number().int().default(0),unreviewed:a.z.number().int().default(0)})).default({})});h.AuditListResultMsg=a.z.object({type:a.z.literal("audit.list.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),audits:a.z.array(a.z.object({id:a.z.string(),role:h.AuditRole,createdAt:a.z.string(),findingCount:a.z.number().int(),bySeverity:a.z.record(a.z.number().int()).default({}),detailLevel:h.AuditDetailLevel.default("technical")})).default([])});h.AuditGetMsg=a.z.object({type:a.z.literal("audit.get"),requestId:a.z.string(),projectId:a.z.string(),auditId:a.z.string()});h.AuditGetResultMsg=a.z.object({type:a.z.literal("audit.get.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),audit:h.AuditRecord.optional()});h.AuditReviewMsg=a.z.object({type:a.z.literal("audit.review"),requestId:a.z.string(),projectId:a.z.string(),auditId:a.z.string(),selected:a.z.array(a.z.string()).optional(),ticketed:a.z.array(a.z.object({findingId:a.z.string(),issueKey:a.z.string()})).default([]),verdicts:a.z.array(a.z.object({findingId:a.z.string(),verdict:a.z.enum(["valid","false-positive","wont-fix"]),note:a.z.string().max(2e3).default("")})).default([]),verdictBy:a.z.string().default("")});h.AuditReviewResultMsg=a.z.object({type:a.z.literal("audit.review.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),audit:h.AuditRecord.optional()});h.KnowledgeListMsg=a.z.object({type:a.z.literal("knowledge.list"),requestId:a.z.string(),projectId:a.z.string()});h.KnowledgeFile=a.z.object({role:h.KnowledgeRole,level:a.z.enum(["global","org","project"]),source:a.z.enum(["pack","lessons","memory"]),name:a.z.string(),content:a.z.string(),editable:a.z.boolean().default(!1)});h.KnowledgeListResultMsg=a.z.object({type:a.z.literal("knowledge.list.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),files:a.z.array(h.KnowledgeFile).default([])});h.KnowledgeSaveMsg=a.z.object({type:a.z.literal("knowledge.save"),requestId:a.z.string(),projectId:a.z.string(),role:h.KnowledgeRole,level:a.z.enum(["org","project"]),source:a.z.enum(["pack","lessons"]),name:a.z.string().min(1).max(100),content:a.z.string().max(6e4),append:a.z.boolean().default(!1),by:a.z.string().default("")});h.KnowledgeSaveResultMsg=a.z.object({type:a.z.literal("knowledge.save.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional()});h.TeamCredsMsg=a.z.object({type:a.z.literal("team.creds"),requestId:a.z.string(),emails:a.z.array(a.z.string()).max(200)});h.TeamCredsResultMsg=a.z.object({type:a.z.literal("team.creds.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),githubShared:a.z.boolean().default(!1),sharedGithubLogin:a.z.string().default(""),entries:a.z.array(a.z.object({email:a.z.string(),jira:a.z.enum(["own","runner-account","missing"]),jiraAs:a.z.string().default(""),github:a.z.enum(["own","shared","missing"]),githubAs:a.z.string().default("")})).default([])});h.ChatFile=a.z.object({name:a.z.string().min(1).max(255),contentBase64:a.z.string().min(1).max(6e6)});h.ChatTurnMsg=a.z.object({type:a.z.literal("chat.turn"),requestId:a.z.string(),projectId:a.z.string(),sessionId:a.z.string().optional(),message:a.z.string().min(1).max(2e4),userName:a.z.string().default(""),model:a.z.string().default(""),files:a.z.array(h.ChatFile).max(8).default([]),replyLanguage:a.z.string().max(60).default(""),replyLanguageInstruction:a.z.string().max(600).default(""),replyStyle:a.z.string().max(30).default(""),pendingMigrations:a.z.array(a.z.string().max(200)).max(50).default([])});h.ChatTurnResultMsg=a.z.object({type:a.z.literal("chat.turn.result"),requestId:a.z.string(),ok:a.z.boolean(),sessionId:a.z.string().default(""),reply:a.z.string().default(""),error:a.z.string().optional(),inputTokens:a.z.number().int().nonnegative().default(0),outputTokens:a.z.number().int().nonnegative().default(0),cacheReadTokens:a.z.number().int().nonnegative().default(0),costUsd:a.z.number().nonnegative().default(0),model:a.z.string().max(200).default(""),contextTokens:a.z.number().int().nonnegative().default(0),contextLimit:a.z.number().int().nonnegative().default(0),compacted:a.z.boolean().default(!1),compactedMessages:a.z.number().int().nonnegative().default(0)});h.ChatCreateTicketMsg=a.z.object({type:a.z.literal("chat.create.ticket"),requestId:a.z.string(),projectId:a.z.string(),summary:a.z.string().min(1).max(250),description:a.z.string().default(""),triggerComment:a.z.string().default(""),requestedBy:a.z.string().default(""),requestedByEmail:a.z.string().default(""),asEpic:a.z.boolean().default(!1),children:a.z.array(a.z.object({summary:a.z.string().min(1),description:a.z.string().default("")})).max(20).default([]),createAs:a.z.enum(["epic_with_children","separate_epics","separate_tasks"]).default("epic_with_children"),files:a.z.array(h.ChatFile).max(8).default([])});h.ChatCreateTicketResultMsg=a.z.object({type:a.z.literal("chat.create.ticket.result"),requestId:a.z.string(),ok:a.z.boolean(),issueKey:a.z.string().default(""),error:a.z.string().optional(),childKeys:a.z.array(a.z.string()).default([])});h.EnvPreflightMsg=a.z.object({type:a.z.literal("env.preflight"),requestId:a.z.string(),projectId:a.z.string(),environmentName:a.z.string().default(""),steps:a.z.array(h.DeployStep).default([]),requiredSecrets:a.z.array(a.z.string()).default([]),workdir:a.z.string().default(""),branch:a.z.string().default(""),publicUrl:a.z.string().default("")});h.EnvPreflightResultMsg=a.z.object({type:a.z.literal("env.preflight.result"),requestId:a.z.string(),ok:a.z.boolean(),checks:a.z.array(a.z.object({name:a.z.string(),ok:a.z.boolean(),detail:a.z.string().default(""),kind:a.z.enum(["connection","content"]).default("connection"),fix:a.z.array(a.z.string()).default([]),fixNote:a.z.string().default("")})).default([])});h.SELF_MIGRATION_DIR="apps/api/prisma/manual";function Sg(t){return/^[A-Za-z0-9][A-Za-z0-9._-]*\.sql$/.test(t)&&!t.includes("..")}h.SelfMigrationApplyMsg=a.z.object({type:a.z.literal("selfmigration.apply"),requestId:a.z.string(),projectId:a.z.string(),environmentName:a.z.string().default(""),file:a.z.string(),urlSecret:a.z.string().default("DATABASE_URL")});h.SelfMigrationApplyResultMsg=a.z.object({type:a.z.literal("selfmigration.apply.result"),requestId:a.z.string(),ok:a.z.boolean(),file:a.z.string().default(""),checks:a.z.array(a.z.object({name:a.z.string(),ok:a.z.boolean(),detail:a.z.string().default(""),fix:a.z.array(a.z.string()).default([])})).default([]),output:a.z.string().max(2e4).default(""),error:a.z.string().default("")});h.DeploySuggestResultMsg=a.z.object({type:a.z.literal("deploy.suggest.result"),requestId:a.z.string(),ok:a.z.boolean(),steps:a.z.array(h.DeployStep).default([]),requiredSecrets:a.z.array(a.z.string()).default([]),notes:a.z.string().default(""),error:a.z.string().optional(),docPath:a.z.string().default(""),docContent:a.z.string().max(1e5).default("")});h.SetupStatusMsg=a.z.object({type:a.z.literal("setup.status"),requestId:a.z.string(),repoNames:a.z.array(a.z.string()).max(100).default([])});h.SetupStatusResultMsg=a.z.object({type:a.z.literal("setup.status.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),jiraConfigured:a.z.boolean().default(!1),jiraEmail:a.z.string().default(""),claude:a.z.object({installed:a.z.boolean(),version:a.z.string().default(""),loggedIn:a.z.boolean()}).optional(),githubTokenSet:a.z.boolean().default(!1),githubLogin:a.z.string().default(""),deploysEnabled:a.z.boolean().default(!1),jiraUserCount:a.z.number().int().default(0),repos:a.z.array(a.z.object({repoName:a.z.string(),mapped:a.z.boolean(),liveMapped:a.z.boolean().default(!0),pathExists:a.z.boolean().default(!1),isGit:a.z.boolean().default(!1),claudeMd:a.z.boolean().default(!1),deployMd:a.z.boolean().default(!1),testMd:a.z.boolean().default(!1),defaultBranch:a.z.string().default(""),githubToken:a.z.boolean().default(!1),githubTokenOwn:a.z.boolean().default(!1)})).default([])});h.SetupClaudeMdGenerateMsg=a.z.object({type:a.z.literal("setup.claudemd.generate"),requestId:a.z.string(),projectId:a.z.string(),kind:a.z.enum(["claude","deploy","design"]).default("claude"),streamId:a.z.string().default(""),environments:a.z.array(a.z.object({name:a.z.string(),branch:a.z.string().default(""),publicUrl:a.z.string().default("")})).default([])});h.SetupClaudeMdGenerateResultMsg=a.z.object({type:a.z.literal("setup.claudemd.generate.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),content:a.z.string().default("")});h.SetupClaudeMdSaveMsg=a.z.object({type:a.z.literal("setup.claudemd.save"),requestId:a.z.string(),projectId:a.z.string(),kind:a.z.enum(["claude","deploy","design"]).default("claude"),overwrite:a.z.boolean().default(!1),content:a.z.string().max(1e5)});h.SetupClaudeMdSaveResultMsg=a.z.object({type:a.z.literal("setup.claudemd.save.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),note:a.z.string().default("")});h.RepoDocSaveMsg=a.z.object({type:a.z.literal("repo.doc.save"),requestId:a.z.string(),projectId:a.z.string(),relPath:a.z.string().min(1).max(200),overwrite:a.z.boolean().default(!1),content:a.z.string().max(2e5)});h.RepoDocSaveResultMsg=a.z.object({type:a.z.literal("repo.doc.save.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),note:a.z.string().default("")});h.RunnerUpdateMsg=a.z.object({type:a.z.literal("runner.update"),requestId:a.z.string()});h.RunResolveConflictMsg=a.z.object({type:a.z.literal("run.resolve.conflict"),requestId:a.z.string(),runId:a.z.string()});h.RunTestFixMsg=a.z.object({type:a.z.literal("run.testfix"),requestId:a.z.string(),runId:a.z.string(),failedTests:a.z.array(h.FailedTest).min(1).max(20)});h.RunTestFixResultMsg=a.z.object({type:a.z.literal("run.testfix.result"),requestId:a.z.string(),ok:a.z.boolean(),note:a.z.string().default(""),headSha:a.z.string().default(""),remaining:a.z.array(h.FailedTest).default([]),costUsd:a.z.number().nonnegative().optional(),inputTokens:a.z.number().int().nonnegative().optional(),outputTokens:a.z.number().int().nonnegative().optional()});h.RunAnswerMsg=a.z.object({type:a.z.literal("run.answer"),requestId:a.z.string(),runId:a.z.string(),text:a.z.string().min(1).max(4e3),answeredBy:a.z.string().default("")});h.RunAnswerResultMsg=a.z.object({type:a.z.literal("run.answer.result"),requestId:a.z.string(),ok:a.z.boolean(),note:a.z.string().default(""),error:a.z.string().optional()});h.RunResolveConflictResultMsg=a.z.object({type:a.z.literal("run.resolve.conflict.result"),requestId:a.z.string(),ok:a.z.boolean(),note:a.z.string().default(""),freeOfCharge:a.z.boolean().default(!1),headSha:a.z.string().default(""),costUsd:a.z.number().nonnegative().optional(),inputTokens:a.z.number().int().nonnegative().optional(),outputTokens:a.z.number().int().nonnegative().optional()});h.RunPrConflictMsg=a.z.object({type:a.z.literal("run.pr.conflict"),runId:a.z.string(),conflicted:a.z.boolean()});h.AgentProfilesMsg=a.z.object({type:a.z.literal("agent.profiles"),requestId:a.z.string()});h.AgentProfilesResultMsg=a.z.object({type:a.z.literal("agent.profiles.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),profiles:a.z.array(a.z.object({agent:a.z.string(),name:a.z.string(),loggedIn:a.z.boolean()})).max(200).default([]),defaultLoggedIn:a.z.boolean().default(!1),agentsWithoutProfiles:a.z.array(a.z.string()).max(20).default([])});h.RunnerUpdateResultMsg=a.z.object({type:a.z.literal("runner.update.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),note:a.z.string().default(""),scheduled:a.z.boolean().default(!1)});h.AutopilotNextMsg=a.z.object({type:a.z.literal("autopilot.next"),requestId:a.z.string()});h.AutopilotNextResultMsg=a.z.object({type:a.z.literal("autopilot.next.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),item:a.z.object({id:a.z.string(),projectId:a.z.string(),issueKey:a.z.string(),ruleId:a.z.string(),baseOverride:a.z.string().default(""),branchOverride:a.z.string().default(""),continueBranch:a.z.boolean().default(!1),autoMerge:a.z.boolean().default(!1)}).nullable().default(null),pausedUntil:a.z.string().default("")});h.AutopilotReportMsg=a.z.object({type:a.z.literal("autopilot.report"),requestId:a.z.string(),itemId:a.z.string(),outcome:a.z.enum(["claimed","failed","paused"]),runId:a.z.string().default(""),error:a.z.string().default("")});h.RunnerToServerMsg=a.z.discriminatedUnion("type",[h.HelloMsg,h.HeartbeatMsg,h.RunClaimMsg,h.RunLogMsg,h.RunUsageMsg,h.RunStatusMsg,h.ProjectTestResultMsg,h.RuleDiagnoseResultMsg,h.DeployClaimMsg,h.DeploySuggestResultMsg,h.EnvPreflightResultMsg,h.SelfMigrationApplyResultMsg,h.ChatTurnResultMsg,h.ChatStreamMsg,h.ChatUsageMsg,h.ChatCreateTicketResultMsg,h.ChatListResultMsg,h.RepoDocsResultMsg,h.RepoDocReadResultMsg,h.ChatLoadResultMsg,h.BoardFetchResultMsg,h.BoardTriggerResultMsg,h.TeamCredsResultMsg,h.AuditStartResultMsg,h.AuditListResultMsg,h.AuditGetResultMsg,h.AuditReviewResultMsg,h.KnowledgeListResultMsg,h.KnowledgeSaveResultMsg,h.EpicListResultMsg,h.EpicSuggestResultMsg,h.JiraUsersResultMsg,h.SetupStatusResultMsg,h.SetupClaudeMdGenerateResultMsg,h.SetupClaudeMdSaveResultMsg,h.RepoDocSaveResultMsg,h.RunnerUpdateResultMsg,h.AgentProfilesResultMsg,h.RunPrConflictMsg,h.RunResolveConflictResultMsg,h.RunTestFixResultMsg,h.RunAnswerResultMsg,h.AuditStatsResultMsg,h.AutopilotNextMsg,h.AutopilotReportMsg]);h.HelloAckMsg=a.z.object({type:a.z.literal("hello.ack"),runnerId:a.z.string(),runnerName:a.z.string(),serverTime:a.z.string()});h.ConfigMsg=a.z.object({type:a.z.literal("config"),projects:a.z.array(h.ProjectConfig),rules:a.z.array(h.RuleConfig),environments:a.z.array(h.EnvironmentConfig).default([]),pollingPaused:a.z.boolean().default(!1)});h.RunClaimResultMsg=a.z.object({type:a.z.literal("run.claim.result"),requestId:a.z.string(),accepted:a.z.boolean(),runId:a.z.string().optional(),reason:a.z.string().optional(),claudeProfile:a.z.string().optional(),actorEmail:a.z.string().optional()});h.ProjectTestMsg=a.z.object({type:a.z.literal("project.test"),requestId:a.z.string(),projectId:a.z.string()});h.RuleDiagnoseMsg=a.z.object({type:a.z.literal("rule.diagnose"),requestId:a.z.string(),ruleId:a.z.string()});h.RunCancelMsg=a.z.object({type:a.z.literal("run.cancel"),runId:a.z.string()});h.RunApprovedMsg=a.z.object({type:a.z.literal("run.approved"),runId:a.z.string(),headSha:a.z.string().optional()});h.RunRejectedMsg=a.z.object({type:a.z.literal("run.rejected"),runId:a.z.string()});h.RunRetryPushMsg=a.z.object({type:a.z.literal("run.retryPush"),runId:a.z.string()});h.DeployStartMsg=a.z.object({type:a.z.literal("deploy.start"),runId:a.z.string(),projectId:a.z.string(),issueKey:a.z.string(),issueSummary:a.z.string().default(""),environment:h.EnvironmentConfig,requestedBy:a.z.string().default(""),attempt:a.z.number().int().positive().default(1)});h.DeployFixMsg=a.z.object({type:a.z.literal("deploy.fix"),requestId:a.z.string(),projectId:a.z.string(),environmentName:a.z.string(),steps:a.z.array(a.z.object({name:a.z.string(),run:a.z.string(),continueOnError:a.z.boolean().default(!1)})),failedStep:a.z.string().default(""),errorText:a.z.string().max(8e3).default("")});h.DeploySuggestMsg=a.z.object({type:a.z.literal("deploy.suggest"),requestId:a.z.string(),projectId:a.z.string(),environmentName:a.z.string(),notes:a.z.string().default(""),timeoutSeconds:a.z.number().int().positive().max(1800).default(300)});h.JiraUsersMsg=a.z.object({type:a.z.literal("jira.users"),requestId:a.z.string(),query:a.z.string().default("")});h.ServerToRunnerMsg=a.z.discriminatedUnion("type",[h.HelloAckMsg,h.ConfigMsg,h.RunClaimResultMsg,h.ProjectTestMsg,h.RuleDiagnoseMsg,h.RunCancelMsg,h.RunApprovedMsg,h.RunRejectedMsg,h.RunRetryPushMsg,h.DeployClaimResultMsg,h.DeployStartMsg,h.DeploySuggestMsg,h.DeployFixMsg,h.EnvPreflightMsg,h.SelfMigrationApplyMsg,h.ChatTurnMsg,h.ChatCreateTicketMsg,h.ChatListMsg,h.RepoDocsMsg,h.RepoDocReadMsg,h.ChatLoadMsg,h.BoardFetchMsg,h.BoardTriggerMsg,h.TeamCredsMsg,h.AuditStartMsg,h.AuditListMsg,h.AuditGetMsg,h.AuditReviewMsg,h.KnowledgeListMsg,h.KnowledgeSaveMsg,h.EpicListMsg,h.EpicSuggestMsg,h.JiraUsersMsg,h.SetupStatusMsg,h.SetupClaudeMdGenerateMsg,h.SetupClaudeMdSaveMsg,h.RepoDocSaveMsg,h.RunnerUpdateMsg,h.AgentProfilesMsg,h.RunResolveConflictMsg,h.RunTestFixMsg,h.RunAnswerMsg,h.AuditStatsMsg,h.AutopilotNextResultMsg]);h.EnrollRequest=a.z.object({enrollToken:a.z.string().min(10),name:a.z.string().min(1).max(100),platform:a.z.string(),runnerVersion:a.z.string()});h.EnrollResponse=a.z.object({runnerId:a.z.string(),runnerToken:a.z.string(),controlPlaneWsUrl:a.z.string()});function Tg(t){return h.RunnerToServerMsg.parse(t)}function xg(t){return h.ServerToRunnerMsg.parse(t)}h.DEFAULT_PLAN_PROMPT_TEMPLATE=`You are a senior engineer asked to assess a Jira ticket. You have read-only access to the repository - do not attempt to modify anything.
|
|
38
38
|
|
|
39
39
|
Ticket {{issueKey}}: {{summary}}
|
|
40
40
|
|
|
@@ -282,13 +282,13 @@ ${i}${o}`:"clean"}`}function Lt(){let t=process.env.ALLWRIGHT_CACHE_DIR??process
|
|
|
282
282
|
`).map(s=>s.trim()).filter(s=>s&&!s.includes("->"))[0]??null}async function ki(t,e,n=6e4){let s=(await F(t,["symbolic-ref","refs/remotes/origin/HEAD"]).catch(()=>"")).trim().replace("refs/remotes/","")||"origin/main",i=await F(t,["diff","--stat",`${s}...${e}`]),o=await F(t,["diff",`${s}...${e}`]);return{base:s,stat:i.slice(0,4e3),diff:o.slice(0,n)}}function Lu(){let t=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(ke.default.existsSync(ce.default.join(Xn.default.homedir(),".cache","ticketpilot"))?ce.default.join(Xn.default.homedir(),".cache","ticketpilot"):ce.default.join(Xn.default.homedir(),".cache","allwright"));return ce.default.join(t,"env-checkouts")}function Ou(t){return t.replace(/[^\w.-]+/g,"_")}function Uu(t,e){return ce.default.join(Lu(),Ou(t),Ou(e))}async function Yo(t){let e=Uu(t.repoName,t.envName);return await F(t.repoPath,["fetch","origin",t.branch],{timeoutMs:3e5}),ke.default.existsSync(ce.default.join(e,".git"))?await F(e,["fetch","origin",t.branch],{timeoutMs:3e5}):(ke.default.rmSync(e,{recursive:!0,force:!0}),ke.default.mkdirSync(ce.default.dirname(e),{recursive:!0,mode:448}),await F(t.repoPath,["worktree","prune"]).catch(()=>{}),await F(t.repoPath,["worktree","add","--detach",e,`origin/${t.branch}`])),t.attached?await F(e,["checkout","-B",t.branch,`origin/${t.branch}`]):await F(e,["checkout","--force","--detach",`origin/${t.branch}`]),e}async function Xo(t,e,n){try{await F(t,["fetch","origin",e],{timeoutMs:3e5})}catch{return{ok:!1,reason:`branch "${e}" does not exist on origin - nothing to promote. Check the environment's ticket branch template against the branch your implement rule creates.`}}try{return await F(t,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyMerged:!0}}catch{}try{return await F(t,["-c",`user.name=${bi}`,"-c",`user.email=${vi}`,"merge","--no-ff","-m",n,`origin/${e}`]),{ok:!0}}catch(r){return await F(t,["merge","--abort"]).catch(()=>{}),{ok:!1,reason:`could not merge "${e}" into the environment branch - ${r instanceof Error?r.message:r}. Resolve it manually and deploy again.`}}}async function Qo(t,e){await F(t,["fetch","origin",e],{timeoutMs:3e5});try{return await F(t,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyUpToDate:!0}}catch{}try{return await F(t,["-c",`user.name=${bi}`,"-c",`user.email=${vi}`,"merge","--no-edit",`origin/${e}`]),{ok:!0,alreadyUpToDate:!1}}catch(n){let s=(await F(t,["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
|
|
283
283
|
`).filter(Boolean);return s.length?{ok:!1,conflicts:s}:(await F(t,["merge","--abort"]).catch(()=>{}),{ok:!1,conflicts:null,reason:n instanceof Error?n.message.slice(0,300):String(n)})}}async function cn(t){await F(t,["merge","--abort"]).catch(()=>{})}async function ea(t,e){await F(t,["add","-A"]),await F(t,["-c",`user.name=${bi}`,"-c",`user.email=${vi}`,"commit","--no-edit","-m",e])}async function ta(t,e){let n=new Set(await Si(t));return e.filter(r=>n.has(r))}async function Si(t){let e=new Set;try{let r=await F(t,["grep","-l","-I","-E","^(<{7}|>{7})( |$)"]);for(let s of r.split(`
|
|
284
284
|
`).filter(Boolean))e.add(s)}catch{}let n=[];try{n=(await F(t,["grep","-l","-I","-E","^={7}$"])).split(`
|
|
285
|
-
`).filter(Boolean).filter(s=>!e.has(s))}catch{}for(let r of n)try{let s=await F(t,["show",`HEAD:${r}`]);/^={7}$/m.test(s)||e.add(r)}catch{e.add(r)}return[...e]}async function Ts(t,e,n){ke.default.mkdirSync(ce.default.dirname(e),{recursive:!0,mode:448}),await F(t,["fetch","origin",n],{timeoutMs:3e5}),await F(t,["worktree","add","--detach",e,`origin/${n}`]),await F(e,["checkout","-B",n,`origin/${n}`])}async function na(t,e){try{await F(t,["push","origin",e],{timeoutMs:3e5})}catch(n){throw new Error(`could not push "${e}" - ${n instanceof Error?n.message:n}. Someone may have pushed to it since this deploy started; retry.`)}}async function ra(t,e,n){try{return await zu("git",["-C",t,"diff","--quiet",e,n,"--"],{timeout:12e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),!1}catch(r){let s=r;if(s.code===1)return!0;throw new Error(`git diff failed comparing ${e}..${n}: ${(s.stderr||s.message||"").trim().slice(0,500)}`)}}async function tr(t){return(await F(t,["config","--get","remote.origin.url"])).trim()}function at(t){let e=/^git@github\.com(?:-[\w.-]+)?:([^/]+)\/(.+?)(\.git)?$/.exec(t)??/^https:\/\/github\.com\/([^/]+)\/(.+?)(\.git)?\/?$/.exec(t)??/^ssh:\/\/git@github\.com(?:-[\w.-]+)?\/([^/]+)\/(.+?)(\.git)?$/.exec(t);return e?{owner:e[1],repo:e[2]}:null}var ke,Xn,ce,Nu,Mu,zu,bi,vi,on,an,Du,Dt,wt=Zs(()=>{"use strict";ke=I(require("node:fs"),1),Xn=I(require("node:os"),1),ce=I(require("node:path"),1),Nu=require("node:child_process"),Mu=require("node:util"),zu=(0,Mu.promisify)(Nu.execFile),bi="Allwright Agent",vi="agent@ticketpilot.local",on=200,an=2e4,Du=[/^\.github\/workflows\//,/^\.git\b/,/(^|\/)\.githooks\//];Dt=".ticketpilot-delete"});function Ti(t,e,n){let r=(n??"").trim().toLowerCase(),s=r?t.githubUsers[r]?.token:void 0;if(s)return{token:s,source:"user"};let i=t.repos[e]?.github?.token;return i?{token:i,source:"repo"}:t.github?.token?{token:t.github.token,source:"global"}:null}function Ee(t,e){return t.repos[e]?.github?.token??t.github?.token??null}function Hu(t,e){let n=[t.jira,...Object.values(t.repos).map(l=>l.jira)].filter(l=>!!l),r=new Set(n.map(l=>l.email.toLowerCase())),s=!!t.github?.token||Object.values(t.repos).some(l=>l.github?.token),i=t.github?.login??Object.values(t.repos).find(l=>l.github?.login)?.github?.login??"",o=e.map(l=>{let u=l.trim().toLowerCase(),c=t.jiraUsers[u]?"own":r.has(u)?"runner-account":"missing",f=c==="own"?t.jiraUsers[u].email:c==="runner-account"?u:"",p=t.githubUsers[u]?"own":s?"shared":"missing",b=p==="own"?t.githubUsers[u].login??"":p==="shared"?i:"";return{email:u,jira:c,jiraAs:f,github:p,githubAs:b}});return{githubShared:s,sharedGithubLogin:i,entries:o}}var nr=Zs(()=>{"use strict"});var or={};Gs(or,{GitHubClient:()=>$e});var Gg,$e,ut=Zs(()=>{"use strict";Gg=process.env.TICKETPILOT_GITHUB_API??"https://api.github.com",$e=class{constructor(e){this.token=e}token;async request(e,n,r){let s=await fetch(`${Gg}${n}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"allwright",...r!==void 0?{"Content-Type":"application/json"}:{}},body:r===void 0?void 0:JSON.stringify(r)}),i=await s.text(),o=null;try{o=i?JSON.parse(i):null}catch{}if(s.status===401)throw new Error("GitHub rejected the token (401) - expired or revoked? Run `allwright github set-token`");if(!s.ok&&s.status!==422){let l=o?.message??i.slice(0,300);throw new Error(`GitHub ${e} ${n} -> ${s.status}: ${l}`)}return{status:s.status,data:o}}async whoami(){let{data:e}=await this.request("GET","/user");return e.login}async createPullRequest(e,n,r){let{status:s,data:i}=await this.request("POST",`/repos/${e}/${n}/pulls`,r);if(s===422){let{data:o}=await this.request("GET",`/repos/${e}/${n}/pulls?head=${encodeURIComponent(`${e}:${r.head}`)}&state=open`);if(o?.length){let l=o[0];return{number:l.number,url:l.html_url,state:l.state,merged:l.merged??!1,headSha:l.head.sha,mergeableState:null,baseRef:l.base?.ref??""}}throw new Error(`GitHub refused the PR (422): ${i?.message??"validation failed"}`)}return{number:i.number,url:i.html_url,state:i.state,merged:i.merged??!1,headSha:i.head.sha,mergeableState:null,baseRef:r.base}}async getReviews(e,n,r){let{data:s}=await this.request("GET",`/repos/${e}/${n}/pulls/${r}/reviews?per_page=100`);return(s??[]).map(i=>({state:i.state??"",commitId:i.commit_id??"",user:i.user?.login??"",submittedAt:i.submitted_at??""}))}async getPullRequest(e,n,r){try{let{data:s}=await this.request("GET",`/repos/${e}/${n}/pulls/${r}`);return{number:s.number,url:s.html_url,state:s.state,merged:s.merged,headSha:s.head.sha,mergeableState:s.mergeable_state??null,baseRef:s.base?.ref??""}}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return null;throw s}}async mergePullRequest(e,n,r,s,i={}){try{return await this.request("PUT",`/repos/${e}/${n}/pulls/${r}/merge`,{merge_method:s,...i.sha?{sha:i.sha}:{},...i.title?{commit_title:i.title}:{}}),{merged:!0}}catch(o){let l=o instanceof Error?o.message:String(o);return l.includes("-> 405")?{merged:!1,reason:`GitHub refused the merge: the branch is not in a mergeable state, or this repository does not allow "${s}" merges. Check the PR for conflicts or required checks, then merge it there.`}:l.includes("-> 409")?{merged:!1,reason:"the branch moved since it was reviewed, so GitHub refused to merge the commit that was approved. Re-review the PR and approve again."}:l.includes("-> 403")?{merged:!1,reason:`this runner's GitHub token is not allowed to merge in ${e}/${n}. It needs write access to the repository - or merge the PR yourself.`}:{merged:!1,reason:l}}}async repoAccess(e,n){try{let{data:r}=await this.request("GET",`/repos/${e}/${n}`);return{ok:!0,canPush:!!(r.permissions?.push||r.permissions?.admin)}}catch(r){let s=r instanceof Error?r.message:String(r);return{ok:!1,canPush:!1,error:s.includes("-> 404")?"not found (private repo this token cannot see, or the name is wrong)":s.slice(0,200)}}}async closePullRequest(e,n,r){await this.request("PATCH",`/repos/${e}/${n}/pulls/${r}`,{state:"closed"})}async deleteBranch(e,n,r){try{await this.request("DELETE",`/repos/${e}/${n}/git/refs/heads/${encodeURIComponent(r)}`)}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return;throw s}}}});var Bt=re((Qk,Xd)=>{"use strict";var Jd=["nodebuffer","arraybuffer","fragments"],Yd=typeof Blob<"u";Yd&&Jd.push("blob");Xd.exports={BINARY_TYPES:Jd,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Yd,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Ns=re((eS,Gi)=>{"use strict";var{EMPTY_BUFFER:ob}=Bt(),Wa=Buffer[Symbol.species];function ab(t,e){if(t.length===0)return ob;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let s=0;s<t.length;s++){let i=t[s];n.set(i,r),r+=i.length}return r<e?new Wa(n.buffer,n.byteOffset,r):n}function Qd(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function eh(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function lb(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Ja(t){if(Ja.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Wa(t):ArrayBuffer.isView(t)?e=new Wa(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Ja.readOnly=!1),e}Gi.exports={concat:ab,mask:Qd,toArrayBuffer:lb,toBuffer:Ja,unmask:eh};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");Gi.exports.mask=function(e,n,r,s,i){i<48?Qd(e,n,r,s,i):t.mask(e,n,r,s,i)},Gi.exports.unmask=function(e,n){e.length<32?eh(e,n):t.unmask(e,n)}}catch{}});var rh=re((tS,nh)=>{"use strict";var th=Symbol("kDone"),Ya=Symbol("kRun"),Xa=class{constructor(e){this[th]=()=>{this.pending--,this[Ya]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ya]()}[Ya](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[th])}}};nh.exports=Xa});var ss=re((nS,ah)=>{"use strict";var Ms=require("zlib"),sh=Ns(),ub=rh(),{kStatusCode:ih}=Bt(),cb=Buffer[Symbol.species],db=Buffer.from([0,0,255,255]),Wi=Symbol("permessage-deflate"),Kt=Symbol("total-length"),ns=Symbol("callback"),fn=Symbol("buffers"),rs=Symbol("error"),Vi,Qa=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,!Vi){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Vi=new ub(n)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[ns];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(s=>!(n.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>s.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let s=n[r];if(s.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(s=s[0],r==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else if(r==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=s})}),e}decompress(e,n,r){Vi.add(s=>{this._decompress(e,n,(i,o)=>{s(),r(i,o)})})}compress(e,n,r){Vi.add(s=>{this._compress(e,n,(i,o)=>{s(),r(i,o)})})}_decompress(e,n,r){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Ms.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Ms.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Wi]=this,this._inflate[Kt]=0,this._inflate[fn]=[],this._inflate.on("error",fb),this._inflate.on("data",oh)}this._inflate[ns]=r,this._inflate.write(e),n&&this._inflate.write(db),this._inflate.flush(()=>{let i=this._inflate[rs];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=sh.concat(this._inflate[fn],this._inflate[Kt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Kt]=0,this._inflate[fn]=[],n&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,n,r){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Ms.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Ms.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[Kt]=0,this._deflate[fn]=[],this._deflate.on("data",hb)}this._deflate[ns]=r,this._deflate.write(e),this._deflate.flush(Ms.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=sh.concat(this._deflate[fn],this._deflate[Kt]);n&&(i=new cb(i.buffer,i.byteOffset,i.length-4)),this._deflate[ns]=null,this._deflate[Kt]=0,this._deflate[fn]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};ah.exports=Qa;function hb(t){this[fn].push(t),this[Kt]+=t.length}function oh(t){if(this[Kt]+=t.length,this[Wi]._maxPayload<1||this[Kt]<=this[Wi]._maxPayload){this[fn].push(t);return}this[rs]=new RangeError("Max payload size exceeded"),this[rs].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[rs][ih]=1009,this.removeListener("data",oh),this.reset()}function fb(t){if(this[Wi]._inflate=null,this[rs]){this[ns](this[rs]);return}t[ih]=1007,this[ns](t)}});var is=re((rS,Ji)=>{"use strict";var{isUtf8:lh}=require("buffer"),{hasBlob:pb}=Bt(),mb=[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 gb(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function el(t){let e=t.length,n=0;for(;n<e;)if((t[n]&128)===0)n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function yb(t){return pb&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Ji.exports={isBlob:yb,isValidStatusCode:gb,isValidUTF8:el,tokenChars:mb};if(lh)Ji.exports.isValidUTF8=function(t){return t.length<24?el(t):lh(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");Ji.exports.isValidUTF8=function(e){return e.length<32?el(e):t(e)}}catch{}});var il=re((sS,mh)=>{"use strict";var{Writable:bb}=require("stream"),uh=ss(),{BINARY_TYPES:vb,EMPTY_BUFFER:ch,kStatusCode:wb,kWebSocket:_b}=Bt(),{concat:tl,toArrayBuffer:kb,unmask:Sb}=Ns(),{isValidStatusCode:Tb,isValidUTF8:dh}=is(),Yi=Buffer[Symbol.species],rt=0,hh=1,fh=2,ph=3,nl=4,rl=5,Xi=6,sl=class extends bb{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||vb[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[_b]=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=rt}_write(e,n,r){if(this._opcode===8&&this._state==rt)return r();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){r(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new Yi(r.buffer,r.byteOffset+e,r.length-e),new Yi(r.buffer,r.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let r=this._buffers[0],s=n.length-e;e>=r.length?n.set(this._buffers.shift(),s):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new Yi(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case rt:this.getInfo(e);break;case hh:this.getPayloadLength16(e);break;case fh:this.getPayloadLength64(e);break;case ph:this.getMask();break;case nl:this.getData(e);break;case rl:case Xi:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let r=(n[0]&64)===64;if(r&&!this._extensions[uh.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=hh:this._payloadLength===127?this._state=fh:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),r=n.readUInt32BE(0);if(r>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=r*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=ph:this._state=nl}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=nl}getData(e){let n=ch;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Sb(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let r=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(r);return}if(this._compressed){this._state=rl,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[uh.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return n(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(o);return}this._fragments.push(i)}this.dataMessage(n),this._state===rt&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=rt;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=tl(r,n):this._binaryType==="arraybuffer"?s=kb(tl(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=rt):(this._state=Xi,setImmediate(()=>{this.emit("message",s,!0),this._state=rt,this.startLoop(e)}))}else{let s=tl(r,n);if(!this._skipUTF8Validation&&!dh(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===rl||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=rt):(this._state=Xi,setImmediate(()=>{this.emit("message",s,!1),this._state=rt,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,ch),this.end();else{let r=e.readUInt16BE(0);if(!Tb(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new Yi(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!dh(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(i);return}this._loop=!1,this.emit("conclude",r,s),this.end()}this._state=rt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=rt):(this._state=Xi,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=rt,this.startLoop(n)}))}createError(e,n,r,s,i){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(o,this.createError),o.code=i,o[wb]=s,o}};mh.exports=sl});var ll=re((oS,bh)=>{"use strict";var{Duplex:iS}=require("stream"),{randomFillSync:xb}=require("crypto"),{types:{isUint8Array:Cb}}=require("util"),gh=ss(),{EMPTY_BUFFER:Ib,kWebSocket:Rb,NOOP:Ab}=Bt(),{isBlob:os,isValidStatusCode:Eb}=is(),{mask:yh,toBuffer:vr}=Ns(),st=Symbol("kByteLength"),$b=Buffer.alloc(4),Qi=8*1024,wr,as=Qi,ht=0,Pb=1,jb=2,ol=class t{constructor(e,n,r){this._extensions=n||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=ht,this.onerror=Ab,this[Rb]=void 0}static frame(e,n){let r,s=!1,i=2,o=!1;n.mask&&(r=n.maskBuffer||$b,n.generateMask?n.generateMask(r):(as===Qi&&(wr===void 0&&(wr=Buffer.alloc(Qi)),xb(wr,0,Qi),as=0),r[0]=wr[as++],r[1]=wr[as++],r[2]=wr[as++],r[3]=wr[as++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let l;typeof e=="string"?(!n.mask||o)&&n[st]!==void 0?l=n[st]:(e=Buffer.from(e),l=e.length):(l=e.length,s=n.mask&&n.readOnly&&!o);let u=l;l>=65536?(i+=8,u=127):l>125&&(i+=2,u=126);let c=Buffer.allocUnsafe(s?l+i:i);return c[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(c[0]|=64),c[1]=u,u===126?c.writeUInt16BE(l,2):u===127&&(c[2]=c[3]=0,c.writeUIntBE(l,4,6)),n.mask?(c[1]|=128,c[i-4]=r[0],c[i-3]=r[1],c[i-2]=r[2],c[i-1]=r[3],o?[c,e]:s?(yh(e,r,c,i,l),[c]):(yh(e,r,e,0,l),[c,e])):[c,e]}close(e,n,r,s){let i;if(e===void 0)i=Ib;else{if(typeof e!="number"||!Eb(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let l=Buffer.byteLength(n);if(l>123)throw new RangeError("The message must not be greater than 123 bytes");if(i=Buffer.allocUnsafe(2+l),i.writeUInt16BE(e,0),typeof n=="string")i.write(n,2);else if(Cb(n))i.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[st]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ht?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(t.frame(i,o),s)}ping(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):os(e)?(s=e.size,i=!1):(e=vr(e),s=e.length,i=vr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[st]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};os(e)?this._state!==ht?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==ht?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}pong(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):os(e)?(s=e.size,i=!1):(e=vr(e),s=e.length,i=vr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[st]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};os(e)?this._state!==ht?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==ht?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let s=this._extensions[gh.extensionName],i=n.binary?2:1,o=n.compress,l,u;typeof e=="string"?(l=Buffer.byteLength(e),u=!1):os(e)?(l=e.size,u=!1):(e=vr(e),l=e.length,u=vr.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=l>=s._threshold),this._compress=o):(o=!1,i=0),n.fin&&(this._firstFragment=!0);let c={[st]:l,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:u,rsv1:o};os(e)?this._state!==ht?this.enqueue([this.getBlobData,e,this._compress,c,r]):this.getBlobData(e,this._compress,c,r):this._state!==ht?this.enqueue([this.dispatch,e,this._compress,c,r]):this.dispatch(e,this._compress,c,r)}getBlobData(e,n,r,s){this._bufferedBytes+=r[st],this._state=jb,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let l=new Error("The socket was closed while the blob was being read");process.nextTick(al,this,l,s);return}this._bufferedBytes-=r[st];let o=vr(i);n?this.dispatch(o,n,r,s):(this._state=ht,this.sendFrame(t.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(Ob,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[gh.extensionName];this._bufferedBytes+=r[st],this._state=Pb,i.compress(e,r.fin,(o,l)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");al(this,u,s);return}this._bufferedBytes-=r[st],this._state=ht,r.readOnly=!1,this.sendFrame(t.frame(l,r),s),this.dequeue()})}dequeue(){for(;this._state===ht&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][st],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][st],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};bh.exports=ol;function al(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let s=t._queue[r],i=s[s.length-1];typeof i=="function"&&i(e)}}function Ob(t,e,n){al(t,e,n),t.onerror(e)}});var Ih=re((aS,Ch)=>{"use strict";var{kForOnEventAttribute:zs,kListener:ul}=Bt(),vh=Symbol("kCode"),wh=Symbol("kData"),_h=Symbol("kError"),kh=Symbol("kMessage"),Sh=Symbol("kReason"),ls=Symbol("kTarget"),Th=Symbol("kType"),xh=Symbol("kWasClean"),Ht=class{constructor(e){this[ls]=null,this[Th]=e}get target(){return this[ls]}get type(){return this[Th]}};Object.defineProperty(Ht.prototype,"target",{enumerable:!0});Object.defineProperty(Ht.prototype,"type",{enumerable:!0});var _r=class extends Ht{constructor(e,n={}){super(e),this[vh]=n.code===void 0?0:n.code,this[Sh]=n.reason===void 0?"":n.reason,this[xh]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[vh]}get reason(){return this[Sh]}get wasClean(){return this[xh]}};Object.defineProperty(_r.prototype,"code",{enumerable:!0});Object.defineProperty(_r.prototype,"reason",{enumerable:!0});Object.defineProperty(_r.prototype,"wasClean",{enumerable:!0});var us=class extends Ht{constructor(e,n={}){super(e),this[_h]=n.error===void 0?null:n.error,this[kh]=n.message===void 0?"":n.message}get error(){return this[_h]}get message(){return this[kh]}};Object.defineProperty(us.prototype,"error",{enumerable:!0});Object.defineProperty(us.prototype,"message",{enumerable:!0});var Ds=class extends Ht{constructor(e,n={}){super(e),this[wh]=n.data===void 0?null:n.data}get data(){return this[wh]}};Object.defineProperty(Ds.prototype,"data",{enumerable:!0});var Nb={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[zs]&&s[ul]===e&&!s[zs])return;let r;if(t==="message")r=function(i,o){let l=new Ds("message",{data:o?i:i.toString()});l[ls]=this,eo(e,this,l)};else if(t==="close")r=function(i,o){let l=new _r("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});l[ls]=this,eo(e,this,l)};else if(t==="error")r=function(i){let o=new us("error",{error:i,message:i.message});o[ls]=this,eo(e,this,o)};else if(t==="open")r=function(){let i=new Ht("open");i[ls]=this,eo(e,this,i)};else return;r[zs]=!!n[zs],r[ul]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[ul]===e&&!n[zs]){this.removeListener(t,n);break}}};Ch.exports={CloseEvent:_r,ErrorEvent:us,Event:Ht,EventTarget:Nb,MessageEvent:Ds};function eo(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var to=re((lS,Rh)=>{"use strict";var{tokenChars:Ls}=is();function xt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function Mb(t){let e=Object.create(null),n=Object.create(null),r=!1,s=!1,i=!1,o,l,u=-1,c=-1,f=-1,p=0;for(;p<t.length;p++)if(c=t.charCodeAt(p),o===void 0)if(f===-1&&Ls[c]===1)u===-1&&(u=p);else if(p!==0&&(c===32||c===9))f===-1&&u!==-1&&(f=p);else if(c===59||c===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let w=t.slice(u,f);c===44?(xt(e,w,n),n=Object.create(null)):o=w,u=f=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(l===void 0)if(f===-1&&Ls[c]===1)u===-1&&(u=p);else if(c===32||c===9)f===-1&&u!==-1&&(f=p);else if(c===59||c===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),xt(n,t.slice(u,f),!0),c===44&&(xt(e,o,n),n=Object.create(null),o=void 0),u=f=-1}else if(c===61&&u!==-1&&f===-1)l=t.slice(u,p),u=f=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(s){if(Ls[c]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:r||(r=!0),s=!1}else if(i)if(Ls[c]===1)u===-1&&(u=p);else if(c===34&&u!==-1)i=!1,f=p;else if(c===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(c===34&&t.charCodeAt(p-1)===61)i=!0;else if(f===-1&&Ls[c]===1)u===-1&&(u=p);else if(u!==-1&&(c===32||c===9))f===-1&&(f=p);else if(c===59||c===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let w=t.slice(u,f);r&&(w=w.replace(/\\/g,""),r=!1),xt(n,l,w),c===44&&(xt(e,o,n),n=Object.create(null),o=void 0),l=void 0,u=f=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(u===-1||i||c===32||c===9)throw new SyntaxError("Unexpected end of input");f===-1&&(f=p);let b=t.slice(u,f);return o===void 0?xt(e,b,n):(l===void 0?xt(n,b,!0):r?xt(n,l,b.replace(/\\/g,"")):xt(n,l,b),xt(e,o,n)),e}function zb(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(r=>[e].concat(Object.keys(r).map(s=>{let i=r[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Rh.exports={format:zb,parse:Mb}});var io=re((dS,Uh)=>{"use strict";var Db=require("events"),Lb=require("https"),Ub=require("http"),$h=require("net"),qb=require("tls"),{randomBytes:Fb,createHash:Bb}=require("crypto"),{Duplex:uS,Readable:cS}=require("stream"),{URL:cl}=require("url"),pn=ss(),Kb=il(),Hb=ll(),{isBlob:Zb}=is(),{BINARY_TYPES:Ah,CLOSE_TIMEOUT:Gb,EMPTY_BUFFER:no,GUID:Vb,kForOnEventAttribute:dl,kListener:Wb,kStatusCode:Jb,kWebSocket:Se,NOOP:Ph}=Bt(),{EventTarget:{addEventListener:Yb,removeEventListener:Xb}}=Ih(),{format:Qb,parse:ev}=to(),{toBuffer:tv}=Ns(),jh=Symbol("kAborted"),hl=[8,13],Zt=["CONNECTING","OPEN","CLOSING","CLOSED"],nv=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,fe=class t extends Db{constructor(e,n,r){super(),this._binaryType=Ah[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=no,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),Oh(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Ah.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,r){let s=new Kb({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new Hb(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[Se]=this,i[Se]=this,e[Se]=this,s.on("conclude",iv),s.on("drain",ov),s.on("error",av),s.on("message",lv),s.on("ping",uv),s.on("pong",cv),i.onerror=dv,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",zh),e.on("data",so),e.on("end",Dh),e.on("error",Lh),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[pn.extensionName]&&this._extensions[pn.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){He(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Mh(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){fl(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||no,n,r)}pong(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){fl(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||no,n,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){fl(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[pn.extensionName]||(s.compress=!1),this._sender.send(e||no,s,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){He(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(fe,"CONNECTING",{enumerable:!0,value:Zt.indexOf("CONNECTING")});Object.defineProperty(fe.prototype,"CONNECTING",{enumerable:!0,value:Zt.indexOf("CONNECTING")});Object.defineProperty(fe,"OPEN",{enumerable:!0,value:Zt.indexOf("OPEN")});Object.defineProperty(fe.prototype,"OPEN",{enumerable:!0,value:Zt.indexOf("OPEN")});Object.defineProperty(fe,"CLOSING",{enumerable:!0,value:Zt.indexOf("CLOSING")});Object.defineProperty(fe.prototype,"CLOSING",{enumerable:!0,value:Zt.indexOf("CLOSING")});Object.defineProperty(fe,"CLOSED",{enumerable:!0,value:Zt.indexOf("CLOSED")});Object.defineProperty(fe.prototype,"CLOSED",{enumerable:!0,value:Zt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(fe.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(fe.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[dl])return e[Wb];return null},set(e){for(let n of this.listeners(t))if(n[dl]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[dl]:!0})}})});fe.prototype.addEventListener=Yb;fe.prototype.removeEventListener=Xb;Uh.exports=fe;function Oh(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Gb,protocolVersion:hl[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=s.autoPong,t._closeTimeout=s.closeTimeout,!hl.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${hl.join(", ")})`);let i;if(e instanceof cl)i=e;else try{i=new cl(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),t._url=i.href;let o=i.protocol==="wss:",l=i.protocol==="ws+unix:",u;if(i.protocol!=="ws:"&&!o&&!l?u=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:l&&!i.pathname?u="The URL's pathname is empty":i.hash&&(u="The URL contains a fragment identifier"),u){let x=new SyntaxError(u);if(t._redirects===0)throw x;ro(t,x);return}let c=o?443:80,f=Fb(16).toString("base64"),p=o?Lb.request:Ub.request,b=new Set,w;if(s.createConnection=s.createConnection||(o?sv:rv),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":f,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(w=new pn({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=Qb({[pn.extensionName]:w.offer()})),n.length){for(let x of n){if(typeof x!="string"||!nv.test(x)||b.has(x))throw new SyntaxError("An invalid or duplicated subprotocol was specified");b.add(x)}s.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),l){let x=s.path.split(":");s.socketPath=x[0],s.path=x[1]}let S;if(s.followRedirects){if(t._redirects===0){t._originalIpc=l,t._originalSecure=o,t._originalHostOrSocketPath=l?s.socketPath:i.host;let x=r&&r.headers;if(r={...r,headers:{}},x)for(let[E,j]of Object.entries(x))r.headers[E.toLowerCase()]=j}else if(t.listenerCount("redirect")===0){let x=l?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!x||t._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,x||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),S=t._req=p(s),t._redirects&&t.emit("redirect",t.url,S)}else S=t._req=p(s);s.timeout&&S.on("timeout",()=>{He(t,S,"Opening handshake has timed out")}),S.on("error",x=>{S===null||S[jh]||(S=t._req=null,ro(t,x))}),S.on("response",x=>{let E=x.headers.location,j=x.statusCode;if(E&&s.followRedirects&&j>=300&&j<400){if(++t._redirects>s.maxRedirects){He(t,S,"Maximum redirects exceeded");return}S.abort();let v;try{v=new cl(E,e)}catch{let H=new SyntaxError(`Invalid URL: ${E}`);ro(t,H);return}Oh(t,v,n,r)}else t.emit("unexpected-response",S,x)||He(t,S,`Unexpected server response: ${x.statusCode}`)}),S.on("upgrade",(x,E,j)=>{if(t.emit("upgrade",x),t.readyState!==fe.CONNECTING)return;S=t._req=null;let v=x.headers.upgrade;if(v===void 0||v.toLowerCase()!=="websocket"){He(t,E,"Invalid Upgrade header");return}let O=Bb("sha1").update(f+Vb).digest("base64");if(x.headers["sec-websocket-accept"]!==O){He(t,E,"Invalid Sec-WebSocket-Accept header");return}let H=x.headers["sec-websocket-protocol"],z;if(H!==void 0?b.size?b.has(H)||(z="Server sent an invalid subprotocol"):z="Server sent a subprotocol but none was requested":b.size&&(z="Server sent no subprotocol"),z){He(t,E,z);return}H&&(t._protocol=H);let B=x.headers["sec-websocket-extensions"];if(B!==void 0){if(!w){He(t,E,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let d;try{d=ev(B)}catch{He(t,E,"Invalid Sec-WebSocket-Extensions header");return}let m=Object.keys(d);if(m.length!==1||m[0]!==pn.extensionName){He(t,E,"Server indicated an extension that was not requested");return}try{w.accept(d[pn.extensionName])}catch{He(t,E,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[pn.extensionName]=w}t.setSocket(E,j,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(S,t):S.end()}function ro(t,e){t._readyState=fe.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function rv(t){return t.path=t.socketPath,$h.connect(t)}function sv(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=$h.isIP(t.host)?"":t.host),qb.connect(t)}function He(t,e,n){t._readyState=fe.CLOSING;let r=new Error(n);Error.captureStackTrace(r,He),e.setHeader?(e[jh]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ro,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function fl(t,e,n){if(e){let r=Zb(e)?e.size:tv(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${Zt[t.readyState]})`);process.nextTick(n,r)}}function iv(t,e){let n=this[Se];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[Se]!==void 0&&(n._socket.removeListener("data",so),process.nextTick(Nh,n._socket),t===1005?n.close():n.close(t,e))}function ov(){let t=this[Se];t.isPaused||t._socket.resume()}function av(t){let e=this[Se];e._socket[Se]!==void 0&&(e._socket.removeListener("data",so),process.nextTick(Nh,e._socket),e.close(t[Jb])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Eh(){this[Se].emitClose()}function lv(t,e){this[Se].emit("message",t,e)}function uv(t){let e=this[Se];e._autoPong&&e.pong(t,!this._isServer,Ph),e.emit("ping",t)}function cv(t){this[Se].emit("pong",t)}function Nh(t){t.resume()}function dv(t){let e=this[Se];e.readyState!==fe.CLOSED&&(e.readyState===fe.OPEN&&(e._readyState=fe.CLOSING,Mh(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Mh(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function zh(){let t=this[Se];if(this.removeListener("close",zh),this.removeListener("data",so),this.removeListener("end",Dh),t._readyState=fe.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[Se]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Eh),t._receiver.on("finish",Eh))}function so(t){this[Se]._receiver.write(t)||this.pause()}function Dh(){let t=this[Se];t._readyState=fe.CLOSING,t._receiver.end(),this.end()}function Lh(){let t=this[Se];this.removeListener("error",Lh),this.on("error",Ph),t&&(t._readyState=fe.CLOSING,this.destroy())}});var Kh=re((fS,Bh)=>{"use strict";var hS=io(),{Duplex:hv}=require("stream");function qh(t){t.emit("close")}function fv(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Fh(t){this.removeListener("error",Fh),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function pv(t,e){let n=!0,r=new hv({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,o){let l=!o&&r._readableState.objectMode?i.toString():i;r.push(l)||t.pause()}),t.once("error",function(i){r.destroyed||(n=!1,r.destroy(i))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(s,i){if(t.readyState===t.CLOSED){i(s),process.nextTick(qh,r);return}let o=!1;t.once("error",function(u){o=!0,i(u)}),t.once("close",function(){o||i(s),process.nextTick(qh,r)}),n&&t.terminate()},r._final=function(s){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(s)});return}t._socket!==null&&(t._socket._writableState.finished?(s(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){s()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(s,i,o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(s,i,o)});return}t.send(s,o)},r.on("end",fv),r.on("error",Fh),r}Bh.exports=pv});var pl=re((pS,Hh)=>{"use strict";var{tokenChars:mv}=is();function gv(t){let e=new Set,n=-1,r=-1,s=0;for(s;s<t.length;s++){let o=t.charCodeAt(s);if(r===-1&&mv[o]===1)n===-1&&(n=s);else if(s!==0&&(o===32||o===9))r===-1&&n!==-1&&(r=s);else if(o===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${s}`);r===-1&&(r=s);let l=t.slice(n,r);if(e.has(l))throw new SyntaxError(`The "${l}" subprotocol is duplicated`);e.add(l),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(n,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}Hh.exports={parse:gv}});var Xh=re((gS,Yh)=>{"use strict";var yv=require("events"),oo=require("http"),{Duplex:mS}=require("stream"),{createHash:bv}=require("crypto"),Zh=to(),kr=ss(),vv=pl(),wv=io(),{CLOSE_TIMEOUT:_v,GUID:kv,kWebSocket:Sv}=Bt(),Tv=/^[+/0-9A-Za-z]{22}==$/,Gh=0,Vh=1,Jh=2,ml=class extends yv{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:_v,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:wv,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=oo.createServer((r,s)=>{let i=oo.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=xv(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Gh}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===Jh){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Us,this);return}if(e&&this.once("close",e),this._state!==Vh)if(this._state=Vh,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(Us,this):process.nextTick(Us,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Us(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,r,s){n.on("error",Wh);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,l=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Sr(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Sr(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!Tv.test(i)){Sr(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(l!==13&&l!==8){Sr(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){qs(n,400);return}let u=e.headers["sec-websocket-protocol"],c=new Set;if(u!==void 0)try{c=vv.parse(u)}catch{Sr(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let f=e.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&f!==void 0){let b=new kr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let w=Zh.parse(f);w[kr.extensionName]&&(b.accept(w[kr.extensionName]),p[kr.extensionName]=b)}catch{Sr(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let b={origin:e.headers[`${l===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(b,(w,S,x,E)=>{if(!w)return qs(n,S||401,x,E);this.completeUpgrade(p,i,c,e,n,r,s)});return}if(!this.options.verifyClient(b))return qs(n,401)}this.completeUpgrade(p,i,c,e,n,r,s)}completeUpgrade(e,n,r,s,i,o,l){if(!i.readable||!i.writable)return i.destroy();if(i[Sv])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Gh)return qs(i,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${bv("sha1").update(n+kv).digest("base64")}`],f=new this.options.WebSocket(null,void 0,this.options);if(r.size){let p=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;p&&(c.push(`Sec-WebSocket-Protocol: ${p}`),f._protocol=p)}if(e[kr.extensionName]){let p=e[kr.extensionName].params,b=Zh.format({[kr.extensionName]:[p]});c.push(`Sec-WebSocket-Extensions: ${b}`),f._extensions=e}this.emit("headers",c,s),i.write(c.concat(`\r
|
|
285
|
+
`).filter(Boolean).filter(s=>!e.has(s))}catch{}for(let r of n)try{let s=await F(t,["show",`HEAD:${r}`]);/^={7}$/m.test(s)||e.add(r)}catch{e.add(r)}return[...e]}async function Ts(t,e,n){ke.default.mkdirSync(ce.default.dirname(e),{recursive:!0,mode:448}),await F(t,["fetch","origin",n],{timeoutMs:3e5}),await F(t,["worktree","add","--detach",e,`origin/${n}`]),await F(e,["checkout","-B",n,`origin/${n}`])}async function na(t,e){try{await F(t,["push","origin",e],{timeoutMs:3e5})}catch(n){throw new Error(`could not push "${e}" - ${n instanceof Error?n.message:n}. Someone may have pushed to it since this deploy started; retry.`)}}async function ra(t,e,n){try{return await zu("git",["-C",t,"diff","--quiet",e,n,"--"],{timeout:12e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),!1}catch(r){let s=r;if(s.code===1)return!0;throw new Error(`git diff failed comparing ${e}..${n}: ${(s.stderr||s.message||"").trim().slice(0,500)}`)}}async function tr(t){return(await F(t,["config","--get","remote.origin.url"])).trim()}function at(t){let e=/^git@github\.com(?:-[\w.-]+)?:([^/]+)\/(.+?)(\.git)?$/.exec(t)??/^https:\/\/github\.com\/([^/]+)\/(.+?)(\.git)?\/?$/.exec(t)??/^ssh:\/\/git@github\.com(?:-[\w.-]+)?\/([^/]+)\/(.+?)(\.git)?$/.exec(t);return e?{owner:e[1],repo:e[2]}:null}var ke,Xn,ce,Nu,Mu,zu,bi,vi,on,an,Du,Dt,wt=Zs(()=>{"use strict";ke=I(require("node:fs"),1),Xn=I(require("node:os"),1),ce=I(require("node:path"),1),Nu=require("node:child_process"),Mu=require("node:util"),zu=(0,Mu.promisify)(Nu.execFile),bi="Allwright Agent",vi="agent@ticketpilot.local",on=200,an=2e4,Du=[/^\.github\/workflows\//,/^\.git\b/,/(^|\/)\.githooks\//];Dt=".ticketpilot-delete"});function Ti(t,e,n){let r=(n??"").trim().toLowerCase(),s=r?t.githubUsers[r]?.token:void 0;if(s)return{token:s,source:"user"};let i=t.repos[e]?.github?.token;return i?{token:i,source:"repo"}:t.github?.token?{token:t.github.token,source:"global"}:null}function Ae(t,e){return t.repos[e]?.github?.token??t.github?.token??null}function Hu(t,e){let n=[t.jira,...Object.values(t.repos).map(l=>l.jira)].filter(l=>!!l),r=new Set(n.map(l=>l.email.toLowerCase())),s=!!t.github?.token||Object.values(t.repos).some(l=>l.github?.token),i=t.github?.login??Object.values(t.repos).find(l=>l.github?.login)?.github?.login??"",o=e.map(l=>{let u=l.trim().toLowerCase(),c=t.jiraUsers[u]?"own":r.has(u)?"runner-account":"missing",f=c==="own"?t.jiraUsers[u].email:c==="runner-account"?u:"",p=t.githubUsers[u]?"own":s?"shared":"missing",b=p==="own"?t.githubUsers[u].login??"":p==="shared"?i:"";return{email:u,jira:c,jiraAs:f,github:p,githubAs:b}});return{githubShared:s,sharedGithubLogin:i,entries:o}}var nr=Zs(()=>{"use strict"});var or={};Gs(or,{GitHubClient:()=>$e});var Gg,$e,ut=Zs(()=>{"use strict";Gg=process.env.TICKETPILOT_GITHUB_API??"https://api.github.com",$e=class{constructor(e){this.token=e}token;async request(e,n,r){let s=await fetch(`${Gg}${n}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"allwright",...r!==void 0?{"Content-Type":"application/json"}:{}},body:r===void 0?void 0:JSON.stringify(r)}),i=await s.text(),o=null;try{o=i?JSON.parse(i):null}catch{}if(s.status===401)throw new Error("GitHub rejected the token (401) - expired or revoked? Run `allwright github set-token`");if(!s.ok&&s.status!==422){let l=o?.message??i.slice(0,300);throw new Error(`GitHub ${e} ${n} -> ${s.status}: ${l}`)}return{status:s.status,data:o}}async whoami(){let{data:e}=await this.request("GET","/user");return e.login}async createPullRequest(e,n,r){let{status:s,data:i}=await this.request("POST",`/repos/${e}/${n}/pulls`,r);if(s===422){let{data:o}=await this.request("GET",`/repos/${e}/${n}/pulls?head=${encodeURIComponent(`${e}:${r.head}`)}&state=open`);if(o?.length){let l=o[0];return{number:l.number,url:l.html_url,state:l.state,merged:l.merged??!1,headSha:l.head.sha,mergeableState:null,baseRef:l.base?.ref??""}}throw new Error(`GitHub refused the PR (422): ${i?.message??"validation failed"}`)}return{number:i.number,url:i.html_url,state:i.state,merged:i.merged??!1,headSha:i.head.sha,mergeableState:null,baseRef:r.base}}async getReviews(e,n,r){let{data:s}=await this.request("GET",`/repos/${e}/${n}/pulls/${r}/reviews?per_page=100`);return(s??[]).map(i=>({state:i.state??"",commitId:i.commit_id??"",user:i.user?.login??"",submittedAt:i.submitted_at??""}))}async getPullRequest(e,n,r){try{let{data:s}=await this.request("GET",`/repos/${e}/${n}/pulls/${r}`);return{number:s.number,url:s.html_url,state:s.state,merged:s.merged,headSha:s.head.sha,mergeableState:s.mergeable_state??null,baseRef:s.base?.ref??""}}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return null;throw s}}async mergePullRequest(e,n,r,s,i={}){try{return await this.request("PUT",`/repos/${e}/${n}/pulls/${r}/merge`,{merge_method:s,...i.sha?{sha:i.sha}:{},...i.title?{commit_title:i.title}:{}}),{merged:!0}}catch(o){let l=o instanceof Error?o.message:String(o);return l.includes("-> 405")?{merged:!1,reason:`GitHub refused the merge: the branch is not in a mergeable state, or this repository does not allow "${s}" merges. Check the PR for conflicts or required checks, then merge it there.`}:l.includes("-> 409")?{merged:!1,reason:"the branch moved since it was reviewed, so GitHub refused to merge the commit that was approved. Re-review the PR and approve again."}:l.includes("-> 403")?{merged:!1,reason:`this runner's GitHub token is not allowed to merge in ${e}/${n}. It needs write access to the repository - or merge the PR yourself.`}:{merged:!1,reason:l}}}async repoAccess(e,n){try{let{data:r}=await this.request("GET",`/repos/${e}/${n}`);return{ok:!0,canPush:!!(r.permissions?.push||r.permissions?.admin)}}catch(r){let s=r instanceof Error?r.message:String(r);return{ok:!1,canPush:!1,error:s.includes("-> 404")?"not found (private repo this token cannot see, or the name is wrong)":s.slice(0,200)}}}async closePullRequest(e,n,r){await this.request("PATCH",`/repos/${e}/${n}/pulls/${r}`,{state:"closed"})}async deleteBranch(e,n,r){try{await this.request("DELETE",`/repos/${e}/${n}/git/refs/heads/${encodeURIComponent(r)}`)}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return;throw s}}}});var Bt=re((Qk,Xd)=>{"use strict";var Jd=["nodebuffer","arraybuffer","fragments"],Yd=typeof Blob<"u";Yd&&Jd.push("blob");Xd.exports={BINARY_TYPES:Jd,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Yd,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Ns=re((eS,Gi)=>{"use strict";var{EMPTY_BUFFER:ob}=Bt(),Wa=Buffer[Symbol.species];function ab(t,e){if(t.length===0)return ob;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let s=0;s<t.length;s++){let i=t[s];n.set(i,r),r+=i.length}return r<e?new Wa(n.buffer,n.byteOffset,r):n}function Qd(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function eh(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function lb(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Ja(t){if(Ja.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Wa(t):ArrayBuffer.isView(t)?e=new Wa(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Ja.readOnly=!1),e}Gi.exports={concat:ab,mask:Qd,toArrayBuffer:lb,toBuffer:Ja,unmask:eh};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");Gi.exports.mask=function(e,n,r,s,i){i<48?Qd(e,n,r,s,i):t.mask(e,n,r,s,i)},Gi.exports.unmask=function(e,n){e.length<32?eh(e,n):t.unmask(e,n)}}catch{}});var rh=re((tS,nh)=>{"use strict";var th=Symbol("kDone"),Ya=Symbol("kRun"),Xa=class{constructor(e){this[th]=()=>{this.pending--,this[Ya]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ya]()}[Ya](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[th])}}};nh.exports=Xa});var ss=re((nS,ah)=>{"use strict";var Ms=require("zlib"),sh=Ns(),ub=rh(),{kStatusCode:ih}=Bt(),cb=Buffer[Symbol.species],db=Buffer.from([0,0,255,255]),Wi=Symbol("permessage-deflate"),Kt=Symbol("total-length"),ns=Symbol("callback"),fn=Symbol("buffers"),rs=Symbol("error"),Vi,Qa=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,!Vi){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Vi=new ub(n)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[ns];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(s=>!(n.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>s.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let s=n[r];if(s.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(s=s[0],r==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else if(r==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=s})}),e}decompress(e,n,r){Vi.add(s=>{this._decompress(e,n,(i,o)=>{s(),r(i,o)})})}compress(e,n,r){Vi.add(s=>{this._compress(e,n,(i,o)=>{s(),r(i,o)})})}_decompress(e,n,r){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Ms.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Ms.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Wi]=this,this._inflate[Kt]=0,this._inflate[fn]=[],this._inflate.on("error",fb),this._inflate.on("data",oh)}this._inflate[ns]=r,this._inflate.write(e),n&&this._inflate.write(db),this._inflate.flush(()=>{let i=this._inflate[rs];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=sh.concat(this._inflate[fn],this._inflate[Kt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Kt]=0,this._inflate[fn]=[],n&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,n,r){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Ms.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Ms.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[Kt]=0,this._deflate[fn]=[],this._deflate.on("data",hb)}this._deflate[ns]=r,this._deflate.write(e),this._deflate.flush(Ms.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=sh.concat(this._deflate[fn],this._deflate[Kt]);n&&(i=new cb(i.buffer,i.byteOffset,i.length-4)),this._deflate[ns]=null,this._deflate[Kt]=0,this._deflate[fn]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};ah.exports=Qa;function hb(t){this[fn].push(t),this[Kt]+=t.length}function oh(t){if(this[Kt]+=t.length,this[Wi]._maxPayload<1||this[Kt]<=this[Wi]._maxPayload){this[fn].push(t);return}this[rs]=new RangeError("Max payload size exceeded"),this[rs].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[rs][ih]=1009,this.removeListener("data",oh),this.reset()}function fb(t){if(this[Wi]._inflate=null,this[rs]){this[ns](this[rs]);return}t[ih]=1007,this[ns](t)}});var is=re((rS,Ji)=>{"use strict";var{isUtf8:lh}=require("buffer"),{hasBlob:pb}=Bt(),mb=[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 gb(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function el(t){let e=t.length,n=0;for(;n<e;)if((t[n]&128)===0)n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function yb(t){return pb&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Ji.exports={isBlob:yb,isValidStatusCode:gb,isValidUTF8:el,tokenChars:mb};if(lh)Ji.exports.isValidUTF8=function(t){return t.length<24?el(t):lh(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");Ji.exports.isValidUTF8=function(e){return e.length<32?el(e):t(e)}}catch{}});var il=re((sS,mh)=>{"use strict";var{Writable:bb}=require("stream"),uh=ss(),{BINARY_TYPES:vb,EMPTY_BUFFER:ch,kStatusCode:wb,kWebSocket:_b}=Bt(),{concat:tl,toArrayBuffer:kb,unmask:Sb}=Ns(),{isValidStatusCode:Tb,isValidUTF8:dh}=is(),Yi=Buffer[Symbol.species],rt=0,hh=1,fh=2,ph=3,nl=4,rl=5,Xi=6,sl=class extends bb{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||vb[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[_b]=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=rt}_write(e,n,r){if(this._opcode===8&&this._state==rt)return r();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){r(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new Yi(r.buffer,r.byteOffset+e,r.length-e),new Yi(r.buffer,r.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let r=this._buffers[0],s=n.length-e;e>=r.length?n.set(this._buffers.shift(),s):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new Yi(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case rt:this.getInfo(e);break;case hh:this.getPayloadLength16(e);break;case fh:this.getPayloadLength64(e);break;case ph:this.getMask();break;case nl:this.getData(e);break;case rl:case Xi:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let r=(n[0]&64)===64;if(r&&!this._extensions[uh.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=hh:this._payloadLength===127?this._state=fh:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),r=n.readUInt32BE(0);if(r>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=r*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=ph:this._state=nl}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=nl}getData(e){let n=ch;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Sb(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let r=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(r);return}if(this._compressed){this._state=rl,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[uh.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return n(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(o);return}this._fragments.push(i)}this.dataMessage(n),this._state===rt&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=rt;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=tl(r,n):this._binaryType==="arraybuffer"?s=kb(tl(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=rt):(this._state=Xi,setImmediate(()=>{this.emit("message",s,!0),this._state=rt,this.startLoop(e)}))}else{let s=tl(r,n);if(!this._skipUTF8Validation&&!dh(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===rl||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=rt):(this._state=Xi,setImmediate(()=>{this.emit("message",s,!1),this._state=rt,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,ch),this.end();else{let r=e.readUInt16BE(0);if(!Tb(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new Yi(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!dh(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(i);return}this._loop=!1,this.emit("conclude",r,s),this.end()}this._state=rt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=rt):(this._state=Xi,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=rt,this.startLoop(n)}))}createError(e,n,r,s,i){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(o,this.createError),o.code=i,o[wb]=s,o}};mh.exports=sl});var ll=re((oS,bh)=>{"use strict";var{Duplex:iS}=require("stream"),{randomFillSync:xb}=require("crypto"),{types:{isUint8Array:Cb}}=require("util"),gh=ss(),{EMPTY_BUFFER:Ib,kWebSocket:Rb,NOOP:Eb}=Bt(),{isBlob:os,isValidStatusCode:Ab}=is(),{mask:yh,toBuffer:vr}=Ns(),st=Symbol("kByteLength"),$b=Buffer.alloc(4),Qi=8*1024,wr,as=Qi,ht=0,Pb=1,jb=2,ol=class t{constructor(e,n,r){this._extensions=n||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=ht,this.onerror=Eb,this[Rb]=void 0}static frame(e,n){let r,s=!1,i=2,o=!1;n.mask&&(r=n.maskBuffer||$b,n.generateMask?n.generateMask(r):(as===Qi&&(wr===void 0&&(wr=Buffer.alloc(Qi)),xb(wr,0,Qi),as=0),r[0]=wr[as++],r[1]=wr[as++],r[2]=wr[as++],r[3]=wr[as++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let l;typeof e=="string"?(!n.mask||o)&&n[st]!==void 0?l=n[st]:(e=Buffer.from(e),l=e.length):(l=e.length,s=n.mask&&n.readOnly&&!o);let u=l;l>=65536?(i+=8,u=127):l>125&&(i+=2,u=126);let c=Buffer.allocUnsafe(s?l+i:i);return c[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(c[0]|=64),c[1]=u,u===126?c.writeUInt16BE(l,2):u===127&&(c[2]=c[3]=0,c.writeUIntBE(l,4,6)),n.mask?(c[1]|=128,c[i-4]=r[0],c[i-3]=r[1],c[i-2]=r[2],c[i-1]=r[3],o?[c,e]:s?(yh(e,r,c,i,l),[c]):(yh(e,r,e,0,l),[c,e])):[c,e]}close(e,n,r,s){let i;if(e===void 0)i=Ib;else{if(typeof e!="number"||!Ab(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let l=Buffer.byteLength(n);if(l>123)throw new RangeError("The message must not be greater than 123 bytes");if(i=Buffer.allocUnsafe(2+l),i.writeUInt16BE(e,0),typeof n=="string")i.write(n,2);else if(Cb(n))i.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[st]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ht?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(t.frame(i,o),s)}ping(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):os(e)?(s=e.size,i=!1):(e=vr(e),s=e.length,i=vr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[st]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};os(e)?this._state!==ht?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==ht?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}pong(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):os(e)?(s=e.size,i=!1):(e=vr(e),s=e.length,i=vr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[st]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};os(e)?this._state!==ht?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==ht?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let s=this._extensions[gh.extensionName],i=n.binary?2:1,o=n.compress,l,u;typeof e=="string"?(l=Buffer.byteLength(e),u=!1):os(e)?(l=e.size,u=!1):(e=vr(e),l=e.length,u=vr.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=l>=s._threshold),this._compress=o):(o=!1,i=0),n.fin&&(this._firstFragment=!0);let c={[st]:l,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:u,rsv1:o};os(e)?this._state!==ht?this.enqueue([this.getBlobData,e,this._compress,c,r]):this.getBlobData(e,this._compress,c,r):this._state!==ht?this.enqueue([this.dispatch,e,this._compress,c,r]):this.dispatch(e,this._compress,c,r)}getBlobData(e,n,r,s){this._bufferedBytes+=r[st],this._state=jb,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let l=new Error("The socket was closed while the blob was being read");process.nextTick(al,this,l,s);return}this._bufferedBytes-=r[st];let o=vr(i);n?this.dispatch(o,n,r,s):(this._state=ht,this.sendFrame(t.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(Ob,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[gh.extensionName];this._bufferedBytes+=r[st],this._state=Pb,i.compress(e,r.fin,(o,l)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");al(this,u,s);return}this._bufferedBytes-=r[st],this._state=ht,r.readOnly=!1,this.sendFrame(t.frame(l,r),s),this.dequeue()})}dequeue(){for(;this._state===ht&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][st],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][st],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};bh.exports=ol;function al(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let s=t._queue[r],i=s[s.length-1];typeof i=="function"&&i(e)}}function Ob(t,e,n){al(t,e,n),t.onerror(e)}});var Ih=re((aS,Ch)=>{"use strict";var{kForOnEventAttribute:zs,kListener:ul}=Bt(),vh=Symbol("kCode"),wh=Symbol("kData"),_h=Symbol("kError"),kh=Symbol("kMessage"),Sh=Symbol("kReason"),ls=Symbol("kTarget"),Th=Symbol("kType"),xh=Symbol("kWasClean"),Ht=class{constructor(e){this[ls]=null,this[Th]=e}get target(){return this[ls]}get type(){return this[Th]}};Object.defineProperty(Ht.prototype,"target",{enumerable:!0});Object.defineProperty(Ht.prototype,"type",{enumerable:!0});var _r=class extends Ht{constructor(e,n={}){super(e),this[vh]=n.code===void 0?0:n.code,this[Sh]=n.reason===void 0?"":n.reason,this[xh]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[vh]}get reason(){return this[Sh]}get wasClean(){return this[xh]}};Object.defineProperty(_r.prototype,"code",{enumerable:!0});Object.defineProperty(_r.prototype,"reason",{enumerable:!0});Object.defineProperty(_r.prototype,"wasClean",{enumerable:!0});var us=class extends Ht{constructor(e,n={}){super(e),this[_h]=n.error===void 0?null:n.error,this[kh]=n.message===void 0?"":n.message}get error(){return this[_h]}get message(){return this[kh]}};Object.defineProperty(us.prototype,"error",{enumerable:!0});Object.defineProperty(us.prototype,"message",{enumerable:!0});var Ds=class extends Ht{constructor(e,n={}){super(e),this[wh]=n.data===void 0?null:n.data}get data(){return this[wh]}};Object.defineProperty(Ds.prototype,"data",{enumerable:!0});var Nb={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[zs]&&s[ul]===e&&!s[zs])return;let r;if(t==="message")r=function(i,o){let l=new Ds("message",{data:o?i:i.toString()});l[ls]=this,eo(e,this,l)};else if(t==="close")r=function(i,o){let l=new _r("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});l[ls]=this,eo(e,this,l)};else if(t==="error")r=function(i){let o=new us("error",{error:i,message:i.message});o[ls]=this,eo(e,this,o)};else if(t==="open")r=function(){let i=new Ht("open");i[ls]=this,eo(e,this,i)};else return;r[zs]=!!n[zs],r[ul]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[ul]===e&&!n[zs]){this.removeListener(t,n);break}}};Ch.exports={CloseEvent:_r,ErrorEvent:us,Event:Ht,EventTarget:Nb,MessageEvent:Ds};function eo(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var to=re((lS,Rh)=>{"use strict";var{tokenChars:Ls}=is();function xt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function Mb(t){let e=Object.create(null),n=Object.create(null),r=!1,s=!1,i=!1,o,l,u=-1,c=-1,f=-1,p=0;for(;p<t.length;p++)if(c=t.charCodeAt(p),o===void 0)if(f===-1&&Ls[c]===1)u===-1&&(u=p);else if(p!==0&&(c===32||c===9))f===-1&&u!==-1&&(f=p);else if(c===59||c===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let w=t.slice(u,f);c===44?(xt(e,w,n),n=Object.create(null)):o=w,u=f=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(l===void 0)if(f===-1&&Ls[c]===1)u===-1&&(u=p);else if(c===32||c===9)f===-1&&u!==-1&&(f=p);else if(c===59||c===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),xt(n,t.slice(u,f),!0),c===44&&(xt(e,o,n),n=Object.create(null),o=void 0),u=f=-1}else if(c===61&&u!==-1&&f===-1)l=t.slice(u,p),u=f=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(s){if(Ls[c]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:r||(r=!0),s=!1}else if(i)if(Ls[c]===1)u===-1&&(u=p);else if(c===34&&u!==-1)i=!1,f=p;else if(c===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(c===34&&t.charCodeAt(p-1)===61)i=!0;else if(f===-1&&Ls[c]===1)u===-1&&(u=p);else if(u!==-1&&(c===32||c===9))f===-1&&(f=p);else if(c===59||c===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let w=t.slice(u,f);r&&(w=w.replace(/\\/g,""),r=!1),xt(n,l,w),c===44&&(xt(e,o,n),n=Object.create(null),o=void 0),l=void 0,u=f=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(u===-1||i||c===32||c===9)throw new SyntaxError("Unexpected end of input");f===-1&&(f=p);let b=t.slice(u,f);return o===void 0?xt(e,b,n):(l===void 0?xt(n,b,!0):r?xt(n,l,b.replace(/\\/g,"")):xt(n,l,b),xt(e,o,n)),e}function zb(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(r=>[e].concat(Object.keys(r).map(s=>{let i=r[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Rh.exports={format:zb,parse:Mb}});var io=re((dS,Uh)=>{"use strict";var Db=require("events"),Lb=require("https"),Ub=require("http"),$h=require("net"),qb=require("tls"),{randomBytes:Fb,createHash:Bb}=require("crypto"),{Duplex:uS,Readable:cS}=require("stream"),{URL:cl}=require("url"),pn=ss(),Kb=il(),Hb=ll(),{isBlob:Zb}=is(),{BINARY_TYPES:Eh,CLOSE_TIMEOUT:Gb,EMPTY_BUFFER:no,GUID:Vb,kForOnEventAttribute:dl,kListener:Wb,kStatusCode:Jb,kWebSocket:Se,NOOP:Ph}=Bt(),{EventTarget:{addEventListener:Yb,removeEventListener:Xb}}=Ih(),{format:Qb,parse:ev}=to(),{toBuffer:tv}=Ns(),jh=Symbol("kAborted"),hl=[8,13],Zt=["CONNECTING","OPEN","CLOSING","CLOSED"],nv=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,fe=class t extends Db{constructor(e,n,r){super(),this._binaryType=Eh[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=no,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),Oh(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Eh.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,r){let s=new Kb({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new Hb(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[Se]=this,i[Se]=this,e[Se]=this,s.on("conclude",iv),s.on("drain",ov),s.on("error",av),s.on("message",lv),s.on("ping",uv),s.on("pong",cv),i.onerror=dv,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",zh),e.on("data",so),e.on("end",Dh),e.on("error",Lh),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[pn.extensionName]&&this._extensions[pn.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){He(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Mh(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){fl(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||no,n,r)}pong(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){fl(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||no,n,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){fl(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[pn.extensionName]||(s.compress=!1),this._sender.send(e||no,s,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){He(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(fe,"CONNECTING",{enumerable:!0,value:Zt.indexOf("CONNECTING")});Object.defineProperty(fe.prototype,"CONNECTING",{enumerable:!0,value:Zt.indexOf("CONNECTING")});Object.defineProperty(fe,"OPEN",{enumerable:!0,value:Zt.indexOf("OPEN")});Object.defineProperty(fe.prototype,"OPEN",{enumerable:!0,value:Zt.indexOf("OPEN")});Object.defineProperty(fe,"CLOSING",{enumerable:!0,value:Zt.indexOf("CLOSING")});Object.defineProperty(fe.prototype,"CLOSING",{enumerable:!0,value:Zt.indexOf("CLOSING")});Object.defineProperty(fe,"CLOSED",{enumerable:!0,value:Zt.indexOf("CLOSED")});Object.defineProperty(fe.prototype,"CLOSED",{enumerable:!0,value:Zt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(fe.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(fe.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[dl])return e[Wb];return null},set(e){for(let n of this.listeners(t))if(n[dl]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[dl]:!0})}})});fe.prototype.addEventListener=Yb;fe.prototype.removeEventListener=Xb;Uh.exports=fe;function Oh(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Gb,protocolVersion:hl[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=s.autoPong,t._closeTimeout=s.closeTimeout,!hl.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${hl.join(", ")})`);let i;if(e instanceof cl)i=e;else try{i=new cl(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),t._url=i.href;let o=i.protocol==="wss:",l=i.protocol==="ws+unix:",u;if(i.protocol!=="ws:"&&!o&&!l?u=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:l&&!i.pathname?u="The URL's pathname is empty":i.hash&&(u="The URL contains a fragment identifier"),u){let x=new SyntaxError(u);if(t._redirects===0)throw x;ro(t,x);return}let c=o?443:80,f=Fb(16).toString("base64"),p=o?Lb.request:Ub.request,b=new Set,w;if(s.createConnection=s.createConnection||(o?sv:rv),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":f,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(w=new pn({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=Qb({[pn.extensionName]:w.offer()})),n.length){for(let x of n){if(typeof x!="string"||!nv.test(x)||b.has(x))throw new SyntaxError("An invalid or duplicated subprotocol was specified");b.add(x)}s.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),l){let x=s.path.split(":");s.socketPath=x[0],s.path=x[1]}let S;if(s.followRedirects){if(t._redirects===0){t._originalIpc=l,t._originalSecure=o,t._originalHostOrSocketPath=l?s.socketPath:i.host;let x=r&&r.headers;if(r={...r,headers:{}},x)for(let[A,j]of Object.entries(x))r.headers[A.toLowerCase()]=j}else if(t.listenerCount("redirect")===0){let x=l?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!x||t._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,x||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),S=t._req=p(s),t._redirects&&t.emit("redirect",t.url,S)}else S=t._req=p(s);s.timeout&&S.on("timeout",()=>{He(t,S,"Opening handshake has timed out")}),S.on("error",x=>{S===null||S[jh]||(S=t._req=null,ro(t,x))}),S.on("response",x=>{let A=x.headers.location,j=x.statusCode;if(A&&s.followRedirects&&j>=300&&j<400){if(++t._redirects>s.maxRedirects){He(t,S,"Maximum redirects exceeded");return}S.abort();let v;try{v=new cl(A,e)}catch{let H=new SyntaxError(`Invalid URL: ${A}`);ro(t,H);return}Oh(t,v,n,r)}else t.emit("unexpected-response",S,x)||He(t,S,`Unexpected server response: ${x.statusCode}`)}),S.on("upgrade",(x,A,j)=>{if(t.emit("upgrade",x),t.readyState!==fe.CONNECTING)return;S=t._req=null;let v=x.headers.upgrade;if(v===void 0||v.toLowerCase()!=="websocket"){He(t,A,"Invalid Upgrade header");return}let O=Bb("sha1").update(f+Vb).digest("base64");if(x.headers["sec-websocket-accept"]!==O){He(t,A,"Invalid Sec-WebSocket-Accept header");return}let H=x.headers["sec-websocket-protocol"],z;if(H!==void 0?b.size?b.has(H)||(z="Server sent an invalid subprotocol"):z="Server sent a subprotocol but none was requested":b.size&&(z="Server sent no subprotocol"),z){He(t,A,z);return}H&&(t._protocol=H);let B=x.headers["sec-websocket-extensions"];if(B!==void 0){if(!w){He(t,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let d;try{d=ev(B)}catch{He(t,A,"Invalid Sec-WebSocket-Extensions header");return}let m=Object.keys(d);if(m.length!==1||m[0]!==pn.extensionName){He(t,A,"Server indicated an extension that was not requested");return}try{w.accept(d[pn.extensionName])}catch{He(t,A,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[pn.extensionName]=w}t.setSocket(A,j,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(S,t):S.end()}function ro(t,e){t._readyState=fe.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function rv(t){return t.path=t.socketPath,$h.connect(t)}function sv(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=$h.isIP(t.host)?"":t.host),qb.connect(t)}function He(t,e,n){t._readyState=fe.CLOSING;let r=new Error(n);Error.captureStackTrace(r,He),e.setHeader?(e[jh]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ro,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function fl(t,e,n){if(e){let r=Zb(e)?e.size:tv(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${Zt[t.readyState]})`);process.nextTick(n,r)}}function iv(t,e){let n=this[Se];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[Se]!==void 0&&(n._socket.removeListener("data",so),process.nextTick(Nh,n._socket),t===1005?n.close():n.close(t,e))}function ov(){let t=this[Se];t.isPaused||t._socket.resume()}function av(t){let e=this[Se];e._socket[Se]!==void 0&&(e._socket.removeListener("data",so),process.nextTick(Nh,e._socket),e.close(t[Jb])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Ah(){this[Se].emitClose()}function lv(t,e){this[Se].emit("message",t,e)}function uv(t){let e=this[Se];e._autoPong&&e.pong(t,!this._isServer,Ph),e.emit("ping",t)}function cv(t){this[Se].emit("pong",t)}function Nh(t){t.resume()}function dv(t){let e=this[Se];e.readyState!==fe.CLOSED&&(e.readyState===fe.OPEN&&(e._readyState=fe.CLOSING,Mh(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Mh(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function zh(){let t=this[Se];if(this.removeListener("close",zh),this.removeListener("data",so),this.removeListener("end",Dh),t._readyState=fe.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[Se]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Ah),t._receiver.on("finish",Ah))}function so(t){this[Se]._receiver.write(t)||this.pause()}function Dh(){let t=this[Se];t._readyState=fe.CLOSING,t._receiver.end(),this.end()}function Lh(){let t=this[Se];this.removeListener("error",Lh),this.on("error",Ph),t&&(t._readyState=fe.CLOSING,this.destroy())}});var Kh=re((fS,Bh)=>{"use strict";var hS=io(),{Duplex:hv}=require("stream");function qh(t){t.emit("close")}function fv(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Fh(t){this.removeListener("error",Fh),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function pv(t,e){let n=!0,r=new hv({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,o){let l=!o&&r._readableState.objectMode?i.toString():i;r.push(l)||t.pause()}),t.once("error",function(i){r.destroyed||(n=!1,r.destroy(i))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(s,i){if(t.readyState===t.CLOSED){i(s),process.nextTick(qh,r);return}let o=!1;t.once("error",function(u){o=!0,i(u)}),t.once("close",function(){o||i(s),process.nextTick(qh,r)}),n&&t.terminate()},r._final=function(s){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(s)});return}t._socket!==null&&(t._socket._writableState.finished?(s(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){s()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(s,i,o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(s,i,o)});return}t.send(s,o)},r.on("end",fv),r.on("error",Fh),r}Bh.exports=pv});var pl=re((pS,Hh)=>{"use strict";var{tokenChars:mv}=is();function gv(t){let e=new Set,n=-1,r=-1,s=0;for(s;s<t.length;s++){let o=t.charCodeAt(s);if(r===-1&&mv[o]===1)n===-1&&(n=s);else if(s!==0&&(o===32||o===9))r===-1&&n!==-1&&(r=s);else if(o===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${s}`);r===-1&&(r=s);let l=t.slice(n,r);if(e.has(l))throw new SyntaxError(`The "${l}" subprotocol is duplicated`);e.add(l),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(n,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}Hh.exports={parse:gv}});var Xh=re((gS,Yh)=>{"use strict";var yv=require("events"),oo=require("http"),{Duplex:mS}=require("stream"),{createHash:bv}=require("crypto"),Zh=to(),kr=ss(),vv=pl(),wv=io(),{CLOSE_TIMEOUT:_v,GUID:kv,kWebSocket:Sv}=Bt(),Tv=/^[+/0-9A-Za-z]{22}==$/,Gh=0,Vh=1,Jh=2,ml=class extends yv{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:_v,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:wv,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=oo.createServer((r,s)=>{let i=oo.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=xv(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Gh}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===Jh){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Us,this);return}if(e&&this.once("close",e),this._state!==Vh)if(this._state=Vh,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(Us,this):process.nextTick(Us,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Us(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,r,s){n.on("error",Wh);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,l=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Sr(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Sr(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!Tv.test(i)){Sr(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(l!==13&&l!==8){Sr(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){qs(n,400);return}let u=e.headers["sec-websocket-protocol"],c=new Set;if(u!==void 0)try{c=vv.parse(u)}catch{Sr(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let f=e.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&f!==void 0){let b=new kr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let w=Zh.parse(f);w[kr.extensionName]&&(b.accept(w[kr.extensionName]),p[kr.extensionName]=b)}catch{Sr(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let b={origin:e.headers[`${l===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(b,(w,S,x,A)=>{if(!w)return qs(n,S||401,x,A);this.completeUpgrade(p,i,c,e,n,r,s)});return}if(!this.options.verifyClient(b))return qs(n,401)}this.completeUpgrade(p,i,c,e,n,r,s)}completeUpgrade(e,n,r,s,i,o,l){if(!i.readable||!i.writable)return i.destroy();if(i[Sv])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Gh)return qs(i,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${bv("sha1").update(n+kv).digest("base64")}`],f=new this.options.WebSocket(null,void 0,this.options);if(r.size){let p=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;p&&(c.push(`Sec-WebSocket-Protocol: ${p}`),f._protocol=p)}if(e[kr.extensionName]){let p=e[kr.extensionName].params,b=Zh.format({[kr.extensionName]:[p]});c.push(`Sec-WebSocket-Extensions: ${b}`),f._extensions=e}this.emit("headers",c,s),i.write(c.concat(`\r
|
|
286
286
|
`).join(`\r
|
|
287
287
|
`)),i.removeListener("error",Wh),f.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(f),f.on("close",()=>{this.clients.delete(f),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Us,this)})),l(f,s)}};Yh.exports=ml;function xv(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let r of Object.keys(e))t.removeListener(r,e[r])}}function Us(t){t._state=Jh,t.emit("close")}function Wh(){this.destroy()}function qs(t,e,n,r){n=n||oo.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...r},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${oo.STATUS_CODES[e]}\r
|
|
288
288
|
`+Object.keys(r).map(s=>`${s}: ${r[s]}`).join(`\r
|
|
289
289
|
`)+`\r
|
|
290
290
|
\r
|
|
291
|
-
`+n)}function Sr(t,e,n,r,s,i){if(t.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,Sr),t.emit("wsClientError",o,n,e)}else qs(n,r,s,i)}});var cf={};Gs(cf,{buildSetupReport:()=>Kv,claudeLoggedIn:()=>uf,repoDefaultBranch:()=>lf});function lf(t){let e=(...s)=>{try{return(0,ho.execFileSync)("git",["-C",t,...s],{encoding:"utf8",timeout:1e4}).trim()}catch{return null}},n=e("symbolic-ref","--short","refs/remotes/origin/HEAD");if(n?.startsWith("origin/"))return n.slice(7);let r=e("rev-parse","--abbrev-ref","HEAD");return r&&r!=="HEAD"?r:""}function uf(t=of.default.homedir()){if(mn.default.existsSync(xr.default.join(t,".claude",".credentials.json")))return!0;try{return!!JSON.parse(mn.default.readFileSync(xr.default.join(t,".claude.json"),"utf8")).oauthAccount}catch{return!1}}async function Kv(t,e){let n=!1,r="";if(Ks&&Date.now()-Ks.at<6e4)n=Ks.installed,r=Ks.version;else{try{let{stdout:o}=await Bv(t.claudeBin,["--version"],{timeout:1e4});n=!0,r=o.trim().slice(0,60)}catch{n=!1}Ks={at:Date.now(),installed:n,version:r}}let s=e.map(o=>{let l=t.repos[o];if(!l)return{repoName:o,mapped:!1,pathExists:!1,isGit:!1,claudeMd:!1,deployMd:!1,testMd:!1,githubToken:!1,githubTokenOwn:!1,defaultBranch:""};let u=mn.default.existsSync(l.path);return{repoName:o,mapped:!0,pathExists:u,isGit:u&&mn.default.existsSync(xr.default.join(l.path,".git")),claudeMd:u&&mn.default.existsSync(xr.default.join(l.path,"CLAUDE.md")),deployMd:u&&mn.default.existsSync(xr.default.join(l.path,"DEPLOY.md")),testMd:u&&mn.default.existsSync(xr.default.join(l.path,"TEST.md")),githubToken:!!Ee(t,o),githubTokenOwn:!!l.github?.token,defaultBranch:u?lf(l.path):""}}),i=Object.values(t.repos).find(o=>o.github?.token);return{jiraConfigured:!!t.jira,jiraEmail:t.jira?.email??"",claude:{installed:n,version:r,loggedIn:uf()},githubTokenSet:!!(t.github?.token||i),githubLogin:t.github?.login??i?.github?.login??"",deploysEnabled:t.deploy.enabled,jiraUserCount:Object.keys(t.jiraUsers).length,repos:s}}var ho,mn,of,xr,af,Bv,Ks,df=Zs(()=>{"use strict";ho=require("node:child_process"),mn=I(require("node:fs"),1),of=I(require("node:os"),1),xr=I(require("node:path"),1),af=require("node:util");nr();Bv=(0,af.promisify)(ho.execFile);Ks=null});var ft=I(require("node:fs"),1),wl=I(require("node:os"),1),ds=I(require("node:path"),1),Gt=require("node:child_process"),Hs=require("node:crypto"),yn=I(require("node:readline/promises"),1);var Dl=I(zl(),1),{program:ew,createCommand:tw,createArgument:nw,createOption:rw,CommanderError:sw,InvalidArgumentError:iw,InvalidOptionArgumentError:ow,Command:Ll,Argument:aw,Option:lw,Help:uw}=Dl.default;var Pt=I(require("node:fs"),1),ti=I(require("node:os"),1),ni=I(require("node:path"),1);var _={};Gs(_,{BRAND:()=>op,DIRTY:()=>bn,EMPTY_PATH:()=>Df,INVALID:()=>K,NEVER:()=>Kp,OK:()=>Re,ParseStatus:()=>xe,Schema:()=>Q,ZodAny:()=>Jt,ZodArray:()=>$t,ZodBigInt:()=>wn,ZodBoolean:()=>_n,ZodBranded:()=>gs,ZodCatch:()=>Pn,ZodDate:()=>kn,ZodDefault:()=>$n,ZodDiscriminatedUnion:()=>Xs,ZodEffects:()=>Ye,ZodEnum:()=>An,ZodError:()=>Me,ZodFirstPartyTypeKind:()=>Z,ZodFunction:()=>ei,ZodIntersection:()=>Cn,ZodIssueCode:()=>R,ZodLazy:()=>In,ZodLiteral:()=>Rn,ZodMap:()=>Pr,ZodNaN:()=>Or,ZodNativeEnum:()=>En,ZodNever:()=>it,ZodNull:()=>Tn,ZodNullable:()=>gt,ZodNumber:()=>vn,ZodObject:()=>ze,ZodOptional:()=>We,ZodParsedType:()=>N,ZodPipeline:()=>ys,ZodPromise:()=>Yt,ZodReadonly:()=>jn,ZodRecord:()=>Qs,ZodSchema:()=>Q,ZodSet:()=>jr,ZodString:()=>Wt,ZodSymbol:()=>Er,ZodTransformer:()=>Ye,ZodTuple:()=>mt,ZodType:()=>Q,ZodUndefined:()=>Sn,ZodUnion:()=>xn,ZodUnknown:()=>Et,ZodVoid:()=>$r,addIssueToContext:()=>P,any:()=>mp,array:()=>vp,bigint:()=>cp,boolean:()=>Jl,coerce:()=>Bp,custom:()=>Gl,date:()=>dp,datetimeRegex:()=>Hl,defaultErrorMap:()=>Rt,discriminatedUnion:()=>Sp,effect:()=>Np,enum:()=>Pp,function:()=>Ap,getErrorMap:()=>Ir,getParsedType:()=>pt,instanceof:()=>lp,intersection:()=>Tp,isAborted:()=>Js,isAsync:()=>Rr,isDirty:()=>Ys,isValid:()=>Vt,late:()=>ap,lazy:()=>Ep,literal:()=>$p,makeIssue:()=>ms,map:()=>Ip,nan:()=>up,nativeEnum:()=>jp,never:()=>yp,null:()=>pp,nullable:()=>zp,number:()=>Wl,object:()=>wp,objectUtil:()=>Eo,oboolean:()=>Fp,onumber:()=>qp,optional:()=>Mp,ostring:()=>Up,pipeline:()=>Lp,preprocess:()=>Dp,promise:()=>Op,quotelessJson:()=>Nf,record:()=>Cp,set:()=>Rp,setErrorMap:()=>zf,strictObject:()=>_p,string:()=>Vl,symbol:()=>hp,transformer:()=>Np,tuple:()=>xp,undefined:()=>fp,union:()=>kp,unknown:()=>gp,util:()=>te,void:()=>bp});var te;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function n(s){throw new Error}t.assertNever=n,t.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},t.getValidEnumValues=s=>{let i=t.objectKeys(s).filter(l=>typeof s[s[l]]!="number"),o={};for(let l of i)o[l]=s[l];return t.objectValues(o)},t.objectValues=s=>t.objectKeys(s).map(function(i){return s[i]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},t.find=(s,i)=>{for(let o of s)if(i(o))return o},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(te||(te={}));var Eo;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Eo||(Eo={}));var N=te.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),pt=t=>{switch(typeof t){case"undefined":return N.undefined;case"string":return N.string;case"number":return Number.isNaN(t)?N.nan:N.number;case"boolean":return N.boolean;case"function":return N.function;case"bigint":return N.bigint;case"symbol":return N.symbol;case"object":return Array.isArray(t)?N.array:t===null?N.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?N.promise:typeof Map<"u"&&t instanceof Map?N.map:typeof Set<"u"&&t instanceof Set?N.set:typeof Date<"u"&&t instanceof Date?N.date:N.object;default:return N.unknown}};var R=te.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"]),Nf=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Me=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(i){return i.message},r={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)r._errors.push(n(o));else{let l=r,u=0;for(;u<o.path.length;){let c=o.path[u];u===o.path.length-1?(l[c]=l[c]||{_errors:[]},l[c]._errors.push(n(o))):l[c]=l[c]||{_errors:[]},l=l[c],u++}}};return s(this),r}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,te.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];n[i]=n[i]||[],n[i].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};Me.create=t=>new Me(t);var Mf=(t,e)=>{let n;switch(t.code){case R.invalid_type:t.received===N.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case R.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,te.jsonStringifyReplacer)}`;break;case R.unrecognized_keys:n=`Unrecognized key(s) in object: ${te.joinValues(t.keys,", ")}`;break;case R.invalid_union:n="Invalid input";break;case R.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${te.joinValues(t.options)}`;break;case R.invalid_enum_value:n=`Invalid enum value. Expected ${te.joinValues(t.options)}, received '${t.received}'`;break;case R.invalid_arguments:n="Invalid function arguments";break;case R.invalid_return_type:n="Invalid function return type";break;case R.invalid_date:n="Invalid date";break;case R.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:te.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case R.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case R.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case R.custom:n="Invalid input";break;case R.invalid_intersection_types:n="Intersection results could not be merged";break;case R.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case R.not_finite:n="Number must be finite";break;default:n=e.defaultError,te.assertNever(t)}return{message:n}},Rt=Mf;var Ul=Rt;function zf(t){Ul=t}function Ir(){return Ul}var ms=t=>{let{data:e,path:n,errorMaps:r,issueData:s}=t,i=[...n,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let l="",u=r.filter(c=>!!c).slice().reverse();for(let c of u)l=c(o,{data:e,defaultError:l}).message;return{...s,path:i,message:l}},Df=[];function P(t,e){let n=Ir(),r=ms({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Rt?void 0:Rt].filter(s=>!!s)});t.common.issues.push(r)}var xe=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let s of n){if(s.status==="aborted")return K;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let s of n){let i=await s.key,o=await s.value;r.push({key:i,value:o})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let s of n){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return K;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(r[i.value]=o.value)}return{status:e.value,value:r}}},K=Object.freeze({status:"aborted"}),bn=t=>({status:"dirty",value:t}),Re=t=>({status:"valid",value:t}),Js=t=>t.status==="aborted",Ys=t=>t.status==="dirty",Vt=t=>t.status==="valid",Rr=t=>typeof Promise<"u"&&t instanceof Promise;var L;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(L||(L={}));var Je=class{constructor(e,n,r,s){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},ql=(t,e)=>{if(Vt(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new Me(t.common.issues);return this._error=n,this._error}}};function J(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:s}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,l)=>{let{message:u}=t;return o.code==="invalid_enum_value"?{message:u??l.defaultError}:typeof l.data>"u"?{message:u??r??l.defaultError}:o.code!=="invalid_type"?{message:l.defaultError}:{message:u??n??l.defaultError}},description:s}}var Q=class{get description(){return this._def.description}_getType(e){return pt(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:pt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new xe,ctx:{common:e.parent.common,data:e.data,parsedType:pt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(Rr(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:pt(e)},s=this._parseSync({data:e,path:r.path,parent:r});return ql(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:pt(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return Vt(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>Vt(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:pt(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(Rr(s)?s:Promise.resolve(s));return ql(r,i)}refine(e,n){let r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,i)=>{let o=e(s),l=()=>i.addIssue({code:R.custom,...r(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(u=>u?!0:(l(),!1)):o?!0:(l(),!1)})}refinement(e,n){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(e){return new Ye({schema:this,typeName:Z.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return We.create(this,this._def)}nullable(){return gt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return $t.create(this)}promise(){return Yt.create(this,this._def)}or(e){return xn.create([this,e],this._def)}and(e){return Cn.create(this,e,this._def)}transform(e){return new Ye({...J(this._def),schema:this,typeName:Z.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new $n({...J(this._def),innerType:this,defaultValue:n,typeName:Z.ZodDefault})}brand(){return new gs({typeName:Z.ZodBranded,type:this,...J(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Pn({...J(this._def),innerType:this,catchValue:n,typeName:Z.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return ys.create(this,e)}readonly(){return jn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Lf=/^c[^\s-]{8,}$/i,Uf=/^[0-9a-z]+$/,qf=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ff=/^[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,Bf=/^[a-z0-9_-]{21}$/i,Kf=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Hf=/^[-+]?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,Gf="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",$o,Vf=/^(?:(?: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])$/,Wf=/^(?:(?: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])$/,Jf=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Yf=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Xf=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Qf=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Bl="((\\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])))",ep=new RegExp(`^${Bl}$`);function Kl(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function tp(t){return new RegExp(`^${Kl(t)}$`)}function Hl(t){let e=`${Bl}T${Kl(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function np(t,e){return!!((e==="v4"||!e)&&Vf.test(t)||(e==="v6"||!e)&&Jf.test(t))}function rp(t,e){if(!Kf.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function sp(t,e){return!!((e==="v4"||!e)&&Wf.test(t)||(e==="v6"||!e)&&Yf.test(t))}var Wt=class t extends Q{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==N.string){let i=this._getOrReturnCtx(e);return P(i,{code:R.invalid_type,expected:N.string,received:i.parsedType}),K}let r=new xe,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),P(s,{code:R.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),P(s,{code:R.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,l=e.data.length<i.value;(o||l)&&(s=this._getOrReturnCtx(e,s),o?P(s,{code:R.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):l&&P(s,{code:R.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")Zf.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"email",code:R.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")$o||($o=new RegExp(Gf,"u")),$o.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"emoji",code:R.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")Ff.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"uuid",code:R.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")Bf.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"nanoid",code:R.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")Lf.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"cuid",code:R.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")Uf.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"cuid2",code:R.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")qf.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"ulid",code:R.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),P(s,{validation:"url",code:R.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"regex",code:R.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),P(s,{code:R.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),P(s,{code:R.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),P(s,{code:R.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Hl(i).test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{code:R.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?ep.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{code:R.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?tp(i).test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{code:R.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?Hf.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"duration",code:R.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?np(e.data,i.version)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"ip",code:R.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?rp(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"jwt",code:R.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?sp(e.data,i.version)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"cidr",code:R.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?Xf.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"base64",code:R.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?Qf.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"base64url",code:R.invalid_string,message:i.message}),r.dirty()):te.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:R.invalid_string,...L.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...L.errToObj(e)})}url(e){return this._addCheck({kind:"url",...L.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...L.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...L.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...L.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...L.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...L.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...L.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...L.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...L.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...L.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...L.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...L.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,...L.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,...L.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...L.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...L.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...L.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...L.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...L.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...L.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...L.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...L.errToObj(n)})}nonempty(e){return this.min(1,L.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};Wt.create=t=>new Wt({checks:[],typeName:Z.ZodString,coerce:t?.coerce??!1,...J(t)});function ip(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,i=Number.parseInt(t.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var vn=class t extends Q{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==N.number){let i=this._getOrReturnCtx(e);return P(i,{code:R.invalid_type,expected:N.number,received:i.parsedType}),K}let r,s=new xe;for(let i of this._def.checks)i.kind==="int"?te.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{code:R.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),P(r,{code:R.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),P(r,{code:R.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?ip(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),P(r,{code:R.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{code:R.not_finite,message:i.message}),s.dirty()):te.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,L.toString(n))}gt(e,n){return this.setLimit("min",e,!1,L.toString(n))}lte(e,n){return this.setLimit("max",e,!0,L.toString(n))}lt(e,n){return this.setLimit("max",e,!1,L.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:L.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:L.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:L.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:L.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:L.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:L.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:L.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:L.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:L.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:L.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&te.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};vn.create=t=>new vn({checks:[],typeName:Z.ZodNumber,coerce:t?.coerce||!1,...J(t)});var wn=class t extends Q{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==N.bigint)return this._getInvalidInput(e);let r,s=new xe;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),P(r,{code:R.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),P(r,{code:R.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),P(r,{code:R.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):te.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return P(n,{code:R.invalid_type,expected:N.bigint,received:n.parsedType}),K}gte(e,n){return this.setLimit("min",e,!0,L.toString(n))}gt(e,n){return this.setLimit("min",e,!1,L.toString(n))}lte(e,n){return this.setLimit("max",e,!0,L.toString(n))}lt(e,n){return this.setLimit("max",e,!1,L.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:L.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:L.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:L.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:L.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:L.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:L.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};wn.create=t=>new wn({checks:[],typeName:Z.ZodBigInt,coerce:t?.coerce??!1,...J(t)});var _n=class extends Q{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==N.boolean){let r=this._getOrReturnCtx(e);return P(r,{code:R.invalid_type,expected:N.boolean,received:r.parsedType}),K}return Re(e.data)}};_n.create=t=>new _n({typeName:Z.ZodBoolean,coerce:t?.coerce||!1,...J(t)});var kn=class t extends Q{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==N.date){let i=this._getOrReturnCtx(e);return P(i,{code:R.invalid_type,expected:N.date,received:i.parsedType}),K}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return P(i,{code:R.invalid_date}),K}let r=new xe,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),P(s,{code:R.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),P(s,{code:R.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):te.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:L.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:L.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};kn.create=t=>new kn({checks:[],coerce:t?.coerce||!1,typeName:Z.ZodDate,...J(t)});var Er=class extends Q{_parse(e){if(this._getType(e)!==N.symbol){let r=this._getOrReturnCtx(e);return P(r,{code:R.invalid_type,expected:N.symbol,received:r.parsedType}),K}return Re(e.data)}};Er.create=t=>new Er({typeName:Z.ZodSymbol,...J(t)});var Sn=class extends Q{_parse(e){if(this._getType(e)!==N.undefined){let r=this._getOrReturnCtx(e);return P(r,{code:R.invalid_type,expected:N.undefined,received:r.parsedType}),K}return Re(e.data)}};Sn.create=t=>new Sn({typeName:Z.ZodUndefined,...J(t)});var Tn=class extends Q{_parse(e){if(this._getType(e)!==N.null){let r=this._getOrReturnCtx(e);return P(r,{code:R.invalid_type,expected:N.null,received:r.parsedType}),K}return Re(e.data)}};Tn.create=t=>new Tn({typeName:Z.ZodNull,...J(t)});var Jt=class extends Q{constructor(){super(...arguments),this._any=!0}_parse(e){return Re(e.data)}};Jt.create=t=>new Jt({typeName:Z.ZodAny,...J(t)});var Et=class extends Q{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Re(e.data)}};Et.create=t=>new Et({typeName:Z.ZodUnknown,...J(t)});var it=class extends Q{_parse(e){let n=this._getOrReturnCtx(e);return P(n,{code:R.invalid_type,expected:N.never,received:n.parsedType}),K}};it.create=t=>new it({typeName:Z.ZodNever,...J(t)});var $r=class extends Q{_parse(e){if(this._getType(e)!==N.undefined){let r=this._getOrReturnCtx(e);return P(r,{code:R.invalid_type,expected:N.void,received:r.parsedType}),K}return Re(e.data)}};$r.create=t=>new $r({typeName:Z.ZodVoid,...J(t)});var $t=class t extends Q{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==N.array)return P(n,{code:R.invalid_type,expected:N.array,received:n.parsedType}),K;if(s.exactLength!==null){let o=n.data.length>s.exactLength.value,l=n.data.length<s.exactLength.value;(o||l)&&(P(n,{code:o?R.too_big:R.too_small,minimum:l?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(P(n,{code:R.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(P(n,{code:R.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((o,l)=>s.type._parseAsync(new Je(n,o,n.path,l)))).then(o=>xe.mergeArray(r,o));let i=[...n.data].map((o,l)=>s.type._parseSync(new Je(n,o,n.path,l)));return xe.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:L.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:L.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:L.toString(n)}})}nonempty(e){return this.min(1,e)}};$t.create=(t,e)=>new $t({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Z.ZodArray,...J(e)});function Ar(t){if(t instanceof ze){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=We.create(Ar(r))}return new ze({...t._def,shape:()=>e})}else return t instanceof $t?new $t({...t._def,type:Ar(t.element)}):t instanceof We?We.create(Ar(t.unwrap())):t instanceof gt?gt.create(Ar(t.unwrap())):t instanceof mt?mt.create(t.items.map(e=>Ar(e))):t}var ze=class t extends Q{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),n=te.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==N.object){let c=this._getOrReturnCtx(e);return P(c,{code:R.invalid_type,expected:N.object,received:c.parsedType}),K}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),l=[];if(!(this._def.catchall instanceof it&&this._def.unknownKeys==="strip"))for(let c in s.data)o.includes(c)||l.push(c);let u=[];for(let c of o){let f=i[c],p=s.data[c];u.push({key:{status:"valid",value:c},value:f._parse(new Je(s,p,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof it){let c=this._def.unknownKeys;if(c==="passthrough")for(let f of l)u.push({key:{status:"valid",value:f},value:{status:"valid",value:s.data[f]}});else if(c==="strict")l.length>0&&(P(s,{code:R.unrecognized_keys,keys:l}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let f of l){let p=s.data[f];u.push({key:{status:"valid",value:f},value:c._parse(new Je(s,p,s.path,f)),alwaysSet:f in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let c=[];for(let f of u){let p=await f.key,b=await f.value;c.push({key:p,value:b,alwaysSet:f.alwaysSet})}return c}).then(c=>xe.mergeObjectSync(r,c)):xe.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(e){return L.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:L.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Z.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of te.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of te.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return Ar(this)}partial(e){let n={};for(let r of te.objectKeys(this.shape)){let s=this.shape[r];e&&!e[r]?n[r]=s:n[r]=s.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of te.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof We;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return Zl(te.objectKeys(this.shape))}};ze.create=(t,e)=>new ze({shape:()=>t,unknownKeys:"strip",catchall:it.create(),typeName:Z.ZodObject,...J(e)});ze.strictCreate=(t,e)=>new ze({shape:()=>t,unknownKeys:"strict",catchall:it.create(),typeName:Z.ZodObject,...J(e)});ze.lazycreate=(t,e)=>new ze({shape:t,unknownKeys:"strip",catchall:it.create(),typeName:Z.ZodObject,...J(e)});var xn=class extends Q{_parse(e){let{ctx:n}=this._processInputParams(e),r=this._def.options;function s(i){for(let l of i)if(l.result.status==="valid")return l.result;for(let l of i)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;let o=i.map(l=>new Me(l.ctx.common.issues));return P(n,{code:R.invalid_union,unionErrors:o}),K}if(n.common.async)return Promise.all(r.map(async i=>{let o={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let u of r){let c={...n,common:{...n.common,issues:[]},parent:null},f=u._parseSync({data:n.data,path:n.path,parent:c});if(f.status==="valid")return f;f.status==="dirty"&&!i&&(i={result:f,ctx:c}),c.common.issues.length&&o.push(c.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let l=o.map(u=>new Me(u));return P(n,{code:R.invalid_union,unionErrors:l}),K}}get options(){return this._def.options}};xn.create=(t,e)=>new xn({options:t,typeName:Z.ZodUnion,...J(e)});var At=t=>t instanceof In?At(t.schema):t instanceof Ye?At(t.innerType()):t instanceof Rn?[t.value]:t instanceof An?t.options:t instanceof En?te.objectValues(t.enum):t instanceof $n?At(t._def.innerType):t instanceof Sn?[void 0]:t instanceof Tn?[null]:t instanceof We?[void 0,...At(t.unwrap())]:t instanceof gt?[null,...At(t.unwrap())]:t instanceof gs||t instanceof jn?At(t.unwrap()):t instanceof Pn?At(t._def.innerType):[],Xs=class t extends Q{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==N.object)return P(n,{code:R.invalid_type,expected:N.object,received:n.parsedType}),K;let r=this.discriminator,s=n.data[r],i=this.optionsMap.get(s);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(P(n,{code:R.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),K)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let s=new Map;for(let i of n){let o=At(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let l of o){if(s.has(l))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(l)}`);s.set(l,i)}}return new t({typeName:Z.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...J(r)})}};function Po(t,e){let n=pt(t),r=pt(e);if(t===e)return{valid:!0,data:t};if(n===N.object&&r===N.object){let s=te.objectKeys(e),i=te.objectKeys(t).filter(l=>s.indexOf(l)!==-1),o={...t,...e};for(let l of i){let u=Po(t[l],e[l]);if(!u.valid)return{valid:!1};o[l]=u.data}return{valid:!0,data:o}}else if(n===N.array&&r===N.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<t.length;i++){let o=t[i],l=e[i],u=Po(o,l);if(!u.valid)return{valid:!1};s.push(u.data)}return{valid:!0,data:s}}else return n===N.date&&r===N.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Cn=class extends Q{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=(i,o)=>{if(Js(i)||Js(o))return K;let l=Po(i.value,o.value);return l.valid?((Ys(i)||Ys(o))&&n.dirty(),{status:n.value,value:l.data}):(P(r,{code:R.invalid_intersection_types}),K)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Cn.create=(t,e,n)=>new Cn({left:t,right:e,typeName:Z.ZodIntersection,...J(n)});var mt=class t extends Q{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==N.array)return P(r,{code:R.invalid_type,expected:N.array,received:r.parsedType}),K;if(r.data.length<this._def.items.length)return P(r,{code:R.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),K;!this._def.rest&&r.data.length>this._def.items.length&&(P(r,{code:R.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let i=[...r.data].map((o,l)=>{let u=this._def.items[l]||this._def.rest;return u?u._parse(new Je(r,o,r.path,l)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>xe.mergeArray(n,o)):xe.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};mt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new mt({items:t,typeName:Z.ZodTuple,rest:null,...J(e)})};var Qs=class t extends Q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==N.object)return P(r,{code:R.invalid_type,expected:N.object,received:r.parsedType}),K;let s=[],i=this._def.keyType,o=this._def.valueType;for(let l in r.data)s.push({key:i._parse(new Je(r,l,r.path,l)),value:o._parse(new Je(r,r.data[l],r.path,l)),alwaysSet:l in r.data});return r.common.async?xe.mergeObjectAsync(n,s):xe.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof Q?new t({keyType:e,valueType:n,typeName:Z.ZodRecord,...J(r)}):new t({keyType:Wt.create(),valueType:e,typeName:Z.ZodRecord,...J(n)})}},Pr=class extends Q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==N.map)return P(r,{code:R.invalid_type,expected:N.map,received:r.parsedType}),K;let s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([l,u],c)=>({key:s._parse(new Je(r,l,r.path,[c,"key"])),value:i._parse(new Je(r,u,r.path,[c,"value"]))}));if(r.common.async){let l=new Map;return Promise.resolve().then(async()=>{for(let u of o){let c=await u.key,f=await u.value;if(c.status==="aborted"||f.status==="aborted")return K;(c.status==="dirty"||f.status==="dirty")&&n.dirty(),l.set(c.value,f.value)}return{status:n.value,value:l}})}else{let l=new Map;for(let u of o){let c=u.key,f=u.value;if(c.status==="aborted"||f.status==="aborted")return K;(c.status==="dirty"||f.status==="dirty")&&n.dirty(),l.set(c.value,f.value)}return{status:n.value,value:l}}}};Pr.create=(t,e,n)=>new Pr({valueType:e,keyType:t,typeName:Z.ZodMap,...J(n)});var jr=class t extends Q{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==N.set)return P(r,{code:R.invalid_type,expected:N.set,received:r.parsedType}),K;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(P(r,{code:R.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(P(r,{code:R.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let i=this._def.valueType;function o(u){let c=new Set;for(let f of u){if(f.status==="aborted")return K;f.status==="dirty"&&n.dirty(),c.add(f.value)}return{status:n.value,value:c}}let l=[...r.data.values()].map((u,c)=>i._parse(new Je(r,u,r.path,c)));return r.common.async?Promise.all(l).then(u=>o(u)):o(l)}min(e,n){return new t({...this._def,minSize:{value:e,message:L.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:L.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};jr.create=(t,e)=>new jr({valueType:t,minSize:null,maxSize:null,typeName:Z.ZodSet,...J(e)});var ei=class t extends Q{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==N.function)return P(n,{code:R.invalid_type,expected:N.function,received:n.parsedType}),K;function r(l,u){return ms({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Ir(),Rt].filter(c=>!!c),issueData:{code:R.invalid_arguments,argumentsError:u}})}function s(l,u){return ms({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Ir(),Rt].filter(c=>!!c),issueData:{code:R.invalid_return_type,returnTypeError:u}})}let i={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof Yt){let l=this;return Re(async function(...u){let c=new Me([]),f=await l._def.args.parseAsync(u,i).catch(w=>{throw c.addIssue(r(u,w)),c}),p=await Reflect.apply(o,this,f);return await l._def.returns._def.type.parseAsync(p,i).catch(w=>{throw c.addIssue(s(p,w)),c})})}else{let l=this;return Re(function(...u){let c=l._def.args.safeParse(u,i);if(!c.success)throw new Me([r(u,c.error)]);let f=Reflect.apply(o,this,c.data),p=l._def.returns.safeParse(f,i);if(!p.success)throw new Me([s(f,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:mt.create(e).rest(Et.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new t({args:e||mt.create([]).rest(Et.create()),returns:n||Et.create(),typeName:Z.ZodFunction,...J(r)})}},In=class extends Q{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};In.create=(t,e)=>new In({getter:t,typeName:Z.ZodLazy,...J(e)});var Rn=class extends Q{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return P(n,{received:n.data,code:R.invalid_literal,expected:this._def.value}),K}return{status:"valid",value:e.data}}get value(){return this._def.value}};Rn.create=(t,e)=>new Rn({value:t,typeName:Z.ZodLiteral,...J(e)});function Zl(t,e){return new An({values:t,typeName:Z.ZodEnum,...J(e)})}var An=class t extends Q{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return P(n,{expected:te.joinValues(r),received:n.parsedType,code:R.invalid_type}),K}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return P(n,{received:n.data,code:R.invalid_enum_value,options:r}),K}return Re(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};An.create=Zl;var En=class extends Q{_parse(e){let n=te.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==N.string&&r.parsedType!==N.number){let s=te.objectValues(n);return P(r,{expected:te.joinValues(s),received:r.parsedType,code:R.invalid_type}),K}if(this._cache||(this._cache=new Set(te.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=te.objectValues(n);return P(r,{received:r.data,code:R.invalid_enum_value,options:s}),K}return Re(e.data)}get enum(){return this._def.values}};En.create=(t,e)=>new En({values:t,typeName:Z.ZodNativeEnum,...J(e)});var Yt=class extends Q{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==N.promise&&n.common.async===!1)return P(n,{code:R.invalid_type,expected:N.promise,received:n.parsedType}),K;let r=n.parsedType===N.promise?n.data:Promise.resolve(n.data);return Re(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Yt.create=(t,e)=>new Yt({type:t,typeName:Z.ZodPromise,...J(e)});var Ye=class extends Q{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Z.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{P(r,o),o.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(r.data,i);if(r.common.async)return Promise.resolve(o).then(async l=>{if(n.value==="aborted")return K;let u=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return u.status==="aborted"?K:u.status==="dirty"?bn(u.value):n.value==="dirty"?bn(u.value):u});{if(n.value==="aborted")return K;let l=this._def.schema._parseSync({data:o,path:r.path,parent:r});return l.status==="aborted"?K:l.status==="dirty"?bn(l.value):n.value==="dirty"?bn(l.value):l}}if(s.type==="refinement"){let o=l=>{let u=s.refinement(l,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){let l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?K:(l.status==="dirty"&&n.dirty(),o(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?K:(l.status==="dirty"&&n.dirty(),o(l.value).then(()=>({status:n.value,value:l.value}))))}if(s.type==="transform")if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Vt(o))return K;let l=s.transform(o.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>Vt(o)?Promise.resolve(s.transform(o.value,i)).then(l=>({status:n.value,value:l})):K);te.assertNever(s)}};Ye.create=(t,e,n)=>new Ye({schema:t,typeName:Z.ZodEffects,effect:e,...J(n)});Ye.createWithPreprocess=(t,e,n)=>new Ye({schema:e,effect:{type:"preprocess",transform:t},typeName:Z.ZodEffects,...J(n)});var We=class extends Q{_parse(e){return this._getType(e)===N.undefined?Re(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};We.create=(t,e)=>new We({innerType:t,typeName:Z.ZodOptional,...J(e)});var gt=class extends Q{_parse(e){return this._getType(e)===N.null?Re(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};gt.create=(t,e)=>new gt({innerType:t,typeName:Z.ZodNullable,...J(e)});var $n=class extends Q{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===N.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};$n.create=(t,e)=>new $n({innerType:t,typeName:Z.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...J(e)});var Pn=class extends Q{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Rr(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Me(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Me(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Pn.create=(t,e)=>new Pn({innerType:t,typeName:Z.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...J(e)});var Or=class extends Q{_parse(e){if(this._getType(e)!==N.nan){let r=this._getOrReturnCtx(e);return P(r,{code:R.invalid_type,expected:N.nan,received:r.parsedType}),K}return{status:"valid",value:e.data}}};Or.create=t=>new Or({typeName:Z.ZodNaN,...J(t)});var op=Symbol("zod_brand"),gs=class extends Q{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},ys=class t extends Q{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?K:i.status==="dirty"?(n.dirty(),bn(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?K:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:Z.ZodPipeline})}},jn=class extends Q{_parse(e){let n=this._def.innerType._parse(e),r=s=>(Vt(s)&&(s.value=Object.freeze(s.value)),s);return Rr(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};jn.create=(t,e)=>new jn({innerType:t,typeName:Z.ZodReadonly,...J(e)});function Fl(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function Gl(t,e={},n){return t?Jt.create().superRefine((r,s)=>{let i=t(r);if(i instanceof Promise)return i.then(o=>{if(!o){let l=Fl(e,r),u=l.fatal??n??!0;s.addIssue({code:"custom",...l,fatal:u})}});if(!i){let o=Fl(e,r),l=o.fatal??n??!0;s.addIssue({code:"custom",...o,fatal:l})}}):Jt.create()}var ap={object:ze.lazycreate},Z;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(Z||(Z={}));var lp=(t,e={message:`Input not instance of ${t.name}`})=>Gl(n=>n instanceof t,e),Vl=Wt.create,Wl=vn.create,up=Or.create,cp=wn.create,Jl=_n.create,dp=kn.create,hp=Er.create,fp=Sn.create,pp=Tn.create,mp=Jt.create,gp=Et.create,yp=it.create,bp=$r.create,vp=$t.create,wp=ze.create,_p=ze.strictCreate,kp=xn.create,Sp=Xs.create,Tp=Cn.create,xp=mt.create,Cp=Qs.create,Ip=Pr.create,Rp=jr.create,Ap=ei.create,Ep=In.create,$p=Rn.create,Pp=An.create,jp=En.create,Op=Yt.create,Np=Ye.create,Mp=We.create,zp=gt.create,Dp=Ye.createWithPreprocess,Lp=ys.create,Up=()=>Vl().optional(),qp=()=>Wl().optional(),Fp=()=>Jl().optional(),Bp={string:(t=>Wt.create({...t,coerce:!0})),number:(t=>vn.create({...t,coerce:!0})),boolean:(t=>_n.create({...t,coerce:!0})),bigint:(t=>wn.create({...t,coerce:!0})),date:(t=>kn.create({...t,coerce:!0}))};var Kp=K;var Yl=_.object({baseUrl:_.string().url(),email:_.string().email(),apiToken:_.string().min(1)}),jo=_.object({controlPlaneUrl:_.string().url(),runnerId:_.string().optional(),runnerToken:_.string().optional(),runnerName:_.string().default(ti.default.hostname()),jira:Yl.optional(),repos:_.record(_.object({path:_.string(),jira:Yl.optional(),github:_.object({token:_.string().min(1),login:_.string().optional()}).optional()})).default({}),github:_.object({token:_.string().min(1),login:_.string().optional()}).optional(),githubUsers:_.record(_.object({token:_.string().min(1),login:_.string().optional()})).default({}),deploy:_.object({enabled:_.boolean().default(!1)}).default({enabled:!1}),environments:_.record(_.object({secrets:_.record(_.string()).default({})})).default({}),claudeProfiles:_.record(_.object({configDir:_.string()})).default({}),claudeBin:_.string().default("claude"),agents:_.record(_.object({bin:_.string()})).default({}),jiraUsers:_.record(_.object({email:_.string().email(),apiToken:_.string().min(1)})).default({}),auditSchedules:_.array(_.object({repoName:_.string(),role:_.enum(["security","testing"]),intervalHours:_.number().int().min(6).max(720)})).default([]),pollIntervalSeconds:_.number().int().min(10).max(600).default(30)});function se(){let t=process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR;if(t)return t;let e=ni.default.join(ti.default.homedir(),".config","allwright"),n=ni.default.join(ti.default.homedir(),".config","ticketpilot");return!Pt.default.existsSync(e)&&Pt.default.existsSync(n)?n:e}function jt(){return ni.default.join(se(),"runner.json")}function ye(){let t=jt();if(!Pt.default.existsSync(t))return null;let e=JSON.parse(Pt.default.readFileSync(t,"utf8"));return jo.parse(e)}function ge(t){let e=se();Pt.default.mkdirSync(e,{recursive:!0,mode:448});let n=jt(),r=n+".tmp";Pt.default.writeFileSync(r,JSON.stringify(t,null,2)+`
|
|
291
|
+
`+n)}function Sr(t,e,n,r,s,i){if(t.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,Sr),t.emit("wsClientError",o,n,e)}else qs(n,r,s,i)}});var cf={};Gs(cf,{buildSetupReport:()=>Kv,claudeLoggedIn:()=>uf,repoDefaultBranch:()=>lf});function lf(t){let e=(...s)=>{try{return(0,ho.execFileSync)("git",["-C",t,...s],{encoding:"utf8",timeout:1e4}).trim()}catch{return null}},n=e("symbolic-ref","--short","refs/remotes/origin/HEAD");if(n?.startsWith("origin/"))return n.slice(7);let r=e("rev-parse","--abbrev-ref","HEAD");return r&&r!=="HEAD"?r:""}function uf(t=of.default.homedir()){if(mn.default.existsSync(xr.default.join(t,".claude",".credentials.json")))return!0;try{return!!JSON.parse(mn.default.readFileSync(xr.default.join(t,".claude.json"),"utf8")).oauthAccount}catch{return!1}}async function Kv(t,e,n){let r=!1,s="";if(Ks&&Date.now()-Ks.at<6e4)r=Ks.installed,s=Ks.version;else{try{let{stdout:l}=await Bv(t.claudeBin,["--version"],{timeout:1e4});r=!0,s=l.trim().slice(0,60)}catch{r=!1}Ks={at:Date.now(),installed:r,version:s}}let i=e.map(l=>{let u=t.repos[l];if(!u)return{repoName:l,mapped:!1,liveMapped:!!n?.repos?.[l],pathExists:!1,isGit:!1,claudeMd:!1,deployMd:!1,testMd:!1,githubToken:!1,githubTokenOwn:!1,defaultBranch:""};let c=mn.default.existsSync(u.path);return{repoName:l,mapped:!0,liveMapped:n?!!n.repos?.[l]:!0,pathExists:c,isGit:c&&mn.default.existsSync(xr.default.join(u.path,".git")),claudeMd:c&&mn.default.existsSync(xr.default.join(u.path,"CLAUDE.md")),deployMd:c&&mn.default.existsSync(xr.default.join(u.path,"DEPLOY.md")),testMd:c&&mn.default.existsSync(xr.default.join(u.path,"TEST.md")),githubToken:!!Ae(t,l),githubTokenOwn:!!u.github?.token,defaultBranch:c?lf(u.path):""}}),o=Object.values(t.repos).find(l=>l.github?.token);return{jiraConfigured:!!t.jira,jiraEmail:t.jira?.email??"",claude:{installed:r,version:s,loggedIn:uf()},githubTokenSet:!!(t.github?.token||o),githubLogin:t.github?.login??o?.github?.login??"",deploysEnabled:t.deploy.enabled,jiraUserCount:Object.keys(t.jiraUsers).length,repos:i}}var ho,mn,of,xr,af,Bv,Ks,df=Zs(()=>{"use strict";ho=require("node:child_process"),mn=I(require("node:fs"),1),of=I(require("node:os"),1),xr=I(require("node:path"),1),af=require("node:util");nr();Bv=(0,af.promisify)(ho.execFile);Ks=null});var ft=I(require("node:fs"),1),wl=I(require("node:os"),1),ds=I(require("node:path"),1),Gt=require("node:child_process"),Hs=require("node:crypto"),yn=I(require("node:readline/promises"),1);var Dl=I(zl(),1),{program:ew,createCommand:tw,createArgument:nw,createOption:rw,CommanderError:sw,InvalidArgumentError:iw,InvalidOptionArgumentError:ow,Command:Ll,Argument:aw,Option:lw,Help:uw}=Dl.default;var Pt=I(require("node:fs"),1),ti=I(require("node:os"),1),ni=I(require("node:path"),1);var _={};Gs(_,{BRAND:()=>op,DIRTY:()=>bn,EMPTY_PATH:()=>Df,INVALID:()=>K,NEVER:()=>Kp,OK:()=>Re,ParseStatus:()=>xe,Schema:()=>Q,ZodAny:()=>Jt,ZodArray:()=>$t,ZodBigInt:()=>wn,ZodBoolean:()=>_n,ZodBranded:()=>gs,ZodCatch:()=>Pn,ZodDate:()=>kn,ZodDefault:()=>$n,ZodDiscriminatedUnion:()=>Xs,ZodEffects:()=>Ye,ZodEnum:()=>En,ZodError:()=>Me,ZodFirstPartyTypeKind:()=>Z,ZodFunction:()=>ei,ZodIntersection:()=>Cn,ZodIssueCode:()=>R,ZodLazy:()=>In,ZodLiteral:()=>Rn,ZodMap:()=>Pr,ZodNaN:()=>Or,ZodNativeEnum:()=>An,ZodNever:()=>it,ZodNull:()=>Tn,ZodNullable:()=>gt,ZodNumber:()=>vn,ZodObject:()=>ze,ZodOptional:()=>We,ZodParsedType:()=>N,ZodPipeline:()=>ys,ZodPromise:()=>Yt,ZodReadonly:()=>jn,ZodRecord:()=>Qs,ZodSchema:()=>Q,ZodSet:()=>jr,ZodString:()=>Wt,ZodSymbol:()=>Ar,ZodTransformer:()=>Ye,ZodTuple:()=>mt,ZodType:()=>Q,ZodUndefined:()=>Sn,ZodUnion:()=>xn,ZodUnknown:()=>At,ZodVoid:()=>$r,addIssueToContext:()=>P,any:()=>mp,array:()=>vp,bigint:()=>cp,boolean:()=>Jl,coerce:()=>Bp,custom:()=>Gl,date:()=>dp,datetimeRegex:()=>Hl,defaultErrorMap:()=>Rt,discriminatedUnion:()=>Sp,effect:()=>Np,enum:()=>Pp,function:()=>Ep,getErrorMap:()=>Ir,getParsedType:()=>pt,instanceof:()=>lp,intersection:()=>Tp,isAborted:()=>Js,isAsync:()=>Rr,isDirty:()=>Ys,isValid:()=>Vt,late:()=>ap,lazy:()=>Ap,literal:()=>$p,makeIssue:()=>ms,map:()=>Ip,nan:()=>up,nativeEnum:()=>jp,never:()=>yp,null:()=>pp,nullable:()=>zp,number:()=>Wl,object:()=>wp,objectUtil:()=>Ao,oboolean:()=>Fp,onumber:()=>qp,optional:()=>Mp,ostring:()=>Up,pipeline:()=>Lp,preprocess:()=>Dp,promise:()=>Op,quotelessJson:()=>Nf,record:()=>Cp,set:()=>Rp,setErrorMap:()=>zf,strictObject:()=>_p,string:()=>Vl,symbol:()=>hp,transformer:()=>Np,tuple:()=>xp,undefined:()=>fp,union:()=>kp,unknown:()=>gp,util:()=>te,void:()=>bp});var te;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function n(s){throw new Error}t.assertNever=n,t.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},t.getValidEnumValues=s=>{let i=t.objectKeys(s).filter(l=>typeof s[s[l]]!="number"),o={};for(let l of i)o[l]=s[l];return t.objectValues(o)},t.objectValues=s=>t.objectKeys(s).map(function(i){return s[i]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},t.find=(s,i)=>{for(let o of s)if(i(o))return o},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(te||(te={}));var Ao;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Ao||(Ao={}));var N=te.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),pt=t=>{switch(typeof t){case"undefined":return N.undefined;case"string":return N.string;case"number":return Number.isNaN(t)?N.nan:N.number;case"boolean":return N.boolean;case"function":return N.function;case"bigint":return N.bigint;case"symbol":return N.symbol;case"object":return Array.isArray(t)?N.array:t===null?N.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?N.promise:typeof Map<"u"&&t instanceof Map?N.map:typeof Set<"u"&&t instanceof Set?N.set:typeof Date<"u"&&t instanceof Date?N.date:N.object;default:return N.unknown}};var R=te.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"]),Nf=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Me=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(i){return i.message},r={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)r._errors.push(n(o));else{let l=r,u=0;for(;u<o.path.length;){let c=o.path[u];u===o.path.length-1?(l[c]=l[c]||{_errors:[]},l[c]._errors.push(n(o))):l[c]=l[c]||{_errors:[]},l=l[c],u++}}};return s(this),r}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,te.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];n[i]=n[i]||[],n[i].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};Me.create=t=>new Me(t);var Mf=(t,e)=>{let n;switch(t.code){case R.invalid_type:t.received===N.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case R.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,te.jsonStringifyReplacer)}`;break;case R.unrecognized_keys:n=`Unrecognized key(s) in object: ${te.joinValues(t.keys,", ")}`;break;case R.invalid_union:n="Invalid input";break;case R.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${te.joinValues(t.options)}`;break;case R.invalid_enum_value:n=`Invalid enum value. Expected ${te.joinValues(t.options)}, received '${t.received}'`;break;case R.invalid_arguments:n="Invalid function arguments";break;case R.invalid_return_type:n="Invalid function return type";break;case R.invalid_date:n="Invalid date";break;case R.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:te.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case R.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case R.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case R.custom:n="Invalid input";break;case R.invalid_intersection_types:n="Intersection results could not be merged";break;case R.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case R.not_finite:n="Number must be finite";break;default:n=e.defaultError,te.assertNever(t)}return{message:n}},Rt=Mf;var Ul=Rt;function zf(t){Ul=t}function Ir(){return Ul}var ms=t=>{let{data:e,path:n,errorMaps:r,issueData:s}=t,i=[...n,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let l="",u=r.filter(c=>!!c).slice().reverse();for(let c of u)l=c(o,{data:e,defaultError:l}).message;return{...s,path:i,message:l}},Df=[];function P(t,e){let n=Ir(),r=ms({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Rt?void 0:Rt].filter(s=>!!s)});t.common.issues.push(r)}var xe=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let s of n){if(s.status==="aborted")return K;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let s of n){let i=await s.key,o=await s.value;r.push({key:i,value:o})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let s of n){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return K;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(r[i.value]=o.value)}return{status:e.value,value:r}}},K=Object.freeze({status:"aborted"}),bn=t=>({status:"dirty",value:t}),Re=t=>({status:"valid",value:t}),Js=t=>t.status==="aborted",Ys=t=>t.status==="dirty",Vt=t=>t.status==="valid",Rr=t=>typeof Promise<"u"&&t instanceof Promise;var U;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(U||(U={}));var Je=class{constructor(e,n,r,s){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},ql=(t,e)=>{if(Vt(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new Me(t.common.issues);return this._error=n,this._error}}};function J(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:s}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,l)=>{let{message:u}=t;return o.code==="invalid_enum_value"?{message:u??l.defaultError}:typeof l.data>"u"?{message:u??r??l.defaultError}:o.code!=="invalid_type"?{message:l.defaultError}:{message:u??n??l.defaultError}},description:s}}var Q=class{get description(){return this._def.description}_getType(e){return pt(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:pt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new xe,ctx:{common:e.parent.common,data:e.data,parsedType:pt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(Rr(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:pt(e)},s=this._parseSync({data:e,path:r.path,parent:r});return ql(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:pt(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return Vt(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>Vt(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:pt(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(Rr(s)?s:Promise.resolve(s));return ql(r,i)}refine(e,n){let r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,i)=>{let o=e(s),l=()=>i.addIssue({code:R.custom,...r(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(u=>u?!0:(l(),!1)):o?!0:(l(),!1)})}refinement(e,n){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(e){return new Ye({schema:this,typeName:Z.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return We.create(this,this._def)}nullable(){return gt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return $t.create(this)}promise(){return Yt.create(this,this._def)}or(e){return xn.create([this,e],this._def)}and(e){return Cn.create(this,e,this._def)}transform(e){return new Ye({...J(this._def),schema:this,typeName:Z.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new $n({...J(this._def),innerType:this,defaultValue:n,typeName:Z.ZodDefault})}brand(){return new gs({typeName:Z.ZodBranded,type:this,...J(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Pn({...J(this._def),innerType:this,catchValue:n,typeName:Z.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return ys.create(this,e)}readonly(){return jn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Lf=/^c[^\s-]{8,}$/i,Uf=/^[0-9a-z]+$/,qf=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ff=/^[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,Bf=/^[a-z0-9_-]{21}$/i,Kf=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Hf=/^[-+]?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,Gf="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",$o,Vf=/^(?:(?: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])$/,Wf=/^(?:(?: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])$/,Jf=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Yf=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Xf=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Qf=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Bl="((\\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])))",ep=new RegExp(`^${Bl}$`);function Kl(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function tp(t){return new RegExp(`^${Kl(t)}$`)}function Hl(t){let e=`${Bl}T${Kl(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function np(t,e){return!!((e==="v4"||!e)&&Vf.test(t)||(e==="v6"||!e)&&Jf.test(t))}function rp(t,e){if(!Kf.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function sp(t,e){return!!((e==="v4"||!e)&&Wf.test(t)||(e==="v6"||!e)&&Yf.test(t))}var Wt=class t extends Q{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==N.string){let i=this._getOrReturnCtx(e);return P(i,{code:R.invalid_type,expected:N.string,received:i.parsedType}),K}let r=new xe,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),P(s,{code:R.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),P(s,{code:R.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,l=e.data.length<i.value;(o||l)&&(s=this._getOrReturnCtx(e,s),o?P(s,{code:R.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):l&&P(s,{code:R.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")Zf.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"email",code:R.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")$o||($o=new RegExp(Gf,"u")),$o.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"emoji",code:R.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")Ff.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"uuid",code:R.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")Bf.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"nanoid",code:R.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")Lf.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"cuid",code:R.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")Uf.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"cuid2",code:R.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")qf.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"ulid",code:R.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),P(s,{validation:"url",code:R.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"regex",code:R.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),P(s,{code:R.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),P(s,{code:R.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),P(s,{code:R.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Hl(i).test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{code:R.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?ep.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{code:R.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?tp(i).test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{code:R.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?Hf.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"duration",code:R.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?np(e.data,i.version)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"ip",code:R.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?rp(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"jwt",code:R.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?sp(e.data,i.version)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"cidr",code:R.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?Xf.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"base64",code:R.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?Qf.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"base64url",code:R.invalid_string,message:i.message}),r.dirty()):te.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:R.invalid_string,...U.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...U.errToObj(e)})}url(e){return this._addCheck({kind:"url",...U.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...U.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...U.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...U.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...U.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...U.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...U.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...U.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...U.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...U.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...U.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...U.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...U.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...U.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...U.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...U.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...U.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...U.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...U.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...U.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...U.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...U.errToObj(n)})}nonempty(e){return this.min(1,U.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};Wt.create=t=>new Wt({checks:[],typeName:Z.ZodString,coerce:t?.coerce??!1,...J(t)});function ip(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,i=Number.parseInt(t.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var vn=class t extends Q{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==N.number){let i=this._getOrReturnCtx(e);return P(i,{code:R.invalid_type,expected:N.number,received:i.parsedType}),K}let r,s=new xe;for(let i of this._def.checks)i.kind==="int"?te.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{code:R.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),P(r,{code:R.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),P(r,{code:R.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?ip(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),P(r,{code:R.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{code:R.not_finite,message:i.message}),s.dirty()):te.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,U.toString(n))}gt(e,n){return this.setLimit("min",e,!1,U.toString(n))}lte(e,n){return this.setLimit("max",e,!0,U.toString(n))}lt(e,n){return this.setLimit("max",e,!1,U.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:U.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:U.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:U.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:U.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:U.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:U.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:U.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:U.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:U.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:U.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&te.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};vn.create=t=>new vn({checks:[],typeName:Z.ZodNumber,coerce:t?.coerce||!1,...J(t)});var wn=class t extends Q{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==N.bigint)return this._getInvalidInput(e);let r,s=new xe;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),P(r,{code:R.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),P(r,{code:R.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),P(r,{code:R.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):te.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return P(n,{code:R.invalid_type,expected:N.bigint,received:n.parsedType}),K}gte(e,n){return this.setLimit("min",e,!0,U.toString(n))}gt(e,n){return this.setLimit("min",e,!1,U.toString(n))}lte(e,n){return this.setLimit("max",e,!0,U.toString(n))}lt(e,n){return this.setLimit("max",e,!1,U.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:U.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:U.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:U.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:U.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:U.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:U.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};wn.create=t=>new wn({checks:[],typeName:Z.ZodBigInt,coerce:t?.coerce??!1,...J(t)});var _n=class extends Q{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==N.boolean){let r=this._getOrReturnCtx(e);return P(r,{code:R.invalid_type,expected:N.boolean,received:r.parsedType}),K}return Re(e.data)}};_n.create=t=>new _n({typeName:Z.ZodBoolean,coerce:t?.coerce||!1,...J(t)});var kn=class t extends Q{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==N.date){let i=this._getOrReturnCtx(e);return P(i,{code:R.invalid_type,expected:N.date,received:i.parsedType}),K}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return P(i,{code:R.invalid_date}),K}let r=new xe,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),P(s,{code:R.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),P(s,{code:R.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):te.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:U.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:U.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};kn.create=t=>new kn({checks:[],coerce:t?.coerce||!1,typeName:Z.ZodDate,...J(t)});var Ar=class extends Q{_parse(e){if(this._getType(e)!==N.symbol){let r=this._getOrReturnCtx(e);return P(r,{code:R.invalid_type,expected:N.symbol,received:r.parsedType}),K}return Re(e.data)}};Ar.create=t=>new Ar({typeName:Z.ZodSymbol,...J(t)});var Sn=class extends Q{_parse(e){if(this._getType(e)!==N.undefined){let r=this._getOrReturnCtx(e);return P(r,{code:R.invalid_type,expected:N.undefined,received:r.parsedType}),K}return Re(e.data)}};Sn.create=t=>new Sn({typeName:Z.ZodUndefined,...J(t)});var Tn=class extends Q{_parse(e){if(this._getType(e)!==N.null){let r=this._getOrReturnCtx(e);return P(r,{code:R.invalid_type,expected:N.null,received:r.parsedType}),K}return Re(e.data)}};Tn.create=t=>new Tn({typeName:Z.ZodNull,...J(t)});var Jt=class extends Q{constructor(){super(...arguments),this._any=!0}_parse(e){return Re(e.data)}};Jt.create=t=>new Jt({typeName:Z.ZodAny,...J(t)});var At=class extends Q{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Re(e.data)}};At.create=t=>new At({typeName:Z.ZodUnknown,...J(t)});var it=class extends Q{_parse(e){let n=this._getOrReturnCtx(e);return P(n,{code:R.invalid_type,expected:N.never,received:n.parsedType}),K}};it.create=t=>new it({typeName:Z.ZodNever,...J(t)});var $r=class extends Q{_parse(e){if(this._getType(e)!==N.undefined){let r=this._getOrReturnCtx(e);return P(r,{code:R.invalid_type,expected:N.void,received:r.parsedType}),K}return Re(e.data)}};$r.create=t=>new $r({typeName:Z.ZodVoid,...J(t)});var $t=class t extends Q{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==N.array)return P(n,{code:R.invalid_type,expected:N.array,received:n.parsedType}),K;if(s.exactLength!==null){let o=n.data.length>s.exactLength.value,l=n.data.length<s.exactLength.value;(o||l)&&(P(n,{code:o?R.too_big:R.too_small,minimum:l?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(P(n,{code:R.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(P(n,{code:R.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((o,l)=>s.type._parseAsync(new Je(n,o,n.path,l)))).then(o=>xe.mergeArray(r,o));let i=[...n.data].map((o,l)=>s.type._parseSync(new Je(n,o,n.path,l)));return xe.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:U.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:U.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:U.toString(n)}})}nonempty(e){return this.min(1,e)}};$t.create=(t,e)=>new $t({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Z.ZodArray,...J(e)});function Er(t){if(t instanceof ze){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=We.create(Er(r))}return new ze({...t._def,shape:()=>e})}else return t instanceof $t?new $t({...t._def,type:Er(t.element)}):t instanceof We?We.create(Er(t.unwrap())):t instanceof gt?gt.create(Er(t.unwrap())):t instanceof mt?mt.create(t.items.map(e=>Er(e))):t}var ze=class t extends Q{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),n=te.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==N.object){let c=this._getOrReturnCtx(e);return P(c,{code:R.invalid_type,expected:N.object,received:c.parsedType}),K}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),l=[];if(!(this._def.catchall instanceof it&&this._def.unknownKeys==="strip"))for(let c in s.data)o.includes(c)||l.push(c);let u=[];for(let c of o){let f=i[c],p=s.data[c];u.push({key:{status:"valid",value:c},value:f._parse(new Je(s,p,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof it){let c=this._def.unknownKeys;if(c==="passthrough")for(let f of l)u.push({key:{status:"valid",value:f},value:{status:"valid",value:s.data[f]}});else if(c==="strict")l.length>0&&(P(s,{code:R.unrecognized_keys,keys:l}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let f of l){let p=s.data[f];u.push({key:{status:"valid",value:f},value:c._parse(new Je(s,p,s.path,f)),alwaysSet:f in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let c=[];for(let f of u){let p=await f.key,b=await f.value;c.push({key:p,value:b,alwaysSet:f.alwaysSet})}return c}).then(c=>xe.mergeObjectSync(r,c)):xe.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(e){return U.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:U.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Z.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of te.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of te.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return Er(this)}partial(e){let n={};for(let r of te.objectKeys(this.shape)){let s=this.shape[r];e&&!e[r]?n[r]=s:n[r]=s.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of te.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof We;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return Zl(te.objectKeys(this.shape))}};ze.create=(t,e)=>new ze({shape:()=>t,unknownKeys:"strip",catchall:it.create(),typeName:Z.ZodObject,...J(e)});ze.strictCreate=(t,e)=>new ze({shape:()=>t,unknownKeys:"strict",catchall:it.create(),typeName:Z.ZodObject,...J(e)});ze.lazycreate=(t,e)=>new ze({shape:t,unknownKeys:"strip",catchall:it.create(),typeName:Z.ZodObject,...J(e)});var xn=class extends Q{_parse(e){let{ctx:n}=this._processInputParams(e),r=this._def.options;function s(i){for(let l of i)if(l.result.status==="valid")return l.result;for(let l of i)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;let o=i.map(l=>new Me(l.ctx.common.issues));return P(n,{code:R.invalid_union,unionErrors:o}),K}if(n.common.async)return Promise.all(r.map(async i=>{let o={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let u of r){let c={...n,common:{...n.common,issues:[]},parent:null},f=u._parseSync({data:n.data,path:n.path,parent:c});if(f.status==="valid")return f;f.status==="dirty"&&!i&&(i={result:f,ctx:c}),c.common.issues.length&&o.push(c.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let l=o.map(u=>new Me(u));return P(n,{code:R.invalid_union,unionErrors:l}),K}}get options(){return this._def.options}};xn.create=(t,e)=>new xn({options:t,typeName:Z.ZodUnion,...J(e)});var Et=t=>t instanceof In?Et(t.schema):t instanceof Ye?Et(t.innerType()):t instanceof Rn?[t.value]:t instanceof En?t.options:t instanceof An?te.objectValues(t.enum):t instanceof $n?Et(t._def.innerType):t instanceof Sn?[void 0]:t instanceof Tn?[null]:t instanceof We?[void 0,...Et(t.unwrap())]:t instanceof gt?[null,...Et(t.unwrap())]:t instanceof gs||t instanceof jn?Et(t.unwrap()):t instanceof Pn?Et(t._def.innerType):[],Xs=class t extends Q{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==N.object)return P(n,{code:R.invalid_type,expected:N.object,received:n.parsedType}),K;let r=this.discriminator,s=n.data[r],i=this.optionsMap.get(s);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(P(n,{code:R.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),K)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let s=new Map;for(let i of n){let o=Et(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let l of o){if(s.has(l))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(l)}`);s.set(l,i)}}return new t({typeName:Z.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...J(r)})}};function Po(t,e){let n=pt(t),r=pt(e);if(t===e)return{valid:!0,data:t};if(n===N.object&&r===N.object){let s=te.objectKeys(e),i=te.objectKeys(t).filter(l=>s.indexOf(l)!==-1),o={...t,...e};for(let l of i){let u=Po(t[l],e[l]);if(!u.valid)return{valid:!1};o[l]=u.data}return{valid:!0,data:o}}else if(n===N.array&&r===N.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<t.length;i++){let o=t[i],l=e[i],u=Po(o,l);if(!u.valid)return{valid:!1};s.push(u.data)}return{valid:!0,data:s}}else return n===N.date&&r===N.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Cn=class extends Q{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=(i,o)=>{if(Js(i)||Js(o))return K;let l=Po(i.value,o.value);return l.valid?((Ys(i)||Ys(o))&&n.dirty(),{status:n.value,value:l.data}):(P(r,{code:R.invalid_intersection_types}),K)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Cn.create=(t,e,n)=>new Cn({left:t,right:e,typeName:Z.ZodIntersection,...J(n)});var mt=class t extends Q{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==N.array)return P(r,{code:R.invalid_type,expected:N.array,received:r.parsedType}),K;if(r.data.length<this._def.items.length)return P(r,{code:R.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),K;!this._def.rest&&r.data.length>this._def.items.length&&(P(r,{code:R.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let i=[...r.data].map((o,l)=>{let u=this._def.items[l]||this._def.rest;return u?u._parse(new Je(r,o,r.path,l)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>xe.mergeArray(n,o)):xe.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};mt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new mt({items:t,typeName:Z.ZodTuple,rest:null,...J(e)})};var Qs=class t extends Q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==N.object)return P(r,{code:R.invalid_type,expected:N.object,received:r.parsedType}),K;let s=[],i=this._def.keyType,o=this._def.valueType;for(let l in r.data)s.push({key:i._parse(new Je(r,l,r.path,l)),value:o._parse(new Je(r,r.data[l],r.path,l)),alwaysSet:l in r.data});return r.common.async?xe.mergeObjectAsync(n,s):xe.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof Q?new t({keyType:e,valueType:n,typeName:Z.ZodRecord,...J(r)}):new t({keyType:Wt.create(),valueType:e,typeName:Z.ZodRecord,...J(n)})}},Pr=class extends Q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==N.map)return P(r,{code:R.invalid_type,expected:N.map,received:r.parsedType}),K;let s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([l,u],c)=>({key:s._parse(new Je(r,l,r.path,[c,"key"])),value:i._parse(new Je(r,u,r.path,[c,"value"]))}));if(r.common.async){let l=new Map;return Promise.resolve().then(async()=>{for(let u of o){let c=await u.key,f=await u.value;if(c.status==="aborted"||f.status==="aborted")return K;(c.status==="dirty"||f.status==="dirty")&&n.dirty(),l.set(c.value,f.value)}return{status:n.value,value:l}})}else{let l=new Map;for(let u of o){let c=u.key,f=u.value;if(c.status==="aborted"||f.status==="aborted")return K;(c.status==="dirty"||f.status==="dirty")&&n.dirty(),l.set(c.value,f.value)}return{status:n.value,value:l}}}};Pr.create=(t,e,n)=>new Pr({valueType:e,keyType:t,typeName:Z.ZodMap,...J(n)});var jr=class t extends Q{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==N.set)return P(r,{code:R.invalid_type,expected:N.set,received:r.parsedType}),K;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(P(r,{code:R.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(P(r,{code:R.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let i=this._def.valueType;function o(u){let c=new Set;for(let f of u){if(f.status==="aborted")return K;f.status==="dirty"&&n.dirty(),c.add(f.value)}return{status:n.value,value:c}}let l=[...r.data.values()].map((u,c)=>i._parse(new Je(r,u,r.path,c)));return r.common.async?Promise.all(l).then(u=>o(u)):o(l)}min(e,n){return new t({...this._def,minSize:{value:e,message:U.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:U.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};jr.create=(t,e)=>new jr({valueType:t,minSize:null,maxSize:null,typeName:Z.ZodSet,...J(e)});var ei=class t extends Q{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==N.function)return P(n,{code:R.invalid_type,expected:N.function,received:n.parsedType}),K;function r(l,u){return ms({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Ir(),Rt].filter(c=>!!c),issueData:{code:R.invalid_arguments,argumentsError:u}})}function s(l,u){return ms({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Ir(),Rt].filter(c=>!!c),issueData:{code:R.invalid_return_type,returnTypeError:u}})}let i={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof Yt){let l=this;return Re(async function(...u){let c=new Me([]),f=await l._def.args.parseAsync(u,i).catch(w=>{throw c.addIssue(r(u,w)),c}),p=await Reflect.apply(o,this,f);return await l._def.returns._def.type.parseAsync(p,i).catch(w=>{throw c.addIssue(s(p,w)),c})})}else{let l=this;return Re(function(...u){let c=l._def.args.safeParse(u,i);if(!c.success)throw new Me([r(u,c.error)]);let f=Reflect.apply(o,this,c.data),p=l._def.returns.safeParse(f,i);if(!p.success)throw new Me([s(f,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:mt.create(e).rest(At.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new t({args:e||mt.create([]).rest(At.create()),returns:n||At.create(),typeName:Z.ZodFunction,...J(r)})}},In=class extends Q{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};In.create=(t,e)=>new In({getter:t,typeName:Z.ZodLazy,...J(e)});var Rn=class extends Q{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return P(n,{received:n.data,code:R.invalid_literal,expected:this._def.value}),K}return{status:"valid",value:e.data}}get value(){return this._def.value}};Rn.create=(t,e)=>new Rn({value:t,typeName:Z.ZodLiteral,...J(e)});function Zl(t,e){return new En({values:t,typeName:Z.ZodEnum,...J(e)})}var En=class t extends Q{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return P(n,{expected:te.joinValues(r),received:n.parsedType,code:R.invalid_type}),K}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return P(n,{received:n.data,code:R.invalid_enum_value,options:r}),K}return Re(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};En.create=Zl;var An=class extends Q{_parse(e){let n=te.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==N.string&&r.parsedType!==N.number){let s=te.objectValues(n);return P(r,{expected:te.joinValues(s),received:r.parsedType,code:R.invalid_type}),K}if(this._cache||(this._cache=new Set(te.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=te.objectValues(n);return P(r,{received:r.data,code:R.invalid_enum_value,options:s}),K}return Re(e.data)}get enum(){return this._def.values}};An.create=(t,e)=>new An({values:t,typeName:Z.ZodNativeEnum,...J(e)});var Yt=class extends Q{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==N.promise&&n.common.async===!1)return P(n,{code:R.invalid_type,expected:N.promise,received:n.parsedType}),K;let r=n.parsedType===N.promise?n.data:Promise.resolve(n.data);return Re(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Yt.create=(t,e)=>new Yt({type:t,typeName:Z.ZodPromise,...J(e)});var Ye=class extends Q{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Z.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{P(r,o),o.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(r.data,i);if(r.common.async)return Promise.resolve(o).then(async l=>{if(n.value==="aborted")return K;let u=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return u.status==="aborted"?K:u.status==="dirty"?bn(u.value):n.value==="dirty"?bn(u.value):u});{if(n.value==="aborted")return K;let l=this._def.schema._parseSync({data:o,path:r.path,parent:r});return l.status==="aborted"?K:l.status==="dirty"?bn(l.value):n.value==="dirty"?bn(l.value):l}}if(s.type==="refinement"){let o=l=>{let u=s.refinement(l,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){let l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?K:(l.status==="dirty"&&n.dirty(),o(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?K:(l.status==="dirty"&&n.dirty(),o(l.value).then(()=>({status:n.value,value:l.value}))))}if(s.type==="transform")if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Vt(o))return K;let l=s.transform(o.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>Vt(o)?Promise.resolve(s.transform(o.value,i)).then(l=>({status:n.value,value:l})):K);te.assertNever(s)}};Ye.create=(t,e,n)=>new Ye({schema:t,typeName:Z.ZodEffects,effect:e,...J(n)});Ye.createWithPreprocess=(t,e,n)=>new Ye({schema:e,effect:{type:"preprocess",transform:t},typeName:Z.ZodEffects,...J(n)});var We=class extends Q{_parse(e){return this._getType(e)===N.undefined?Re(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};We.create=(t,e)=>new We({innerType:t,typeName:Z.ZodOptional,...J(e)});var gt=class extends Q{_parse(e){return this._getType(e)===N.null?Re(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};gt.create=(t,e)=>new gt({innerType:t,typeName:Z.ZodNullable,...J(e)});var $n=class extends Q{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===N.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};$n.create=(t,e)=>new $n({innerType:t,typeName:Z.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...J(e)});var Pn=class extends Q{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Rr(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Me(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Me(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Pn.create=(t,e)=>new Pn({innerType:t,typeName:Z.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...J(e)});var Or=class extends Q{_parse(e){if(this._getType(e)!==N.nan){let r=this._getOrReturnCtx(e);return P(r,{code:R.invalid_type,expected:N.nan,received:r.parsedType}),K}return{status:"valid",value:e.data}}};Or.create=t=>new Or({typeName:Z.ZodNaN,...J(t)});var op=Symbol("zod_brand"),gs=class extends Q{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},ys=class t extends Q{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?K:i.status==="dirty"?(n.dirty(),bn(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?K:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:Z.ZodPipeline})}},jn=class extends Q{_parse(e){let n=this._def.innerType._parse(e),r=s=>(Vt(s)&&(s.value=Object.freeze(s.value)),s);return Rr(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};jn.create=(t,e)=>new jn({innerType:t,typeName:Z.ZodReadonly,...J(e)});function Fl(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function Gl(t,e={},n){return t?Jt.create().superRefine((r,s)=>{let i=t(r);if(i instanceof Promise)return i.then(o=>{if(!o){let l=Fl(e,r),u=l.fatal??n??!0;s.addIssue({code:"custom",...l,fatal:u})}});if(!i){let o=Fl(e,r),l=o.fatal??n??!0;s.addIssue({code:"custom",...o,fatal:l})}}):Jt.create()}var ap={object:ze.lazycreate},Z;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(Z||(Z={}));var lp=(t,e={message:`Input not instance of ${t.name}`})=>Gl(n=>n instanceof t,e),Vl=Wt.create,Wl=vn.create,up=Or.create,cp=wn.create,Jl=_n.create,dp=kn.create,hp=Ar.create,fp=Sn.create,pp=Tn.create,mp=Jt.create,gp=At.create,yp=it.create,bp=$r.create,vp=$t.create,wp=ze.create,_p=ze.strictCreate,kp=xn.create,Sp=Xs.create,Tp=Cn.create,xp=mt.create,Cp=Qs.create,Ip=Pr.create,Rp=jr.create,Ep=ei.create,Ap=In.create,$p=Rn.create,Pp=En.create,jp=An.create,Op=Yt.create,Np=Ye.create,Mp=We.create,zp=gt.create,Dp=Ye.createWithPreprocess,Lp=ys.create,Up=()=>Vl().optional(),qp=()=>Wl().optional(),Fp=()=>Jl().optional(),Bp={string:(t=>Wt.create({...t,coerce:!0})),number:(t=>vn.create({...t,coerce:!0})),boolean:(t=>_n.create({...t,coerce:!0})),bigint:(t=>wn.create({...t,coerce:!0})),date:(t=>kn.create({...t,coerce:!0}))};var Kp=K;var Yl=_.object({baseUrl:_.string().url(),email:_.string().email(),apiToken:_.string().min(1)}),jo=_.object({controlPlaneUrl:_.string().url(),runnerId:_.string().optional(),runnerToken:_.string().optional(),runnerName:_.string().default(ti.default.hostname()),jira:Yl.optional(),repos:_.record(_.object({path:_.string(),jira:Yl.optional(),github:_.object({token:_.string().min(1),login:_.string().optional()}).optional()})).default({}),github:_.object({token:_.string().min(1),login:_.string().optional()}).optional(),githubUsers:_.record(_.object({token:_.string().min(1),login:_.string().optional()})).default({}),deploy:_.object({enabled:_.boolean().default(!1)}).default({enabled:!1}),environments:_.record(_.object({secrets:_.record(_.string()).default({})})).default({}),claudeProfiles:_.record(_.object({configDir:_.string()})).default({}),claudeBin:_.string().default("claude"),agents:_.record(_.object({bin:_.string()})).default({}),jiraUsers:_.record(_.object({email:_.string().email(),apiToken:_.string().min(1)})).default({}),auditSchedules:_.array(_.object({repoName:_.string(),role:_.enum(["security","testing"]),intervalHours:_.number().int().min(6).max(720)})).default([]),pollIntervalSeconds:_.number().int().min(10).max(600).default(30)});function se(){let t=process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR;if(t)return t;let e=ni.default.join(ti.default.homedir(),".config","allwright"),n=ni.default.join(ti.default.homedir(),".config","ticketpilot");return!Pt.default.existsSync(e)&&Pt.default.existsSync(n)?n:e}function jt(){return ni.default.join(se(),"runner.json")}function ye(){let t=jt();if(!Pt.default.existsSync(t))return null;let e=JSON.parse(Pt.default.readFileSync(t,"utf8"));return jo.parse(e)}function ge(t){let e=se();Pt.default.mkdirSync(e,{recursive:!0,mode:448});let n=jt(),r=n+".tmp";Pt.default.writeFileSync(r,JSON.stringify(t,null,2)+`
|
|
292
292
|
`,{mode:384}),Pt.default.renameSync(r,n),Pt.default.chmodSync(n,384)}function ri(t,e){return`${t}:${e}`}function Ot(t,e,n){return t.environments[ri(e,n)]?.secrets??{}}function ie(){let t=ye();if(!t)throw new Error(`No runner config found at ${jt()}. Run \`allwright init\` first.`);return t}var si=require("node:child_process"),qe=I(require("node:fs"),1),ii=I(require("node:path"),1);var Hp=new Set(["runner.log","runner.pid"]);function Zp(t){return qe.default.readdirSync(t).filter(e=>!Hp.has(e)&&!/\.bak-\d+$/.test(e)).sort()}function Xl(t){let e=se();if(!qe.default.existsSync(e))throw new Error(`nothing to export - ${e} does not exist`);let n=Zp(e);if(!n.length)throw new Error(`nothing to export - ${e} is empty`);let r=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),s=ii.default.resolve(t||`ticketpilot-backup-${r}.tgz`);return qe.default.writeFileSync(s,"",{mode:384}),(0,si.execFileSync)("tar",["-czf",s,"-C",e,...n]),qe.default.chmodSync(s,384),{file:s,entries:n}}function Ql(t){let e=ii.default.resolve(t);if(!qe.default.existsSync(e))throw new Error(`backup file not found: ${e}`);let n=(0,si.execFileSync)("tar",["-tzf",e],{encoding:"utf8"}).split(`
|
|
293
293
|
`).filter(Boolean);for(let i of n)if(i.startsWith("/")||i.split("/").includes(".."))throw new Error(`refusing to import - unsafe path in archive: ${i}`);let r=se(),s;qe.default.existsSync(r)&&qe.default.readdirSync(r).length&&(s=`${r}.bak-${Date.now()}`,qe.default.renameSync(r,s)),qe.default.mkdirSync(r,{recursive:!0,mode:448}),(0,si.execFileSync)("tar",["-xzf",e,"-C",r]);for(let i of qe.default.readdirSync(r)){let o=ii.default.join(r,i);qe.default.statSync(o).isFile()&&qe.default.chmodSync(o,384)}return{restored:n.map(i=>i.replace(/\/$/,"")).sort(),previousDir:s}}var Nr=I(require("node:fs"),1),Xt=I(require("node:path"),1),oi=".ticketpilot-attachments",Gp=15*1024*1024,Vp=50*1024*1024,eu=20;function tu(t,e){let n=Xt.default.basename(t).replace(/[^\w.\- ()]/g,"_").replace(/^\.+/,"").slice(-100)||"file",r=n,s=1;for(;e.has(r);)r=`${s++}-${n}`;return e.add(r),r}async function Mr(t,e,n,r){if(!e.length)return"";let s=Xt.default.join(n,oi);Nr.default.mkdirSync(s,{recursive:!0});let i=new Set,o=[],l=0;for(let u of e){if(o.length>=eu){r("warn",`attachment cap reached (${eu} files) - skipping the rest`);break}if(u.size>Gp){r("warn",`skipping attachment "${u.filename}" - ${Yp(u.size)} MB exceeds the 15 MB limit`);continue}if(l+u.size>Vp){r("warn",`attachment size budget reached - skipping "${u.filename}" and the rest`);break}try{let c=await t.downloadAttachment(u.contentUrl),f=tu(u.filename,i);Nr.default.writeFileSync(Xt.default.join(s,f),c),l+=c.length,o.push(`- ${oi}/${f} (${u.mimeType||"unknown type"}, ${Oo(c.length)} KB)`),r("info",`Downloaded attachment "${u.filename}" (${Oo(c.length)} KB)`)}catch(c){r("warn",`could not download attachment "${u.filename}": ${c instanceof Error?c.message:c}`)}}return o.length?`
|
|
294
294
|
|
|
@@ -383,7 +383,7 @@ Explore the repository first - entry points, routes, storage, tests - then audit
|
|
|
383
383
|
"evidence": [{"file": "<repo-relative path>", "line": <number, omit if n/a>, "note": "<what is there>"}],
|
|
384
384
|
"fix": "<2-4 sentences: concrete fix, specific to this code>"}]}
|
|
385
385
|
\`\`\`
|
|
386
|
-
Rules: every finding needs at least one evidence file you actually read - findings without real evidence will be DELETED from your report. Max 25 findings, worst first. An empty findings list with an honest summary is a valid, good answer.`+u}function nc(t){let n=t.match(/```(?:json)?\s*(\{[\s\S]*\})\s*```(?![\s\S]*```)/)?.[1]??t.match(/\{[\s\S]*"findings"[\s\S]*\}/)?.[0];if(!n)return{error:"the agent's report contained no JSON block"};let r;try{r=JSON.parse(n)}catch{return{error:"the agent's JSON report did not parse"}}if(!Array.isArray(r.findings))return{error:"the report has no findings array"};let s=[],i=0,o=new Set;for(let l of r.findings.slice(0,25)){let u=
|
|
386
|
+
Rules: every finding needs at least one evidence file you actually read - findings without real evidence will be DELETED from your report. Max 25 findings, worst first. An empty findings list with an honest summary is a valid, good answer.`+u}function nc(t){let n=t.match(/```(?:json)?\s*(\{[\s\S]*\})\s*```(?![\s\S]*```)/)?.[1]??t.match(/\{[\s\S]*"findings"[\s\S]*\}/)?.[0];if(!n)return{error:"the agent's report contained no JSON block"};let r;try{r=JSON.parse(n)}catch{return{error:"the agent's JSON report did not parse"}}if(!Array.isArray(r.findings))return{error:"the report has no findings array"};let s=[],i=0,o=new Set;for(let l of r.findings.slice(0,25)){let u=Eg(l),c=u?Ci.AuditFinding.safeParse(u):null;if(!c?.success){i++;continue}let f=c.data.id;for(;o.has(f);)f=`${f}-2`;o.add(f),s.push({...c.data,id:f})}return{summary:typeof r.summary=="string"?r.summary.trim().slice(0,2e3):"",findings:s,dropped:i}}function Eg(t){if(typeof t!="object"||t===null)return null;let e=t,n=typeof e.severity=="string"?e.severity.toLowerCase():"",r=Array.isArray(e.evidence)?e.evidence.filter(i=>typeof i=="object"&&i!==null).map(i=>({file:typeof i.file=="string"?i.file:"",...ec(i.line)?{line:ec(i.line)}:{},note:typeof i.note=="string"?i.note:""})).filter(i=>i.file):[],s=typeof e.ruleId=="string"?e.ruleId.trim().toUpperCase():"";return{id:Ag(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:Ci.AuditSeverity.options.includes(n)?n:void 0,area:typeof e.area=="string"?e.area.slice(0,60):"",evidence:r,fix:typeof e.fix=="string"?e.fix.slice(0,2e3):""}}function ec(t){let e=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):NaN;return Number.isInteger(e)&&e>0?e:void 0}function Ag(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"finding"}function $g(t){try{let e=ca.default.readFileSync(t,"utf8");return e?e.split(`
|
|
387
387
|
`).length:0}catch{return null}}function rc(t,e){let n=xi.default.resolve(t),r=[],s=[],i=0;for(let o of e){let l=[];for(let u of o.evidence){let c=u.file.trim().replace(/^\.\//,""),f=xi.default.resolve(n,c);if(f!==n&&!f.startsWith(n+xi.default.sep))continue;let p;try{p=ca.default.statSync(f)}catch{continue}if(p.isFile()){if(u.line!==void 0){let b=$g(f);if(b!==null&&u.line>b){l.push({...u,line:void 0}),i++;continue}}l.push(u)}}if(!l.length){s.push({title:o.title,files:o.evidence.map(u=>u.file)});continue}r.push({...o,evidence:l})}return{findings:r,droppedFindings:s,correctedLines:i}}var Cs=I(require("node:fs"),1),da=I(require("node:path"),1),sc=I(_e(),1);var Pg=20;function ic(){return da.default.join(se(),"audits.json")}function Vr(){try{return{byProject:JSON.parse(Cs.default.readFileSync(ic(),"utf8")).byProject??{}}}catch{return{byProject:{}}}}function oc(t){let e=ic();Cs.default.mkdirSync(da.default.dirname(e),{recursive:!0,mode:448});let n=e+".tmp";Cs.default.writeFileSync(n,JSON.stringify(t,null,2),{mode:384}),Cs.default.renameSync(n,e)}function ac(t,e){let n=Vr(),r=n.byProject[t]??[];r.unshift(sc.AuditRecord.parse(e)),n.byProject[t]=r.slice(0,Pg),oc(n)}function lc(t){return(Vr().byProject[t]??[]).map(e=>{let n={};for(let r of e.findings)n[r.severity]=(n[r.severity]??0)+1;return{id:e.id,role:e.role,createdAt:e.createdAt,findingCount:e.findings.length,bySeverity:n,detailLevel:e.detailLevel??"technical"}})}function uc(t,e){let n=Vr(),r=e?Date.parse(e):NaN,s={};for(let i of t){let o=(n.byProject[i]??[]).filter(u=>!Number.isFinite(r)||Date.parse(u.createdAt)>=r);if(!o.length)continue;let l={audits:o.length,findings:0,valid:0,falsePositive:0,wontFix:0,unreviewed:0};for(let u of o){l.findings+=u.findings.length;for(let c of u.findings){let f=u.verdicts[c.id]?.verdict;f==="valid"?l.valid++:f==="false-positive"?l.falsePositive++:f==="wont-fix"?l.wontFix++:l.unreviewed++}}s[i]=l}return s}function ha(t,e,n){let r=Vr(),i=(r.byProject[t]??[]).find(l=>l.id===e);if(!i)return null;i.ticketed??={},i.verdicts??={},i.lessonsWritten??=[];let o=new Set(i.findings.map(l=>l.id));n.selected&&(i.review={selected:n.selected.filter(l=>o.has(l)),updatedAt:new Date().toISOString()});for(let l of n.ticketed??[])o.has(l.findingId)&&(i.ticketed={...i.ticketed,[l.findingId]:l.issueKey});for(let l of n.verdicts??[])o.has(l.findingId)&&(i.verdicts={...i.verdicts,[l.findingId]:{verdict:l.verdict,note:l.note,by:n.verdictBy??"",at:new Date().toISOString()}});for(let l of n.markLessonsWritten??[])o.has(l)&&!i.lessonsWritten.includes(l)&&i.lessonsWritten.push(l);return oc(r),i}function cc(t,e){return(Vr().byProject[t]??[]).find(s=>s.role===e&&(s.scope?.kind??"repo")==="repo")?.createdAt??null}function dc(t,e){return(Vr().byProject[t]??[]).find(n=>n.id===e)??null}wt();var je=I(require("node:fs"),1),kt=I(require("node:path"),1),mc=I(_e(),1);var Ut=I(require("node:fs"),1),fa=I(require("node:path"),1),jg=25e4,Og=2e5,hc=`# Incident ledger
|
|
388
388
|
|
|
389
389
|
Machine-written facts about this repository's runs: what failed, what
|
|
@@ -567,11 +567,11 @@ ${t.trim()}`}function wc(t){let e=[];for(let r of mc.KnowledgeRole.options)for(l
|
|
|
567
567
|
`)){let s=r.trim();!s||s.startsWith("#")||e.push(s)}return e.slice(0,10)}async function sr(t,e,n={}){let r=[],s=n.perCommandTimeoutMs??6e5;for(let i of e){n.onProgress?.(`running: ${i}`);let o=Date.now(),l=await new Promise(u=>{let c=(0,kc.spawn)("bash",["-lc",i],{cwd:t,env:{...process.env,CI:"1",FORCE_COLOR:"0"}}),f="",p=w=>{f+=w.toString(),f.length>2e5&&(f=f.slice(-1e5))};c.stdout.on("data",p),c.stderr.on("data",p);let b=setTimeout(()=>{c.kill("SIGKILL"),f+=`
|
|
568
568
|
[killed: timed out]`},s);c.on("close",w=>{clearTimeout(b),u({command:i,exitCode:w??-1,durationMs:Date.now()-o,tail:f.slice(-4e3)})}),c.on("error",w=>{clearTimeout(b),u({command:i,exitCode:-1,durationMs:Date.now()-o,tail:String(w)})})});n.onProgress?.(`exit ${l.exitCode} in ${Math.round(l.durationMs/1e3)}s: ${i}`),r.push(l)}return r}async function Yr(t){let{packs:e,lessons:n}=Ii(t.role,t.repoPath);if(!e.length)return{ok:!1,error:`no knowledge packs found for the ${t.role} role - add markdown files under ~/.config/ticketpilot/knowledge/${t.role}/ on the runner`};let r="";if(t.scope.kind==="ticket"&&t.scope.ref){let b=t.scope.ref,w="";try{let x=await t.jira.getIssue(b);w=`Ticket ${b}: ${x.summary}
|
|
569
569
|
|
|
570
|
-
${x.description}`.slice(0,4e3)}catch{w=`Ticket ${b} (could not fetch its text from Jira).`}let S=await Jo(t.repoPath,b).catch(()=>null);if(S){let{base:x,stat:
|
|
570
|
+
${x.description}`.slice(0,4e3)}catch{w=`Ticket ${b} (could not fetch its text from Jira).`}let S=await Jo(t.repoPath,b).catch(()=>null);if(S){let{base:x,stat:A,diff:j}=await ki(t.repoPath,S).catch(()=>({base:"",stat:"",diff:""}));r=`${w}
|
|
571
571
|
|
|
572
572
|
Its implementation branch \`${S}\` vs \`${x}\`:
|
|
573
573
|
\`\`\`
|
|
574
|
-
${
|
|
574
|
+
${A}\`\`\`
|
|
575
575
|
\`\`\`diff
|
|
576
576
|
${j}
|
|
577
577
|
\`\`\``}else r=`${w}
|
|
@@ -587,14 +587,14 @@ ${S.tail.slice(-2e3)}`).join(`
|
|
|
587
587
|
|
|
588
588
|
---
|
|
589
589
|
|
|
590
|
-
`))}let o=t.model||t.agent.adapter.deepModel,l=t.detailLevel??"technical",u=await t.agent.adapter.run({repoPath:t.repoPath,prompt:tc(t.role,e,n,{scopeNote:r,testResults:s,detailLevel:l}),timeoutSeconds:480,bin:t.agent.bin,mode:"read_only",maxTurns:120,sessionId:(0,va.randomUUID)(),model:o,onLog:(b,w)=>{b==="agent"&&y.info(`[audit:${t.role}] ${w.slice(0,160)}`)}}),c=nc(u.resultText);if("error"in c)return{ok:!1,error:c.error};let f=rc(t.repoPath,c.findings);for(let b of f.droppedFindings)y.warn(`[audit:${t.role}] dropped "${b.title}" - cited files do not exist: `+b.files.join(", "));let p={id:(0,va.randomUUID)(),role:t.role,createdAt:new Date().toISOString(),model:u.model||o,summary:c.summary,packNames:e.map(b=>b.name),findings:f.findings,costUsd:u.costUsd??0,ticketed:{},verdicts:{},lessonsWritten:[],scope:t.scope,detailLevel:l,...i?{testRun:i}:{}};return ac(t.projectId,p),y.info(`Audit (${t.role}${t.scope.kind!=="repo"?` \xB7 ${t.scope.kind}:${t.scope.ref}`:""}) done: ${f.findings.length} finding(s)`+(c.dropped?`, ${c.dropped} malformed`:"")+(f.droppedFindings.length?`, ${f.droppedFindings.length} dropped for citing files that do not exist`:"")+(f.correctedLines?`, ${f.correctedLines} bad line number(s) stripped`:"")),{ok:!0,audit:p}}var hn=I(_e(),1);var $a=I(require("node:fs"),1),Mi=I(require("node:path"),1),zi=require("node:crypto"),we=I(_e(),1);var ir=I(_e(),1);var wa=I(require("node:fs"),1),Cc=I(require("node:os"),1),
|
|
590
|
+
`))}let o=t.model||t.agent.adapter.deepModel,l=t.detailLevel??"technical",u=await t.agent.adapter.run({repoPath:t.repoPath,prompt:tc(t.role,e,n,{scopeNote:r,testResults:s,detailLevel:l}),timeoutSeconds:480,bin:t.agent.bin,mode:"read_only",maxTurns:120,sessionId:(0,va.randomUUID)(),model:o,onLog:(b,w)=>{b==="agent"&&y.info(`[audit:${t.role}] ${w.slice(0,160)}`)}}),c=nc(u.resultText);if("error"in c)return{ok:!1,error:c.error};let f=rc(t.repoPath,c.findings);for(let b of f.droppedFindings)y.warn(`[audit:${t.role}] dropped "${b.title}" - cited files do not exist: `+b.files.join(", "));let p={id:(0,va.randomUUID)(),role:t.role,createdAt:new Date().toISOString(),model:u.model||o,summary:c.summary,packNames:e.map(b=>b.name),findings:f.findings,costUsd:u.costUsd??0,ticketed:{},verdicts:{},lessonsWritten:[],scope:t.scope,detailLevel:l,...i?{testRun:i}:{}};return ac(t.projectId,p),y.info(`Audit (${t.role}${t.scope.kind!=="repo"?` \xB7 ${t.scope.kind}:${t.scope.ref}`:""}) done: ${f.findings.length} finding(s)`+(c.dropped?`, ${c.dropped} malformed`:"")+(f.droppedFindings.length?`, ${f.droppedFindings.length} dropped for citing files that do not exist`:"")+(f.correctedLines?`, ${f.correctedLines} bad line number(s) stripped`:"")),{ok:!0,audit:p}}var hn=I(_e(),1);var $a=I(require("node:fs"),1),Mi=I(require("node:path"),1),zi=require("node:crypto"),we=I(_e(),1);var ir=I(_e(),1);var wa=I(require("node:fs"),1),Cc=I(require("node:os"),1),Ei=I(require("node:path"),1),Ic=require("node:child_process"),Rc=I(require("node:readline"),1),Ec=I(_e(),1);function Ri(t){return`
|
|
591
591
|
|
|
592
592
|
YOUR CAPABILITIES IN THIS RUN - state them accurately, never guess:
|
|
593
593
|
- You CANNOT run shell commands, install anything, restart services, touch a database, or reach any machine. There is no shell tool here and asking for permission will not create one.
|
|
594
594
|
`+(t==="edit_no_shell"?`- You CAN read files and CREATE or EDIT files inside this working directory.
|
|
595
595
|
`:`- You can ONLY read: Read, Glob and Grep inside this working directory. You cannot create or change a single file.
|
|
596
|
-
`)+'NEVER offer to do something outside this list, and never ask "shall I do X?" when X is outside it - offering it and then failing costs the person a whole turn and their trust. Say plainly what you cannot do here, then name the route that CAN do it (a ticket, an implement run, or a command for a human to run).'}var qg=4e3,Fg={read_only:["Read(./**)","Glob(./**)","Grep(./**)"],edit_no_shell:["Read(./**)","Glob(./**)","Grep(./**)","Edit(./**)","Write(./**)"]};function Bg(t){if(process.env.ANTHROPIC_API_KEY)return"API key";let e=t??Ai.default.join(Cc.default.homedir(),".claude");try{if(wa.default.existsSync(Ai.default.join(e,".credentials.json"))||wa.default.existsSync(Ai.default.join(e,"credentials.json")))return"subscription"}catch{}return"unknown"}async function Kg(t){let e=["-p","--output-format","stream-json","--verbose","--allowedTools",Fg[t.mode].join(","),"--max-turns",String(t.maxTurns??60),...t.model?["--model",t.model]:[],...t.resume?["--resume",t.sessionId]:["--session-id",t.sessionId]],n=Bg(t.configDir);return n!=="unknown"&&t.onLog("info",n==="subscription"?"Billing: Claude subscription - costs shown are notional list prices, not money charged":"Billing: Anthropic API key - costs shown are actual metered spend"),new Promise(r=>{let s=(0,Ic.spawn)(t.bin,e,{cwd:t.repoPath,env:t.configDir?{...process.env,CLAUDE_CONFIG_DIR:t.configDir}:process.env,stdio:["pipe","pipe","pipe"]}),i={ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,billingMode:n==="subscription"?"subscription":n==="API key"?"api":"unknown"},o=0,l=0,u=0,c=0,f=0,p=()=>{if(!t.onUsage)return;let v=Date.now();v-f<qg||(f=v,t.onUsage({inputTokens:l,outputTokens:u,cacheReadTokens:c,turns:o}))},b=!1,w=()=>{b||(b=!0,clearTimeout(x),t.signal?.removeEventListener("abort",S),r(i))},S=()=>{i.cancelled=!0,i.error="stopped from the dashboard",t.onLog("error",i.error),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),3e3).unref()};t.signal?.addEventListener("abort",S,{once:!0});let x=setTimeout(()=>{i.timedOut=!0,i.error=`run exceeded ${t.timeoutSeconds}s wall-clock limit`,t.onLog("error",i.error),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),5e3).unref()},t.timeoutSeconds*1e3);s.stdin.write(t.prompt+Ri(t.mode)),s.stdin.end(),Rc.default.createInterface({input:s.stdout}).on("line",v=>{if(!v.trim())return;let O;try{O=JSON.parse(v)}catch{t.onLog("agent",v.slice(0,1e3));return}if(O.type==="system"&&O.subtype==="init")i.model=typeof O.model=="string"?O.model:void 0,t.onLog("info",`Claude Code session started (model: ${O.model??"default"})`);else if(O.type==="assistant"){o+=1;let H=O.message?.usage;H&&(l+=Number(H.input_tokens??0)+Number(H.cache_creation_input_tokens??0),u+=Number(H.output_tokens??0),c+=Number(H.cache_read_input_tokens??0),p());for(let z of O.message?.content??[])if(z.type==="text"&&z.text?.trim())t.onLog("agent",z.text.trim().slice(0,4e3));else if(z.type==="tool_use"){let B=z.input??{},d=["file_path","path","pattern","command","description","url"].map(g=>typeof B[g]=="string"?`${g}=${B[g]}`:null).filter(Boolean).join(" "),m=JSON.stringify(B).slice(0,400);t.onLog("info",`tool ${z.name} ${d?`${d} `:""}${m}`)}}else O.type==="result"&&(i.costUsd=Number(O.total_cost_usd??0),i.inputTokens=Number(O.usage?.input_tokens??0)+Number(O.usage?.cache_creation_input_tokens??0),i.outputTokens=Number(O.usage?.output_tokens??0),l=Math.max(i.inputTokens,l),u=Math.max(i.outputTokens,u),i.inputTokens=l,i.outputTokens=u,c=Number(O.usage?.cache_read_input_tokens??c),i.cacheReadTokens=c,t.onUsage&&(t.onUsage({inputTokens:l,outputTokens:u,cacheReadTokens:c,costUsd:i.costUsd,turns:o}),f=Date.now()),O.subtype==="success"&&!O.is_error?(i.ok=!0,i.resultText=String(O.result??"")):O.subtype==="error_max_turns"?(i.turnLimitHit=!0,i.error=`hit the ${t.maxTurns??60}-turn limit before finishing`):(i.error=String(O.result??O.subtype??"unknown Claude Code error"),/rate.?limit|usage limit|limit (reached|exceeded)|overloaded/i.test(i.error)&&(i.error=`Claude usage limit hit for this account - the run will work again once the limit window resets. Original error: ${i.error.slice(0,400)}`)))});let j="";s.stderr.on("data",v=>{j=(j+v.toString()).slice(-2e3)}),s.on("error",v=>{i.error=`failed to start ${t.bin}: ${v.message}`,t.onLog("error",i.error),w()}),s.on("close",v=>{!i.ok&&!i.error&&(i.error=i.timedOut?i.error:`claude exited with code ${v}${j?`: ${j.slice(-500)}`:""}`),w()})})}var Ei={id:"claude-code",displayName:"Claude Code",fastModel:"claude-sonnet-5",deepModel:"claude-fable-5",capabilities:Ac.REGISTERED_AGENTS.find(t=>t.id==="claude-code").capabilities,run:Kg};var Ec=require("node:child_process"),$c=I(require("node:readline"),1),Pc=I(_e(),1);async function Hg(t){if(t.mode!=="read_only")return{ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,error:"the codex adapter only supports read-only runs - its write sandbox cannot exclude shell, and Allwright never weakens a guarantee silently"};if(t.resume)return{ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,error:"the codex adapter cannot resume sessions"};let e=["exec","--json","--sandbox","read-only","--skip-git-repo-check","--cd",t.repoPath,...t.model?["--model",t.model]:[],"-"];return new Promise(n=>{let r=(0,Ec.spawn)(t.bin,e,{cwd:t.repoPath,env:process.env,stdio:["pipe","pipe","pipe"]}),s={ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,cacheReadTokens:0},i="",o=!1,l=()=>{o||(o=!0,clearTimeout(u),n(s))},u=setTimeout(()=>{s.timedOut=!0,s.error=`run exceeded ${t.timeoutSeconds}s wall-clock limit`,t.onLog("error",s.error),r.kill("SIGTERM"),setTimeout(()=>r.kill("SIGKILL"),5e3).unref()},t.timeoutSeconds*1e3);r.stdin.write(t.prompt+Ri(t.mode)),r.stdin.end(),$c.default.createInterface({input:r.stdout}).on("line",p=>{if(!p.trim())return;let b;try{b=JSON.parse(p)}catch{t.onLog("agent",p.slice(0,1e3));return}let w=b.item??b.msg??b,S=w?.type??b.type,x=w?.text??w?.message??"";S==="agent_message"&&typeof x=="string"&&x.trim()?(i=x,t.onLog("agent",x.trim().slice(0,4e3))):S==="command_execution"||S==="exec_command_begin"?t.onLog("info",`tool ${String(w?.command??"").slice(0,300)}`):S==="error"&&typeof x=="string"&&x&&t.onLog("error",x.slice(0,1e3))});let f="";r.stderr.on("data",p=>{f=(f+p.toString()).slice(-2e3)}),r.on("error",p=>{s.error=`failed to start ${t.bin}: ${p.message} - is the Codex CLI installed and logged in?`,t.onLog("error",s.error),l()}),r.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")+(f?`: ${f.slice(-500)}`:"")),l()})})}var _a={id:"codex",fastModel:"",deepModel:"",displayName:"OpenAI Codex CLI (experimental)",capabilities:Pc.REGISTERED_AGENTS.find(t=>t.id==="codex").capabilities,run:Hg};var Zg={[Ei.id]:Ei,[_a.id]:_a};function Be(t){return Zg[t||ir.DEFAULT_AGENT_ID]??null}function Ue(t,e){return!e||e===Ei.id?t.claudeBin:t.agents[e]?.bin??e}function dn(t,e){let n=Be(t);if(!n)return`no agent adapter named "${t}" on this runner - update the runner, or set the rule's agent to "${ir.DEFAULT_AGENT_ID}"`;let r=(0,ir.missingAgentCapabilities)(n.id,e);return r&&r.length?`agent "${n.displayName}" cannot run ${e} rules: it cannot guarantee ${r.join(", ")}. Allwright refuses rather than weakening the isolation silently.`:null}function Ke(t,e,n){let r=e.defaultAgent||ir.DEFAULT_AGENT_ID,s=Be(r);if(!s)return{error:`this project's default agent "${r}" is not on this runner - update the runner, or change the project's agent`};let i=(0,ir.missingAgentCapabilities)(s.id,n);return i&&i.length?{error:`this project's default agent "${s.displayName}" cannot power this - it lacks ${i.join(", ")}. Change the project's agent, or use one that can.`}:{adapter:s,bin:Ue(t,s.id)}}function qt(t,e){return t.replace(/\{\{(\w+)\}\}/g,(n,r)=>r in e?e[r]:n)}var Bc=I(_e(),1);ut();nr();wt();var Oe=I(require("node:fs"),1),Xr=I(require("node:path"),1);var Vg=_.object({runId:_.string(),issueKey:_.string(),repoName:_.string(),owner:_.string(),repo:_.string(),prNumber:_.number().int(),prUrl:_.string(),branch:_.string(),headSha:_.string(),doneLabel:_.string(),failedLabel:_.string(),jiraTransition:_.string().optional(),mergeOnApprove:_.boolean().default(!1),mergeMethod:_.enum(["squash","merge","rebase"]).default("squash"),autoMerge:_.boolean().default(!1),nextDecisionSeq:_.number().int().default(1e5),changesRequestedNotified:_.boolean().optional(),conflictNotified:_.boolean().optional(),agentConfigDir:_.string().optional()}),Wg=_.record(Vg),Jg=_.object({runId:_.string(),issueKey:_.string(),issueSummary:_.string().default(""),projectId:_.string(),repoName:_.string(),environmentName:_.string(),requestedBy:_.string().default(""),createdAt:_.string()}),Yg=_.record(Jg),Xg=_.object({runId:_.string(),issueKey:_.string(),kind:_.enum(["plan","implement"]),repoPath:_.string(),sessionId:_.string(),doneLabel:_.string(),failedLabel:_.string(),timeoutSeconds:_.number(),createdAt:_.string(),questionsPostedAt:_.string(),rounds:_.number().int().default(1),nextLogSeq:_.number().int().nonnegative().default(0),baseRepoPath:_.string().optional(),repoName:_.string().optional(),branch:_.string().optional(),baseBranch:_.string().optional(),jiraTransition:_.string().optional(),jiraTransitionOnMerge:_.string().optional(),requireApproval:_.boolean().optional(),maxTurns:_.number().int().optional(),runTests:_.boolean().default(!0),mergeOnApprove:_.boolean().default(!1),mergeMethod:_.enum(["squash","merge","rebase"]).default("squash"),autoMerge:_.boolean().default(!1),issueSummary:_.string().default(""),claudeConfigDir:_.string().optional(),agent:_.string().optional(),model:_.string().optional(),actorEmail:_.string().optional()}),Qg=_.object({runId:_.string(),issueKey:_.string(),issueSummary:_.string().default(""),repoName:_.string(),baseRepoPath:_.string(),branch:_.string(),baseBranch:_.string(),headSha:_.string(),requireApproval:_.boolean(),mergeOnApprove:_.boolean().default(!1),mergeMethod:_.enum(["squash","merge","rebase"]).default("squash"),autoMerge:_.boolean().default(!1),doneLabel:_.string(),failedLabel:_.string(),jiraTransition:_.string().optional(),jiraTransitionOnMerge:_.string().optional(),actorEmail:_.string().optional(),resultSummary:_.string().default(""),prSummary:_.string().default(""),costUsd:_.number().default(0),nextLogSeq:_.number().int().default(1e5),createdAt:_.string()}),ey=_.record(Qg),ty=_.object({runId:_.string(),issueKey:_.string(),repoName:_.string(),owner:_.string(),repo:_.string(),prNumber:_.number().int(),prUrl:_.string(),jiraTransitionOnMerge:_.string().default(""),createdAt:_.string()}),ny=_.record(ty),ry=_.record(Xg);function jc(){return Xr.default.join(se(),"pending-runs.json")}function ka(){return Xr.default.join(se(),"pending-deploys.json")}function Sa(){return Xr.default.join(se(),"pending-inputs.json")}function Ta(){return Xr.default.join(se(),"merge-watch.json")}function xa(){return Xr.default.join(se(),"pending-pushes.json")}function Ca(){let t=xa();if(!Oe.default.existsSync(t))return{};try{return ey.parse(JSON.parse(Oe.default.readFileSync(t,"utf8")))}catch{return{}}}function $i(t){let e=Ca();e[t.runId]=t,Ft(xa(),e)}function Pi(t){return Ca()[t]??null}function Ia(t){let e=Ca();t in e&&(delete e[t],Ft(xa(),e))}function ji(){let t=Ta();if(!Oe.default.existsSync(t))return{};try{return ny.parse(JSON.parse(Oe.default.readFileSync(t,"utf8")))}catch{return{}}}function Oc(t){let e=ji();e[t.runId]=t,Ft(Ta(),e)}function Rs(t){let e=ji();t in e&&(delete e[t],Ft(Ta(),e))}function As(){let t=jc();if(!Oe.default.existsSync(t))return{};try{return Wg.parse(JSON.parse(Oe.default.readFileSync(t,"utf8")))}catch{return{}}}function Ft(t,e){Oe.default.mkdirSync(se(),{recursive:!0,mode:448});let n=t+".tmp";Oe.default.writeFileSync(n,JSON.stringify(e,null,2)+`
|
|
597
|
-
`,{mode:384}),Oe.default.renameSync(n,t),Oe.default.chmodSync(t,384)}function Nc(t){Ft(jc(),t)}function ct(t){let e=
|
|
596
|
+
`)+'NEVER offer to do something outside this list, and never ask "shall I do X?" when X is outside it - offering it and then failing costs the person a whole turn and their trust. Say plainly what you cannot do here, then name the route that CAN do it (a ticket, an implement run, or a command for a human to run).'}var qg=4e3,Fg={read_only:["Read(./**)","Glob(./**)","Grep(./**)"],edit_no_shell:["Read(./**)","Glob(./**)","Grep(./**)","Edit(./**)","Write(./**)"]};function Bg(t){if(process.env.ANTHROPIC_API_KEY)return"API key";let e=t??Ei.default.join(Cc.default.homedir(),".claude");try{if(wa.default.existsSync(Ei.default.join(e,".credentials.json"))||wa.default.existsSync(Ei.default.join(e,"credentials.json")))return"subscription"}catch{}return"unknown"}async function Kg(t){let e=["-p","--output-format","stream-json","--verbose","--allowedTools",Fg[t.mode].join(","),"--max-turns",String(t.maxTurns??60),...t.model?["--model",t.model]:[],...t.resume?["--resume",t.sessionId]:["--session-id",t.sessionId]],n=Bg(t.configDir);return n!=="unknown"&&t.onLog("info",n==="subscription"?"Billing: Claude subscription - costs shown are notional list prices, not money charged":"Billing: Anthropic API key - costs shown are actual metered spend"),new Promise(r=>{let s=(0,Ic.spawn)(t.bin,e,{cwd:t.repoPath,env:t.configDir?{...process.env,CLAUDE_CONFIG_DIR:t.configDir}:process.env,stdio:["pipe","pipe","pipe"]}),i={ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,billingMode:n==="subscription"?"subscription":n==="API key"?"api":"unknown"},o=0,l=0,u=0,c=0,f=0,p=()=>{if(!t.onUsage)return;let v=Date.now();v-f<qg||(f=v,t.onUsage({inputTokens:l,outputTokens:u,cacheReadTokens:c,turns:o}))},b=!1,w=()=>{b||(b=!0,clearTimeout(x),t.signal?.removeEventListener("abort",S),r(i))},S=()=>{i.cancelled=!0,i.error="stopped from the dashboard",t.onLog("error",i.error),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),3e3).unref()};t.signal?.addEventListener("abort",S,{once:!0});let x=setTimeout(()=>{i.timedOut=!0,i.error=`run exceeded ${t.timeoutSeconds}s wall-clock limit`,t.onLog("error",i.error),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),5e3).unref()},t.timeoutSeconds*1e3);s.stdin.write(t.prompt+Ri(t.mode)),s.stdin.end(),Rc.default.createInterface({input:s.stdout}).on("line",v=>{if(!v.trim())return;let O;try{O=JSON.parse(v)}catch{t.onLog("agent",v.slice(0,1e3));return}if(O.type==="system"&&O.subtype==="init")i.model=typeof O.model=="string"?O.model:void 0,t.onLog("info",`Claude Code session started (model: ${O.model??"default"})`);else if(O.type==="assistant"){o+=1;let H=O.message?.usage;H&&(l+=Number(H.input_tokens??0)+Number(H.cache_creation_input_tokens??0),u+=Number(H.output_tokens??0),c+=Number(H.cache_read_input_tokens??0),p());for(let z of O.message?.content??[])if(z.type==="text"&&z.text?.trim())t.onLog("agent",z.text.trim().slice(0,4e3));else if(z.type==="tool_use"){let B=z.input??{},d=["file_path","path","pattern","command","description","url"].map(g=>typeof B[g]=="string"?`${g}=${B[g]}`:null).filter(Boolean).join(" "),m=JSON.stringify(B).slice(0,400);t.onLog("info",`tool ${z.name} ${d?`${d} `:""}${m}`)}}else O.type==="result"&&(i.costUsd=Number(O.total_cost_usd??0),i.inputTokens=Number(O.usage?.input_tokens??0)+Number(O.usage?.cache_creation_input_tokens??0),i.outputTokens=Number(O.usage?.output_tokens??0),l=Math.max(i.inputTokens,l),u=Math.max(i.outputTokens,u),i.inputTokens=l,i.outputTokens=u,c=Number(O.usage?.cache_read_input_tokens??c),i.cacheReadTokens=c,t.onUsage&&(t.onUsage({inputTokens:l,outputTokens:u,cacheReadTokens:c,costUsd:i.costUsd,turns:o}),f=Date.now()),O.subtype==="success"&&!O.is_error?(i.ok=!0,i.resultText=String(O.result??"")):O.subtype==="error_max_turns"?(i.turnLimitHit=!0,i.error=`hit the ${t.maxTurns??60}-turn limit before finishing`):(i.error=String(O.result??O.subtype??"unknown Claude Code error"),/rate.?limit|usage limit|limit (reached|exceeded)|overloaded/i.test(i.error)&&(i.error=`Claude usage limit hit for this account - the run will work again once the limit window resets. Original error: ${i.error.slice(0,400)}`)))});let j="";s.stderr.on("data",v=>{j=(j+v.toString()).slice(-2e3)}),s.on("error",v=>{i.error=`failed to start ${t.bin}: ${v.message}`,t.onLog("error",i.error),w()}),s.on("close",v=>{!i.ok&&!i.error&&(i.error=i.timedOut?i.error:`claude exited with code ${v}${j?`: ${j.slice(-500)}`:""}`),w()})})}var Ai={id:"claude-code",displayName:"Claude Code",fastModel:"claude-sonnet-5",deepModel:"claude-fable-5",capabilities:Ec.REGISTERED_AGENTS.find(t=>t.id==="claude-code").capabilities,run:Kg};var Ac=require("node:child_process"),$c=I(require("node:readline"),1),Pc=I(_e(),1);async function Hg(t){if(t.mode!=="read_only")return{ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,error:"the codex adapter only supports read-only runs - its write sandbox cannot exclude shell, and Allwright never weakens a guarantee silently"};if(t.resume)return{ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,error:"the codex adapter cannot resume sessions"};let e=["exec","--json","--sandbox","read-only","--skip-git-repo-check","--cd",t.repoPath,...t.model?["--model",t.model]:[],"-"];return new Promise(n=>{let r=(0,Ac.spawn)(t.bin,e,{cwd:t.repoPath,env:process.env,stdio:["pipe","pipe","pipe"]}),s={ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,cacheReadTokens:0},i="",o=!1,l=()=>{o||(o=!0,clearTimeout(u),n(s))},u=setTimeout(()=>{s.timedOut=!0,s.error=`run exceeded ${t.timeoutSeconds}s wall-clock limit`,t.onLog("error",s.error),r.kill("SIGTERM"),setTimeout(()=>r.kill("SIGKILL"),5e3).unref()},t.timeoutSeconds*1e3);r.stdin.write(t.prompt+Ri(t.mode)),r.stdin.end(),$c.default.createInterface({input:r.stdout}).on("line",p=>{if(!p.trim())return;let b;try{b=JSON.parse(p)}catch{t.onLog("agent",p.slice(0,1e3));return}let w=b.item??b.msg??b,S=w?.type??b.type,x=w?.text??w?.message??"";S==="agent_message"&&typeof x=="string"&&x.trim()?(i=x,t.onLog("agent",x.trim().slice(0,4e3))):S==="command_execution"||S==="exec_command_begin"?t.onLog("info",`tool ${String(w?.command??"").slice(0,300)}`):S==="error"&&typeof x=="string"&&x&&t.onLog("error",x.slice(0,1e3))});let f="";r.stderr.on("data",p=>{f=(f+p.toString()).slice(-2e3)}),r.on("error",p=>{s.error=`failed to start ${t.bin}: ${p.message} - is the Codex CLI installed and logged in?`,t.onLog("error",s.error),l()}),r.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")+(f?`: ${f.slice(-500)}`:"")),l()})})}var _a={id:"codex",fastModel:"",deepModel:"",displayName:"OpenAI Codex CLI (experimental)",capabilities:Pc.REGISTERED_AGENTS.find(t=>t.id==="codex").capabilities,run:Hg};var Zg={[Ai.id]:Ai,[_a.id]:_a};function Be(t){return Zg[t||ir.DEFAULT_AGENT_ID]??null}function Ue(t,e){return!e||e===Ai.id?t.claudeBin:t.agents[e]?.bin??e}function dn(t,e){let n=Be(t);if(!n)return`no agent adapter named "${t}" on this runner - update the runner, or set the rule's agent to "${ir.DEFAULT_AGENT_ID}"`;let r=(0,ir.missingAgentCapabilities)(n.id,e);return r&&r.length?`agent "${n.displayName}" cannot run ${e} rules: it cannot guarantee ${r.join(", ")}. Allwright refuses rather than weakening the isolation silently.`:null}function Ke(t,e,n){let r=e.defaultAgent||ir.DEFAULT_AGENT_ID,s=Be(r);if(!s)return{error:`this project's default agent "${r}" is not on this runner - update the runner, or change the project's agent`};let i=(0,ir.missingAgentCapabilities)(s.id,n);return i&&i.length?{error:`this project's default agent "${s.displayName}" cannot power this - it lacks ${i.join(", ")}. Change the project's agent, or use one that can.`}:{adapter:s,bin:Ue(t,s.id)}}function qt(t,e){return t.replace(/\{\{(\w+)\}\}/g,(n,r)=>r in e?e[r]:n)}var Bc=I(_e(),1);ut();nr();wt();var Oe=I(require("node:fs"),1),Xr=I(require("node:path"),1);var Vg=_.object({runId:_.string(),issueKey:_.string(),repoName:_.string(),owner:_.string(),repo:_.string(),prNumber:_.number().int(),prUrl:_.string(),branch:_.string(),headSha:_.string(),doneLabel:_.string(),failedLabel:_.string(),jiraTransition:_.string().optional(),mergeOnApprove:_.boolean().default(!1),mergeMethod:_.enum(["squash","merge","rebase"]).default("squash"),autoMerge:_.boolean().default(!1),nextDecisionSeq:_.number().int().default(1e5),changesRequestedNotified:_.boolean().optional(),conflictNotified:_.boolean().optional(),agentConfigDir:_.string().optional()}),Wg=_.record(Vg),Jg=_.object({runId:_.string(),issueKey:_.string(),issueSummary:_.string().default(""),projectId:_.string(),repoName:_.string(),environmentName:_.string(),requestedBy:_.string().default(""),createdAt:_.string()}),Yg=_.record(Jg),Xg=_.object({runId:_.string(),issueKey:_.string(),kind:_.enum(["plan","implement"]),repoPath:_.string(),sessionId:_.string(),doneLabel:_.string(),failedLabel:_.string(),timeoutSeconds:_.number(),createdAt:_.string(),questionsPostedAt:_.string(),rounds:_.number().int().default(1),nextLogSeq:_.number().int().nonnegative().default(0),baseRepoPath:_.string().optional(),repoName:_.string().optional(),branch:_.string().optional(),baseBranch:_.string().optional(),jiraTransition:_.string().optional(),jiraTransitionOnMerge:_.string().optional(),requireApproval:_.boolean().optional(),maxTurns:_.number().int().optional(),runTests:_.boolean().default(!0),mergeOnApprove:_.boolean().default(!1),mergeMethod:_.enum(["squash","merge","rebase"]).default("squash"),autoMerge:_.boolean().default(!1),issueSummary:_.string().default(""),claudeConfigDir:_.string().optional(),agent:_.string().optional(),model:_.string().optional(),actorEmail:_.string().optional()}),Qg=_.object({runId:_.string(),issueKey:_.string(),issueSummary:_.string().default(""),repoName:_.string(),baseRepoPath:_.string(),branch:_.string(),baseBranch:_.string(),headSha:_.string(),requireApproval:_.boolean(),mergeOnApprove:_.boolean().default(!1),mergeMethod:_.enum(["squash","merge","rebase"]).default("squash"),autoMerge:_.boolean().default(!1),doneLabel:_.string(),failedLabel:_.string(),jiraTransition:_.string().optional(),jiraTransitionOnMerge:_.string().optional(),actorEmail:_.string().optional(),resultSummary:_.string().default(""),prSummary:_.string().default(""),costUsd:_.number().default(0),nextLogSeq:_.number().int().default(1e5),createdAt:_.string()}),ey=_.record(Qg),ty=_.object({runId:_.string(),issueKey:_.string(),repoName:_.string(),owner:_.string(),repo:_.string(),prNumber:_.number().int(),prUrl:_.string(),jiraTransitionOnMerge:_.string().default(""),createdAt:_.string()}),ny=_.record(ty),ry=_.record(Xg);function jc(){return Xr.default.join(se(),"pending-runs.json")}function ka(){return Xr.default.join(se(),"pending-deploys.json")}function Sa(){return Xr.default.join(se(),"pending-inputs.json")}function Ta(){return Xr.default.join(se(),"merge-watch.json")}function xa(){return Xr.default.join(se(),"pending-pushes.json")}function Ca(){let t=xa();if(!Oe.default.existsSync(t))return{};try{return ey.parse(JSON.parse(Oe.default.readFileSync(t,"utf8")))}catch{return{}}}function $i(t){let e=Ca();e[t.runId]=t,Ft(xa(),e)}function Pi(t){return Ca()[t]??null}function Ia(t){let e=Ca();t in e&&(delete e[t],Ft(xa(),e))}function ji(){let t=Ta();if(!Oe.default.existsSync(t))return{};try{return ny.parse(JSON.parse(Oe.default.readFileSync(t,"utf8")))}catch{return{}}}function Oc(t){let e=ji();e[t.runId]=t,Ft(Ta(),e)}function Rs(t){let e=ji();t in e&&(delete e[t],Ft(Ta(),e))}function Es(){let t=jc();if(!Oe.default.existsSync(t))return{};try{return Wg.parse(JSON.parse(Oe.default.readFileSync(t,"utf8")))}catch{return{}}}function Ft(t,e){Oe.default.mkdirSync(se(),{recursive:!0,mode:448});let n=t+".tmp";Oe.default.writeFileSync(n,JSON.stringify(e,null,2)+`
|
|
597
|
+
`,{mode:384}),Oe.default.renameSync(n,t),Oe.default.chmodSync(t,384)}function Nc(t){Ft(jc(),t)}function ct(t){let e=Es();e[t.runId]=t,Nc(e)}function Qr(t){return Es()[t]??null}function ar(t){let e=Es();t in e&&(delete e[t],Nc(e))}function Ra(){let t=ka();if(!Oe.default.existsSync(t))return{};try{return Yg.parse(JSON.parse(Oe.default.readFileSync(t,"utf8")))}catch{return{}}}function Mc(t){let e=Ra();e[t.runId]=t,Ft(ka(),e)}function Oi(t){return Ra()[t]??null}function Ni(t){let e=Ra();t in e&&(delete e[t],Ft(ka(),e))}function lr(){let t=Sa();if(!Oe.default.existsSync(t))return{};try{return ry.parse(JSON.parse(Oe.default.readFileSync(t,"utf8")))}catch{return{}}}function zc(t){let e=lr();e[t.runId]=t,Ft(Sa(),e)}function Dc(t){return lr()[t]??null}function St(t){let e=lr();t in e&&(delete e[t],Ft(Sa(),e))}var sy=`
|
|
598
598
|
|
|
599
599
|
NEVER create or modify CI/workflow files (.github/workflows/, .githooks/ or similar CI config) - the runner refuses to push them, and the refusal costs the whole run. When the ticket needs something enforced on every change, use a path that is yours to edit instead: add the check as a command in TEST.md (this runner executes TEST.md commands after every implement run and posts the results into the PR), wire it into a script CI already runs (package.json test/build scripts, the test suite itself), or - only if it truly must be a workflow file - put the exact proposed YAML in your summary for a human to apply by hand.`,iy=`
|
|
600
600
|
|
|
@@ -624,7 +624,7 @@ This repository has working rules taught to Allwright - follow them:
|
|
|
624
624
|
Lessons from earlier runs on this repository (human-confirmed - follow them BEFORE writing code, they exist because a run got this wrong once):
|
|
625
625
|
`+o}return r}catch{return""}}function Pa(t){return $a.default.existsSync(Mi.default.join(t,"DESIGN.md"))?`
|
|
626
626
|
|
|
627
|
-
This repository has a DESIGN.md at its root: read it before doing any user-facing work (UI, copy, styling) and follow it. Where the ticket and DESIGN.md conflict, say so instead of silently picking one.`:""}var Kc=5,Uc=2,uy=8,qc=2,cy="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
|
|
627
|
+
This repository has a DESIGN.md at its root: read it before doing any user-facing work (UI, copy, styling) and follow it. Where the ticket and DESIGN.md conflict, say so instead of silently picking one.`:""}var Kc=5,Uc=2,uy=8,qc=2,cy="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 As(t,e,n,r){let s=Date.now(),i="";r&&(i=await r().catch(()=>""));let o=await t.run(e),l=0,u="",c=r?uy:Uc;for(;!o.ok&&o.turnLimitHit&&!o.cancelled&&t.capabilities.sessionResume;){if(l>=c){u=`resume cap (${c}) reached`;break}if(r&&l>=Uc){let p=await r().catch(()=>""),b=p!==""&&p!==i;if(i=p,!b){u="the last resume produced no new work";break}if(Date.now()-s>e.timeoutSeconds*qc*1e3){u=`wall-clock budget (${qc}x the rule's timeout) exhausted`;break}}l++,n("info",`Turn limit hit mid-work - auto-resuming the same session (resume ${l}, cap ${c})`);let f=await t.run({...e,prompt:cy,resume:!0});f.costUsd+=o.costUsd,f.inputTokens+=o.inputTokens,f.outputTokens+=o.outputTokens,o=f}return!o.ok&&o.turnLimitHit&&t.capabilities.sessionResume&&(o.error=`${o.error??"hit the turn limit"} - even after ${l} automatic same-session resume(s)${u?` (stopped: ${u})`:""}. The ticket is probably too large for one run: raise the rule's max turns, or split the ticket.`),o}var Aa=new Map;function Hc(t){let e=Aa.get(t);return e?(e.abort(),!0):!1}async function ts(t,e,n,r,s){let i=new AbortController;Aa.set(t,i);try{return await As(e,{...n,signal:i.signal},r,s)}finally{Aa.delete(t)}}function ur(t,e,n=0){let r=n;return{emit:(l,u)=>{e.send({type:"run.log",runId:t,seq:r++,ts:new Date().toISOString(),level:l,message:u}),l!=="agent"&&y.info(`[run ${t}] ${u}`)},setStatus:(l,u={})=>{e.send({type:"run.status",runId:t,status:l,...u})},sendUsage:l=>{e.send({type:"run.usage",runId:t,inputTokens:Math.round(l.inputTokens),outputTokens:Math.round(l.outputTokens),cacheReadTokens:l.cacheReadTokens===void 0?void 0:Math.round(l.cacheReadTokens),costUsd:l.costUsd,turns:l.turns})},nextSeq:()=>r}}async function Di(t){return t.rule.action.type==="implement"?fy(t):t.rule.action.type==="respond"?hy(t):dy(t)}async function dy(t){let{emit:e,setStatus:n,sendUsage:r,nextSeq:s}=ur(t.runId,t.transport),{trigger:i}=t.rule,o=t.rule.action;if(o.type!=="plan_only")return;let l=dn(o.agent,o.type);if(l){e("error",l),await es(t,l),n("failed",{error:l});return}let u=(0,zi.randomUUID)();try{n("running"),e("info",`Run started for ${t.issueKey} (rule "${t.rule.name}", plan-only)`),e("info",`Fetching ${t.issueKey} from Jira`);let c=await t.jira.getIssue(t.issueKey),f=qt(o.promptTemplate,{issueKey:c.key,summary:c.summary,description:c.description||"(no description)",comments:Ps(c.comments)})+await Mr(t.jira,c.attachments,t.repoPath,e)+Pa(t.repoPath)+we.NEEDS_INPUT_OPTIONS_PROMPT;e("info",`Starting Claude Code in ${t.repoPath} - read-only tools, path-jailed to the repo, timeout ${o.timeoutSeconds}s`);let p=await ts(t.runId,Be(o.agent),{repoPath:t.repoPath,prompt:f,timeoutSeconds:o.timeoutSeconds,bin:Ue(t.cfg,o.agent),configDir:t.claudeConfigDir,mode:"read_only",model:o.model||void 0,sessionId:u,onLog:(S,x)=>e(S,x),onUsage:r},e),b={costUsd:p.costUsd,inputTokens:p.inputTokens,outputTokens:p.outputTokens,billingMode:p.billingMode,model:p.model};if(!p.ok||!p.resultText.trim()){let S=p.error??"Claude Code produced no output";e("error",`Run failed: ${S}`),await es(t,S),n(p.timedOut?"timed_out":"failed",{error:S,...p.cancelled?{errorKind:"guard"}:{},...b});return}let w=js(p.resultText);if(w){await Li({kind:"plan",runId:t.runId,issueKey:t.issueKey,repoPath:t.repoPath,sessionId:u,doneLabel:i.doneLabel,failedLabel:i.failedLabel,timeoutSeconds:o.timeoutSeconds,jira:t.jira,nextLogSeq:s(),rounds:1,claudeConfigDir:t.claudeConfigDir,agent:o.agent,model:o.model},w,e,n,b);return}await Zc({runId:t.runId,issueKey:t.issueKey,doneLabel:i.doneLabel,jira:t.jira,resultText:p.resultText,costFields:b,emit:e,setStatus:n})}catch(c){let f=c instanceof Error?c.message:String(c);e("error",`Run failed: ${f}`),await es(t,f),n("failed",{error:f})}finally{Qt(t.repoPath)}}async function ja(t,e,n,r){let{emit:s,setStatus:i,sendUsage:o,nextSeq:l}=ur(t.runId,r.transport,t.nextLogSeq);try{i("running"),s("info",`Reply received on ${t.issueKey} - continuing run \`${t.runId}\``);let u=nd(e)+await Mr(r.jiraFor(t.repoName??""),n,t.repoPath,s),c=await ts(t.runId,Be(t.agent),{repoPath:t.repoPath,prompt:u,timeoutSeconds:t.timeoutSeconds,bin:Ue(r.cfg,t.agent??""),configDir:t.claudeConfigDir,mode:"read_only",model:t.model||void 0,sessionId:t.sessionId,resume:!0,onLog:(b,w)=>s(b,w),onUsage:o},s),f={costUsd:c.costUsd,inputTokens:c.inputTokens,outputTokens:c.outputTokens,billingMode:c.billingMode,model:c.model};if(!c.ok||!c.resultText.trim()){let b=c.error??"Claude Code produced no output";s("error",`Run failed: ${b}`),await Tt(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,b),St(t.runId),i(c.timedOut?"timed_out":"failed",{error:b,...c.cancelled?{errorKind:"guard"}:{},...f});return}let p=js(c.resultText);if(p){if(t.rounds>=Kc){await rd(r.jiraFor(t.repoName??""),t,s,i,f);return}await Li({kind:"plan",runId:t.runId,issueKey:t.issueKey,repoPath:t.repoPath,sessionId:t.sessionId,doneLabel:t.doneLabel,failedLabel:t.failedLabel,timeoutSeconds:t.timeoutSeconds,jira:r.jiraFor(t.repoName??""),nextLogSeq:l(),rounds:t.rounds+1,createdAt:t.createdAt,claudeConfigDir:t.claudeConfigDir,actorEmail:t.actorEmail,agent:t.agent,model:t.model},p,s,i,f);return}await Zc({runId:t.runId,issueKey:t.issueKey,doneLabel:t.doneLabel,jira:r.jiraFor(t.repoName??""),resultText:c.resultText,costFields:f,emit:s,setStatus:i}),St(t.runId)}catch(u){let c=u instanceof Error?u.message:String(u);s("error",`Run failed: ${c}`),await Tt(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,c),St(t.runId),i("failed",{error:c})}finally{Qt(t.repoPath)}}async function Zc(t){let{runId:e,issueKey:n,doneLabel:r,jira:s,resultText:i,costFields:o,emit:l,setStatus:u}=t;u("posting",o),l("info",`Posting plan to ${n} (${i.length} chars)`);let c=`
|
|
628
628
|
|
|
629
629
|
---
|
|
630
630
|
_Allwright plan-only run \`${e}\` \xB7 cost $${o.costUsd.toFixed(4)} \xB7 no code was written._`;await s.addComment(n,i+c),await s.editLabels(n,{add:[r],remove:[we.NEEDS_INPUT_LABEL]}),l("info",`Labeled ${n} with "${r}"`),u("succeeded",{...o,resultSummary:cr(i)}),l("info",`Run succeeded \xB7 $${o.costUsd.toFixed(4)}`)}async function hy(t){let{emit:e,setStatus:n,sendUsage:r}=ur(t.runId,t.transport),s=t.rule.action;if(s.type!=="respond")return;let i=dn(s.agent,s.type);if(i){e("error",i),await t.jira.addComment(t.issueKey,`**Allwright could not answer this question.**
|
|
@@ -635,11 +635,11 @@ Error: ${f.slice(0,800)}
|
|
|
635
635
|
|
|
636
636
|
Ask again in a new comment to retry. (run \`${t.runId}\`)`).catch(p=>y.error(`could not post answer failure to ${t.issueKey}: ${p}`)),n(u.timedOut?"timed_out":"failed",{error:f,...u.cancelled?{errorKind:"guard"}:{},...c});return}n("posting",c),e("info",`Posting answer to ${t.issueKey} (${u.resultText.length} chars)`),await t.jira.addComment(t.issueKey,u.resultText),n("succeeded",{...c,resultSummary:cr(u.resultText)}),e("info",`Run succeeded \xB7 $${u.costUsd.toFixed(4)}`)}catch(o){let l=o instanceof Error?o.message:String(o);e("error",`Run failed: ${l}`),n("failed",{error:l})}finally{Qt(t.repoPath)}}async function Gc(t,e,n,r){let s=`${e}-wip`;try{return Qt(t),await Qn(t,`WIP: turn limit exhausted (Allwright run ${n})`),await Ho(t,s),r("info",`Partial work preserved on branch "${s}"`),s}catch(i){return r("warn",`could not preserve partial work: ${i instanceof Error?i.message:i}`),null}}function Vc(t){return`
|
|
637
637
|
|
|
638
|
-
Partial work from this run is saved on branch \`${t}\` - it was NOT safety-checked or reviewed and never merges on its own; a future run or a developer can pick it up.`}async function fy(t){let{emit:e,setStatus:n,sendUsage:r,nextSeq:s}=ur(t.runId,t.transport),{trigger:i}=t.rule,o=t.rule.action;if(o.type!=="implement")return;let l=dn(o.agent,o.type);if(l){e("error",l),await es(t,l),n("failed",{error:l});return}let u=Mi.default.join(Lt(),t.runId),c=qt(o.branchTemplate,{issueKey:t.issueKey}),f=(0,zi.randomUUID)(),p=!1,b=!1;try{if(!Ti(ye()??t.cfg,t.project.repoName,t.actorEmail))throw new Error("no GitHub token applies to this repo - run `allwright github set-token` (runner-wide) or `github set <repoName>` (this repo only)");if(c===o.baseBranch&&!t.continueBranch)throw new Error(`rendered branch "${c}" equals the base branch - refusing (check the rule's branch template)`);if(n("running"),e("info",`Run started for ${t.issueKey} (rule "${t.rule.name}", implement)`),o.jiraTransitionOnStart)try{await t.jira.transitionByName(t.issueKey,o.jiraTransitionOnStart)?e("info",`Jira transition "${o.jiraTransitionOnStart}" applied at run start`):e("warn",`no transition named "${o.jiraTransitionOnStart}" is available from this ticket's current status - continuing anyway`)}catch(H){e("warn",`Jira start transition failed: ${H instanceof Error?H.message:H} - continuing anyway`)}let w=await tr(t.repoPath);if(e("info",`Repo origin: ${w}`),!at(w))throw new Error(`origin "${w}" is not a GitHub remote - implement mode supports GitHub only`);e("info",`Fetching ${t.issueKey} from Jira`);let S=await t.jira.getIssue(t.issueKey),x=t.continueBranch?c:o.baseBranch;e("info",t.continueBranch?`Continuing branch "${c}" from origin/${c} (autopilot batch)`:`Preparing worktree on branch "${c}" from origin/${o.baseBranch}`),await ln(t.repoPath,x),await Go(t.repoPath,c),await Vo(t.repoPath,u,c,x),p=!0;let
|
|
638
|
+
Partial work from this run is saved on branch \`${t}\` - it was NOT safety-checked or reviewed and never merges on its own; a future run or a developer can pick it up.`}async function fy(t){let{emit:e,setStatus:n,sendUsage:r,nextSeq:s}=ur(t.runId,t.transport),{trigger:i}=t.rule,o=t.rule.action;if(o.type!=="implement")return;let l=dn(o.agent,o.type);if(l){e("error",l),await es(t,l),n("failed",{error:l});return}let u=Mi.default.join(Lt(),t.runId),c=qt(o.branchTemplate,{issueKey:t.issueKey}),f=(0,zi.randomUUID)(),p=!1,b=!1;try{if(!Ti(ye()??t.cfg,t.project.repoName,t.actorEmail))throw new Error("no GitHub token applies to this repo - run `allwright github set-token` (runner-wide) or `github set <repoName>` (this repo only)");if(c===o.baseBranch&&!t.continueBranch)throw new Error(`rendered branch "${c}" equals the base branch - refusing (check the rule's branch template)`);if(n("running"),e("info",`Run started for ${t.issueKey} (rule "${t.rule.name}", implement)`),o.jiraTransitionOnStart)try{await t.jira.transitionByName(t.issueKey,o.jiraTransitionOnStart)?e("info",`Jira transition "${o.jiraTransitionOnStart}" applied at run start`):e("warn",`no transition named "${o.jiraTransitionOnStart}" is available from this ticket's current status - continuing anyway`)}catch(H){e("warn",`Jira start transition failed: ${H instanceof Error?H.message:H} - continuing anyway`)}let w=await tr(t.repoPath);if(e("info",`Repo origin: ${w}`),!at(w))throw new Error(`origin "${w}" is not a GitHub remote - implement mode supports GitHub only`);e("info",`Fetching ${t.issueKey} from Jira`);let S=await t.jira.getIssue(t.issueKey),x=t.continueBranch?c:o.baseBranch;e("info",t.continueBranch?`Continuing branch "${c}" from origin/${c} (autopilot batch)`:`Preparing worktree on branch "${c}" from origin/${o.baseBranch}`),await ln(t.repoPath,x),await Go(t.repoPath,c),await Vo(t.repoPath,u,c,x),p=!0;let A=qt(o.promptTemplate,{issueKey:S.key,summary:S.summary,description:S.description||"(no description)",comments:Ps(S.comments)})+await Mr(t.jira,S.attachments,u,e)+Pa(u)+ly(t.repoPath)+sy+we.NEEDS_INPUT_OPTIONS_PROMPT+iy+(t.project.goLiveIssueKey?oy:"")+(o.writeTests?Bc.WRITE_TESTS_PROMPT:"")+(o.updateMemory?we.MEMORY_UPDATE_PROMPT:"");e("info",`Starting Claude Code in the worktree - edit tools enabled, path-jailed, no shell, timeout ${o.timeoutSeconds}s`);let j=await ts(t.runId,Be(o.agent),{repoPath:u,prompt:A,timeoutSeconds:o.timeoutSeconds,bin:Ue(t.cfg,o.agent),configDir:t.claudeConfigDir,mode:"edit_no_shell",model:o.model||void 0,maxTurns:o.maxTurns,sessionId:f,onLog:(H,z)=>e(H,z),onUsage:r},e,()=>wi(u)),v={costUsd:j.costUsd,inputTokens:j.inputTokens,outputTokens:j.outputTokens,billingMode:j.billingMode,model:j.model};if(!j.ok){let H=j.error??"Claude Code failed";e("error",`Run failed: ${H}`);let z=H;if(j.turnLimitHit){let B=await Gc(u,c,t.runId,e);B&&(z+=Vc(B))}lt(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:"implement failed",detail:H.slice(0,500)}),await es(t,z),n(j.timedOut?"timed_out":"failed",{error:H,...j.cancelled?{errorKind:"guard"}:{},...v});return}let O=js(j.resultText);if(O){b=!0,await Li({kind:"implement",runId:t.runId,issueKey:t.issueKey,repoPath:u,sessionId:f,doneLabel:i.doneLabel,failedLabel:i.failedLabel,timeoutSeconds:o.timeoutSeconds,jira:t.jira,nextLogSeq:s(),rounds:1,claudeConfigDir:t.claudeConfigDir,agent:o.agent,model:o.model,actorEmail:t.actorEmail,baseRepoPath:t.repoPath,repoName:t.project.repoName,branch:c,baseBranch:o.baseBranch,jiraTransition:o.jiraTransition,jiraTransitionOnMerge:o.jiraTransitionOnMerge,requireApproval:o.requireApproval,mergeOnApprove:o.mergeOnApprove,mergeMethod:o.mergeMethod,autoMerge:o.autoMerge,runTests:o.runTests,maxTurns:o.maxTurns,issueSummary:S.summary},O,e,n,v);return}Qt(u),await Wc({runId:t.runId,issueKey:t.issueKey,issueSummary:S.summary,worktreePath:u,agentConfigDir:t.claudeConfigDir,baseRepoPath:t.repoPath,branch:c,baseBranch:o.baseBranch,jiraTransition:o.jiraTransition,jiraTransitionOnMerge:o.jiraTransitionOnMerge,requireApproval:o.requireApproval,doneLabel:i.doneLabel,failedLabel:i.failedLabel,repoName:t.project.repoName,jira:t.jira,cfg:t.cfg,actorEmail:t.actorEmail,resultText:j.resultText,costFields:v,runTests:o.runTests,fixSession:{sessionId:f,agent:o.agent,model:o.model,timeoutSeconds:o.timeoutSeconds,maxTurns:o.maxTurns},sendUsage:r,mergeOnApprove:o.mergeOnApprove,mergeMethod:o.mergeMethod,autoMerge:o.autoMerge,emit:e,setStatus:n})}catch(w){let S=w instanceof Error?w.message:String(w);e("error",`Run failed: ${S}`),lt(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:"implement failed",detail:S.slice(0,500)}),await es(t,S),n("failed",{error:S})}finally{p&&!b&&await vt(t.repoPath,u).catch(()=>{})}}async function Oa(t,e,n,r){let{emit:s,setStatus:i,sendUsage:o,nextSeq:l}=ur(t.runId,r.transport,t.nextLogSeq),u=t.repoPath,c=!1;try{if(!Ti(ye()??r.cfg,t.repoName??"",t.actorEmail))throw new Error("no GitHub token applies to this repo - run `allwright github set-token` (runner-wide) or `github set <repoName>` (this repo only)");i("running"),s("info",`Reply received on ${t.issueKey} - continuing run \`${t.runId}\``);let f=nd(e)+await Mr(r.jiraFor(t.repoName??""),n,u,s),p=await ts(t.runId,Be(t.agent),{repoPath:u,prompt:f,timeoutSeconds:t.timeoutSeconds,bin:Ue(r.cfg,t.agent??""),configDir:t.claudeConfigDir,mode:"edit_no_shell",model:t.model||void 0,maxTurns:t.maxTurns??120,sessionId:t.sessionId,resume:!0,onLog:(S,x)=>s(S,x),onUsage:o},s,()=>wi(u)),b={costUsd:p.costUsd,inputTokens:p.inputTokens,outputTokens:p.outputTokens,billingMode:p.billingMode,model:p.model};if(!p.ok){let S=p.error??"Claude Code failed";s("error",`Run failed: ${S}`);let x=S;if(p.turnLimitHit&&t.branch){let A=await Gc(u,t.branch,t.runId,s);A&&(x+=Vc(A))}await Tt(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,x),St(t.runId),i(p.timedOut?"timed_out":"failed",{error:S,...p.cancelled?{errorKind:"guard"}:{},...b});return}let w=js(p.resultText);if(w){if(t.rounds>=Kc){await rd(r.jiraFor(t.repoName??""),t,s,i,b);return}c=!0,await Li({kind:"implement",runId:t.runId,issueKey:t.issueKey,repoPath:u,sessionId:t.sessionId,doneLabel:t.doneLabel,failedLabel:t.failedLabel,timeoutSeconds:t.timeoutSeconds,jira:r.jiraFor(t.repoName??""),nextLogSeq:l(),rounds:t.rounds+1,createdAt:t.createdAt,claudeConfigDir:t.claudeConfigDir,actorEmail:t.actorEmail,agent:t.agent,model:t.model,baseRepoPath:t.baseRepoPath,repoName:t.repoName,branch:t.branch,baseBranch:t.baseBranch,jiraTransition:t.jiraTransition,jiraTransitionOnMerge:t.jiraTransitionOnMerge,requireApproval:t.requireApproval,mergeOnApprove:t.mergeOnApprove,mergeMethod:t.mergeMethod,autoMerge:t.autoMerge,runTests:t.runTests,maxTurns:t.maxTurns,issueSummary:t.issueSummary},w,s,i,b);return}Qt(u),await Wc({runId:t.runId,issueKey:t.issueKey,issueSummary:t.issueSummary,worktreePath:u,agentConfigDir:t.claudeConfigDir,baseRepoPath:t.baseRepoPath??u,branch:t.branch,baseBranch:t.baseBranch,jiraTransition:t.jiraTransition,requireApproval:t.requireApproval??!0,doneLabel:t.doneLabel,failedLabel:t.failedLabel,repoName:t.repoName,jira:r.jiraFor(t.repoName??""),cfg:r.cfg,actorEmail:t.actorEmail,resultText:p.resultText,costFields:b,runTests:t.runTests,fixSession:{sessionId:t.sessionId,agent:t.agent??"",model:t.model,timeoutSeconds:t.timeoutSeconds,maxTurns:t.maxTurns},sendUsage:o,mergeOnApprove:t.mergeOnApprove,mergeMethod:t.mergeMethod,autoMerge:t.autoMerge??!1,emit:s,setStatus:i}),St(t.runId)}catch(f){let p=f instanceof Error?f.message:String(f);s("error",`Run failed: ${p}`),await Tt(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,p),St(t.runId),i("failed",{error:p})}finally{c||await vt(t.baseRepoPath??u,u).catch(()=>{})}}async function Wc(t){let{runId:e,issueKey:n,issueSummary:r,worktreePath:s,baseRepoPath:i,branch:o,baseBranch:l,jiraTransition:u,jiraTransitionOnMerge:c,requireApproval:f,doneLabel:p,failedLabel:b,repoName:w,jira:S,cfg:x,actorEmail:A,runTests:j,mergeOnApprove:v,mergeMethod:O,autoMerge:H,resultText:z,costFields:B,emit:d,setStatus:m}=t,g=await Hr(s);g.deleted.length&&d("info",`Deleted ${g.deleted.length} file(s) listed in ${Dt}: `+g.deleted.slice(0,10).join(", ")+(g.deleted.length>10?", \u2026":""));for(let ve of g.refused)d("warn",`${Dt} entry refused: ${ve}`);d("info","Committing changes"),await Qn(s,`${n}: ${r}
|
|
639
639
|
|
|
640
|
-
Allwright run ${e}`);let C=await un(s,l);if(!C.ok){let ve=C.forbidden.length?`refusing to push: changes touch protected paths (${C.forbidden.slice(0,5).join(", ")}) - CI/workflow files can exfiltrate repo secrets and are never pushed by the agent. Apply those files' changes yourself, or re-run the ticket with them out of scope.`:`refusing to push: change is too large (${C.files} files, ${C.insertions+C.deletions} lines; limits ${on}/${an})`;d("error",ve),await Tt(S,n,e,b,ve),m("failed",{error:ve,errorKind:"guard",...B});return}d("info",`Diff: ${C.files} file(s), +${C.insertions}/-${C.deletions}`);let M={...B},V="",W="",ee,D
|
|
641
|
-
${ae.tail.slice(-1500)}`));let Cr="";if(Ie.length&&t.fixSession){let ae=await my({runId:e,issueKey:n,worktreePath:s,baseBranch:l,fixSession:t.fixSession,agentConfigDir:t.agentConfigDir,cfg:x,failed:Ie,emit:d,sendUsage:t.sendUsage,baseCost:M});if(M.costUsd+=ae.cost.costUsd,M.inputTokens+=ae.cost.inputTokens,M.outputTokens+=ae.cost.outputTokens,ae.outcome==="cancelled"){let Ge="stopped by a person during the automatic test-fix attempt - nothing was pushed";d("warn",Ge),$i({runId:e,issueKey:n,issueSummary:r,mergeOnApprove:v,mergeMethod:O,autoMerge:H,repoName:w,baseRepoPath:i,branch:o,baseBranch:l,headSha:await tt(s),requireApproval:f,doneLabel:p,failedLabel:b,jiraTransition:u,jiraTransitionOnMerge:c,actorEmail:
|
|
642
|
-
${Ge.tail.slice(-1500)}`));Cr=Ie.length?`One automatic same-session fix attempt ran; the results above are AFTER it. First pass: ${fo} failure(s). ${ae.note}`:`The first pass had ${fo} failure(s); one automatic same-session fix attempt resolved them. ${ae.note}`}else Cr=ae.note}ee=Ie.slice(0,20).map(ae=>({command:ae.command.slice(0,500),exitCode:ae.exitCode,tail:ae.tail.slice(-4e3)})),
|
|
640
|
+
Allwright run ${e}`);let C=await un(s,l);if(!C.ok){let ve=C.forbidden.length?`refusing to push: changes touch protected paths (${C.forbidden.slice(0,5).join(", ")}) - CI/workflow files can exfiltrate repo secrets and are never pushed by the agent. Apply those files' changes yourself, or re-run the ticket with them out of scope.`:`refusing to push: change is too large (${C.files} files, ${C.insertions+C.deletions} lines; limits ${on}/${an})`;d("error",ve),await Tt(S,n,e,b,ve),m("failed",{error:ve,errorKind:"guard",...B});return}d("info",`Diff: ${C.files} file(s), +${C.insertions}/-${C.deletions}`);let M={...B},V="",W="",ee,L,D;if(j){let ve=Wr(s);if(!ve)d("info","No TEST.md in this repo - skipping the test run (nothing documented to run)");else{let be=Jr($a.default.readFileSync(ve,"utf8"));if(!be.length)d("info",`${Mi.default.basename(ve)} lists no commands - nothing to run`);else{d("info",`Running ${be.length} documented test command(s) - no tokens, plain shell`);let ue=await sr(s,be,{perCommandTimeoutMs:15*6e4}),Ie=ue.filter(ae=>ae.exitCode!==0),fo=Ie.length;for(let ae of ue)d(ae.exitCode===0?"info":"warn",`${ae.exitCode===0?"PASS":"FAIL"} ${ae.command} (exit ${ae.exitCode})`+(ae.exitCode===0?"":`
|
|
641
|
+
${ae.tail.slice(-1500)}`));let Cr="";if(Ie.length&&t.fixSession){let ae=await my({runId:e,issueKey:n,worktreePath:s,baseBranch:l,fixSession:t.fixSession,agentConfigDir:t.agentConfigDir,cfg:x,failed:Ie,emit:d,sendUsage:t.sendUsage,baseCost:M});if(M.costUsd+=ae.cost.costUsd,M.inputTokens+=ae.cost.inputTokens,M.outputTokens+=ae.cost.outputTokens,ae.outcome==="cancelled"){let Ge="stopped by a person during the automatic test-fix attempt - nothing was pushed";d("warn",Ge),$i({runId:e,issueKey:n,issueSummary:r,mergeOnApprove:v,mergeMethod:O,autoMerge:H,repoName:w,baseRepoPath:i,branch:o,baseBranch:l,headSha:await tt(s),requireApproval:f,doneLabel:p,failedLabel:b,jiraTransition:u,jiraTransitionOnMerge:c,actorEmail:A,resultSummary:Fc(z),prSummary:Ea(z)??"",costUsd:M.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),await Tt(S,n,e,b,`${Ge}. The commit survived on the runner - "Retry push" on the run's dashboard page ships it without a new agent run.`),m("failed",{error:Ge,errorKind:"guard",retryAvailable:!0,...M});return}if(ae.outcome==="committed"){W=ae.resultText,d("info",`Re-running ${be.length} documented test command(s) after the fix`),ue=await sr(s,be,{perCommandTimeoutMs:15*6e4}),Ie=ue.filter(Ge=>Ge.exitCode!==0);for(let Ge of ue)d(Ge.exitCode===0?"info":"warn",`${Ge.exitCode===0?"PASS":"FAIL"} ${Ge.command} (exit ${Ge.exitCode})`+(Ge.exitCode===0?"":`
|
|
642
|
+
${Ge.tail.slice(-1500)}`));Cr=Ie.length?`One automatic same-session fix attempt ran; the results above are AFTER it. First pass: ${fo} failure(s). ${ae.note}`:`The first pass had ${fo} failure(s); one automatic same-session fix attempt resolved them. ${ae.note}`}else Cr=ae.note}ee=Ie.slice(0,20).map(ae=>({command:ae.command.slice(0,500),exitCode:ae.exitCode,tail:ae.tail.slice(-4e3)})),L=ue.length-Ie.length,D=ue.length,V=`
|
|
643
643
|
|
|
644
644
|
### Tests
|
|
645
645
|
`+ue.map(ae=>`- ${ae.exitCode===0?"PASS":"FAIL"} \`${ae.command}\``).join(`
|
|
@@ -651,11 +651,11 @@ All ${ue.length} passed.`)+(Cr?`
|
|
|
651
651
|
|
|
652
652
|
${Cr}`:""),Ie.length&&d("warn",`${Ie.length} test command(s) failed - the PR will say so; review before merging`),fo>0&<(i,{issueKey:n,runId:e,title:Ie.length?`TEST.md commands failing at PR (${Ie.length} of ${ue.length})`:"TEST.md failures fixed by same-session retry",detail:ue.map(ae=>`${ae.exitCode===0?"PASS":"FAIL"} ${ae.command}`).join(`
|
|
653
653
|
`)+(Cr?`
|
|
654
|
-
${Cr}`:"")})}}}let ne=await tr(s),de=at(ne);if(!de){let ve=`origin "${ne}" is not a GitHub remote - implement mode supports GitHub only`;d("error",ve),await Tt(S,n,e,b,ve),m("failed",{error:ve,...B});return}let he=await tt(s),Ne=Fc(z),pe=(W?
|
|
654
|
+
${Cr}`:"")})}}}let ne=await tr(s),de=at(ne);if(!de){let ve=`origin "${ne}" is not a GitHub remote - implement mode supports GitHub only`;d("error",ve),await Tt(S,n,e,b,ve),m("failed",{error:ve,...B});return}let he=await tt(s),Ne=Fc(z),pe=(W?Ea(W):null)??Ea(z);try{await Jc({gitDir:s,ownerRepo:de,runId:e,issueKey:n,issueSummary:r,agentConfigDir:t.agentConfigDir,branch:o,baseBranch:l,jiraTransition:u,jiraTransitionOnMerge:c,requireApproval:f,doneLabel:p,failedLabel:b,repoName:w,jira:S,cfg:x,actorEmail:A,mergeOnApprove:v,mergeMethod:O,autoMerge:H,summary:Ne,prSummary:pe??void 0,cost:M,testReport:V,failedTests:ee,testsPassed:L,testsTotal:D,goLiveDraft:(W?Lc(W):null)??Lc(z)??void 0,emit:d,setStatus:m})}catch(ve){let be=ve instanceof Error?ve.message:String(ve);$i({runId:e,issueKey:n,issueSummary:r,mergeOnApprove:v,mergeMethod:O,autoMerge:H,repoName:w,baseRepoPath:i,branch:o,baseBranch:l,headSha:he,requireApproval:f,doneLabel:p,failedLabel:b,jiraTransition:u,jiraTransitionOnMerge:c,actorEmail:A,resultSummary:Ne,prSummary:pe??"",costUsd:M.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),d("error",`Run failed: ${be}`),d("info",`The commit itself survived on the runner (branch ${o}) - fix the cause, then use "Retry push" on this run's dashboard page.`),await Tt(S,n,e,b,`${be}
|
|
655
655
|
|
|
656
656
|
The agent's commit survived on the runner - "Retry push" on the dashboard's run page re-pushes it without a new agent run.`),m("failed",{error:be,retryAvailable:!0,...M})}}var py={costUsd:0,inputTokens:0,outputTokens:0};async function my(t){let{runId:e,issueKey:n,worktreePath:r,baseBranch:s,fixSession:i,cfg:o,failed:l,emit:u,sendUsage:c,baseCost:f}=t,p=Be(i.agent);if(!p?.capabilities.sessionResume){let j=`No automatic fix attempt: the ${i.agent||"configured"} adapter cannot resume sessions.`;return u("info",j),{outcome:"skipped",note:j,cost:py}}u("info",`${l.length} test command(s) failed - resuming the same agent session for one fix attempt (same session = cached context, not a re-explore)`);let b=await tt(r),w=await ts(e,p,{repoPath:r,prompt:ay(l),timeoutSeconds:i.timeoutSeconds,bin:Ue(o,i.agent),configDir:t.agentConfigDir,mode:"edit_no_shell",model:i.model||void 0,maxTurns:Math.min(i.maxTurns??120,60),sessionId:i.sessionId,resume:!0,onLog:(j,v)=>u(j,v),onUsage:c?j=>c({...j,inputTokens:f.inputTokens+j.inputTokens,outputTokens:f.outputTokens+j.outputTokens,costUsd:j.costUsd===void 0?void 0:f.costUsd+j.costUsd}):void 0},u),S={costUsd:w.costUsd,inputTokens:w.inputTokens,outputTokens:w.outputTokens};if(w.cancelled)return{outcome:"cancelled",cost:S};if(!w.ok){let j=`One automatic fix attempt did not complete (${w.error??"agent error"}) - the results above are from the original work.`;return u("warn",j),{outcome:"agent_failed",note:j,cost:S}}if(js(w.resultText)){let j="One automatic fix attempt asked for human input instead of fixing - the original commit ships unchanged; answer on the PR instead.";return u("warn",j),{outcome:"agent_failed",note:j,cost:S}}let x=await Hr(r);for(let j of x.refused)u("warn",`${Dt} entry refused: ${j}`);try{await Qn(r,`${n}: fix failing TEST.md commands
|
|
657
657
|
|
|
658
|
-
Allwright run ${e} (automatic test-fix attempt)`)}catch{let j=`An automatic fix attempt concluded no code change was warranted: ${cr(w.resultText)}`;return u("info",j),{outcome:"no_changes",note:j,cost:S}}let
|
|
658
|
+
Allwright run ${e} (automatic test-fix attempt)`)}catch{let j=`An automatic fix attempt concluded no code change was warranted: ${cr(w.resultText)}`;return u("info",j),{outcome:"no_changes",note:j,cost:S}}let A=await un(r,s);if(!A.ok){await Zr(r,b);let j=A.forbidden.length?`An automatic fix attempt touched protected paths (${A.forbidden.slice(0,3).join(", ")}) and was discarded - the results above are from the original work.`:"An automatic fix attempt pushed the diff past the safety limits and was discarded - the results above are from the original work.";return u("warn",j),{outcome:"reverted",note:j,cost:S}}return{outcome:"committed",note:`Fix attempt: ${cr(w.resultText)}`,resultText:w.resultText,cost:S}}async function Jc(t){let{gitDir:e,ownerRepo:n,runId:r,issueKey:s,issueSummary:i,mergeOnApprove:o,mergeMethod:l,autoMerge:u,branch:c,baseBranch:f,jiraTransition:p,jiraTransitionOnMerge:b,requireApproval:w,doneLabel:S,failedLabel:x,repoName:A,jira:j,cfg:v,actorEmail:O,summary:H,prSummary:z,cost:B,testReport:d,emit:m,setStatus:g}=t;m("info",`Pushing ${c} to origin`),await er(e,c);let C=await _i(e,c),V=`${z?.trim()?`${z.trim()}
|
|
659
659
|
|
|
660
660
|
<details>
|
|
661
661
|
<summary>Technical details</summary>
|
|
@@ -666,13 +666,13 @@ ${H}
|
|
|
666
666
|
|
|
667
667
|
---
|
|
668
668
|
Jira: ${new URL(`/browse/${s}`,v.jira?.baseUrl??"").toString()}
|
|
669
|
-
_Allwright implement run \`${r}\` \xB7 cost $${B.costUsd.toFixed(4)}. `+(d?"Tests were run by the runner, not the agent._":"The agent has no shell and no tests were run here - review accordingly._");m("info","Opening pull request");let W=Ti(ye()??v,
|
|
669
|
+
_Allwright implement run \`${r}\` \xB7 cost $${B.costUsd.toFixed(4)}. `+(d?"Tests were run by the runner, not the agent._":"The agent has no shell and no tests were run here - review accordingly._");m("info","Opening pull request");let W=Ti(ye()??v,A,O);W.source==="user"&&m("info",`PR will be authored with ${O}'s own GitHub token`);let L=await new $e(W.token).createPullRequest(n.owner,n.repo,{title:`${s}: ${i}`.slice(0,250),head:c,base:f,body:V});m("info",`PR ready: ${L.url}`),Oc({runId:r,issueKey:s,repoName:A,owner:n.owner,repo:n.repo,prNumber:L.number,prUrl:L.url,jiraTransitionOnMerge:b??"",createdAt:new Date().toISOString()}),g("posting",B);let D={nextDecisionSeq:1e5,runId:r,issueKey:s,repoName:A,owner:n.owner,repo:n.repo,prNumber:L.number,prUrl:L.url,branch:c,headSha:C,doneLabel:S,failedLabel:x,jiraTransition:p,mergeOnApprove:o,mergeMethod:l,autoMerge:u,agentConfigDir:t.agentConfigDir};if(w)ct(D),await j.addComment(s,`**Allwright opened a pull request for review.**
|
|
670
670
|
|
|
671
|
-
PR: ${
|
|
671
|
+
PR: ${L.url}
|
|
672
672
|
|
|
673
|
-
Approve the PR on GitHub OR on the Allwright dashboard - either completes the run. Rejecting on the dashboard closes the PR and deletes the branch. (run \`${r}\`)`),g("awaiting_approval",{...B,prUrl:
|
|
673
|
+
Approve the PR on GitHub OR on the Allwright dashboard - either completes the run. Rejecting on the dashboard closes the PR and deletes the branch. (run \`${r}\`)`),g("awaiting_approval",{...B,prUrl:L.url,headSha:C,resultSummary:cr(z?.trim()||H),retryAvailable:!1,...t.failedTests!==void 0?{failedTests:t.failedTests}:{},...t.testsPassed!==void 0?{testsPassed:t.testsPassed}:{},...t.testsTotal!==void 0?{testsTotal:t.testsTotal}:{},...t.goLiveDraft!==void 0?{goLiveDraft:t.goLiveDraft}:{}}),m("info",`Awaiting approval on the dashboard \xB7 $${B.costUsd.toFixed(4)}`);else{if(u){m("info",`Auto-merging PR #${L.number} (${l})`);let de=Ae(v,A),he=de?await new $e(de).mergePullRequest(n.owner,n.repo,L.number,l,{sha:C,title:`${s} (#${L.number})`}):{merged:!1,reason:"no GitHub token applies to this repo"};he.merged?m("info",`PR #${L.number} merged`):(m("warn",`Auto-merge did not go through - ${he.reason}. The PR stays open.`),await j.addComment(s,`**Allwright:** the work is done and the PR is open, but auto-merge did not go through - ${he.reason}
|
|
674
674
|
|
|
675
|
-
PR: ${
|
|
675
|
+
PR: ${L.url}`))}let ne=(ye()??v).repos[A]?.path;ne&&Is(ne,s)&<(ne,{issueKey:s,runId:r,title:"shipped after earlier failure",detail:`PR ${L.url} merged/opened straight-through.`}),await Yc({jira:j,issueKey:s},D,m),g("succeeded",{...B,prUrl:L.url,headSha:C,resultSummary:cr(z?.trim()||H),retryAvailable:!1,...t.failedTests!==void 0?{failedTests:t.failedTests}:{},...t.testsPassed!==void 0?{testsPassed:t.testsPassed}:{},...t.testsTotal!==void 0?{testsTotal:t.testsTotal}:{},...t.goLiveDraft!==void 0?{goLiveDraft:t.goLiveDraft}:{}}),m("info",`Run succeeded \xB7 ${L.url} \xB7 $${B.costUsd.toFixed(4)}`)}}async function Yc(t,e,n){let r=null;if(e.jiraTransition)try{await t.jira.transitionByName(e.issueKey,e.jiraTransition)?n("info",`Jira transition "${e.jiraTransition}" applied`):(r=`no transition named "${e.jiraTransition}" is available from this ticket's current status - the PR is fine, but move the ticket manually`,n("warn",r))}catch(i){r=`Jira transition failed: ${i instanceof Error?i.message:i}`,n("warn",r)}let s=e.mergeOnApprove;return await t.jira.addComment(e.issueKey,(s?`**Allwright: implementation complete - the pull request was merged.**
|
|
676
676
|
|
|
677
677
|
PR: ${e.prUrl}`:`**Allwright: the change is approved, but NOT merged yet.**
|
|
678
678
|
|
|
@@ -682,9 +682,9 @@ This rule is set to "my team merges on GitHub", so Allwright deliberately did no
|
|
|
682
682
|
|
|
683
683
|
Note: ${r}`:"")+`
|
|
684
684
|
|
|
685
|
-
(run \`${e.runId}\`)`),await t.jira.editLabels(e.issueKey,{add:[e.doneLabel],remove:[we.NEEDS_INPUT_LABEL]}),r}async function $s(t,e,n){let r=Qr(e);if(!r){y.warn(`run.approved for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:s,setStatus:i}=ed(t,e);try{let o=
|
|
685
|
+
(run \`${e.runId}\`)`),await t.jira.editLabels(e.issueKey,{add:[e.doneLabel],remove:[we.NEEDS_INPUT_LABEL]}),r}async function $s(t,e,n){let r=Qr(e);if(!r){y.warn(`run.approved for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:s,setStatus:i}=ed(t,e);try{let o=Ae(ye()??t.cfg,r.repoName);if(!o)throw new Error("GitHub token missing on this runner");let l=new $e(o);s("info",`Approval received for ${r.issueKey} - verifying PR state`);let u=await l.getPullRequest(r.owner,r.repo,r.prNumber);if(!u)throw new Error(`PR #${r.prNumber} no longer exists on GitHub`);if(u.state==="closed"&&!u.merged)throw new Error(`PR #${r.prNumber} was closed on GitHub without merging`);let c=n??r.headSha;if(u.state==="open"&&u.headSha!==c){let f=`PR #${r.prNumber} changed since review started (${c.slice(0,7)} \u2192 ${u.headSha.slice(0,7)}) - approval not applied. Re-review the PR and approve again.`;s("warn",f),await t.jiraFor(r.repoName??"").addComment(r.issueKey,`**Allwright:** ${f}`),i("awaiting_approval",{prUrl:r.prUrl,headSha:u.headSha,resultSummary:f});return}if(r.mergeOnApprove&&u.state==="open"&&!u.merged){s("info",`Merging PR #${r.prNumber} (${r.mergeMethod})`);let f=await l.mergePullRequest(r.owner,r.repo,r.prNumber,r.mergeMethod,{sha:c,title:`${r.issueKey} (#${r.prNumber})`});if(!f.merged){let p=`Approved, but the merge did not go through - ${f.reason}`;s("warn",p),await t.jiraFor(r.repoName??"").addComment(r.issueKey,`**Allwright:** ${p}
|
|
686
686
|
|
|
687
|
-
PR: ${r.prUrl}`),i("awaiting_approval",{prUrl:r.prUrl,headSha:u.headSha,resultSummary:p});return}s("info",`PR #${r.prNumber} merged`)}{let f=(ye()??t.cfg).repos[r.repoName??""]?.path;f&&Is(f,r.issueKey)&<(f,{issueKey:r.issueKey,runId:e,title:"shipped after earlier failure",detail:`PR ${r.prUrl} approved and completed.`})}await Yc({jira:t.jiraFor(r.repoName??""),issueKey:r.issueKey},r,s),i("succeeded",{prUrl:r.prUrl,...r.mergeOnApprove?{}:{resultSummary:"Approved, but the PR was NOT merged - this rule leaves merging to your team on GitHub. Nothing ships until someone merges it."}}),s("info",r.mergeOnApprove?"Run completed after approval":'Run completed after approval - the PR is still OPEN because this rule does not merge on approval. Merge it on GitHub, or turn on "Merge the PR when I approve" in the rule.'),ar(e)}catch(o){let l=o instanceof Error?o.message:String(o);s("error",`Approval handling failed: ${l}`),await td(t,r,l),i("failed",{error:l}),ar(e)}}async function Xc(t,e){let n=Qr(e);if(!n){y.warn(`run.rejected for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:r,setStatus:s}=ed(t,e);try{let i=
|
|
687
|
+
PR: ${r.prUrl}`),i("awaiting_approval",{prUrl:r.prUrl,headSha:u.headSha,resultSummary:p});return}s("info",`PR #${r.prNumber} merged`)}{let f=(ye()??t.cfg).repos[r.repoName??""]?.path;f&&Is(f,r.issueKey)&<(f,{issueKey:r.issueKey,runId:e,title:"shipped after earlier failure",detail:`PR ${r.prUrl} approved and completed.`})}await Yc({jira:t.jiraFor(r.repoName??""),issueKey:r.issueKey},r,s),i("succeeded",{prUrl:r.prUrl,...r.mergeOnApprove?{}:{resultSummary:"Approved, but the PR was NOT merged - this rule leaves merging to your team on GitHub. Nothing ships until someone merges it."}}),s("info",r.mergeOnApprove?"Run completed after approval":'Run completed after approval - the PR is still OPEN because this rule does not merge on approval. Merge it on GitHub, or turn on "Merge the PR when I approve" in the rule.'),ar(e)}catch(o){let l=o instanceof Error?o.message:String(o);s("error",`Approval handling failed: ${l}`),await td(t,r,l),i("failed",{error:l}),ar(e)}}async function Xc(t,e){let n=Qr(e);if(!n){y.warn(`run.rejected for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:r,setStatus:s}=ed(t,e);try{let i=Ae(ye()??t.cfg,n.repoName);if(!i)throw new Error("GitHub token missing on this runner");let o=new $e(i);r("info",`Rejection received for ${n.issueKey} - closing PR #${n.prNumber}`);let l=await o.getPullRequest(n.owner,n.repo,n.prNumber);l&&l.state==="open"&&await o.closePullRequest(n.owner,n.repo,n.prNumber),l?.merged||await o.deleteBranch(n.owner,n.repo,n.branch),await t.jiraFor(n.repoName??"").addComment(n.issueKey,`**Allwright: changes rejected.**
|
|
688
688
|
|
|
689
689
|
The pull request was closed and the branch deleted. This ticket is labeled \`${n.failedLabel}\`; remove the label to try again. (run \`${n.runId}\`)`),await t.jiraFor(n.repoName??"").editLabels(n.issueKey,{add:[n.failedLabel]}),s("failed",{error:"rejected by user"}),r("info","PR closed, branch deleted, ticket labeled"),ar(e)}catch(i){let o=i instanceof Error?i.message:String(i);r("error",`Rejection handling failed: ${o}`),await td(t,n,o),s("failed",{error:o}),ar(e)}}async function Qc(t,e){let n=Pi(e);if(!n){y.warn(`run.retryPush for ${e}: no retry record (already pushed, or invalidated?)`);let{emit:l,setStatus:u,sendUsage:c}=ur(e,t.transport,1e5);l("error","Retry push requested, but this runner holds no retry record for the run - it was already used or never saved. Re-run the ticket instead."),u("failed",{retryAvailable:!1});return}let{emit:r,setStatus:s,sendUsage:i,nextSeq:o}=ur(e,t.transport,n.nextLogSeq);try{let l=await _i(n.baseRepoPath,n.branch);if(l!==n.headSha){r("error",`Retry push aborted: branch ${n.branch} no longer holds the commit this run produced (expected ${n.headSha.slice(0,7)}, ${l?`found ${l.slice(0,7)}`:"the branch is gone"}) - a newer run has likely reused the branch. Re-run the ticket instead.`),Ia(e),s("failed",{retryAvailable:!1});return}let u=await tr(n.baseRepoPath),c=at(u);if(!c)throw new Error(`origin "${u}" is not a GitHub remote`);r("info",`Retry push for ${n.issueKey}: branch ${n.branch} at ${n.headSha.slice(0,7)}`);let f=t.jiraFor(n.repoName);await Jc({gitDir:n.baseRepoPath,ownerRepo:c,runId:n.runId,issueKey:n.issueKey,issueSummary:n.issueSummary,branch:n.branch,baseBranch:n.baseBranch,jiraTransition:n.jiraTransition,jiraTransitionOnMerge:n.jiraTransitionOnMerge,requireApproval:n.requireApproval,mergeOnApprove:n.mergeOnApprove??!1,mergeMethod:n.mergeMethod??"squash",autoMerge:n.autoMerge??!1,doneLabel:n.doneLabel,failedLabel:n.failedLabel,repoName:n.repoName,jira:f,cfg:ye()??t.cfg,actorEmail:n.actorEmail,summary:n.resultSummary,prSummary:n.prSummary||void 0,cost:{costUsd:n.costUsd},emit:r,setStatus:s}),Ia(e),await f.editLabels(n.issueKey,{remove:[n.failedLabel]}).catch(()=>{})}catch(l){let u=l instanceof Error?l.message:String(l);r("error",`Retry push failed: ${u}`),$i({...n,nextLogSeq:o()}),s("failed",{error:u,retryAvailable:!0})}}function ed(t,e){let n=1e5;return{emit:(i,o)=>{t.transport.send({type:"run.log",runId:e,seq:n++,ts:new Date().toISOString(),level:i,message:o}),i!=="agent"&&y.info(`[run ${e}] ${o}`)},setStatus:(i,o={})=>{t.transport.send({type:"run.status",runId:e,status:i,...o})}}}async function td(t,e,n){try{await t.jiraFor(e.repoName??"").addComment(e.issueKey,`**Allwright could not complete the approval decision.**
|
|
690
690
|
|
|
@@ -708,7 +708,7 @@ Reply with your answers in a comment on this ticket - or answer on the run page
|
|
|
708
708
|
|
|
709
709
|
Error: ${s.slice(0,800)}
|
|
710
710
|
|
|
711
|
-
This ticket has been labeled \`${r}\` and will not be retried automatically. To retry, fix the cause and remove the \`${r}\` label. (run \`${n}\`)`),await t.editLabels(e,{add:[r],remove:[we.NEEDS_INPUT_LABEL]})}catch(i){y.error(`could not post failure comment to ${e}: ${i}`)}}function Fc(t){let e=t.split(/\n##\s*(?:PR summary|Go-live draft)\s*\n/i)[0],n=/##\s*Summary of changes\s*\n([\s\S]*)$/i.exec(e);return(n?n[1]:e).trim().slice(0,8e3)||"(no summary provided)"}function
|
|
711
|
+
This ticket has been labeled \`${r}\` and will not be retried automatically. To retry, fix the cause and remove the \`${r}\` label. (run \`${n}\`)`),await t.editLabels(e,{add:[r],remove:[we.NEEDS_INPUT_LABEL]})}catch(i){y.error(`could not post failure comment to ${e}: ${i}`)}}function Fc(t){let e=t.split(/\n##\s*(?:PR summary|Go-live draft)\s*\n/i)[0],n=/##\s*Summary of changes\s*\n([\s\S]*)$/i.exec(e);return(n?n[1]:e).trim().slice(0,8e3)||"(no summary provided)"}function Ea(t){let e=/##\s*PR summary\s*\n([\s\S]*?)(?=\n##\s|$)/i.exec(t),n=e?e[1].trim():"";return n?n.slice(0,2e3):null}function cr(t){for(let e of t.split(`
|
|
712
712
|
`)){let n=e.replace(/^#+\s*/,"").trim();if(n.length>10)return n.slice(0,200)}return t.slice(0,200)}var hr=I(require("node:fs"),1);var Na=I(require("node:fs"),1),sd=I(require("node:os"),1),Ui=I(require("node:path"),1);function yy(){try{return sd.default.userInfo().username}catch{return"the user the runner service runs as"}}function by(t,e){let n=Ui.default.join(t,"apps","api","prisma","manual"),r=Ui.default.join(t,"prisma","manual");for(let s of[n,r]){let i;try{i=Na.default.readdirSync(s).filter(o=>o.endsWith(".sql")).sort()}catch{continue}for(let o of i.reverse())try{let l=Na.default.readFileSync(Ui.default.join(s,o),"utf8");if(new RegExp(`"${e}"`,"i").test(l))return o}catch{}}return null}function id(t,e){let n=t.slice(-4e3),r=yy(),s=e?.cwd?` -C ${e.cwd}`:"",i=/column "([^"]+)" of relation "([^"]+)" does not exist/i.exec(n)??/column ([\w.]+) does not exist/i.exec(n)??/The column `?([\w.]+)`? does not exist in the current database/i.exec(n)??/relation "([^"]+)" does not exist/i.exec(n);if(i){let l=(i[1]??"").split(".").pop()??"",u=e?.cwd?by(e.cwd,l):null;return{cause:`The code expects "${l}" in the database and the database does not have it. This is not a deploy-steps problem: a schema change shipped with the code, and the SQL that applies it is a HUMAN step by design`+(u?` - it is \`prisma/manual/${u}\`, checked in and not yet applied.`:"."),commands:u?[`cd apps/api && npx prisma db execute --file prisma/manual/${u} # dev/test database`,`cd apps/api && npx prisma db execute --url "$PROD_DATABASE_URL" --file prisma/manual/${u} # the live one`]:[`ls apps/api/prisma/manual/ # find the migration that adds "${l}"`,"cd apps/api && npx prisma db execute --file prisma/manual/<that file>"],note:"Apply it to EVERY database the code talks to - the test database and the live one are usually different, and applying only one turns a red build into a green build that breaks at runtime. Then re-run the deploy."}}if(/could not read (Username|Password) for/i.test(n)||/Authentication failed for .*https/i.test(n)||/fatal: Authentication failed/i.test(n))return{cause:`git needs a GitHub credential for the account this deploy runs as (${r}) and has none. It tried to ask, found no terminal, and gave up. Allwright's own GitHub token is NOT used here: deploy steps are plain shell, so they see only this machine's git config - which is why the same repo can push fine from Allwright and still fail this step.`,commands:[`sudo -u ${r} git${s} ls-remote origin >/dev/null && echo "AUTH OK" || echo "AUTH FAIL"`,`sudo -u ${r} gh auth setup-git # if you signed in with the gh CLI - its login does not reach git by itself`,`sudo -u ${r} git config --global credential.helper store # then one manual 'git fetch' to save the token`],note:`Or switch the checkout to SSH and give ${r} a deploy key: git${s} remote set-url origin git@github.com:OWNER/REPO.git. Never paste a token into a deploy step - it ends up in run logs and screenshots.`};if(/Permission denied \(publickey/i.test(n))return{cause:`SSH could not authenticate to the git host as ${r}. The key either does not exist for that account, or is not the one registered with the repository.`,commands:[`sudo -u ${r} ssh -T git@github.com # expect "successfully authenticated"`,`sudo -u ${r} ls -l ~/.ssh/`],note:"Add that account's public key as a deploy key on the repository (read-only is enough to fetch)."};if(/Host key verification failed/i.test(n))return{cause:`The git host is not in ${r}'s known_hosts, and ssh will not accept it unattended.`,commands:[`sudo -u ${r} ssh-keyscan github.com >> ~/.ssh/known_hosts`],note:"Run it as that user - a known_hosts entry under your own account does nothing for the service."};let o=/(?:^|\n)(?:bash: )?([\w.-]+): command not found/i.exec(n);return o?{cause:`"${o[1]}" is not on the PATH of the account this deploy runs as (${r}). A tool installed through nvm, asdf or a shell profile usually is not: the service starts with a bare environment, not your login shell.`,commands:[`sudo -u ${r} which ${o[1]} || echo "not on this account's PATH"`,`command -v ${o[1]} # where YOUR shell finds it`],note:"Either install it system-wide, or use the absolute path in the step - the path your own shell resolves is not the one the deploy gets."}:/EACCES|Permission denied(?!\s*\(publickey)/i.test(n)?{cause:`A path in this step is not writable by the account the deploy runs as (${r}).`,commands:[`sudo -u ${r} test -w ${e?.cwd??"<the path>"} && echo writable || echo "NOT writable"`],note:"Fix the ownership of that path rather than running the deploy as root - a root-owned build directory breaks the next deploy the other way."}:null}function od(t){return t?`
|
|
713
713
|
|
|
714
714
|
What this means: ${t.cause}
|
|
@@ -760,9 +760,9 @@ ${B.slice(0,800)}
|
|
|
760
760
|
`)+`
|
|
761
761
|
|
|
762
762
|
`:"")+`Nothing after it ran. Full log is on the Allwright dashboard. (run \`${t.runId}\`)`),lt(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.name} failed`,detail:`step ${v+1} "${O.name}" exit ${z.code}`+(z.tail?`
|
|
763
|
-
${i(z.tail).slice(0,500)}`:"")}),l.length&&ld(e,l),n("failed",{error:m.slice(0,1600),deployedRef:f,...l.length?{manualSteps:l}:{}});return}e("info",`\u2713 step ${v+1}/${r.steps.length}: ${O.name}`)}n("posting");let x=Math.round((Date.now()-o)/1e3),
|
|
763
|
+
${i(z.tail).slice(0,500)}`:"")}),l.length&&ld(e,l),n("failed",{error:m.slice(0,1600),deployedRef:f,...l.length?{manualSteps:l}:{}});return}e("info",`\u2713 step ${v+1}/${r.steps.length}: ${O.name}`)}n("posting");let x=Math.round((Date.now()-o)/1e3),A=null;r.publicUrl?.trim()&&(A=await Ey(r.publicUrl.trim()),e(A?"warn":"info",A??`${r.publicUrl.trim()} points at this machine - the deploy is live there`)),t.issueKey!==pr.BRANCH_DEPLOY_ISSUE_KEY&&await dt(t,`**Allwright deployed \`${t.issueKey}\` to \`${r.name}\`.**
|
|
764
764
|
|
|
765
|
-
`+(
|
|
765
|
+
`+(A?`> **Live where?** ${A}
|
|
766
766
|
|
|
767
767
|
`:"")+(l.length?`**${l.length} step(s) still need a person - Allwright did not run these:**
|
|
768
768
|
`+l.map(v=>`- \`${v.command}\`${v.why?` - ${v.why}`:""}`).join(`
|
|
@@ -771,14 +771,14 @@ ${i(z.tail).slice(0,500)}`:"")}),l.length&&ld(e,l),n("failed",{error:m.slice(0,1
|
|
|
771
771
|
`:"")+(f?`Commit: \`${f.slice(0,10)}\`${r.branch?` on \`${r.branch}\``:""}
|
|
772
772
|
`:"")+`${r.steps.length} step(s) in ${x}s.`+(t.requestedBy?` Requested by ${t.requestedBy}.`:"")+`
|
|
773
773
|
|
|
774
|
-
(run \`${t.runId}\`)`);let j=await Sy(t,e,f);t.project.goLiveIssueKey&&e("info",`Go-live checklist: this project keeps one on ${t.project.goLiveIssueKey} - review it before shipping to production`),Is(t.repoPath,t.issueKey)&<(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.name} succeeded after earlier failure`,detail:f?`commit ${f.slice(0,10)}`:void 0}),l.length&&ld(e,l),n("succeeded",{resultSummary:`Deployed to ${r.name}${f?` at ${f.slice(0,10)}`:""} in ${x}s`+(j!==null?` \xB7 ${j} ticket(s) moved to "${r.deployToColumn}"`:"")+(l.length?` \xB7 ${l.length} manual step(s) left for you`:"")+(
|
|
774
|
+
(run \`${t.runId}\`)`);let j=await Sy(t,e,f);t.project.goLiveIssueKey&&e("info",`Go-live checklist: this project keeps one on ${t.project.goLiveIssueKey} - review it before shipping to production`),Is(t.repoPath,t.issueKey)&<(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.name} succeeded after earlier failure`,detail:f?`commit ${f.slice(0,10)}`:void 0}),l.length&&ld(e,l),n("succeeded",{resultSummary:`Deployed to ${r.name}${f?` at ${f.slice(0,10)}`:""} in ${x}s`+(j!==null?` \xB7 ${j} ticket(s) moved to "${r.deployToColumn}"`:"")+(l.length?` \xB7 ${l.length} manual step(s) left for you`:"")+(A?` \xB7 NOT reachable at ${r.publicUrl} yet`:""),deployedRef:f,...l.length?{manualSteps:l}:{}}),e("info",`Deploy to "${r.name}" succeeded in ${x}s`)}async function Sy(t,e,n){let r=t.environment;if(!r.deployFromColumn||!r.deployToColumn)return null;let s=new Date().toISOString().slice(0,10),i;try{i=await t.jira.search(`project = "${t.project.jiraProjectKey}" AND status = "${r.deployFromColumn}" ORDER BY updated ASC`,50)}catch(l){return e("warn",`deploy succeeded, but listing tickets in "${r.deployFromColumn}" failed: ${l instanceof Error?l.message:l} - move them by hand`),null}if(!i.length)return e("info",`No tickets in "${r.deployFromColumn}" to move`),0;e("info",`Moving ${i.length} ticket(s) from "${r.deployFromColumn}" to "${r.deployToColumn}"`);let o=0;for(let l of i)try{if(await t.jira.addComment(l.key,`**Allwright: deployed to \`${r.name}\` on ${s}.**
|
|
775
775
|
|
|
776
776
|
`+(n?`Commit: \`${n.slice(0,10)}\`${r.branch?` on \`${r.branch}\``:""}
|
|
777
777
|
`:"")+(t.requestedBy?`Requested by ${t.requestedBy}. `:"")+`(run \`${t.runId}\`)`),!await t.jira.transitionByName(l.key,r.deployToColumn)){e("warn",`${l.key}: no workflow transition to "${r.deployToColumn}" from its current status - left in place`),await t.jira.addComment(l.key,`**Allwright could not move this ticket to \`${r.deployToColumn}\`** - no such transition from its current status. The deploy itself succeeded; move it by hand. (run \`${t.runId}\`)`).catch(()=>{});continue}o++,e("info",`\u2713 ${l.key} \u2192 "${r.deployToColumn}"`)}catch(u){e("warn",`${l.key}: sweep failed (${u instanceof Error?u.message:u}) - left in "${r.deployFromColumn}"`)}return e("info",`Moved ${o}/${i.length} ticket(s) to "${r.deployToColumn}"`),o}async function Ty(t,e){let n=t.environment,r=n.previousEnvBranch,s=(l,u=!1)=>({error:l,guard:u,comment:`**Allwright could not deploy \`${t.issueKey}\` to \`${n.name}\`.**
|
|
778
778
|
|
|
779
779
|
${l}
|
|
780
780
|
|
|
781
|
-
(run \`${t.runId}\`)`});e("info",`Checking "${n.branch}" is in sync with "${r}" before deploying`);try{await ln(t.repoPath,r),await ln(t.repoPath,n.branch)}catch(l){return s(`sync check could not fetch branches: ${l instanceof Error?l.message:String(l)}`)}let i;try{i=await ra(t.repoPath,`origin/${r}`,`origin/${n.branch}`)}catch(l){return s(`sync check failed: ${l instanceof Error?l.message:String(l)}`)}if(!i)return e("info",`"${n.branch}" already matches "${r}" - continuing`),null;e("warn",`"${n.branch}" and "${r}" have diverged - opening a PR instead of deploying`);let o=
|
|
781
|
+
(run \`${t.runId}\`)`});e("info",`Checking "${n.branch}" is in sync with "${r}" before deploying`);try{await ln(t.repoPath,r),await ln(t.repoPath,n.branch)}catch(l){return s(`sync check could not fetch branches: ${l instanceof Error?l.message:String(l)}`)}let i;try{i=await ra(t.repoPath,`origin/${r}`,`origin/${n.branch}`)}catch(l){return s(`sync check failed: ${l instanceof Error?l.message:String(l)}`)}if(!i)return e("info",`"${n.branch}" already matches "${r}" - continuing`),null;e("warn",`"${n.branch}" and "${r}" have diverged - opening a PR instead of deploying`);let o=Ae(ye()??t.cfg,t.project.repoName);if(!o)return s(`"${n.branch}" and "${r}" have diverged, and no GitHub token applies to this repo to open a PR. Run \`allwright github set-token\`, or merge them manually, then retry the deploy.`,!0);try{let l=await tr(t.repoPath),u=at(l);if(!u)throw new Error(`could not parse a GitHub owner/repo from origin "${l}"`);let f=await new $e(o).createPullRequest(u.owner,u.repo,{title:`Sync ${n.name} (${n.branch}) with ${r}`,head:r,base:n.branch,body:`Allwright opened this automatically while trying to deploy \`${t.issueKey}\` to \`${n.name}\`: \`${n.branch}\` doesn't have everything that's on \`${r}\` yet, so deploying now would ship different code than what was validated there. Merge this PR, then retry the deploy.
|
|
782
782
|
|
|
783
783
|
(run \`${t.runId}\`)`});return s(`"${n.branch}" is not in sync with "${r}" - opened ${f.url} to catch it up. Merge that, then retry the deploy.`,!0)}catch(l){return s(`could not open a sync PR: ${l instanceof Error?l.message:String(l)}`)}}function xy(t,e){if(!e.trim())return t;let n=dr.default.resolve(t,e),r=dr.default.relative(t,n);if(r.startsWith("..")||dr.default.isAbsolute(r))throw new Error(`working directory "${e}" is outside the repository checkout`);return n}function Cy(t){return new Promise(e=>{let n=(0,fr.spawn)("bash",["-lc",t.command],{cwd:t.cwd,env:t.env,detached:!0,stdio:["ignore","pipe","pipe"]}),r=[],s=c=>{r.push(c),r.length>20&&r.shift()},i=!1,o=!1,l=c=>{i||(i=!0,clearTimeout(u),e({code:c,timedOut:o,tail:r.join(`
|
|
784
784
|
`)}))},u=setTimeout(()=>{o=!0,ud(n.pid,"SIGTERM"),setTimeout(()=>ud(n.pid,"SIGKILL"),1e4).unref()},t.timeoutMs);za.default.createInterface({input:n.stdout}).on("line",c=>{s(c),t.onLine("info",c)}),za.default.createInterface({input:n.stderr}).on("line",c=>{s(c),t.onLine("warn",c)}),n.on("error",c=>{s(`failed to start: ${c.message}`),l(127)}),n.on("close",c=>l(c??1))})}function ud(t,e){if(t)try{process.kill(-t,e)}catch{try{process.kill(t,e)}catch{}}}function Ua(t){let e=t.filter(n=>n&&n.length>=6).sort((n,r)=>r.length-n.length);return e.length?n=>{let r=n;for(let s of e)r=r.split(s).join("***");return r}:n=>n}async function dt(t,e){if(t.issueKey!==pr.BRANCH_DEPLOY_ISSUE_KEY)try{await t.jira.addComment(t.issueKey,e)}catch(n){y.error(`could not post deploy comment to ${t.issueKey}: ${n}`)}}function qa(t){return Oi(t)!==null}async function md(t,e){let n=Oi(e);if(!n)return;let{emit:r,setStatus:s}=La({runId:e,transport:t.transport}),i=t.lookup(n.projectId,n.environmentName);if(!i){let l=`approved, but environment "${n.environmentName}" is no longer in this runner's config (deleted or renamed?) - nothing was deployed`;r("error",l),s("failed",{error:l}),Ni(e);return}Ni(e);let o={runId:e,project:i.project,environment:i.environment,issueKey:n.issueKey,issueSummary:n.issueSummary,repoPath:i.repoPath,cfg:t.cfg,jira:t.jiraFor(i.project.repoName),transport:t.transport,requestedBy:n.requestedBy};r("info",`Approved - running the ${i.environment.steps.length} deploy step(s) now`);try{await pd(o,r,s)}catch(l){let u=l instanceof Error?l.message:String(l);r("error",`Deploy failed: ${u}`),await dt(o,`**Allwright deploy failed.**
|
|
@@ -787,7 +787,7 @@ ${u.slice(0,800)}`),s("failed",{error:u})}}async function gd(t,e){let n=Oi(e);if
|
|
|
787
787
|
|
|
788
788
|
No deploy step was executed. (run \`${e}\`)`)}catch(o){y.error(`could not post rejection comment to ${n.issueKey}: ${o}`)}s("failed",{error:"deploy rejected by a reviewer"})}var Iy=_.object({steps:_.array(pr.DeployStep).max(50).default([]),requiredSecrets:_.array(_.string()).max(50).default([]),notes:_.string().default("")}),Ry=[".ticketpilot/deploy.md","DEPLOY.md","DEPLOYMENT.md","docs/DEPLOY.md","docs/deploy.md","docs/deployment.md"],cd=24e3;function Fi(t){for(let e of Ry){let n=dr.default.join(t,e);try{if(!hr.default.existsSync(n))continue;let r=hr.default.readFileSync(n,"utf8");if(!r.trim())continue;return{path:e,content:r.length>cd?r.slice(0,cd)+`
|
|
789
789
|
|
|
790
|
-
[\u2026document truncated\u2026]`:r}}catch{continue}}return null}var dd=["docker","docker-compose","pm2","systemctl","node","pnpm","npm","yarn","make","python3","pip","rsync","ssh","caddy","nginx"];function yd(t){return bd("bash",["-lc",`command -v ${JSON.stringify(t)}`]).trim().length>0}function bd(t,e){try{let n=(0,fr.spawnSync)(t,e,{encoding:"utf8",timeout:5e3});return n.status===0?n.stdout??"":""}catch{return""}}async function
|
|
790
|
+
[\u2026document truncated\u2026]`:r}}catch{continue}}return null}var dd=["docker","docker-compose","pm2","systemctl","node","pnpm","npm","yarn","make","python3","pip","rsync","ssh","caddy","nginx"];function yd(t){return bd("bash",["-lc",`command -v ${JSON.stringify(t)}`]).trim().length>0}function bd(t,e){try{let n=(0,fr.spawnSync)(t,e,{encoding:"utf8",timeout:5e3});return n.status===0?n.stdout??"":""}catch{return""}}async function Ey(t){let e;try{e=new URL(t)}catch{return null}let n=[];try{let{resolve4:i,resolve6:o}=await import("node:dns/promises"),[l,u]=await Promise.all([i(e.hostname).catch(()=>[]),o(e.hostname).catch(()=>[])]);n=[...l,...u]}catch{n=[]}if(!n.length)return`${e.hostname} does not resolve yet - this build is on THIS machine, but nothing points at it. Users see whatever your DNS points at today.`;let r=await import("node:os"),s=new Set(Object.values(r.networkInterfaces()).flatMap(i=>i??[]).filter(i=>!i.internal).map(i=>i.address));return n.some(i=>s.has(i))?null:`${e.hostname} resolves to ${n.slice(0,3).join(", ")}, which is not an address of this machine. If you front it with a CDN or load balancer that is expected; otherwise this deploy changed nothing for users - they are still being served by the old server until the DNS record moves.`}async function Ay(t,e){let n;try{n=new URL(t)}catch{e.push({name:"public-url",ok:!1,detail:`not a valid URL: ${t}`});return}try{let{lookup:r}=await import("node:dns/promises"),s=await r(n.hostname);e.push({name:"public-url-dns",ok:!0,detail:`${n.hostname} \u2192 ${s.address}`})}catch{e.push({name:"public-url-dns",ok:!1,detail:`${n.hostname} does not resolve - add an A/CNAME record for it at your DNS provider (changes can take a few minutes to propagate)`});return}if(n.protocol==="https:"){let r=await import("node:tls");await new Promise(s=>{let i=r.connect({host:n.hostname,port:Number(n.port||443),servername:n.hostname,timeout:8e3},()=>{let o=i.getPeerCertificate(),l=o?.valid_to?Math.round((new Date(o.valid_to).getTime()-Date.now())/864e5):NaN;e.push(Number.isFinite(l)&&l>0?{name:"public-url-tls",ok:l>14,detail:`certificate valid, expires in ${l} day(s)${l<=14?" - renew soon":""}`}:{name:"public-url-tls",ok:!1,detail:"certificate expired or unreadable"}),i.end(),s()});i.on("error",o=>{e.push({name:"public-url-tls",ok:!1,detail:`TLS handshake failed: ${o.message} - is a certificate installed for this hostname?`}),s()}),i.on("timeout",()=>{e.push({name:"public-url-tls",ok:!1,detail:"TLS handshake timed out"}),i.destroy(),s()})})}try{let r=await fetch(n.toString(),{method:"GET",redirect:"manual",signal:AbortSignal.timeout(1e4)});e.push({name:"public-url-reachable",ok:r.status<500,detail:`HTTP ${r.status}${r.status>=300&&r.status<400?` \u2192 ${r.headers.get("location")??""}`:""}`})}catch(r){e.push({name:"public-url-reachable",ok:!1,detail:`not reachable from the runner: ${r instanceof Error?r.message:String(r)}`})}}function $y(t){let e=t.match(/\/(?:var|home|opt|srv)\/[\w./-]+/g)??[],n=[...new Set(e.map(s=>s.replace(/[.,;:)\]'"`]+$/,"")))].slice(0,12);return n.length?`
|
|
791
791
|
- absolute paths the document mentions, checked on THIS machine:
|
|
792
792
|
${n.map(s=>` - ${s}: ${hr.default.existsSync(s)?"EXISTS on this machine":"not found on this machine"}`).join(`
|
|
793
793
|
`)}`:""}function Py(){let t=[],e=(n,r)=>{try{let s=(0,fr.execFileSync)(r,["--version"],{encoding:"utf8",timeout:5e3}).trim();t.push(`- ${n}: ${s}`)}catch{}};for(let n of["node","npm","python3"]){let r="";try{r=(0,fr.execFileSync)("which",[n],{encoding:"utf8",timeout:5e3}).trim()}catch{continue}e(`${n} in the RUNNER's PATH (${r}) - deploy steps run with THIS`,r);for(let s of[`/usr/bin/${n}`,`/usr/local/bin/${n}`])s!==r&&hr.default.existsSync(s)&&e(`${n} at ${s}`,s)}return t.length?`
|
|
@@ -796,11 +796,11 @@ ${t.map(n=>` ${n}`).join(`
|
|
|
796
796
|
`)}`:""}function vd(t,e,n,r=""){let s=dd.filter(l=>yd(l)),i=dd.filter(l=>!s.includes(l)),o=Object.keys(Ot(t,e,n));return`About the machine these steps will run on (gathered by the runner, trust it):
|
|
797
797
|
- available tools: ${s.join(", ")||"(none of the common ones)"}
|
|
798
798
|
- NOT installed: ${i.join(", ")||"(none missing)"}
|
|
799
|
-
- secrets already stored for this environment (names only): ${o.join(", ")||"(none yet)"}`+Py()+$y(r)}async function wd(t){let e=[];if(t.publicUrl?.trim()&&await
|
|
799
|
+
- secrets already stored for this environment (names only): ${o.join(", ")||"(none yet)"}`+Py()+$y(r)}async function wd(t){let e=[];if(t.publicUrl?.trim()&&await Ay(t.publicUrl.trim(),e),e.push(hr.default.existsSync(t.repoPath)?{name:"repo-path",ok:!0,detail:t.repoPath}:{name:"repo-path",ok:!1,detail:`checkout missing: ${t.repoPath}`}),e.push({name:"deploys-enabled",ok:t.cfg.deploy.enabled,detail:t.cfg.deploy.enabled?"enabled on this runner":"disabled - run: allwright deploy enable (then restart the runner)"}),t.workdir){let l=dr.default.isAbsolute(t.workdir)?t.workdir:dr.default.join(t.repoPath,t.workdir);e.push(hr.default.existsSync(l)?{name:"workdir",ok:!0,detail:l}:{name:"workdir",ok:!1,detail:`does not exist: ${l}`})}if(t.branch){let l=bd("git",["-C",t.repoPath,"ls-remote","--heads","origin",t.branch]);e.push(l.trim()?{name:"branch",ok:!0,detail:`origin/${t.branch} exists`}:{name:"branch",ok:!1,detail:`origin has no branch "${t.branch}" (or the remote is unreachable)`})}let n=Ot(t.cfg,t.repoName,t.environmentName),r=new Set(t.requiredSecrets);for(let l of t.steps)for(let u of l.run.matchAll(/\$\{?([A-Z][A-Z0-9_]{2,})\}?/g))r.add(u[1]);let s=[...r].filter(l=>!n[l]&&!process.env[l]);e.push({name:"secrets",ok:s.length===0,detail:s.length?`missing: ${s.join(", ")} - set with: allwright env set "${t.repoName}" "${t.environmentName}" ${s[0]}=...`:`${r.size} present`});let i=new Set;for(let l of t.steps)for(let u of l.run.split(/&&|\|\||;|\|/)){let c=u.trim().split(/\s+/),f=c.shift();for(;f&&(/^[A-Za-z_][A-Za-z0-9_]*=/.test(f)||f==="sudo"||f==="env"||f==="nohup");)f=c.shift();!f||f.startsWith("$")||f.startsWith("#")||f.startsWith("(")||i.add(f)}let o=[...i].filter(l=>!yd(l));return e.push({name:"binaries",ok:o.length===0,detail:o.length?`not found on this machine: ${o.join(", ")}`:`${i.size} found: ${[...i].slice(0,12).join(", ")}`}),{ok:e.every(l=>l.ok),checks:e}}async function _d(t){let e=vd(t.cfg,t.repoName,t.environmentName),n=qt(fd.DEPLOY_FIX_PROMPT_TEMPLATE,{envName:t.environmentName,steps:t.steps.map((f,p)=>`${p+1}. [${f.name}]${f.continueOnError?" (continues on error)":""}
|
|
800
800
|
${f.run}`).join(`
|
|
801
801
|
`),failedStep:t.failedStep||"(unknown)",errorText:t.errorText||"(no error text recorded)",machineContext:e}),r=await t.agent.adapter.run({repoPath:t.repoPath,prompt:n,timeoutSeconds:240,bin:t.agent.bin,mode:"read_only",maxTurns:40,sessionId:(0,Da.randomUUID)(),onLog:()=>{}});if(!r.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:r.error??"the agent produced no output"};let s=Sd(r.resultText),i=(r.resultText.split(/```/)[0]??"").replace(/^\s*CAUSE TYPE:.*$/im,"").trim(),l=/```(?:markdown|md)\s*\n([\s\S]*?)```/i.exec(r.resultText)?.[1]?.trim()??"",u=l?Fi(t.repoPath):null;if(!s)return{ok:!1,steps:[],requiredSecrets:[],notes:i,error:i?"the agent diagnosed the failure (see its notes) but did not produce an applicable step list - the cause may live outside the steps":`the agent's answer was not in the expected shape. It started: "${r.resultText.trim().slice(0,200).replace(/\s+/g," ")}\u2026"`};let c=/^\s*CAUSE TYPE:\s*(CODE|MACHINE)\b/im.exec(r.resultText)?.[1]?.toUpperCase();return c?{ok:!1,steps:[],requiredSecrets:[],notes:i,error:c==="MACHINE"?"this is not a steps problem - the steps are right, but this machine is missing an access or a credential (git has no way to authenticate, a key is absent, something is not installed). The diagnosis above says what to run ON THAT MACHINE. Allwright will not paste a credential into a deploy recipe to work around it.":"this is not a steps problem - the deploy failed because the code or the database is not ready (a build error, a failing test, or a migration that was never applied). Changing deploy steps cannot fix it; the diagnosis above says what a person has to change."}:{ok:!0,...s,notes:i||s.notes,docPath:u?.path??(l?"DEPLOY.md":""),docContent:l}}async function kd(t){let e=Fi(t.repoPath);if(!e)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:'this repo has no deploy document. Create DEPLOY.md at the repo root (or .ticketpilot/deploy.md) describing how this project actually deploys - the same commands you run by hand. "Ask Claude for steps" translates that document; it does not guess.'};let n=vd(t.cfg,t.repoName,t.environmentName,e.content),r=qt(pr.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE,{envName:t.environmentName,docPath:e.path,docContent:e.content,notes:t.notes.trim()||"(nothing specified)",machineContext:n}),s=await t.agent.adapter.run({repoPath:t.repoPath,prompt:r,timeoutSeconds:t.timeoutSeconds,bin:t.agent.bin,mode:"read_only",maxTurns:30,sessionId:(0,Da.randomUUID)(),onLog:()=>{}});if(!s.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:s.error??"Claude Code produced no output"};let i=Sd(s.resultText);return i?{ok:!0,...i}:(y.warn(`deploy step suggestion could not be parsed. Claude's raw answer follows:
|
|
802
802
|
`+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 Sd(t){for(let e of jy(t)){let n;try{n=JSON.parse(e)}catch{continue}let r=Iy.safeParse(Oy(n));if(r.success&&r.data.steps.length||r.success&&r.data.notes.trim())return r.data}return null}function jy(t){let e=[];for(let s of t.matchAll(/```[a-zA-Z0-9_-]*[ \t]*\r?\n([\s\S]*?)```/g))s[1].trim()&&e.push(s[1]);let n=t.indexOf("{"),r=t.lastIndexOf("}");return n>=0&&r>n&&e.push(t.slice(n,r+1)),e}function Oy(t){if(!t||typeof t!="object")return t;let e=t,r=(Array.isArray(t)?t:Array.isArray(e.steps)?e.steps:Array.isArray(e.deploy_steps)?e.deploy_steps:Array.isArray(e.deploySteps)?e.deploySteps:[]).map((o,l)=>{if(typeof o=="string")return o.trim()?{name:hd(o,l),run:o.trim()}:null;if(!o||typeof o!="object")return null;let u=o,c=Ma(u.run,u.command,u.cmd,u.script,u.shell);return c?{name:(Ma(u.name,u.title,u.description)??hd(c,l)).slice(0,120),run:c,continueOnError:u.continueOnError===!0||u.continue_on_error===!0}:null}).filter(Boolean),s=e.requiredSecrets??e.required_secrets??e.secrets,i=Array.isArray(s)?s.filter(o=>typeof o=="string"):s&&typeof s=="object"?Object.keys(s):[];return{steps:r.slice(0,50),requiredSecrets:i.slice(0,50),notes:Ma(e.notes,e.note,e.explanation)??""}}function Ma(...t){for(let e of t)if(typeof e=="string"&&e.trim())return e.trim()}function hd(t,e){return(t.split(`
|
|
803
|
-
`)[0].trim()||`Step ${e+1}`).slice(0,120)}wt();ut();nr();function Bi(t,e){if(!t.componentRoutes.length)return{project:t};let n=e.filter(Boolean);if(!n.length)return{error:`no Jira component set - project "${t.name}" routes by component (${t.componentRoutes.map(i=>i.component).join(", ")}); set one on the ticket`};let r=t.componentRoutes.filter(i=>n.includes(i.component));if(!r.length)return{error:`component(s) [${n.join(", ")}] not mapped - known: `+t.componentRoutes.map(i=>`${i.component}\u2192${i.repoName}`).join(", ")};let s=new Set(r.map(i=>i.repoName));return s.size>1?{error:`components map to DIFFERENT repos (${[...s].join(", ")}) - ambiguous, refusing`}:{project:{...t,repoName:r[0].repoName}}}var Td=24*3600*1e3,Ki=14,Ny=Ki*24*3600*1e3,My=new Set(["to","on","this","the","a","an","env","environment","please","now","it"]),Hi=class{constructor(e,n,r){this.cfg=e;this.jiraFor=n;this.transport=r}cfg;jiraFor;transport;projects=[];rules=[];environments=[];inFlight=new Set;autopilotPausedUntil=0;get busyCount(){return Math.max(this.inFlight.size,this.activeWork)}activeWork=0;get idle(){return!this.ticking&&this.inFlight.size===0&&this.activeWork===0}repoQueues=new Map;envQueues=new Map;timer=null;ticking=!1;paused=!1;jiraOf(e){return this.jiraFor(e.repoName)}routingWarned=new Set;warnRoutingOnce(e,n){this.routingWarned.has(e)||(this.routingWarned.add(e),y.warn(`Component routing refused - ${n}`))}resolveClaudeProfile(e,n){if(!n)return;let r=this.cfg.claudeProfiles[n]?.configDir;return!r&&e&&(this.transport.send({type:"run.log",runId:e,seq:99e3,ts:new Date().toISOString(),level:"warn",message:`Claude profile "${n}" is not set up on this runner (allwright claude login "${n}") - using the runner's own login instead.`}),y.warn(`run ${e}: claude profile "${n}" missing locally - using default login`)),r}setConfig(e,n,r=!1,s=[]){this.projects=e,this.rules=n,this.environments=s;let i=n.filter(o=>o.enabled).length;y.info(`config synced: ${e.length} project(s), ${n.length} rule(s) (${i} enabled), ${s.length} environment(s)`),r!==this.paused&&(y.info(r?"polling paused from the dashboard":"polling resumed from the dashboard"),this.paused=r)}start(){let e=this.cfg.pollIntervalSeconds*1e3;this.timer=setInterval(()=>{this.tick()},e),this.tick(),y.info(`polling Jira every ${this.cfg.pollIntervalSeconds}s`)}stop(){this.timer&&clearInterval(this.timer)}lastScheduleCheck=0;auditInFlight=!1;async runScheduledAudits(){if(!(!this.cfg.auditSchedules.length||this.auditInFlight)&&!(Date.now()-this.lastScheduleCheck<15*6e4)){this.lastScheduleCheck=Date.now();for(let e of this.cfg.auditSchedules){let n=this.projects.find(s=>s.repoName===e.repoName);if(!n)continue;let r=cc(n.id,e.role);if(!(r&&Date.now()-new Date(r).getTime()<e.intervalHours*36e5)){this.auditInFlight=!0;try{y.info(`Scheduled ${e.role} audit of ${e.repoName} starting (every ${e.intervalHours}h)`);let s=Ke(this.cfg,n,"assist");if("error"in s){y.warn(`Scheduled audit skipped: ${s.error}`);continue}let i=await Yr({projectId:n.id,repoPath:this.cfg.repos[e.repoName]?.path??"",role:e.role,scope:{kind:"repo",ref:""},model:"",agent:s,jira:this.jiraFor(e.repoName)});if(i.ok){let o=i.audit.findings.length;y.info(`Scheduled audit done: ${o} finding(s) - drift visible on the Audits page`)}else y.warn(`Scheduled audit failed: ${i.error}`)}catch(s){y.warn(`Scheduled audit crashed: ${s instanceof Error?s.message:String(s)}`)}finally{this.auditInFlight=!1}break}}}}async tick(){if(!(this.ticking||this.paused||!this.transport.connected)){this.ticking=!0;try{await this.runScheduledAudits(),await this.sweepMergedPRs(),await this.sweepGitHubApprovals();let e=new Set;for(let n of this.rules){if(!n.enabled)continue;let r=this.projects.find(i=>i.id===n.projectId);if(!r)continue;let s=this.cfg.repos[r.repoName];if(!s){y.warn(`rule "${n.name}": no local path for repo "${r.repoName}" - run: allwright repo add "${r.repoName}" /path/to/checkout`);continue}n.action.type==="deploy"?await this.pollDeployRule(n,r,s.path):n.action.type==="respond"?await this.pollRespondRule(n,r,s.path):(e.has(r.id)||(e.add(r.id),await this.sweepNeedsInput(r)),n.trigger.type==="comment_keyword"&&await this.sweepRevisions(n,r),await this.pollRule(n,r,s.path))}await this.pullAutopilotWork()}catch(e){y.warn(`poll tick failed: ${e instanceof Error?e.message:e}`)}finally{this.ticking=!1}}}async pullAutopilotWork(){if(this.inFlight.size>0||this.autopilotPausedUntil>Date.now())return;let e=await this.transport.requestAutopilotNext();if(!e?.ok)return;if(e.pausedUntil){let S=Date.parse(e.pausedUntil);Number.isFinite(S)&&(this.autopilotPausedUntil=S);return}let n=e.item;if(!n)return;let r=this.rules.find(S=>S.id===n.ruleId&&S.enabled),s=this.projects.find(S=>S.id===n.projectId);if(!r||!s){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:"the rule or project this item was queued against no longer exists"});return}let i=Bi(s,[]),o="project"in i?i.project:s,l=this.cfg.repos[o.repoName];if(!l){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:`no local checkout mapped for "${o.repoName}" on this machine`});return}let u=n.baseOverride||n.branchOverride||n.autoMerge?{...r,action:r.action.type==="implement"?{...r.action,...n.baseOverride?{baseBranch:n.baseOverride}:{},...n.branchOverride?{branchTemplate:n.branchOverride}:{},...n.autoMerge?{requireApproval:!1,autoMerge:!0}:{}}:r.action}:r;y.info(`autopilot: taking ${n.issueKey} (${r.name})`+(n.branchOverride?` -> shared branch ${n.branchOverride}`:"")+(n.baseOverride?` -> stacked on ${n.baseOverride}`:""));let c=this.jiraOf(o),f="";try{f=(await c.getIssue(n.issueKey))?.summary??""}catch(S){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:`could not read ${n.issueKey} from Jira: ${S instanceof Error?S.message:String(S)}`});return}let p=await this.transport.claimRun({ruleId:r.id,issueKey:n.issueKey,issueSummary:f,triggerFingerprint:`autopilot:${n.id}`,dedupKey:`autopilot:${n.id}`});if(!p.accepted||!p.runId){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:p.reason??"the control plane refused the run"});return}this.transport.sendAutopilotReport({itemId:n.id,outcome:"claimed",runId:p.runId});let b=`${r.id}:${n.issueKey}`;this.inFlight.add(b);let w=this.resolveClaudeProfile(p.runId,p.claudeProfile);this.enqueueForRepo(l.path,async()=>{try{await Di({runId:p.runId,rule:u,project:o,issueKey:n.issueKey,repoPath:l.path,cfg:this.cfg,jira:c,transport:this.transport,claudeConfigDir:w,actorEmail:p.actorEmail,continueBranch:n.continueBranch})}finally{this.inFlight.delete(b)}})}async sweepGitHubApprovals(){let e=Object.values(
|
|
803
|
+
`)[0].trim()||`Step ${e+1}`).slice(0,120)}wt();ut();nr();function Bi(t,e){if(!t.componentRoutes.length)return{project:t};let n=e.filter(Boolean);if(!n.length)return{error:`no Jira component set - project "${t.name}" routes by component (${t.componentRoutes.map(i=>i.component).join(", ")}); set one on the ticket`};let r=t.componentRoutes.filter(i=>n.includes(i.component));if(!r.length)return{error:`component(s) [${n.join(", ")}] not mapped - known: `+t.componentRoutes.map(i=>`${i.component}\u2192${i.repoName}`).join(", ")};let s=new Set(r.map(i=>i.repoName));return s.size>1?{error:`components map to DIFFERENT repos (${[...s].join(", ")}) - ambiguous, refusing`}:{project:{...t,repoName:r[0].repoName}}}var Td=24*3600*1e3,Ki=14,Ny=Ki*24*3600*1e3,My=new Set(["to","on","this","the","a","an","env","environment","please","now","it"]),Hi=class{constructor(e,n,r){this.cfg=e;this.jiraFor=n;this.transport=r}cfg;jiraFor;transport;projects=[];rules=[];environments=[];inFlight=new Set;autopilotPausedUntil=0;get busyCount(){return Math.max(this.inFlight.size,this.activeWork)}activeWork=0;get idle(){return!this.ticking&&this.inFlight.size===0&&this.activeWork===0}repoQueues=new Map;envQueues=new Map;timer=null;ticking=!1;paused=!1;jiraOf(e){return this.jiraFor(e.repoName)}routingWarned=new Set;warnRoutingOnce(e,n){this.routingWarned.has(e)||(this.routingWarned.add(e),y.warn(`Component routing refused - ${n}`))}resolveClaudeProfile(e,n){if(!n)return;let r=this.cfg.claudeProfiles[n]?.configDir;return!r&&e&&(this.transport.send({type:"run.log",runId:e,seq:99e3,ts:new Date().toISOString(),level:"warn",message:`Claude profile "${n}" is not set up on this runner (allwright claude login "${n}") - using the runner's own login instead.`}),y.warn(`run ${e}: claude profile "${n}" missing locally - using default login`)),r}setConfig(e,n,r=!1,s=[]){this.projects=e,this.rules=n,this.environments=s;let i=n.filter(o=>o.enabled).length;y.info(`config synced: ${e.length} project(s), ${n.length} rule(s) (${i} enabled), ${s.length} environment(s)`),r!==this.paused&&(y.info(r?"polling paused from the dashboard":"polling resumed from the dashboard"),this.paused=r)}start(){let e=this.cfg.pollIntervalSeconds*1e3;this.timer=setInterval(()=>{this.tick()},e),this.tick(),y.info(`polling Jira every ${this.cfg.pollIntervalSeconds}s`)}stop(){this.timer&&clearInterval(this.timer)}lastScheduleCheck=0;auditInFlight=!1;async runScheduledAudits(){if(!(!this.cfg.auditSchedules.length||this.auditInFlight)&&!(Date.now()-this.lastScheduleCheck<15*6e4)){this.lastScheduleCheck=Date.now();for(let e of this.cfg.auditSchedules){let n=this.projects.find(s=>s.repoName===e.repoName);if(!n)continue;let r=cc(n.id,e.role);if(!(r&&Date.now()-new Date(r).getTime()<e.intervalHours*36e5)){this.auditInFlight=!0;try{y.info(`Scheduled ${e.role} audit of ${e.repoName} starting (every ${e.intervalHours}h)`);let s=Ke(this.cfg,n,"assist");if("error"in s){y.warn(`Scheduled audit skipped: ${s.error}`);continue}let i=await Yr({projectId:n.id,repoPath:this.cfg.repos[e.repoName]?.path??"",role:e.role,scope:{kind:"repo",ref:""},model:"",agent:s,jira:this.jiraFor(e.repoName)});if(i.ok){let o=i.audit.findings.length;y.info(`Scheduled audit done: ${o} finding(s) - drift visible on the Audits page`)}else y.warn(`Scheduled audit failed: ${i.error}`)}catch(s){y.warn(`Scheduled audit crashed: ${s instanceof Error?s.message:String(s)}`)}finally{this.auditInFlight=!1}break}}}}async tick(){if(!(this.ticking||this.paused||!this.transport.connected)){this.ticking=!0;try{await this.runScheduledAudits(),await this.sweepMergedPRs(),await this.sweepGitHubApprovals();let e=new Set;for(let n of this.rules){if(!n.enabled)continue;let r=this.projects.find(i=>i.id===n.projectId);if(!r)continue;let s=this.cfg.repos[r.repoName];if(!s){y.warn(`rule "${n.name}": no local path for repo "${r.repoName}" - run: allwright repo add "${r.repoName}" /path/to/checkout`);continue}n.action.type==="deploy"?await this.pollDeployRule(n,r,s.path):n.action.type==="respond"?await this.pollRespondRule(n,r,s.path):(e.has(r.id)||(e.add(r.id),await this.sweepNeedsInput(r)),n.trigger.type==="comment_keyword"&&await this.sweepRevisions(n,r),await this.pollRule(n,r,s.path))}await this.pullAutopilotWork()}catch(e){y.warn(`poll tick failed: ${e instanceof Error?e.message:e}`)}finally{this.ticking=!1}}}async pullAutopilotWork(){if(this.inFlight.size>0||this.autopilotPausedUntil>Date.now())return;let e=await this.transport.requestAutopilotNext();if(!e?.ok)return;if(e.pausedUntil){let S=Date.parse(e.pausedUntil);Number.isFinite(S)&&(this.autopilotPausedUntil=S);return}let n=e.item;if(!n)return;let r=this.rules.find(S=>S.id===n.ruleId&&S.enabled),s=this.projects.find(S=>S.id===n.projectId);if(!r||!s){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:"the rule or project this item was queued against no longer exists"});return}let i=Bi(s,[]),o="project"in i?i.project:s,l=this.cfg.repos[o.repoName];if(!l){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:`no local checkout mapped for "${o.repoName}" on this machine`});return}let u=n.baseOverride||n.branchOverride||n.autoMerge?{...r,action:r.action.type==="implement"?{...r.action,...n.baseOverride?{baseBranch:n.baseOverride}:{},...n.branchOverride?{branchTemplate:n.branchOverride}:{},...n.autoMerge?{requireApproval:!1,autoMerge:!0}:{}}:r.action}:r;y.info(`autopilot: taking ${n.issueKey} (${r.name})`+(n.branchOverride?` -> shared branch ${n.branchOverride}`:"")+(n.baseOverride?` -> stacked on ${n.baseOverride}`:""));let c=this.jiraOf(o),f="";try{f=(await c.getIssue(n.issueKey))?.summary??""}catch(S){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:`could not read ${n.issueKey} from Jira: ${S instanceof Error?S.message:String(S)}`});return}let p=await this.transport.claimRun({ruleId:r.id,issueKey:n.issueKey,issueSummary:f,triggerFingerprint:`autopilot:${n.id}`,dedupKey:`autopilot:${n.id}`});if(!p.accepted||!p.runId){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:p.reason??"the control plane refused the run"});return}this.transport.sendAutopilotReport({itemId:n.id,outcome:"claimed",runId:p.runId});let b=`${r.id}:${n.issueKey}`;this.inFlight.add(b);let w=this.resolveClaudeProfile(p.runId,p.claudeProfile);this.enqueueForRepo(l.path,async()=>{try{await Di({runId:p.runId,rule:u,project:o,issueKey:n.issueKey,repoPath:l.path,cfg:this.cfg,jira:c,transport:this.transport,claudeConfigDir:w,actorEmail:p.actorEmail,continueBranch:n.continueBranch})}finally{this.inFlight.delete(b)}})}async sweepGitHubApprovals(){let e=Object.values(Es());if(!e.length)return;let n=ye()??this.cfg,r=new Map,s=i=>{let o=Ae(n,i);if(!o)return null;let l=r.get(o);return l||r.set(o,l=new $e(o)),l};for(let i of e.slice(0,10)){let o=s(i.repoName);if(!o)continue;let l=`gh-approve:${i.runId}`;if(this.inFlight.has(l))continue;let u,c;try{[u,c]=await Promise.all([o.getReviews(i.owner,i.repo,i.prNumber),o.getPullRequest(i.owner,i.repo,i.prNumber)])}catch(w){y.warn(`review check failed for ${i.owner}/${i.repo}#${i.prNumber}: ${w instanceof Error?w.message:w}`);continue}if(!c)continue;let f={cfg:this.cfg,jiraFor:this.jiraFor,transport:this.transport};if(c.merged){y.info(`PR #${i.prNumber} for ${i.issueKey} was merged on GitHub - completing the run`),this.inFlight.add(l);try{await $s(f,i.runId,c.headSha)}finally{this.inFlight.delete(l)}continue}if(c.state==="closed"){y.info(`PR #${i.prNumber} for ${i.issueKey} was closed unmerged on GitHub - failing the run`);let w=this.jiraFor(i.repoName),S=`PR #${i.prNumber} was closed on GitHub without merging`;await w.addComment(i.issueKey,`**Allwright: the pull request for this ticket was closed on GitHub without merging.**
|
|
804
804
|
|
|
805
805
|
PR: ${i.prUrl}
|
|
806
806
|
|
|
@@ -812,7 +812,7 @@ To fix: Reject this run on the Allwright dashboard (that closes the conflicted P
|
|
|
812
812
|
|
|
813
813
|
PR: ${i.prUrl}
|
|
814
814
|
|
|
815
|
-
Reply to the review on GitHub, or reject the run on the Allwright dashboard and re-trigger with new instructions. (run \`${i.runId}\`)`).catch(()=>{}),ct({...i,changesRequestedNotified:!0}),y.info(`changes requested on PR #${i.prNumber} for ${i.issueKey} - ticket notified`));continue}if(b.commitId===c.headSha){y.info(`PR #${i.prNumber} for ${i.issueKey} approved on GitHub by ${b.user} - completing the run`),this.inFlight.add(l);try{await $s(f,i.runId,b.commitId)}catch(w){y.warn(`github-approval completion failed for ${i.runId}: ${w instanceof Error?w.message:w}`)}finally{this.inFlight.delete(l)}}}}}async sweepMergedPRs(){let e=Object.values(ji());if(!e.length)return;let n=ye()??this.cfg,r=new Map,s=l=>{let u=
|
|
815
|
+
Reply to the review on GitHub, or reject the run on the Allwright dashboard and re-trigger with new instructions. (run \`${i.runId}\`)`).catch(()=>{}),ct({...i,changesRequestedNotified:!0}),y.info(`changes requested on PR #${i.prNumber} for ${i.issueKey} - ticket notified`));continue}if(b.commitId===c.headSha){y.info(`PR #${i.prNumber} for ${i.issueKey} approved on GitHub by ${b.user} - completing the run`),this.inFlight.add(l);try{await $s(f,i.runId,b.commitId)}catch(w){y.warn(`github-approval completion failed for ${i.runId}: ${w instanceof Error?w.message:w}`)}finally{this.inFlight.delete(l)}}}}}async sweepMergedPRs(){let e=Object.values(ji());if(!e.length)return;let n=ye()??this.cfg,r=new Map,s=l=>{let u=Ae(n,l);if(!u)return null;let c=r.get(u);return c||r.set(u,c=new $e(u)),c},i=20,o=720*3600*1e3;for(let l of e.slice(0,i)){let u=s(l.repoName);if(!u)continue;if(Date.now()-new Date(l.createdAt).getTime()>o){y.warn(`merge watch for ${l.issueKey} PR #${l.prNumber} is over 30 days old - dropping`),Rs(l.runId);continue}let c;try{c=await u.getPullRequest(l.owner,l.repo,l.prNumber)}catch(b){y.warn(`merge check failed for ${l.owner}/${l.repo}#${l.prNumber}: ${b instanceof Error?b.message:b}`);continue}if(!c){Rs(l.runId);continue}if(c.state==="open")continue;if(!c.merged){Rs(l.runId);continue}let f=this.jiraFor(l.repoName),p="";if(l.jiraTransitionOnMerge)try{p=await f.transitionByName(l.issueKey,l.jiraTransitionOnMerge)?`
|
|
816
816
|
|
|
817
817
|
Ticket moved to **${l.jiraTransitionOnMerge}**.`:`
|
|
818
818
|
|
|
@@ -828,7 +828,7 @@ ${n}
|
|
|
828
828
|
|
|
829
829
|
This run is continuing from where it left off. (run \`${e}\`)`),await o.editLabels(s.issueKey,{remove:[hn.NEEDS_INPUT_LABEL]})}catch(p){this.inFlight.delete(i);let b=p instanceof Error?p.message:String(p);return{ok:!1,note:"",error:`could not write the answer to ${s.issueKey}: ${b}`}}y.info(`answer received from the dashboard for ${s.issueKey} - resuming run ${e}`);let u=r?`${r}: ${n}`:n,c={jiraFor:this.jiraFor,transport:this.transport,cfg:this.cfg},f=s.kind==="implement"?s.baseRepoPath??s.repoPath:s.repoPath;return this.enqueueForRepo(f,async()=>{try{s.kind==="implement"?await Oa(s,u,l,c):await ja(s,u,l,c)}finally{this.inFlight.delete(i)}}),{ok:!0,note:`Answer sent - the run is continuing, and it was posted to ${s.issueKey} too.`}}async abandonStaleInput(e,n){y.warn(`${e.issueKey}: needs-input unanswered for over ${Ki}d - abandoning run ${e.runId}`);try{await this.jiraOf(n).addComment(e.issueKey,`**Allwright gave up waiting for an answer.**
|
|
830
830
|
|
|
831
|
-
No reply arrived within ${Ki} days of the question above. This ticket has been labeled \`${e.failedLabel}\`; remove it and re-trigger to try again. (run \`${e.runId}\`)`),await this.jiraOf(n).editLabels(e.issueKey,{add:[e.failedLabel],remove:[hn.NEEDS_INPUT_LABEL]})}catch(r){y.warn(`could not post staleness notice for ${e.issueKey}: ${r}`)}e.kind==="implement"&&await vt(e.baseRepoPath??e.repoPath,e.repoPath).catch(()=>{}),St(e.runId),this.transport.send({type:"run.status",runId:e.runId,status:"failed",error:`no reply within ${Ki} days`})}async pollRule(e,n,r){let s=e.trigger.type==="label_added"?await this.matchLabelTrigger(e,n):await this.matchCommentTrigger(e,n);for(let i of s){let o=`${e.id}:${i.issueKey}`;if(this.inFlight.has(o))continue;let l=Bi(n,i.components??[]);if("error"in l){this.warnRoutingOnce(`${e.id}:${i.issueKey}`,`${i.issueKey}: ${l.error}`);continue}let u=l.project,c=u.repoName===n.repoName?r:this.cfg.repos[u.repoName]?.path;if(!c){this.warnRoutingOnce(`${e.id}:${i.issueKey}:path`,`${i.issueKey}: routed to repo "${u.repoName}" but it has no local checkout - run: allwright repo add "${u.repoName}" /path/to/checkout`);continue}let f=await this.transport.claimRun({ruleId:e.id,issueKey:i.issueKey,issueSummary:i.summary,triggerFingerprint:i.fingerprint,triggeredByAccountId:i.triggeredByAccountId});if(!f.accepted||!f.runId){f.reason!=="duplicate"&&y.warn(`claim rejected for ${i.issueKey}: ${f.reason??"unknown"}`);continue}this.inFlight.add(o),y.info(`claimed run ${f.runId} for ${i.issueKey}`+(u.repoName!==n.repoName?` (routed \u2192 ${u.repoName})`:"")+(f.claudeProfile?` (claude profile "${f.claudeProfile}")`:""));let p=this.resolveClaudeProfile(f.runId,f.claudeProfile);this.enqueueForRepo(c,async()=>{try{await Di({runId:f.runId,rule:e,project:u,issueKey:i.issueKey,repoPath:c,cfg:this.cfg,jira:this.jiraOf(u),transport:this.transport,claudeConfigDir:p,actorEmail:f.actorEmail})}finally{this.inFlight.delete(o)}})}}async pollRespondRule(e,n,r){let s=e.trigger;if(s.type!=="comment_keyword"||e.action.type!=="respond")return;let i=await this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=s.keyword.toLowerCase(),l=Date.now()-Td;for(let u of i){let c=await this.jiraOf(n).getIssue(u.key);for(let f of c.comments){if(!f.body.toLowerCase().includes(o)||_t(f.body)||new Date(f.created).getTime()<l||!f.id)continue;let p=`respond:${f.id}`;if(this.inFlight.has(p))continue;let b=Bi(n,u.components??[]);if("error"in b){this.warnRoutingOnce(`${e.id}:${u.key}`,`${u.key}: ${b.error}`);continue}let w=b.project,S=w.repoName===n.repoName?r:this.cfg.repos[w.repoName]?.path;if(!S){this.warnRoutingOnce(`${e.id}:${u.key}:path`,`${u.key}: routed to repo "${w.repoName}" but it has no local checkout - run: allwright repo add "${w.repoName}" /path/to/checkout`);continue}let x=await this.transport.claimRun({ruleId:e.id,issueKey:u.key,issueSummary:u.summary,triggerFingerprint:`question by ${f.author} at ${f.created}`,dedupKey:`respond:comment:${f.id}`,triggeredByAccountId:f.authorAccountId??void 0});if(!x.accepted||!x.runId){x.reason!=="duplicate"&&y.warn(`respond claim rejected for ${u.key}: ${x.reason??"unknown"}`);continue}this.inFlight.add(p),y.info(`claimed respond run ${x.runId}: ${u.key} (comment ${f.id})`+(w.repoName!==n.repoName?` (routed \u2192 ${w.repoName})`:"")+(x.claudeProfile?` (claude profile "${x.claudeProfile}")`:""));let
|
|
831
|
+
No reply arrived within ${Ki} days of the question above. This ticket has been labeled \`${e.failedLabel}\`; remove it and re-trigger to try again. (run \`${e.runId}\`)`),await this.jiraOf(n).editLabels(e.issueKey,{add:[e.failedLabel],remove:[hn.NEEDS_INPUT_LABEL]})}catch(r){y.warn(`could not post staleness notice for ${e.issueKey}: ${r}`)}e.kind==="implement"&&await vt(e.baseRepoPath??e.repoPath,e.repoPath).catch(()=>{}),St(e.runId),this.transport.send({type:"run.status",runId:e.runId,status:"failed",error:`no reply within ${Ki} days`})}async pollRule(e,n,r){let s=e.trigger.type==="label_added"?await this.matchLabelTrigger(e,n):await this.matchCommentTrigger(e,n);for(let i of s){let o=`${e.id}:${i.issueKey}`;if(this.inFlight.has(o))continue;let l=Bi(n,i.components??[]);if("error"in l){this.warnRoutingOnce(`${e.id}:${i.issueKey}`,`${i.issueKey}: ${l.error}`);continue}let u=l.project,c=u.repoName===n.repoName?r:this.cfg.repos[u.repoName]?.path;if(!c){this.warnRoutingOnce(`${e.id}:${i.issueKey}:path`,`${i.issueKey}: routed to repo "${u.repoName}" but it has no local checkout - run: allwright repo add "${u.repoName}" /path/to/checkout`);continue}let f=await this.transport.claimRun({ruleId:e.id,issueKey:i.issueKey,issueSummary:i.summary,triggerFingerprint:i.fingerprint,triggeredByAccountId:i.triggeredByAccountId});if(!f.accepted||!f.runId){f.reason!=="duplicate"&&y.warn(`claim rejected for ${i.issueKey}: ${f.reason??"unknown"}`);continue}this.inFlight.add(o),y.info(`claimed run ${f.runId} for ${i.issueKey}`+(u.repoName!==n.repoName?` (routed \u2192 ${u.repoName})`:"")+(f.claudeProfile?` (claude profile "${f.claudeProfile}")`:""));let p=this.resolveClaudeProfile(f.runId,f.claudeProfile);this.enqueueForRepo(c,async()=>{try{await Di({runId:f.runId,rule:e,project:u,issueKey:i.issueKey,repoPath:c,cfg:this.cfg,jira:this.jiraOf(u),transport:this.transport,claudeConfigDir:p,actorEmail:f.actorEmail})}finally{this.inFlight.delete(o)}})}}async pollRespondRule(e,n,r){let s=e.trigger;if(s.type!=="comment_keyword"||e.action.type!=="respond")return;let i=await this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=s.keyword.toLowerCase(),l=Date.now()-Td;for(let u of i){let c=await this.jiraOf(n).getIssue(u.key);for(let f of c.comments){if(!f.body.toLowerCase().includes(o)||_t(f.body)||new Date(f.created).getTime()<l||!f.id)continue;let p=`respond:${f.id}`;if(this.inFlight.has(p))continue;let b=Bi(n,u.components??[]);if("error"in b){this.warnRoutingOnce(`${e.id}:${u.key}`,`${u.key}: ${b.error}`);continue}let w=b.project,S=w.repoName===n.repoName?r:this.cfg.repos[w.repoName]?.path;if(!S){this.warnRoutingOnce(`${e.id}:${u.key}:path`,`${u.key}: routed to repo "${w.repoName}" but it has no local checkout - run: allwright repo add "${w.repoName}" /path/to/checkout`);continue}let x=await this.transport.claimRun({ruleId:e.id,issueKey:u.key,issueSummary:u.summary,triggerFingerprint:`question by ${f.author} at ${f.created}`,dedupKey:`respond:comment:${f.id}`,triggeredByAccountId:f.authorAccountId??void 0});if(!x.accepted||!x.runId){x.reason!=="duplicate"&&y.warn(`respond claim rejected for ${u.key}: ${x.reason??"unknown"}`);continue}this.inFlight.add(p),y.info(`claimed respond run ${x.runId}: ${u.key} (comment ${f.id})`+(w.repoName!==n.repoName?` (routed \u2192 ${w.repoName})`:"")+(x.claudeProfile?` (claude profile "${x.claudeProfile}")`:""));let A={author:f.author,body:f.body},j=this.resolveClaudeProfile(x.runId,x.claudeProfile);this.enqueueForRepo(S,async()=>{try{await Di({runId:x.runId,rule:e,project:w,issueKey:u.key,repoPath:S,cfg:this.cfg,jira:this.jiraOf(w),transport:this.transport,question:A,claudeConfigDir:j,actorEmail:x.actorEmail})}finally{this.inFlight.delete(p)}})}}}async sweepRevisions(e,n){let r=e.trigger;if(r.type!=="comment_keyword")return;let s;try{s=await this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND labels = "${r.doneLabel}" AND updated >= "-2d"`,10)}catch(o){y.warn(`revision sweep failed for ${n.jiraProjectKey}: ${o instanceof Error?o.message:o}`);return}let i=r.keyword.toLowerCase();for(let o of s)try{let l=await this.jiraOf(n).getIssue(o.key),u=null;for(let f of l.comments)_t(f.body)&&(u=Math.max(u??0,new Date(f.created).getTime()));if(u===null||!l.comments.some(f=>!_t(f.body)&&f.body.toLowerCase().includes(i)&&new Date(f.created).getTime()>u))continue;await this.jiraOf(n).editLabels(o.key,{remove:[r.doneLabel]}),y.info(`revision requested on ${o.key} (new "${r.keyword}" after completion) - done label removed, rule will re-fire`)}catch(l){y.warn(`revision check failed for ${o.key}: ${l instanceof Error?l.message:l}`)}}async pollDeployRule(e,n,r){if(e.action.type!=="deploy")return;let s=e.trigger.type==="status_changed"?await this.matchStatusDeploys(e,n):await this.matchCommentDeploys(e,n);for(let i of s){let o=`deploy:${i.dedupKey}`;if(this.inFlight.has(o))continue;let l=await this.transport.claimDeploy({projectId:n.id,ruleId:e.id,issueKey:i.issueKey,issueSummary:i.summary,environmentName:i.environmentName,requestedByAccountId:i.requestedByAccountId,requestedByDisplayName:i.requestedByDisplayName,dedupKey:i.dedupKey,triggerFingerprint:i.fingerprint});if(!l.accepted||!l.runId||!l.environment){if(l.code==="duplicate")continue;l.reason&&l.runId?(await this.jiraOf(n).addComment(i.issueKey,`**Allwright did not deploy this ticket.**
|
|
832
832
|
|
|
833
833
|
${l.reason}`+(i.requestedByAccountId?`
|
|
834
834
|
|
|
@@ -843,7 +843,7 @@ Rules:
|
|
|
843
843
|
- When you are done, every listed file must contain no conflict markers and must be syntactically valid.
|
|
844
844
|
|
|
845
845
|
Conflicted files:
|
|
846
|
-
`;async function Id(t){let{cfg:e,repoPath:n,branch:r,baseBranch:s,issueKey:i,onLog:o}=t,l=Cd.default.join(Lt(),`conflict-${(0,Fa.randomUUID)().slice(0,8)}`),u=!1;try{o("info",`Preparing a worktree for ${r} to merge ${s} into it`),await Ts(n,l,r),u=!0;let c=await Qo(l,s);if(c.ok&&c.alreadyUpToDate)return o("info",`${r} already contains ${s} - nothing to merge`),{ok:!0,freeOfCharge:!0,note:`This branch already contains ${s}, so there was nothing to merge - GitHub's conflict flag was out of date. Refresh the PR.`};if(!c.ok&&c.conflicts===null)return{ok:!1,note:`The merge could not even be started: ${c.reason}`};let f={},p=!1;if(!c.ok){let S=c.conflicts;o("info",`git merged everything except ${S.length} file(s): ${S.slice(0,20).join(", ")}`+(S.length>20?", \u2026":""));let x=Be(t.agentId);if(!x)return await cn(l),{ok:!1,note:`no adapter for agent "${t.agentId}" on this runner`};let
|
|
846
|
+
`;async function Id(t){let{cfg:e,repoPath:n,branch:r,baseBranch:s,issueKey:i,onLog:o}=t,l=Cd.default.join(Lt(),`conflict-${(0,Fa.randomUUID)().slice(0,8)}`),u=!1;try{o("info",`Preparing a worktree for ${r} to merge ${s} into it`),await Ts(n,l,r),u=!0;let c=await Qo(l,s);if(c.ok&&c.alreadyUpToDate)return o("info",`${r} already contains ${s} - nothing to merge`),{ok:!0,freeOfCharge:!0,note:`This branch already contains ${s}, so there was nothing to merge - GitHub's conflict flag was out of date. Refresh the PR.`};if(!c.ok&&c.conflicts===null)return{ok:!1,note:`The merge could not even be started: ${c.reason}`};let f={},p=!1;if(!c.ok){let S=c.conflicts;o("info",`git merged everything except ${S.length} file(s): ${S.slice(0,20).join(", ")}`+(S.length>20?", \u2026":""));let x=Be(t.agentId);if(!x)return await cn(l),{ok:!1,note:`no adapter for agent "${t.agentId}" on this runner`};let A=dn(t.agentId,"edit_no_shell");if(A)return await cn(l),{ok:!1,note:`${A} Resolve the conflicts yourself on branch ${r}, or use Rebuild on current base.`};o("info",`Asking ${x.displayName} to resolve only those files`);let j=-1,v=setInterval(()=>{ta(l,S).then(z=>{let B=S.filter(d=>!z.includes(d));B.length!==j&&(j=B.length,o("info",`Conflict progress: ${B.length}/${S.length} resolved`+(B.length?` \xB7 clean: ${B.join(", ")}`:"")+(z.length?` \xB7 still conflicted: ${z.join(", ")}`:"")))}).catch(()=>{})},12e3),O=await As(x,{repoPath:l,prompt:Dy+S.map(z=>`- ${z}`).join(`
|
|
847
847
|
`),timeoutSeconds:t.timeoutSeconds,bin:Ue(e,t.agentId),configDir:t.configDir,mode:"edit_no_shell",sessionId:(0,Fa.randomUUID)(),onLog:(z,B)=>o(z,B)},(z,B)=>o(z==="warn"?"warn":z,B));if(clearInterval(v),f={costUsd:O.costUsd,inputTokens:O.inputTokens,outputTokens:O.outputTokens},!O.ok)return await cn(l),{ok:!1,...f,note:`The agent could not do the resolution: ${O.error??"it produced no output"}. Nothing was changed - the merge was rolled back. Fix that first, then Resolve again.`};p=!0;let H=await Si(l);if(H.length)return await cn(l),{ok:!1,...f,note:`The agent left conflict markers in ${H.slice(0,5).join(", ")}, so nothing was pushed and the merge was rolled back. Resolve it by hand on ${r}, or use Rebuild on current base to redo the ticket against today's base.`};await ea(l,`${i}: merge ${s}, conflicts resolved by the agent
|
|
848
848
|
|
|
849
849
|
Resolved via Allwright`)}let b=await un(l,s);if(!b.ok){let S=b.forbidden.length?`the merged result touches protected paths (${b.forbidden.slice(0,5).join(", ")})`:`the merged result is too large (${b.files} files, ${b.insertions+b.deletions} lines; limits ${on}/${an})`;return await cn(l),{ok:!1,...f,note:`Nothing was pushed: ${S}. The merge was rolled back.`}}await er(l,r);let w=await tt(l);return o("info",`Pushed the merge to ${r} (${w.slice(0,7)})`),{ok:!0,...f,freeOfCharge:!p,headSha:w,note:p?`Merged ${s} into ${r}; the agent resolved the overlapping files. The PR is the same one - review the merge commit, then approve.`:`Merged ${s} into ${r} cleanly - no agent was needed, so this cost nothing. The PR is the same one; review and approve.`}}catch(c){return await cn(l).catch(()=>{}),{ok:!1,note:`Could not resolve the conflict: ${c instanceof Error?c.message.slice(0,300):String(c)}`}}finally{u&&(await vt(n,l).catch(()=>{}),xd.default.rmSync(l,{recursive:!0,force:!0}))}}var Ba=I(require("node:fs"),1),Rd=I(require("node:path"),1),Ka=require("node:crypto");wt();function Ly(t,e){let n=e.map(r=>`$ ${r.command} (exit ${r.exitCode})
|
|
@@ -859,11 +859,11 @@ Your ONLY job is to make these commands pass, with the smallest change possible.
|
|
|
859
859
|
- If a failure is clearly pre-existing on the base branch and unrelated to this PR's change, leave the code alone and say so in one sentence.
|
|
860
860
|
- Do not ask questions; if you cannot fix something safely, say what you found and stop.
|
|
861
861
|
- You have no shell; the runner re-runs every documented command after you finish.
|
|
862
|
-
End with one short paragraph stating exactly what you changed, or why you changed nothing.`}async function
|
|
862
|
+
End with one short paragraph stating exactly what you changed, or why you changed nothing.`}async function Ed(t){let{cfg:e,repoPath:n,branch:r,baseBranch:s,issueKey:i,failedTests:o,onLog:l}=t,u=Rd.default.join(Lt(),`testfix-${(0,Ka.randomUUID)().slice(0,8)}`),c=!1;try{let f=Be(t.agentId);if(!f)return{ok:!1,note:`no adapter for agent "${t.agentId}" on this runner`};let p=dn(t.agentId,"edit_no_shell");if(p)return{ok:!1,note:p};l("info",`Preparing a worktree on ${r} for the test fix`),await ln(n,r),await Ts(n,u,r),c=!0,await Zr(u,`origin/${r}`);let b=await tt(u);l("info",`Asking ${f.displayName} to fix ${o.length} failing test command(s) - narrow prompt, failure output included, no re-exploration`);let w=await As(f,{repoPath:u,prompt:Ly(i,o),timeoutSeconds:t.timeoutSeconds,bin:Ue(e,t.agentId),configDir:t.configDir,mode:"edit_no_shell",maxTurns:60,sessionId:(0,Ka.randomUUID)(),onLog:(d,m)=>l(d,m)},(d,m)=>l(d==="warn"?"warn":d,m)),S={costUsd:w.costUsd,inputTokens:w.inputTokens,outputTokens:w.outputTokens};if(!w.ok)return{ok:!1,...S,note:`The fix agent could not run: ${w.error??"it produced no output"}. Nothing was changed or pushed.`};let x=await Hr(u);for(let d of x.refused)l("warn",`${Dt} entry refused: ${d}`);let A=!0;try{await Qn(u,`${i}: fix failing TEST.md commands
|
|
863
863
|
|
|
864
|
-
Allwright test-fix run`)}catch{
|
|
865
|
-
${g.tail.slice(-1500)}`));v=m.filter(g=>g.exitCode!==0).slice(0,20).map(g=>({command:g.command.slice(0,500),exitCode:g.exitCode,tail:g.tail.slice(-4e3)})),H=m.length,O=m.length-v.length}}await er(u,r);let B=await tt(u);return l("info",`Pushed the fix to ${r} (${B.slice(0,7)})`),{ok:!0,...S,headSha:B,remaining:v,testsPassed:O,testsTotal:H,note:v.length?`The fix was pushed, but ${v.length} command(s) still fail - output is in the run log. The PR is the same one; review the new commit.`:"All documented test commands pass now. The PR is the same one - review the fix commit, then approve."}}catch(f){return{ok:!1,note:`Could not fix the tests: ${f instanceof Error?f.message.slice(0,300):String(f)}`}}finally{c&&(await vt(n,u).catch(()=>{}),Ba.default.rmSync(u,{recursive:!0,force:!0}))}}ut();var mr=I(require("node:fs"),1),$d=I(require("node:path"),1);var Uy=_.object({role:_.enum(["user","agent"]),text:_.string(),steps:_.array(_.string()).default([]),files:_.array(_.string()).default([])}),qy=_.object({sessionId:_.string(),projectId:_.string(),title:_.string().default(""),updatedAt:_.string(),messages:_.array(Uy).default([])}),Fy=_.record(qy),By=10,Ky=200,
|
|
866
|
-
`,{mode:384}),mr.default.renameSync(n,e),mr.default.chmodSync(e,384)}function jd(t,e,n,r,s=[],i=[]){let o=Ha(),u=o[e]??{sessionId:e,projectId:t,title:n.slice(0,80),updatedAt:new Date().toISOString(),messages:[]};u.messages.push({role:"user",text:n.slice(0,
|
|
864
|
+
Allwright test-fix run`)}catch{A=!1}if(!A){let d=`The agent changed nothing - its own conclusion: ${w.resultText.trim().slice(0,400)||"(no explanation given)"}`;return l("info",d),{ok:!0,...S,remaining:o,note:d}}let j=await un(u,s);if(!j.ok){await Zr(u,b);let d=j.forbidden.length?`the fixed result touches protected paths (${j.forbidden.slice(0,5).join(", ")})`:`the fixed result is too large (${j.files} files, ${j.insertions+j.deletions} lines; limits ${on}/${an})`;return{ok:!1,...S,note:`Nothing was pushed: ${d}. The fix commit was discarded; the PR is unchanged.`}}let v=o,O,H,z=Wr(u);if(z){let d=Jr(Ba.default.readFileSync(z,"utf8"));if(d.length){l("info",`Re-running ${d.length} documented test command(s)`);let m=await sr(u,d,{perCommandTimeoutMs:15*6e4});for(let g of m)l(g.exitCode===0?"info":"warn",`${g.exitCode===0?"PASS":"FAIL"} ${g.command} (exit ${g.exitCode})`+(g.exitCode===0?"":`
|
|
865
|
+
${g.tail.slice(-1500)}`));v=m.filter(g=>g.exitCode!==0).slice(0,20).map(g=>({command:g.command.slice(0,500),exitCode:g.exitCode,tail:g.tail.slice(-4e3)})),H=m.length,O=m.length-v.length}}await er(u,r);let B=await tt(u);return l("info",`Pushed the fix to ${r} (${B.slice(0,7)})`),{ok:!0,...S,headSha:B,remaining:v,testsPassed:O,testsTotal:H,note:v.length?`The fix was pushed, but ${v.length} command(s) still fail - output is in the run log. The PR is the same one; review the new commit.`:"All documented test commands pass now. The PR is the same one - review the fix commit, then approve."}}catch(f){return{ok:!1,note:`Could not fix the tests: ${f instanceof Error?f.message.slice(0,300):String(f)}`}}finally{c&&(await vt(n,u).catch(()=>{}),Ba.default.rmSync(u,{recursive:!0,force:!0}))}}ut();var mr=I(require("node:fs"),1),$d=I(require("node:path"),1);var Uy=_.object({role:_.enum(["user","agent"]),text:_.string(),steps:_.array(_.string()).default([]),files:_.array(_.string()).default([])}),qy=_.object({sessionId:_.string(),projectId:_.string(),title:_.string().default(""),updatedAt:_.string(),messages:_.array(Uy).default([])}),Fy=_.record(qy),By=10,Ky=200,Ad=2e4,Hy=30,Zy=2e3,Gy=8,Vy=255;function Pd(){return $d.default.join(se(),"chat-sessions.json")}function Ha(){let t=Pd();if(!mr.default.existsSync(t))return{};try{return Fy.parse(JSON.parse(mr.default.readFileSync(t,"utf8")))}catch{return{}}}function Wy(t){mr.default.mkdirSync(se(),{recursive:!0,mode:448});let e=Pd(),n=e+".tmp";mr.default.writeFileSync(n,JSON.stringify(t,null,2)+`
|
|
866
|
+
`,{mode:384}),mr.default.renameSync(n,e),mr.default.chmodSync(e,384)}function jd(t,e,n,r,s=[],i=[]){let o=Ha(),u=o[e]??{sessionId:e,projectId:t,title:n.slice(0,80),updatedAt:new Date().toISOString(),messages:[]};u.messages.push({role:"user",text:n.slice(0,Ad),steps:[],files:i.slice(0,Gy).map(f=>f.slice(0,Vy))},{role:"agent",text:r.slice(0,Ad),steps:s.slice(0,Hy).map(f=>f.slice(0,Zy)),files:[]}),u.messages=u.messages.slice(-Ky),u.updatedAt=new Date().toISOString(),o[e]=u;let c=Object.values(o).filter(f=>f.projectId===u.projectId).sort((f,p)=>p.updatedAt.localeCompare(f.updatedAt));for(let f of c.slice(By))delete o[f.sessionId];Wy(o)}function Od(t){return Object.values(Ha()).filter(e=>e.projectId===t).sort((e,n)=>n.updatedAt.localeCompare(e.updatedAt)).map(e=>({sessionId:e.sessionId,title:e.title,updatedAt:e.updatedAt,messageCount:e.messages.length}))}function Os(t){return Ha()[t]??null}var Nd=36,Md=60;function zd(t){let e=t.toLowerCase();return e?e.includes("[1m]")||e.includes("-1m")?1e6:e.includes("haiku")||e.includes("sonnet")||e.includes("opus")||e.includes("fable")?2e5:0:0}var Jy=`This conversation is being COMPACTED: it continues in a fresh window that will only have your summary, so anything you leave out is gone. Summarize it now under these headings, in under 500 words total:
|
|
867
867
|
Goal: what the user is trying to achieve.
|
|
868
868
|
Decided: choices already made, including ones you talked them out of - each as one line.
|
|
869
869
|
Constraints: rules, preferences and corrections the user gave you.
|
|
@@ -883,10 +883,10 @@ TWO OPTIONAL BLOCKS, for the dashboard's benefit. Never mention them in your pro
|
|
|
883
883
|
\`\`\`
|
|
884
884
|
1 to 3 short suggestions, written AS THE USER (first person, imperative) - they are typed into the user's box, not yours. Skip the block entirely when nothing obvious follows; a wrong guess costs the user more than no guess.
|
|
885
885
|
Never emit both blocks in one reply, and never let either replace the actual answer.`;var gr=I(require("node:fs"),1),nt=I(require("node:path"),1),Za=300,Yy=4,Ud=512*1024,Xy=new Set([".git","node_modules","dist","build","out",".next","vendor","coverage",".venv","venv","__pycache__",".turbo",".cache"]),qd=/\.mdx?$/i;function Fd(t){let e=nt.default.resolve(t),n=[],r=(s,i)=>{if(i>Yy||n.length>=Za)return;let o;try{o=gr.default.readdirSync(s,{withFileTypes:!0})}catch{return}for(let l of o){if(n.length>=Za)return;if(!l.isFile()||!qd.test(l.name))continue;let u=nt.default.join(s,l.name);try{let c=gr.default.statSync(u);n.push({path:nt.default.relative(e,u).split(nt.default.sep).join("/"),sizeBytes:c.size,updatedAt:c.mtime.toISOString()})}catch{}}for(let l of o){if(n.length>=Za)return;!l.isDirectory()||l.isSymbolicLink()||Xy.has(l.name)||l.name.startsWith(".")||r(nt.default.join(s,l.name),i+1)}};return r(e,0),n}function Bd(t,e){let n=nt.default.resolve(t);if(!qd.test(e))return{ok:!1,error:"only markdown files can be opened here"};let r=nt.default.resolve(n,e);if(r!==n&&!r.startsWith(n+nt.default.sep))return{ok:!1,error:"that path is outside the project checkout"};let s;try{s=gr.default.realpathSync(r)}catch{return{ok:!1,error:"file not found in this checkout"}}let i=(()=>{try{return gr.default.realpathSync(n)}catch{return n}})();if(s!==i&&!s.startsWith(i+nt.default.sep))return{ok:!1,error:"that path links outside the project checkout"};let o;try{o=gr.default.statSync(s)}catch{return{ok:!1,error:"file not found in this checkout"}}if(!o.isFile())return{ok:!1,error:"that path is not a file"};try{let l=gr.default.readFileSync(s,"utf8"),u=Buffer.byteLength(l,"utf8")>Ud;return{ok:!0,path:nt.default.relative(i,s).split(nt.default.sep).join("/"),content:u?l.slice(0,Ud):l,truncated:u}}catch(l){return{ok:!1,error:l instanceof Error?l.message:"could not read the file"}}}var Ze=I(_e(),1);var Zi=I(require("node:fs"),1),Kd=I(require("node:path"),1);var Qy=_.object({id:_.string(),name:_.string().default(""),jiraProjectKey:_.string().default(""),repoName:_.string().default(""),jiraSiteUrl:_.string().default("")}),eb=_.array(Qy);function Hd(){return Kd.default.join(se(),"synced-projects.json")}function Zd(t){try{let e=t.map(n=>({id:n.id,name:n.name,jiraProjectKey:n.jiraProjectKey,repoName:n.repoName,jiraSiteUrl:n.jiraSiteUrl??""}));Zi.default.mkdirSync(se(),{recursive:!0}),Zi.default.writeFileSync(Hd(),JSON.stringify(e,null,2),{mode:384})}catch{}}function tb(){try{let t=eb.safeParse(JSON.parse(Zi.default.readFileSync(Hd(),"utf8")));return t.success?t.data:[]}catch{return[]}}function Gd(t){return tb().find(e=>e.repoName===t)??null}var Va=I(require("node:fs"),1),yr=I(require("node:path"),1),Vd=require("node:child_process"),br=I(_e(),1);var nb=15e4,Ga=(t,e,n,r="")=>({ok:!1,file:t,checks:[e],output:r,error:n});function rb(t){let e=yr.default.join(t,"node_modules",".bin","prisma");return Va.default.existsSync(e)?{bin:e,prefix:[]}:{bin:"npx",prefix:["--yes","prisma"]}}function sb(t,e){if(!(0,br.isSelfMigrationFilename)(e))return null;let n=yr.default.join(t,br.SELF_MIGRATION_DIR),r=yr.default.resolve(n,e),s=yr.default.relative(n,r);return s!==e||s.startsWith("..")||yr.default.isAbsolute(s)?null:r}async function Wd(t){let{file:e}=t,n=sb(t.repoPath,e);if(!n)return Ga(e,{name:"file",ok:!1,detail:`"${e}" is not a migration filename`,fix:[]},`"${e}" is not a migration filename`);if(!Va.default.existsSync(n))return Ga(e,{name:"file",ok:!1,detail:`${br.SELF_MIGRATION_DIR}/${e} does not exist in this checkout`,fix:[`cd ${t.repoPath} && git pull`]},`${br.SELF_MIGRATION_DIR}/${e} is not in this checkout - it may be newer than the code here`);let s=Ot(t.cfg,t.repoName,t.environmentName)[t.urlSecret]?.trim();if(!s)return Ga(e,{name:"database url",ok:!1,detail:`no ${t.urlSecret} in this runner's secret store for "${t.repoName}:${t.environmentName}" - the value stays on this machine`,fix:[`allwright env set ${t.repoName} ${t.environmentName} "${t.urlSecret}=postgresql://\u2026"`]},`this runner has no ${t.urlSecret} for "${t.environmentName}"`);let i=yr.default.join(t.repoPath,"apps","api"),{bin:o,prefix:l}=rb(i),u=Ua([s]),c=await ib(o,[...l,"db","execute","--url",s,"--file",n],i),f=u(c.output).slice(-8e3);return c.code!==0?{ok:!1,file:e,checks:[{name:"apply",ok:!1,detail:`prisma db execute exited ${c.code}`,fix:[`cd apps/api && npx prisma db execute --url "$DATABASE_URL" --file prisma/manual/${e}`]}],output:f,error:`applying ${e} failed (exit ${c.code})`}:{ok:!0,file:e,checks:[{name:"apply",ok:!0,detail:`${br.SELF_MIGRATION_DIR}/${e} applied`,fix:[]}],output:f,error:""}}function ib(t,e,n){return new Promise(r=>{(0,Vd.execFile)(t,e,{cwd:n,timeout:nb,maxBuffer:4*1024*1024,encoding:"utf8"},(s,i,o)=>{let l=[i,o].filter(Boolean).join(`
|
|
886
|
-
`).trim();if(!s)return r({code:0,output:l});let u=typeof s.code=="number"?s.code:1;r({code:u||1,output:l||s.message})})})}var Cv=I(Kh(),1),Iv=I(to(),1),Rv=I(ss(),1),Av=I(il(),1),Ev=I(ll(),1),$v=I(pl(),1),Qh=I(io(),1),Pv=I(Xh(),1);var gl=Qh.default;var Fs=I(require("node:crypto"),1),Ct=I(_e(),1);function jv(t){let e=t&&typeof t=="object"&&"name"in t?String(t.name):null;return e?`"${e}"`:"(unnamed)"}function yl(t,e,n,r){t.push(`dropped ${e} ${n} - this runner is out of date and does not understand it yet (${r}). Update the runner (npm install -g @ticketpilot/runner) to pick it up.`)}function Ov(t){if(!t||typeof t!="object"||t.type!=="config")return null;let e=t,n=[],r=[];for(let l of Array.isArray(e.projects)?e.projects:[]){let u=Ct.ProjectConfig.safeParse(l);u.success?r.push(u.data):yl(n,"project","",u.error.issues[0]?.message??"invalid shape")}let s=[];for(let l of Array.isArray(e.rules)?e.rules:[]){let u=Ct.RuleConfig.safeParse(l);u.success?s.push(u.data):yl(n,"rule",jv(l),u.error.issues[0]?.message??"invalid shape")}let i=[];for(let l of Array.isArray(e.environments)?e.environments:[]){let u=Ct.EnvironmentConfig.safeParse(l);u.success?i.push(u.data):yl(n,"environment","",u.error.issues[0]?.message??"invalid shape")}return{msg:{type:"config",projects:r,rules:s,environments:i,pollingPaused:typeof e.pollingPaused=="boolean"?e.pollingPaused:!1},warnings:n}}var Nv=2e4,Mv=6e4,zv=5e3,ao=class{constructor(e,n,r,s){this.wsUrl=e;this.runnerToken=n;this.meta=r;this.events=s}wsUrl;runnerToken;meta;events;ws=null;queue=[];pending=new Map;backoffMs=1e3;heartbeat=null;closed=!1;bootAnnounced=!1;start(){this.closed=!1,this.connect()}stop(){this.closed=!0,this.heartbeat&&clearInterval(this.heartbeat),this.ws?.close()}get connected(){return this.ws?.readyState===gl.OPEN}connect(){if(this.closed)return;y.info(`connecting to control plane at ${this.wsUrl}`);let e=new gl(this.wsUrl,{headers:{authorization:`Bearer ${this.runnerToken}`}});this.ws=e,e.on("open",()=>{this.backoffMs=1e3,this.sendNow({type:"hello",protocolVersion:Ct.PROTOCOL_VERSION,runnerVersion:this.meta.runnerVersion,platform:`${process.platform}/${process.arch} node${process.versions.node}`,justBooted:!this.bootAnnounced});let n=this.queue.splice(0,this.queue.length);for(let r of n)this.sendNow(r);this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=setInterval(()=>{this.send({type:"heartbeat",ts:new Date().toISOString()})},Nv)}),e.on("message",n=>{let r;try{r=JSON.parse(n.toString())}catch(i){y.warn(`ignoring malformed server message (bad JSON): ${i}`);return}let s;try{s=(0,Ct.parseServerMsg)(r)}catch(i){let o=Ov(r);if(!o){y.warn(`ignoring malformed server message: ${i}`);return}for(let l of o.warnings)y.warn(l);y.warn(`config push had ${o.warnings.length} ${o.warnings.length===1?"entry":"entries"} this runner doesn't understand - applied everything else instead of dropping the whole config`),s=o.msg}this.handle(s)}),e.on("close",n=>{if(this.heartbeat&&clearInterval(this.heartbeat),n===4001)y.error("control plane rejected this runner version (protocol mismatch). Update with: npm install -g @ticketpilot/runner");else if(n===4003){y.error("this runner has been revoked from the control plane UI. Re-enroll with a fresh token if this was not intended."),this.closed=!0;return}if(this.closed)return;let r=Math.random()*.3+.85,s=Math.round(this.backoffMs*r);y.warn(`disconnected (code ${n}); reconnecting in ${Math.round(s/1e3)}s`),setTimeout(()=>this.connect(),s),this.backoffMs=Math.min(this.backoffMs*2,Mv)}),e.on("error",n=>{y.warn(`websocket error: ${n.message}`)})}handle(e){if(e.type==="hello.ack"){this.bootAnnounced=!0,y.info(`connected as runner "${e.runnerName}" (${e.runnerId})`);return}if(e.type==="run.claim.result"||e.type==="deploy.claim.result"||e.type==="autopilot.next.result"){let n=this.pending.get(e.requestId);n&&(clearTimeout(n.timer),this.pending.delete(e.requestId),n.resolve(e));return}if(e.type==="config")return this.events.onConfig(e);if(e.type==="project.test")return this.events.onProjectTest(e);if(e.type==="rule.diagnose")return this.events.onRuleDiagnose(e);if(e.type==="run.cancel")return this.events.onCancel(e.runId);if(e.type==="run.approved")return this.events.onApproved(e.runId,e.headSha);if(e.type==="run.rejected")return this.events.onRejected(e.runId);if(e.type==="run.retryPush")return this.events.onRetryPush(e.runId);if(e.type==="deploy.start")return this.events.onDeployStart(e);if(e.type==="deploy.suggest")return this.events.onDeploySuggest(e);if(e.type==="deploy.fix")return this.events.onDeployFix(e);if(e.type==="env.preflight")return this.events.onEnvPreflight(e);if(e.type==="selfmigration.apply")return this.events.onSelfMigrationApply(e);if(e.type==="chat.turn")return this.events.onChatTurn(e);if(e.type==="chat.create.ticket")return this.events.onChatCreateTicket(e);if(e.type==="chat.list")return this.events.onChatList(e);if(e.type==="repo.docs")return this.events.onRepoDocs(e);if(e.type==="repo.doc.read")return this.events.onRepoDocRead(e);if(e.type==="chat.load")return this.events.onChatLoad(e);if(e.type==="board.fetch")return this.events.onBoardFetch(e);if(e.type==="board.trigger")return this.events.onBoardTrigger(e);if(e.type==="audit.start")return this.events.onAuditStart(e);if(e.type==="audit.list")return this.events.onAuditList(e);if(e.type==="audit.get")return this.events.onAuditGet(e);if(e.type==="audit.review")return this.events.onAuditReview(e);if(e.type==="knowledge.list")return this.events.onKnowledgeList(e);if(e.type==="knowledge.save")return this.events.onKnowledgeSave(e);if(e.type==="epic.list")return this.events.onEpicList(e);if(e.type==="epic.suggest")return this.events.onEpicSuggest(e);if(e.type==="team.creds")return this.events.onTeamCreds(e);if(e.type==="jira.users")return this.events.onJiraUsers(e);if(e.type==="setup.status")return this.events.onSetupStatus(e);if(e.type==="setup.claudemd.generate")return this.events.onSetupClaudeMdGenerate(e);if(e.type==="setup.claudemd.save")return this.events.onSetupClaudeMdSave(e);if(e.type==="repo.doc.save")return this.events.onRepoDocSave(e);if(e.type==="runner.update")return this.events.onRunnerUpdate(e);if(e.type==="agent.profiles")return this.events.onAgentProfiles(e);if(e.type==="run.resolve.conflict")return this.events.onResolveConflict(e);if(e.type==="run.testfix")return this.events.onTestFix(e);if(e.type==="run.answer")return this.events.onRunAnswer(e);if(e.type==="audit.stats")return this.events.onAuditStats(e)}sendNow(e){this.ws?.send(JSON.stringify(e))}send(e){if(this.connected){this.sendNow(e);return}if(this.queue.length>=zv){let n=this.queue.findIndex(r=>r.type==="run.log");n>=0?this.queue.splice(n,1):this.queue.shift()}this.queue.push(e)}async claimRun(e){if(!this.connected)return{accepted:!1,reason:"control plane offline"};let n=Fs.default.randomUUID(),r=await new Promise(s=>{let i=setTimeout(()=>{this.pending.delete(n),s(null)},15e3);this.pending.set(n,{resolve:s,timer:i}),this.sendNow({type:"run.claim",requestId:n,...e})});return!r||r.type!=="run.claim.result"?{accepted:!1,reason:"claim timed out"}:{accepted:r.accepted,runId:r.runId,reason:r.reason,claudeProfile:r.claudeProfile,actorEmail:r.actorEmail}}async requestAutopilotNext(){if(!this.connected)return null;let e=Fs.default.randomUUID(),n=await new Promise(r=>{let s=setTimeout(()=>{this.pending.delete(e),r(null)},15e3);this.pending.set(e,{resolve:r,timer:s}),this.sendNow({type:"autopilot.next",requestId:e})});return!n||n.type!=="autopilot.next.result"?null:{ok:n.ok,item:n.item,pausedUntil:n.pausedUntil}}sendAutopilotReport(e){this.send({type:"autopilot.report",requestId:Fs.default.randomUUID(),itemId:e.itemId,outcome:e.outcome,runId:e.runId??"",error:e.error??""})}async claimDeploy(e){if(!this.connected)return{accepted:!1,reason:"control plane offline"};let n=Fs.default.randomUUID(),r=await new Promise(s=>{let i=setTimeout(()=>{this.pending.delete(n),s(null)},15e3);this.pending.set(n,{resolve:s,timer:i}),this.sendNow({type:"deploy.claim",requestId:n,...e})});return!r||r.type!=="deploy.claim.result"?{accepted:!1,reason:"deploy authorization timed out"}:{accepted:r.accepted,runId:r.runId,environment:r.environment,reason:r.reason,code:r.code}}sendDeploySuggestResult(e,n){this.send({type:"deploy.suggest.result",requestId:e,...n,docPath:n.docPath??"",docContent:n.docContent??""})}sendChatTurnResult(e,n){this.send({type:"chat.turn.result",requestId:e,...n,inputTokens:n.inputTokens??0,outputTokens:n.outputTokens??0,cacheReadTokens:n.cacheReadTokens??0,costUsd:n.costUsd??0,model:n.model??"",contextTokens:n.contextTokens??0,contextLimit:n.contextLimit??0,compacted:n.compacted??!1,compactedMessages:n.compactedMessages??0})}sendChatCreateTicketResult(e,n){this.send({type:"chat.create.ticket.result",requestId:e,...n,childKeys:n.childKeys??[]})}sendChatListResult(e,n){this.send({type:"chat.list.result",requestId:e,sessions:n})}sendRepoDocsResult(e,n){this.send({type:"repo.docs.result",requestId:e,...n})}sendRepoDocReadResult(e,n){this.send({type:"repo.doc.read.result",requestId:e,...n})}sendChatLoadResult(e,n){this.send({type:"chat.load.result",requestId:e,...n,messages:n.messages.map(r=>({...r,steps:r.steps??[],files:r.files??[]}))})}sendBoardFetchResult(e,n){this.send({type:"board.fetch.result",requestId:e,...n,browseBaseUrl:n.browseBaseUrl??""})}sendAuditStartResult(e,n){this.send({type:"audit.start.result",requestId:e,...n})}sendAuditListResult(e,n){this.send({type:"audit.list.result",requestId:e,ok:n.ok,error:n.error,audits:(n.audits??[]).map(r=>({...r,detailLevel:r.detailLevel??"technical"}))})}sendAuditGetResult(e,n){this.send({type:"audit.get.result",requestId:e,...n})}sendAuditReviewResult(e,n){this.send({type:"audit.review.result",requestId:e,...n})}sendKnowledgeListResult(e,n){this.send({type:"knowledge.list.result",requestId:e,ok:n.ok,error:n.error,files:n.files??[]})}sendKnowledgeSaveResult(e,n){this.send({type:"knowledge.save.result",requestId:e,...n})}sendEpicListResult(e,n){this.send({type:"epic.list.result",requestId:e,ok:n.ok,error:n.error,epics:n.epics??[],children:n.children??[]})}sendEpicSuggestResult(e,n){this.send({type:"epic.suggest.result",requestId:e,ok:n.ok,error:n.error,issueKey:n.issueKey??"",reason:n.reason??"",considered:n.considered??0})}sendTeamCredsResult(e,n){this.send({type:"team.creds.result",requestId:e,ok:n.ok,error:n.error,githubShared:n.githubShared??!1,sharedGithubLogin:n.sharedGithubLogin??"",entries:n.entries??[]})}sendBoardTriggerResult(e,n){this.send({type:"board.trigger.result",requestId:e,...n})}sendAuditStatsResult(e,n){this.send({type:"audit.stats.result",requestId:e,ok:n.ok,error:n.error,byProject:n.byProject??{}})}sendRunnerUpdateResult(e,n){this.send({type:"runner.update.result",requestId:e,ok:n.ok,error:n.error,note:n.note??"",scheduled:n.scheduled??!1})}sendSetupClaudeMdGenerateResult(e,n){this.send({type:"setup.claudemd.generate.result",requestId:e,ok:n.ok,error:n.error,content:n.content??""})}sendSetupClaudeMdSaveResult(e,n){this.send({type:"setup.claudemd.save.result",requestId:e,ok:n.ok,error:n.error,note:n.note??""})}sendResolveConflictResult(e,n){this.send({type:"run.resolve.conflict.result",requestId:e,ok:n.ok,note:n.note??"",freeOfCharge:n.freeOfCharge??!1,headSha:n.headSha??"",costUsd:n.costUsd,inputTokens:n.inputTokens,outputTokens:n.outputTokens})}sendTestFixResult(e,n){this.send({type:"run.testfix.result",requestId:e,ok:n.ok,note:n.note??"",headSha:n.headSha??"",remaining:n.remaining??[],costUsd:n.costUsd,inputTokens:n.inputTokens,outputTokens:n.outputTokens})}sendRunAnswerResult(e,n){this.send({type:"run.answer.result",requestId:e,ok:n.ok,note:n.note??"",error:n.error})}sendAgentProfilesResult(e,n){this.send({type:"agent.profiles.result",requestId:e,ok:n.ok,error:n.error,profiles:n.profiles??[],defaultLoggedIn:n.defaultLoggedIn??!1,agentsWithoutProfiles:n.agentsWithoutProfiles??[]})}sendRepoDocSaveResult(e,n){this.send({type:"repo.doc.save.result",requestId:e,ok:n.ok,error:n.error,note:n.note??""})}sendSetupStatusResult(e,n){this.send({type:"setup.status.result",requestId:e,ok:n.ok,error:n.error,jiraConfigured:n.jiraConfigured??!1,jiraEmail:n.jiraEmail??"",claude:n.claude,githubTokenSet:n.githubTokenSet??!1,githubLogin:n.githubLogin??"",deploysEnabled:n.deploysEnabled??!1,jiraUserCount:n.jiraUserCount??0,repos:n.repos??[]})}sendEnvPreflightResult(e,n){this.send({type:"env.preflight.result",requestId:e,...n,checks:this.withFixDefaults(n.checks)})}sendSelfMigrationApplyResult(e,n){this.send({type:"selfmigration.apply.result",requestId:e,...n})}sendJiraUsersResult(e,n){this.send({type:"jira.users.result",requestId:e,...n})}withFixDefaults(e){return e.map(n=>({...n,kind:n.kind??"connection",fix:n.fix??[],fixNote:n.fixNote??""}))}sendProjectTestResult(e,n,r){this.send({type:"project.test.result",requestId:e,ok:n,checks:this.withFixDefaults(r)})}sendRuleDiagnoseResult(e,n){this.send({type:"rule.diagnose.result",requestId:e,...n,checks:this.withFixDefaults(n.checks)})}};var lo=I(require("node:fs"),1),cs=I(require("node:path"),1),tf=require("node:child_process"),Dv=/\.mdx?$/i,ef=6,Lv=/^[\w.\- ()]+$/;function Uv(t,e){let n=e.trim().replace(/\\/g,"/").replace(/^\.\//,"");if(!n)return{ok:!1,error:"empty path"};if(cs.default.isAbsolute(n))return{ok:!1,error:"path must be repo-relative"};if(!Dv.test(n))return{ok:!1,error:"only markdown files (.md) can be saved"};let r=n.split("/");if(r.length>ef)return{ok:!1,error:`path deeper than ${ef} levels`};for(let o of r)if(o==="."||o===".."||!Lv.test(o))return{ok:!1,error:`invalid path segment "${o}"`};if(r[0]===".git")return{ok:!1,error:"cannot write under .git"};let s=cs.default.resolve(t),i=cs.default.resolve(s,n);return i!==s&&!i.startsWith(s+cs.default.sep)?{ok:!1,error:"path escapes the checkout"}:{ok:!0,abs:i,rel:n}}async function bl(t){let e=Uv(t.repoPath,t.relPath);if(!e.ok)return{ok:!1,error:e.error};if(lo.default.existsSync(e.abs)&&!t.overwrite)return{ok:!1,error:`${e.rel} already exists in this checkout`};lo.default.mkdirSync(cs.default.dirname(e.abs),{recursive:!0}),lo.default.writeFileSync(e.abs,t.content.endsWith(`
|
|
886
|
+
`).trim();if(!s)return r({code:0,output:l});let u=typeof s.code=="number"?s.code:1;r({code:u||1,output:l||s.message})})})}var Cv=I(Kh(),1),Iv=I(to(),1),Rv=I(ss(),1),Ev=I(il(),1),Av=I(ll(),1),$v=I(pl(),1),Qh=I(io(),1),Pv=I(Xh(),1);var gl=Qh.default;var Fs=I(require("node:crypto"),1),Ct=I(_e(),1);function jv(t){let e=t&&typeof t=="object"&&"name"in t?String(t.name):null;return e?`"${e}"`:"(unnamed)"}function yl(t,e,n,r){t.push(`dropped ${e} ${n} - this runner is out of date and does not understand it yet (${r}). Update the runner (npm install -g @ticketpilot/runner) to pick it up.`)}function Ov(t){if(!t||typeof t!="object"||t.type!=="config")return null;let e=t,n=[],r=[];for(let l of Array.isArray(e.projects)?e.projects:[]){let u=Ct.ProjectConfig.safeParse(l);u.success?r.push(u.data):yl(n,"project","",u.error.issues[0]?.message??"invalid shape")}let s=[];for(let l of Array.isArray(e.rules)?e.rules:[]){let u=Ct.RuleConfig.safeParse(l);u.success?s.push(u.data):yl(n,"rule",jv(l),u.error.issues[0]?.message??"invalid shape")}let i=[];for(let l of Array.isArray(e.environments)?e.environments:[]){let u=Ct.EnvironmentConfig.safeParse(l);u.success?i.push(u.data):yl(n,"environment","",u.error.issues[0]?.message??"invalid shape")}return{msg:{type:"config",projects:r,rules:s,environments:i,pollingPaused:typeof e.pollingPaused=="boolean"?e.pollingPaused:!1},warnings:n}}var Nv=2e4,Mv=6e4,zv=5e3,ao=class{constructor(e,n,r,s){this.wsUrl=e;this.runnerToken=n;this.meta=r;this.events=s}wsUrl;runnerToken;meta;events;ws=null;queue=[];pending=new Map;backoffMs=1e3;heartbeat=null;closed=!1;bootAnnounced=!1;start(){this.closed=!1,this.connect()}stop(){this.closed=!0,this.heartbeat&&clearInterval(this.heartbeat),this.ws?.close()}get connected(){return this.ws?.readyState===gl.OPEN}connect(){if(this.closed)return;y.info(`connecting to control plane at ${this.wsUrl}`);let e=new gl(this.wsUrl,{headers:{authorization:`Bearer ${this.runnerToken}`}});this.ws=e,e.on("open",()=>{this.backoffMs=1e3,this.sendNow({type:"hello",protocolVersion:Ct.PROTOCOL_VERSION,runnerVersion:this.meta.runnerVersion,platform:`${process.platform}/${process.arch} node${process.versions.node}`,justBooted:!this.bootAnnounced});let n=this.queue.splice(0,this.queue.length);for(let r of n)this.sendNow(r);this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=setInterval(()=>{this.send({type:"heartbeat",ts:new Date().toISOString()})},Nv)}),e.on("message",n=>{let r;try{r=JSON.parse(n.toString())}catch(i){y.warn(`ignoring malformed server message (bad JSON): ${i}`);return}let s;try{s=(0,Ct.parseServerMsg)(r)}catch(i){let o=Ov(r);if(!o){y.warn(`ignoring malformed server message: ${i}`);return}for(let l of o.warnings)y.warn(l);y.warn(`config push had ${o.warnings.length} ${o.warnings.length===1?"entry":"entries"} this runner doesn't understand - applied everything else instead of dropping the whole config`),s=o.msg}this.handle(s)}),e.on("close",n=>{if(this.heartbeat&&clearInterval(this.heartbeat),n===4001)y.error("control plane rejected this runner version (protocol mismatch). Update with: npm install -g @ticketpilot/runner");else if(n===4003){y.error("this runner has been revoked from the control plane UI. Re-enroll with a fresh token if this was not intended."),this.closed=!0;return}if(this.closed)return;let r=Math.random()*.3+.85,s=Math.round(this.backoffMs*r);y.warn(`disconnected (code ${n}); reconnecting in ${Math.round(s/1e3)}s`),setTimeout(()=>this.connect(),s),this.backoffMs=Math.min(this.backoffMs*2,Mv)}),e.on("error",n=>{y.warn(`websocket error: ${n.message}`)})}handle(e){if(e.type==="hello.ack"){this.bootAnnounced=!0,y.info(`connected as runner "${e.runnerName}" (${e.runnerId})`);return}if(e.type==="run.claim.result"||e.type==="deploy.claim.result"||e.type==="autopilot.next.result"){let n=this.pending.get(e.requestId);n&&(clearTimeout(n.timer),this.pending.delete(e.requestId),n.resolve(e));return}if(e.type==="config")return this.events.onConfig(e);if(e.type==="project.test")return this.events.onProjectTest(e);if(e.type==="rule.diagnose")return this.events.onRuleDiagnose(e);if(e.type==="run.cancel")return this.events.onCancel(e.runId);if(e.type==="run.approved")return this.events.onApproved(e.runId,e.headSha);if(e.type==="run.rejected")return this.events.onRejected(e.runId);if(e.type==="run.retryPush")return this.events.onRetryPush(e.runId);if(e.type==="deploy.start")return this.events.onDeployStart(e);if(e.type==="deploy.suggest")return this.events.onDeploySuggest(e);if(e.type==="deploy.fix")return this.events.onDeployFix(e);if(e.type==="env.preflight")return this.events.onEnvPreflight(e);if(e.type==="selfmigration.apply")return this.events.onSelfMigrationApply(e);if(e.type==="chat.turn")return this.events.onChatTurn(e);if(e.type==="chat.create.ticket")return this.events.onChatCreateTicket(e);if(e.type==="chat.list")return this.events.onChatList(e);if(e.type==="repo.docs")return this.events.onRepoDocs(e);if(e.type==="repo.doc.read")return this.events.onRepoDocRead(e);if(e.type==="chat.load")return this.events.onChatLoad(e);if(e.type==="board.fetch")return this.events.onBoardFetch(e);if(e.type==="board.trigger")return this.events.onBoardTrigger(e);if(e.type==="audit.start")return this.events.onAuditStart(e);if(e.type==="audit.list")return this.events.onAuditList(e);if(e.type==="audit.get")return this.events.onAuditGet(e);if(e.type==="audit.review")return this.events.onAuditReview(e);if(e.type==="knowledge.list")return this.events.onKnowledgeList(e);if(e.type==="knowledge.save")return this.events.onKnowledgeSave(e);if(e.type==="epic.list")return this.events.onEpicList(e);if(e.type==="epic.suggest")return this.events.onEpicSuggest(e);if(e.type==="team.creds")return this.events.onTeamCreds(e);if(e.type==="jira.users")return this.events.onJiraUsers(e);if(e.type==="setup.status")return this.events.onSetupStatus(e);if(e.type==="setup.claudemd.generate")return this.events.onSetupClaudeMdGenerate(e);if(e.type==="setup.claudemd.save")return this.events.onSetupClaudeMdSave(e);if(e.type==="repo.doc.save")return this.events.onRepoDocSave(e);if(e.type==="runner.update")return this.events.onRunnerUpdate(e);if(e.type==="agent.profiles")return this.events.onAgentProfiles(e);if(e.type==="run.resolve.conflict")return this.events.onResolveConflict(e);if(e.type==="run.testfix")return this.events.onTestFix(e);if(e.type==="run.answer")return this.events.onRunAnswer(e);if(e.type==="audit.stats")return this.events.onAuditStats(e)}sendNow(e){this.ws?.send(JSON.stringify(e))}send(e){if(this.connected){this.sendNow(e);return}if(this.queue.length>=zv){let n=this.queue.findIndex(r=>r.type==="run.log");n>=0?this.queue.splice(n,1):this.queue.shift()}this.queue.push(e)}async claimRun(e){if(!this.connected)return{accepted:!1,reason:"control plane offline"};let n=Fs.default.randomUUID(),r=await new Promise(s=>{let i=setTimeout(()=>{this.pending.delete(n),s(null)},15e3);this.pending.set(n,{resolve:s,timer:i}),this.sendNow({type:"run.claim",requestId:n,...e})});return!r||r.type!=="run.claim.result"?{accepted:!1,reason:"claim timed out"}:{accepted:r.accepted,runId:r.runId,reason:r.reason,claudeProfile:r.claudeProfile,actorEmail:r.actorEmail}}async requestAutopilotNext(){if(!this.connected)return null;let e=Fs.default.randomUUID(),n=await new Promise(r=>{let s=setTimeout(()=>{this.pending.delete(e),r(null)},15e3);this.pending.set(e,{resolve:r,timer:s}),this.sendNow({type:"autopilot.next",requestId:e})});return!n||n.type!=="autopilot.next.result"?null:{ok:n.ok,item:n.item,pausedUntil:n.pausedUntil}}sendAutopilotReport(e){this.send({type:"autopilot.report",requestId:Fs.default.randomUUID(),itemId:e.itemId,outcome:e.outcome,runId:e.runId??"",error:e.error??""})}async claimDeploy(e){if(!this.connected)return{accepted:!1,reason:"control plane offline"};let n=Fs.default.randomUUID(),r=await new Promise(s=>{let i=setTimeout(()=>{this.pending.delete(n),s(null)},15e3);this.pending.set(n,{resolve:s,timer:i}),this.sendNow({type:"deploy.claim",requestId:n,...e})});return!r||r.type!=="deploy.claim.result"?{accepted:!1,reason:"deploy authorization timed out"}:{accepted:r.accepted,runId:r.runId,environment:r.environment,reason:r.reason,code:r.code}}sendDeploySuggestResult(e,n){this.send({type:"deploy.suggest.result",requestId:e,...n,docPath:n.docPath??"",docContent:n.docContent??""})}sendChatTurnResult(e,n){this.send({type:"chat.turn.result",requestId:e,...n,inputTokens:n.inputTokens??0,outputTokens:n.outputTokens??0,cacheReadTokens:n.cacheReadTokens??0,costUsd:n.costUsd??0,model:n.model??"",contextTokens:n.contextTokens??0,contextLimit:n.contextLimit??0,compacted:n.compacted??!1,compactedMessages:n.compactedMessages??0})}sendChatCreateTicketResult(e,n){this.send({type:"chat.create.ticket.result",requestId:e,...n,childKeys:n.childKeys??[]})}sendChatListResult(e,n){this.send({type:"chat.list.result",requestId:e,sessions:n})}sendRepoDocsResult(e,n){this.send({type:"repo.docs.result",requestId:e,...n})}sendRepoDocReadResult(e,n){this.send({type:"repo.doc.read.result",requestId:e,...n})}sendChatLoadResult(e,n){this.send({type:"chat.load.result",requestId:e,...n,messages:n.messages.map(r=>({...r,steps:r.steps??[],files:r.files??[]}))})}sendBoardFetchResult(e,n){this.send({type:"board.fetch.result",requestId:e,...n,browseBaseUrl:n.browseBaseUrl??""})}sendAuditStartResult(e,n){this.send({type:"audit.start.result",requestId:e,...n})}sendAuditListResult(e,n){this.send({type:"audit.list.result",requestId:e,ok:n.ok,error:n.error,audits:(n.audits??[]).map(r=>({...r,detailLevel:r.detailLevel??"technical"}))})}sendAuditGetResult(e,n){this.send({type:"audit.get.result",requestId:e,...n})}sendAuditReviewResult(e,n){this.send({type:"audit.review.result",requestId:e,...n})}sendKnowledgeListResult(e,n){this.send({type:"knowledge.list.result",requestId:e,ok:n.ok,error:n.error,files:n.files??[]})}sendKnowledgeSaveResult(e,n){this.send({type:"knowledge.save.result",requestId:e,...n})}sendEpicListResult(e,n){this.send({type:"epic.list.result",requestId:e,ok:n.ok,error:n.error,epics:n.epics??[],children:n.children??[]})}sendEpicSuggestResult(e,n){this.send({type:"epic.suggest.result",requestId:e,ok:n.ok,error:n.error,issueKey:n.issueKey??"",reason:n.reason??"",considered:n.considered??0})}sendTeamCredsResult(e,n){this.send({type:"team.creds.result",requestId:e,ok:n.ok,error:n.error,githubShared:n.githubShared??!1,sharedGithubLogin:n.sharedGithubLogin??"",entries:n.entries??[]})}sendBoardTriggerResult(e,n){this.send({type:"board.trigger.result",requestId:e,...n})}sendAuditStatsResult(e,n){this.send({type:"audit.stats.result",requestId:e,ok:n.ok,error:n.error,byProject:n.byProject??{}})}sendRunnerUpdateResult(e,n){this.send({type:"runner.update.result",requestId:e,ok:n.ok,error:n.error,note:n.note??"",scheduled:n.scheduled??!1})}sendSetupClaudeMdGenerateResult(e,n){this.send({type:"setup.claudemd.generate.result",requestId:e,ok:n.ok,error:n.error,content:n.content??""})}sendSetupClaudeMdSaveResult(e,n){this.send({type:"setup.claudemd.save.result",requestId:e,ok:n.ok,error:n.error,note:n.note??""})}sendResolveConflictResult(e,n){this.send({type:"run.resolve.conflict.result",requestId:e,ok:n.ok,note:n.note??"",freeOfCharge:n.freeOfCharge??!1,headSha:n.headSha??"",costUsd:n.costUsd,inputTokens:n.inputTokens,outputTokens:n.outputTokens})}sendTestFixResult(e,n){this.send({type:"run.testfix.result",requestId:e,ok:n.ok,note:n.note??"",headSha:n.headSha??"",remaining:n.remaining??[],costUsd:n.costUsd,inputTokens:n.inputTokens,outputTokens:n.outputTokens})}sendRunAnswerResult(e,n){this.send({type:"run.answer.result",requestId:e,ok:n.ok,note:n.note??"",error:n.error})}sendAgentProfilesResult(e,n){this.send({type:"agent.profiles.result",requestId:e,ok:n.ok,error:n.error,profiles:n.profiles??[],defaultLoggedIn:n.defaultLoggedIn??!1,agentsWithoutProfiles:n.agentsWithoutProfiles??[]})}sendRepoDocSaveResult(e,n){this.send({type:"repo.doc.save.result",requestId:e,ok:n.ok,error:n.error,note:n.note??""})}sendSetupStatusResult(e,n){this.send({type:"setup.status.result",requestId:e,ok:n.ok,error:n.error,jiraConfigured:n.jiraConfigured??!1,jiraEmail:n.jiraEmail??"",claude:n.claude,githubTokenSet:n.githubTokenSet??!1,githubLogin:n.githubLogin??"",deploysEnabled:n.deploysEnabled??!1,jiraUserCount:n.jiraUserCount??0,repos:n.repos??[]})}sendEnvPreflightResult(e,n){this.send({type:"env.preflight.result",requestId:e,...n,checks:this.withFixDefaults(n.checks)})}sendSelfMigrationApplyResult(e,n){this.send({type:"selfmigration.apply.result",requestId:e,...n})}sendJiraUsersResult(e,n){this.send({type:"jira.users.result",requestId:e,...n})}withFixDefaults(e){return e.map(n=>({...n,kind:n.kind??"connection",fix:n.fix??[],fixNote:n.fixNote??""}))}sendProjectTestResult(e,n,r){this.send({type:"project.test.result",requestId:e,ok:n,checks:this.withFixDefaults(r)})}sendRuleDiagnoseResult(e,n){this.send({type:"rule.diagnose.result",requestId:e,...n,checks:this.withFixDefaults(n.checks)})}};var lo=I(require("node:fs"),1),cs=I(require("node:path"),1),tf=require("node:child_process"),Dv=/\.mdx?$/i,ef=6,Lv=/^[\w.\- ()]+$/;function Uv(t,e){let n=e.trim().replace(/\\/g,"/").replace(/^\.\//,"");if(!n)return{ok:!1,error:"empty path"};if(cs.default.isAbsolute(n))return{ok:!1,error:"path must be repo-relative"};if(!Dv.test(n))return{ok:!1,error:"only markdown files (.md) can be saved"};let r=n.split("/");if(r.length>ef)return{ok:!1,error:`path deeper than ${ef} levels`};for(let o of r)if(o==="."||o===".."||!Lv.test(o))return{ok:!1,error:`invalid path segment "${o}"`};if(r[0]===".git")return{ok:!1,error:"cannot write under .git"};let s=cs.default.resolve(t),i=cs.default.resolve(s,n);return i!==s&&!i.startsWith(s+cs.default.sep)?{ok:!1,error:"path escapes the checkout"}:{ok:!0,abs:i,rel:n}}async function bl(t){let e=Uv(t.repoPath,t.relPath);if(!e.ok)return{ok:!1,error:e.error};if(lo.default.existsSync(e.abs)&&!t.overwrite)return{ok:!1,error:`${e.rel} already exists in this checkout`};lo.default.mkdirSync(cs.default.dirname(e.abs),{recursive:!0}),lo.default.writeFileSync(e.abs,t.content.endsWith(`
|
|
887
887
|
`)?t.content:t.content+`
|
|
888
|
-
`);let n=s=>new Promise((i,o)=>{(0,tf.execFile)("git",["-C",t.repoPath,...s],{timeout:12e4},(l,u,c)=>l?o(new Error(c||l.message)):i())}),r="";try{await n(["add",e.rel]),await n(["-c","user.name=Allwright","-c","user.email=runner@allwright.local","commit","-m",t.commitMessage]);try{await n(["push"]),r="committed and pushed to the repo"}catch(s){r="committed locally, but push failed: "+(s instanceof Error?s.message.slice(0,200):"unknown")+" - push it from the server when convenient"}}catch(s){r="file written, but commit failed: "+(s instanceof Error?s.message.slice(0,200):"unknown")+" - commit it from the server when convenient"}return{ok:!0,note:r}}var Tr=I(require("node:fs"),1),vl=I(require("node:path"),1),uo=require("node:child_process"),rf=require("node:util");nr();wt();var sf=I(_e(),1),nf=(0,rf.promisify)(uo.execFile);function qv(t){try{return new URL(t).host}catch{return t}}function Fv(t){try{return(0,uo.execFileSync)("git",["-C",t,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim()}catch{return null}}async function co(t,e,n=[],r){let s=[],i=t.repos[e.repoName]?.jira,o=i??t.jira,l=(e.jiraSiteUrl??"").trim().toLowerCase();if(!o)s.push({name:"jira-credentials",ok:!1,detail:"no Jira credentials configured on this runner"});else if(!l)s.push({name:"jira-site",ok:!1,detail:"this project has not said which Atlassian site it is on, so nothing here can be verified - a credential that authenticates somewhere else would look like a pass.",fixNote:"This one is fixed in the dashboard, not on the server: open the project and fill in its Atlassian site (for example yourcompany.atlassian.net), then run this test again."});else{let p=qv(o.baseUrl),b=i?"this repo's own Jira credential":"the runner-wide Jira credential";if(p!==l)s.push({name:"jira-site",ok:!1,detail:`this project is on ${l}, but ${b} is for ${p}.`,fix:[`allwright jira set "${e.repoName}"`],fixNote:`"${e.repoName}" in that command is this project's REPO NAME - the label that ties the project here to a checkout on the server (the same one used with allwright repo add). Not the Jira key, not a folder path. The command asks for three things for ${l}: the base URL (https://${l}), your Jira account email, and an API token from id.atlassian.com/manage-profile/security/api-tokens. They are stored on this server only. Restart afterwards: allwright stop && allwright start`});else{let w=new Pe(o);try{let S=await w.myself();s.push({name:"jira-auth",ok:!0,detail:`authenticated as ${S.displayName} on ${p} (${b})`});try{await w.search(`project = "${e.jiraProjectKey}" ORDER BY created DESC`,1),s.push({name:"jira-project",ok:!0,detail:`project ${e.jiraProjectKey} is readable on ${p}`})}catch(x){s.push({name:"jira-project",ok:!1,detail:`cannot read project ${e.jiraProjectKey} on ${p}: ${Bs(x)}`})}}catch(S){s.push({name:"jira-auth",ok:!1,detail:`Jira auth failed on ${p}: ${Bs(S)}`})}}}let u=t.repos[e.repoName];if(u&&Tr.default.existsSync(u.path)){let p=vl.default.join(u.path,"CLAUDE.md"),b=Tr.default.existsSync(p)&&Tr.default.readFileSync(p,"utf8").trim().length>0;s.push({name:"memory-file",kind:"content",ok:b,detail:b?"CLAUDE.md present - the agent has project memory":"MISSING: CLAUDE.md at the repo root. Rules can't be enabled until the project has a memory file - it is what makes every run smarter than the last.",...b?{}:{fixNote:"No command needed: the setup step below this one drafts CLAUDE.md by reading the repo, shows it to you, and commits it when you approve. Writing it by hand works too - any honest description of what the project is and how it is built beats an empty file."}});let w=Fi(u.path);s.push({name:"deploy-doc",kind:"content",ok:w!==null,detail:w?`${w.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.",...w?{}:{fixNote:"Only needed if this project will deploy from Allwright. The setup wizard can draft DEPLOY.md the same way it drafts CLAUDE.md - describe how you deploy today (the commands you actually run), and the agent proposes steps a human saves. Skip it if you only want tickets to become pull requests."}})}if(!u)s.push({name:"repo-path",ok:!1,detail:`no local path mapped for repo "${e.repoName}" - run: allwright repo add "${e.repoName}" /path/to/checkout`});else if(!Tr.default.existsSync(u.path))s.push({name:"repo-path",ok:!1,detail:`path does not exist: ${u.path}`});else{let p=Tr.default.existsSync(vl.default.join(u.path,".git"));s.push({name:"repo-path",ok:!0,detail:`${u.path}${p?" (git checkout)":" (warning: not a git checkout)"}`})}let c=[...new Set([e.defaultAgent||"claude-code",...r??[]])];for(let p of c){let b=Ue(t,p),w=p==="claude-code"?"claude-code":`agent:${p}`;try{let{stdout:S}=await nf(b,["--version"],{timeout:15e3});s.push({name:w,ok:!0,detail:S.trim().slice(0,100)})}catch(S){s.push({name:w,ok:!1,detail:`cannot run "${b}" for agent "${p}": ${Bs(S)}`,fixNote:p==="claude-code"?"Install Claude Code on this server (npm install -g @anthropic-ai/claude-code) and log it in.":`Install the "${p}" CLI on this server, or point the runner at its binary in the config's agents section.`})}}try{let{stdout:p}=await nf("git",["--version"],{timeout:15e3});s.push({name:"git",ok:!0,detail:p.trim().slice(0,100)})}catch(p){s.push({name:"git",ok:!1,detail:`cannot run git: ${Bs(p)}`})}let f=Ee(t,e.repoName);if(!f)s.push({name:"github-token",ok:!1,detail:`no GitHub token applies to "${e.repoName}" - implement rules cannot push.`,fix:[`allwright github set "${e.repoName}"`,"allwright github set-token"],fixNote:`"${e.repoName}" is this project's REPO NAME - the same label used with allwright repo add, not a folder path. The first command stores a token for this repo alone (separately revocable); the second stores one shared by every repo on this server. Both print the exact permission checklist before asking. In short: create it at ${sf.GITHUB_TOKEN_PERMISSIONS.where}, with the RESOURCE OWNER set to the org that owns the repo (the usual mistake), Contents and Pull requests both Read and write.`});else try{let{GitHubClient:p}=await Promise.resolve().then(()=>(ut(),or)),b=new p(f),w=await b.whoami(),S=u&&Tr.default.existsSync(u.path)?Fv(u.path):null,x=S?at(S):null;if(!x)s.push({name:"github-token",ok:!0,detail:`authenticated as ${w} - repo access not checked (no local checkout yet)`});else{let E=await b.repoAccess(x.owner,x.repo);s.push({name:"github-token",ok:E.ok&&E.canPush,detail:E.ok?E.canPush?`${w} has push access to ${x.owner}/${x.repo}`:`${w} can read ${x.owner}/${x.repo} but NOT push to it - implement rules will fail at the push`:`${w} cannot see ${x.owner}/${x.repo}: ${E.error}`,...E.ok&&E.canPush?{}:{fix:[`allwright github set "${e.repoName}"`],fixNote:`Two ways: edit the existing PAT on GitHub and add ${x.owner}/${x.repo} to it with contents:write and pull_requests:write - or give this repo its own token with the command above. A fine-grained PAT only ever covers ONE organisation, so a repo in a different org than your other projects always needs its own.`}})}}catch(p){s.push({name:"github-token",ok:!1,detail:Bs(p)})}if(n.length){t.deploy.enabled?s.push({name:"deploy",ok:!0,detail:"deployments enabled on this runner"}):s.push({name:"deploy",ok:!1,detail:"deployments are disabled on this runner - run `allwright deploy enable` to allow it to execute your saved deploy steps"});for(let p of n){let b=Ot(t,e.repoName,p.name),w=p.requiredSecrets.filter(S=>!b[S]&&!process.env[S]);s.push({name:`env:${p.name}`,ok:w.length===0,detail:w.length?`missing secret(s): ${w.join(", ")} - allwright env set "${e.repoName}" "${p.name}" ${w[0]}=...`:`${p.steps.length} step(s), ${p.requiredSecrets.length} secret(s) present`+(p.branch?`, deploys origin/${p.branch}`:"")})}}return s}function Bs(t){return(t instanceof Error?t.message:String(t)).slice(0,300)}var Te=new Ll;Te.name("allwright").description("Allwright runner - runs on YOUR machine, holds YOUR credentials locally, connects outbound-only to the control plane. Your Jira token, Anthropic key and source code never leave this host.").version(yi);function hf(t){y.info(`Create the token at ${Ze.GITHUB_TOKEN_PERMISSIONS.where}`);for(let e of Ze.GITHUB_TOKEN_PERMISSIONS.steps)y.info(` - ${e}`);y.info(Ze.GITHUB_TOKEN_PERMISSIONS.note),y.info(`Then paste it below for ${t}.`)}Te.command("init").description("Interactive setup: enroll this runner and store credentials locally").option("--cp-url <url>","control plane URL").option("--enroll-token <token>","enrolment token from the Allwright UI").option("--name <name>","runner name",wl.default.hostname()).option("--jira-url <url>","Jira base URL, e.g. https://yourorg.atlassian.net").option("--jira-email <email>","Jira account email").option("--jira-token <token>","Jira API token (stored locally only)").action(async t=>{let e=yn.default.createInterface({input:process.stdin,output:process.stdout}),n=async(r,s,i=!1)=>{if(s)return s;let o=await e.question(`${r}: `);if(!o.trim())throw new Error(`${r} is required`);return o.trim()};try{let r=await n("Control plane URL",t.cpUrl),s=await n("Enrolment token (from the web UI)",t.enrollToken),i=await n("Jira base URL (https://yourorg.atlassian.net)",t.jiraUrl),o=await n("Jira account email",t.jiraEmail),l=await n("Jira API token (create at id.atlassian.com/manage-profile/security/api-tokens)",t.jiraToken,!0),u=jo.parse({controlPlaneUrl:r,runnerName:t.name,jira:{baseUrl:i,email:o,apiToken:l}}),c=await new Pe(u.jira).myself();y.info(`Jira credential OK - authenticated as ${c.displayName}`),u=await ju(u,s),y.info(`Enrolled as runner "${u.runnerName}" (${u.runnerId})`),y.info(`Credentials saved to ${jt()} (mode 600, this machine only)`),y.info("Next: map your repo with `allwright repo add <repoName> <localPath>`, then `allwright start`")}finally{e.close()}});var _l=Te.command("repo").description("Map control-plane repo names to local checkouts");_l.command("add <repoName> <localPath>").description("Map a repo name (as configured in the web UI) to a local checkout path").action(async(t,e)=>{let n=ie();n.repos[t]={path:e},ge(n),y.info(`mapped repo "${t}" -> ${e}`);try{let{originUrl:r}=await Promise.resolve().then(()=>(wt(),qu));y.info(` origin remote: ${await r(e)} - make sure this is the repo you meant`)}catch{y.warn(` could not read an origin remote at ${e} - is it a git checkout?`)}gn()});_l.command("list").description("Show configured repo mappings").action(()=>{let t=ie(),e=Object.entries(t.repos);if(!e.length)return y.info("no repos mapped yet");for(let[n,r]of e)y.info(`${n} -> ${r.path}`)});var ff=Te.command("claude").description("Per-user Claude login profiles - each teammate's runs bill their OWN Claude account");ff.command("login <profileName>").description("Create (or re-login) a named Claude profile. Opens Claude Code interactively with its own config directory - have the PERSON WHOSE ACCOUNT IT IS complete the /login flow with their credentials, then exit. Assign the profile to their user on the dashboard's Team page.").action(async t=>{if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new Error("profile name: letters, digits, dots, dashes and underscores only");let e=ie(),n=e.claudeProfiles[t]?.configDir??`${jt().replace(/runner\.json$/,"")}claude-profiles/${t}`;ft.default.mkdirSync(n,{recursive:!0,mode:448}),e.claudeProfiles[t]={configDir:n},ge(e),y.info(`profile "${t}" -> ${n}`),y.info("Opening Claude Code with this profile. In it: run /login, complete the browser flow"),y.info("with the account this profile belongs to, then exit Claude (ctrl+c twice or /exit).");let r=(0,Gt.spawn)(e.claudeBin,[],{env:{...process.env,CLAUDE_CONFIG_DIR:n},stdio:"inherit"});await new Promise(s=>r.on("exit",()=>s())),y.info(`Done. Assign it on the dashboard: Team -> the user -> Claude profile = "${t}".`),gn()});ff.command("list").description("Show configured Claude profiles and whether each looks logged in").action(()=>{let t=ie(),e=Object.entries(t.claudeProfiles);if(y.info("default: this OS user's own Claude login (no profile)"),!e.length)return y.info("no named profiles yet - allwright claude login <name>");for(let[n,r]of e){let s=ft.default.existsSync(r.configDir)&&ft.default.readdirSync(r.configDir).length>0;y.info(`${n} -> ${r.configDir} ${s?"(logged in)":"(NOT logged in yet)"}`)}});_l.command("remove <repoName>").description("Unmap a repo from this runner: removes the mapping plus its per-repo Jira/GitHub overrides and env secrets from the config. Does NOT touch the checkout on disk or anything in the control plane - delete the project on the dashboard separately.").action(t=>{let e=ie();if(!e.repos[t]){let i=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${t}" - mapped repos: ${i}`)}let n=e.repos[t].path;delete e.repos[t];let r=Object.keys(e.environments).filter(i=>i.startsWith(`${t}:`));for(let i of r)delete e.environments[i];let s=e.auditSchedules.length;e.auditSchedules=e.auditSchedules.filter(i=>i.repoName!==t),ge(e),y.info(`Removed "${t}" (was ${n})`),r.length&&y.info(`Also removed ${r.length} environment secret set(s): ${r.join(", ")}`),e.auditSchedules.length!==s&&y.info("Also removed its audit schedule(s)"),y.info("The checkout on disk was NOT touched - remove it yourself if you want it gone."),y.info("Restart the runner to apply. Dashboard project (if any) is deleted separately there.")});var kl=Te.command("service").description("Run the runner as a system service (starts on boot, restarts on crash)");kl.command("install").description("Install + start the systemd service - detects node, this script, your user and home; no hand-written unit files. Run with sudo. (--print shows the unit without installing.)").option("--print","print the generated unit file and exit").action(t=>{if(t.print){y.info(`
|
|
889
|
-
`+ua(la()));return}Vu(y)});kl.command("uninstall").description("Stop and remove the systemd service (config/credentials untouched)").action(()=>Wu(y));kl.command("status").description("systemctl status for the runner service").action(()=>{(0,Gt.spawn)("systemctl",["status","allwright","--no-pager"],{stdio:"inherit"}).on("exit",e=>process.exit(e??0))});Te.command("update").description("Update the runner to the latest published version (npm install -g allwright@latest). Restart the runner afterwards - and only when no runs are active.").action(async()=>{y.info("Updating: npm install -g allwright@latest");let t=(0,Gt.spawn)("npm",["install","-g","allwright@latest"],{stdio:"inherit"});await new Promise((e,n)=>{t.on("exit",r=>r===0?e():n(new Error(`npm exited with code ${r}`))),t.on("error",n)}),y.info("Updated. Restart the runner service to load the new version (check active runs first).")});var hs=Te.command("jira").description("Per-repo Jira site overrides - for projects living on a different Atlassian site");hs.command("set <repoName>").description("Store Jira credentials for ONE repo's project (e.g. a project on a different *.atlassian.net site than the runner's main credential). Prompts on stdin; stored locally only, like every other credential.").action(async t=>{let e=ie();if(!e.repos[t]){let l=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${t}" - mapped repos: ${l}. Run \`allwright repo add\` first.`)}let n=Gd(t),r=(n?.jiraSiteUrl??"").trim(),s=r?`https://${r}`:"",i=e.jira?.email??"";if(s&&i&&e.jira?.apiToken){let l={baseUrl:s,email:i,apiToken:e.jira.apiToken};try{let u=await new Pe(l).myself();if(e.repos[t].jira=l,ge(e),y.info(`The token already on this server works on ${r} - authenticated as ${u.displayName}. Saved it for "${t}"; nothing to type.`),n?.jiraProjectKey)try{await new Pe(l).search(`project = "${n.jiraProjectKey}"`,1),y.info(`Project ${n.jiraProjectKey} is readable with it.`)}catch{y.warn(`Authenticated, but project ${n.jiraProjectKey} is not readable with this account. Ask a Jira admin for access, or re-run this command to enter a different account's token.`)}gn();return}catch{y.info(`The token already on this server does not work on ${r} - asking for one that does.`)}}let o=yn.default.createInterface({input:process.stdin,output:process.stdout});try{let u=(await o.question(s?`Jira base URL [${s}]: `:"Jira base URL for this repo (https://yourorg.atlassian.net): ")).trim()||s,f=(await o.question(i?`Jira account email [${i}]: `:"Jira account email: ")).trim()||i,p=(await o.question("Jira API token (id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!u||!f||!p)throw new Error("all three values are required");let b={baseUrl:u,email:f,apiToken:p},w=await new Pe(b).myself();y.info(`Jira credential OK - authenticated as ${w.displayName} on ${u}`),e.repos[t].jira=b,ge(e),y.info(`Saved: repo "${t}" now polls ${u} (other repos keep the runner-wide credential)`),gn()}finally{o.close()}});hs.command("set-token").description("Replace the RUNNER-WIDE Jira credential (the one every repo without an override uses). Until now this was only set at init - and Atlassian API tokens expire, which surfaces as boards quietly going empty. Prompts on stdin; validated before saving; applies live, no restart.").action(async()=>{let t=ie(),e=yn.default.createInterface({input:process.stdin,output:process.stdout});try{let n=t.jira?.baseUrl??"",r=t.jira?.email??"",s=(await e.question(n?`Jira base URL [${n}]: `:"Jira base URL (https://yourorg.atlassian.net): ")).trim()||n,i=(await e.question(r?`Jira account email [${r}]: `:"Jira account email: ")).trim()||r,o=(await e.question("Jira API token (id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!s||!i||!o)throw new Error("all three values are required");let l={baseUrl:s,email:i,apiToken:o},u=await new Pe(l).myself();t.jira=l,ge(t),y.info(`Jira credential OK - authenticated as ${u.displayName} on ${s}`),y.info(`Saved to ${jt()} (mode 600, this machine only). Repo overrides are untouched.`),gn()}finally{e.close()}});hs.command("show").description("Show which Jira site each repo uses (never prints tokens)").action(()=>{let t=ie();y.info(`runner-wide: ${t.jira?`${t.jira.baseUrl} (${t.jira.email})`:"(not configured)"}`);for(let[e,n]of Object.entries(t.repos))y.info(`${e} -> ${n.jira?`${n.jira.baseUrl} (${n.jira.email})`:"(runner-wide credential)"}`)});hs.command("user-add <ticketpilotEmail>").description("Store a PERSON's own Jira credential, so board buttons and Compose tickets they click post to Jira under THEIR Atlassian identity instead of the runner's account. Keyed by their Allwright login email. Prompts on stdin; stored locally only. Picked up on the next click - no restart needed.").action(async t=>{let e=ie(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=yn.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await r.question(`Their ATLASSIAN account email [${n}]: `)).trim()||n,i=(await r.question("Their Jira API token (they create it at id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!i)throw new Error("API token is required");let o=[e.jira,...Object.values(e.repos).map(c=>c.jira)].filter(c=>!!c),l=new Set,u=!1;for(let c of o)if(!l.has(c.baseUrl)){l.add(c.baseUrl);try{let f=await new Pe({baseUrl:c.baseUrl,email:s,apiToken:i}).myself();y.info(`${c.baseUrl}: OK - authenticated as ${f.displayName}`),u=!0}catch{y.warn(`${c.baseUrl}: this credential does NOT work there (fine if they don't use that site)`)}}if(!u)throw new Error("credential failed on every configured Jira site - nothing saved");e.jiraUsers[n]={email:s,apiToken:i},ge(e),y.info(`Saved. Dashboard actions by ${n} now post to Jira as ${s}. No restart needed.`)}finally{r.close()}});hs.command("user-list").description("Show which Allwright users have their own Jira credential here (never prints tokens)").action(()=>{let t=ie(),e=Object.entries(t.jiraUsers);if(!e.length)return y.info("none yet - everyone's dashboard clicks require one: allwright jira user-add <their-ticketpilot-email>");for(let[n,r]of e)y.info(`${n} -> posts to Jira as ${r.email}`)});hs.command("user-remove <ticketpilotEmail>").description("Delete a person's stored Jira credential").action(t=>{let e=ie(),n=t.trim().toLowerCase();if(!e.jiraUsers[n])throw new Error(`no credential stored for ${n}`);delete e.jiraUsers[n],ge(e),y.info(`Removed. Dashboard actions by ${n} will now be refused until a new credential is added.`)});var fs=Te.command("github").description("GitHub credential for implement-mode rules");fs.command("set-token").description("Store a GitHub token for opening pull requests (implement rules). Stored locally only, like your Jira token. Recommended: a fine-grained PAT scoped to the repo with contents:write + pull_requests:write.").option("--token <token>","GitHub token (omit to be prompted)").action(async t=>{let e=yn.default.createInterface({input:process.stdin,output:process.stdout});try{let n=t.token??void hf("every repo on this server")??(await e.question("GitHub token: ")).trim();if(!n)throw new Error("token is required");let{GitHubClient:r}=await Promise.resolve().then(()=>(ut(),or)),s=await new r(n).whoami(),i=ie();i.github={token:n,login:s},ge(i),y.info(`GitHub token OK - authenticated as ${s}`),y.info(`Saved to ${jt()} (mode 600, this machine only)`)}finally{e.close()}});fs.command("set <repoName>").description("Store a GitHub token for ONE repo only - overrides the runner-wide token for that repo's PRs and PR-watching. Useful when projects need separately revocable access. Prompts on stdin; stored locally only.").action(async t=>{let e=ie();if(!e.repos[t]){let i=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${t}" - mapped repos: ${i}. Run \`allwright repo add\` first.`)}let n=e.github?.token,r=e.repos[t]?.path;if(n&&r&&ft.default.existsSync(r))try{let i=(0,Gt.execFileSync)("git",["-C",r,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim(),o=at(i);if(o){let{GitHubClient:l}=await Promise.resolve().then(()=>(ut(),or)),u=new l(n),c=await u.repoAccess(o.owner,o.repo);if(c.ok&&c.canPush){let f=await u.whoami();y.info(`The shared token on this server already has push access to ${o.owner}/${o.repo} as ${f} - "${t}" needs nothing of its own. Storing a second token here would only give you two to rotate.`),y.info("Want a separately revocable one anyway? Paste it at the prompt below; press Enter to leave things as they are.")}}}catch{}let s=yn.default.createInterface({input:process.stdin,output:process.stdout});try{hf(`"${t}"`);let i=(await s.question(`GitHub token for "${t}": `)).trim();if(!i&&n){y.info(`Nothing changed - "${t}" keeps using the shared token.`);return}if(!i)throw new Error("token is required");let{GitHubClient:o}=await Promise.resolve().then(()=>(ut(),or)),l=await new o(i).whoami();e.repos[t].github={token:i,login:l},ge(e),y.info(`GitHub token OK - authenticated as ${l}`),y.info(`Saved: repo "${t}" now uses its own token (other repos keep the runner-wide one)`)}finally{s.close()}});fs.command("user-add <ticketpilotEmail>").description("Store a PERSON's own GitHub token, so PRs from implement runs THEY trigger are authored by their GitHub account. Keyed by their Allwright login email. Optional - without it their runs fall back to the repo/runner-wide token. Needs contents:write + pull_requests:write on the repos they'll touch.").action(async t=>{let e=ie(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=yn.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await r.question(`GitHub token for ${n}: `)).trim();if(!s)throw new Error("token is required");let{GitHubClient:i}=await Promise.resolve().then(()=>(ut(),or)),o=await new i(s).whoami();e.githubUsers[n]={token:s,login:o},ge(e),y.info(`GitHub token OK - authenticated as ${o}`),y.info(`Saved. Implement runs triggered by ${n} now open PRs as ${o}. No restart needed.`)}finally{r.close()}});fs.command("user-list").description("Show which Allwright users have their own GitHub token here (never prints tokens)").action(()=>{let t=ie(),e=Object.entries(t.githubUsers);if(!e.length)return y.info("no per-user GitHub tokens - everyone's PRs use the repo/runner-wide token");for(let[n]of e)y.info(`${n} -> own GitHub token stored`)});fs.command("user-remove <ticketpilotEmail>").description("Delete a person's stored GitHub token (their runs fall back to the shared token)").action(t=>{let e=ie(),n=t.trim().toLowerCase();if(!e.githubUsers[n])throw new Error(`no GitHub token stored for ${n}`);delete e.githubUsers[n],ge(e),y.info(`Removed. ${n}'s runs use the repo/runner-wide token again.`)});fs.command("show").description("Show which GitHub token each repo and person would use (never prints tokens)").action(()=>{let t=ie();y.info(`runner-wide: ${t.github?.token?"token set":"(not configured)"}`);for(let[n,r]of Object.entries(t.repos))y.info(`${n} -> ${r.github?.token?"own repo token":"runner-wide token"}`);let e=Object.keys(t.githubUsers);y.info(e.length?`per-user tokens: ${e.join(", ")}`:"per-user tokens: (none)")});var Sl=Te.command("audit").description("Recurring specialist audits on this runner");Sl.command("schedule <repoName> <role> <intervalHours>").description("Audit this repo's project on a cadence (role: security|testing; interval in hours, min 6). Runs on the runner's own clock; reports land in the Audits page history, where the diff-vs-previous view shows drift. Advisory only - nothing blocks.").action((t,e,n)=>{let r=ie();if(!r.repos[t]){let i=Object.keys(r.repos).join(", ")||"(none)";throw new Error(`unknown repo "${t}" - mapped repos: ${i}`)}if(e!=="security"&&e!=="testing")throw new Error('role must be "security" or "testing"');let s=parseInt(n,10);if(!Number.isInteger(s)||s<6||s>720)throw new Error("intervalHours must be 6-720");r.auditSchedules=[...r.auditSchedules.filter(i=>!(i.repoName===t&&i.role===e)),{repoName:t,role:e,intervalHours:s}],ge(r),y.info(`Scheduled: ${e} audit of "${t}" every ${s}h. Restart the runner to apply.`)});Sl.command("schedules").description("List scheduled audits").action(()=>{let t=ie();if(!t.auditSchedules.length)return y.info("no scheduled audits - allwright audit schedule <repo> <role> <hours>");for(let e of t.auditSchedules)y.info(`${e.repoName} \xB7 ${e.role} \xB7 every ${e.intervalHours}h`)});Sl.command("unschedule <repoName> <role>").description("Remove a scheduled audit").action((t,e)=>{let n=ie(),r=n.auditSchedules.length;if(n.auditSchedules=n.auditSchedules.filter(s=>!(s.repoName===t&&s.role===e)),n.auditSchedules.length===r)throw new Error("no such schedule");ge(n),y.info("Removed. Restart the runner to apply.")});var Tl=Te.command("deploy").description("Deployment settings for this machine");Tl.command("enable").description("Allow this runner to execute the deploy steps saved in the dashboard. Those steps are shell commands that run here, as this user - so this switch lives on the machine, not in the web UI, and only someone with shell access can flip it.").action(()=>{let t=ie();t.deploy={enabled:!0},ge(t),y.info("deployments ENABLED on this runner"),y.info("This runner will now execute the deploy steps configured for your environments. Review them in the dashboard before shipping to production."),gn()});Tl.command("disable").description("Stop this runner from executing any deploy steps").action(()=>{let t=ie();t.deploy={enabled:!1},ge(t),y.info("deployments DISABLED on this runner"),gn()});Tl.command("status").description("Show whether deployments are enabled here, and which env secrets are stored").action(()=>{let t=ie();y.info(`deployments: ${t.deploy.enabled?"enabled":"disabled"}`);let e=Object.entries(t.environments);if(!e.length)return y.info("no environment secrets stored");for(let[n,r]of e){let s=Object.keys(r.secrets);y.info(`${n}: ${s.length?s.join(", "):"(no secrets)"}`)}});var xl=Te.command("env").description("Per-environment deploy secrets. Values stay on this machine, like your Jira token.");xl.command("set <repoName> <envName> <assignments...>").description('Store secrets for one environment, e.g. env set acme/api production "SSH_HOST=1.2.3.4" "SSH_USER=deploy". Your deploy steps reference these as $SSH_HOST. The control plane only ever learns the NAMES.').action((t,e,n)=>{let r=ie(),s=ri(t,e),i=r.environments[s]??{secrets:{}},o=[];for(let l of n){let u=l.indexOf("=");if(u<=0)throw new Error(`expected KEY=VALUE, got "${l}"`);let c=l.slice(0,u).trim();i.secrets[c]=l.slice(u+1),o.push(c)}r.environments[s]=i,ge(r),y.info(`stored ${o.length} secret(s) for ${s}: ${o.join(", ")}`),y.info(`Saved to ${jt()} (mode 600, this machine only)`),gn()});xl.command("unset <repoName> <envName> <names...>").description("Remove stored secrets for an environment").action((t,e,n)=>{let r=ie(),s=ri(t,e),i=r.environments[s];if(!i)return y.info(`nothing stored for ${s}`);for(let o of n)delete i.secrets[o];r.environments[s]=i,ge(r),y.info(`removed ${n.join(", ")} from ${s}`)});xl.command("list").description("Show which environments have secrets stored here (names only, never values)").action(()=>{let t=ie(),e=Object.entries(t.environments);if(!e.length)return y.info("no environment secrets stored");for(let[n,r]of e)y.info(`${n}: ${Object.keys(r.secrets).join(", ")||"(none)"}`)});Te.command("export [file]").description("Back up ALL runner state (config+secrets, knowledge, audits, chats) to one tarball").action(t=>{try{let e=Xl(t);y.info(`Backup written: ${e.file} (${e.entries.length} entries, mode 600)`),y.warn("This file CONTAINS YOUR SECRETS (Jira/GitHub tokens). Keep it private - anyone holding it can act as this runner."),y.info(`Restore on any machine with: allwright import ${ds.default.basename(e.file)}`)}catch(e){y.error(e instanceof Error?e.message:String(e)),process.exitCode=1}});Te.command("import <file>").description("Restore runner state from an `export` tarball (existing config is kept as a .bak dir)").action(t=>{let e=On();if(e&&Nn(e)){y.error("the runner is running - stop it first (systemctl stop allwright, or `allwright stop` for a pid-file daemon), then import."),process.exitCode=1;return}try{let n=Ql(t);y.info(`Restored ${n.restored.length} entries into ${se()}`),n.previousDir&&y.info(`Previous config kept at ${n.previousDir}`),y.info("Start the runner and it will reconnect with the restored identity.")}catch(n){y.error(n instanceof Error?n.message:String(n)),process.exitCode=1}});Te.command("test").description("Check local setup: Jira auth, repo mappings, Claude Code binary").action(async()=>{let t=ie(),e=Object.keys(t.repos);if(!t.jira){y.error("no Jira credentials configured - run `allwright init`"),process.exitCode=1;return}let n=e.length?e.map(s=>({jiraProjectKey:"*",repoName:s})):[{jiraProjectKey:"*",repoName:"(none mapped)"}],r=!0;for(let s of n){let i=await co(t,s);for(let o of i){if(s.jiraProjectKey==="*"&&o.name==="jira-project")continue;let l=o.ok?"PASS":"FAIL";(o.ok?y.info:y.error)(`[${l}] ${o.name}: ${o.detail}`),r&&=o.ok}}r||(process.exitCode=1)});function gn(){let t=On();if(t&&Nn(t)&&process.platform!=="win32")try{process.kill(t,"SIGHUP"),y.info("running runner reloaded its config live - no restart needed");return}catch{}let e=t?au(t):null;y.info(e?`No background runner found to reload, but a service named "${e}" exists here: sudo systemctl kill -s HUP ${e} - otherwise it applies on the next start.`:"No background runner found to reload. Under systemd: sudo systemctl kill -s HUP <your allwright service> (allwright service install names it 'allwright'; installs predating the rename use 'ticketpilot-runner') - otherwise it applies on the next allwright start.")}function Hv(t){if(!t.runnerToken)throw new Error("runner not enrolled - run `allwright init`");if(!t.jira)throw new Error("no Jira credentials - run `allwright init`");let e=ou();e.ok||(y.warn(`another runner is already running on this machine (pid ${e.pid}). Two runner processes with one identity kick each other off the control plane every second. Stop the other one first: \`allwright stop\` (background runner) or \`sudo systemctl stop allwright\` (service).`),process.exit(1)),process.on("exit",Mo);let n=new Pe(t.jira),r=new Map,s=d=>{let m=t.repos[d]?.jira;if(!m)return n;let g=r.get(d);return g||(g=new Pe(m),r.set(d,g)),g},i=new Map,o=(d,m)=>{let g=Ku(ye()??t,d,m);switch(g.kind){case"legacy":return{jira:s(d),authored:!1};case"self":return{jira:s(d),authored:!0};case"missing":return{error:g.error};case"user":{let C=`${g.creds.baseUrl}:${g.creds.email}:${g.creds.apiToken.slice(-6)}`,M=i.get(C);return M||(M=new Pe(g.creds),i.set(C,M)),{jira:M,authored:!0}}}},l=new URL("/api/runner/ws",t.controlPlaneUrl);l.protocol=l.protocol==="https:"?"wss:":"ws:";let u=[],c=[],f=[],p,b=null,w={cfg:t,jiraFor:s,transport:null},S=new Set,x=d=>{let m=u.find(C=>C.id===d),g=m&&t.repos[m.repoName];return m&&g?{project:m,repoPath:g.path}:null},E=d=>{let m=u.find(M=>M.id===d),g=t.runnerName?`This runner ("${t.runnerName}")`:"This runner";if(!m)return`${g} does not know that project at all - it may have been deleted, or this runner has not synced yet.`;let C=Object.keys(t.repos).join(", ")||"(none)";return`${g} has no local checkout for "${m.name}" (repo "${m.repoName}"). Repos mapped here: ${C}. Either pin the project to the runner that HAS that repo (Dashboard \u2192 the project \u2192 Edit \u2192 Runner) - do this when several runners are online and the project is unpinned, because then the request goes to whichever one answers first - or map the repo on this machine: allwright repo add ${m.repoName} /path/to/checkout`},j={cfg:t,jiraFor:s,get transport(){return w.transport},lookup:(d,m)=>{let g=x(d),C=f.find(M=>M.projectId===d&&M.name===m);return g&&C?{...g,environment:C}:null}},v=new ao(l.toString(),t.runnerToken,{runnerVersion:yi},{onConfig:d=>{u=d.projects,Zd(d.projects),c=d.rules,f=d.environments,p.setConfig(d.projects,d.rules,d.pollingPaused,d.environments)},onDeployFix:async d=>{let m=x(d.projectId);if(!m){v.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:E(d.projectId)});return}let g=Ke(t,m.project,"assist");if("error"in g){v.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:g.error});return}y.info(`investigating failed deploy of "${d.environmentName}" (step: ${d.failedStep||"?"})`);let C=await _d({agent:g,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,steps:d.steps,failedStep:d.failedStep,errorText:d.errorText,cfg:t});v.sendDeploySuggestResult(d.requestId,C)},onProjectTest:async d=>{let m=u.find(C=>C.id===d.projectId);if(!m){v.sendProjectTestResult(d.requestId,!1,[{name:"config",ok:!1,detail:"project not in this runner's synced config yet"}]);return}y.info(`running connection test for project "${m.name}"`);let g=await co(ye()??t,m,f.filter(C=>C.projectId===m.id),c.filter(C=>C.projectId===m.id).map(C=>"agent"in C.action?C.action.agent:"").filter(Boolean));v.sendProjectTestResult(d.requestId,g.every(C=>C.ok),g)},onRuleDiagnose:async d=>{let m=c.find(D=>D.id===d.ruleId),g=m&&u.find(D=>D.id===m.projectId);if(!m||!g){v.sendRuleDiagnoseResult(d.requestId,{checks:[{name:"config",ok:!1,detail:"rule not in this runner's synced config yet"}],matchedCount:0,excludedCount:0,excludedSample:[]});return}y.info(`diagnosing rule "${m.name}"`);let C=await co(ye()??t,g,m.action.type==="deploy"?f.filter(D=>D.projectId===g.id):[]),M=m.action.type==="implement"?C:C.filter(D=>D.name!=="github-token"),{matchedCount:V,excludedCount:W,excludedSample:ee}=await p.diagnoseRule(m,g);v.sendRuleDiagnoseResult(d.requestId,{checks:M,matchedCount:V,excludedCount:W,excludedSample:ee})},onCancel:d=>{Hc(d)?y.info(`run ${d} stopped from the dashboard`):y.warn(`cancel requested for run ${d}, but nothing is running under that id here - it likely finished already`)},onApproved:(d,m)=>{if(qa(d)){md(j,d).catch(g=>y.error(`deploy approval crashed for ${d}: ${g instanceof Error?g.stack:g}`));return}$s(w,d,m).catch(g=>y.error(`approval handling crashed for ${d}: ${g instanceof Error?g.stack:g}`))},onRetryPush:d=>{let m=Pi(d),g=()=>Qc(w,d).catch(C=>y.error(`retry push crashed for ${d}: ${C instanceof Error?C.stack:C}`));m?p.runOnRepoQueue(m.baseRepoPath,g):g()},onRejected:d=>{if(qa(d)){gd(j,d).catch(m=>y.error(`deploy rejection crashed for ${d}: ${m instanceof Error?m.stack:m}`));return}Xc(w,d).catch(m=>y.error(`rejection handling crashed for ${d}: ${m instanceof Error?m.stack:m}`))},onDeployStart:d=>{let m=`${d.runId}#${d.attempt}`;if(S.has(m))return;S.add(m);let g=x(d.projectId);if(!g){let C=E(d.projectId);y.error(`deploy ${d.runId}: ${C}`),v.send({type:"run.status",runId:d.runId,status:"failed",error:C});return}y.info(`deploy ${d.runId} requested from the dashboard: ${d.issueKey} \u2192 ${d.environment.name}`),p.runOnEnvironmentQueue(d.environment.id,()=>qi({runId:d.runId,project:g.project,environment:d.environment,issueKey:d.issueKey,issueSummary:d.issueSummary,repoPath:g.repoPath,cfg:t,jira:s(g.project.repoName),transport:v,requestedBy:d.requestedBy}).catch(C=>y.error(`deploy crashed for ${d.runId}: ${C instanceof Error?C.stack:C}`)))},onDeploySuggest:async d=>{let m=x(d.projectId);if(!m){v.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:E(d.projectId)});return}let g=Ke(t,m.project,"assist");if("error"in g){v.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:g.error});return}y.info(`asking ${g.adapter.displayName} for "${d.environmentName}" deploy steps in ${m.repoPath}`);let C=await kd({agent:g,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,notes:d.notes,timeoutSeconds:d.timeoutSeconds,cfg:t});v.sendDeploySuggestResult(d.requestId,C)},onEnvPreflight:async d=>{let m=x(d.projectId);if(!m){v.sendEnvPreflightResult(d.requestId,{ok:!1,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project"}]});return}let g=await wd({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,steps:d.steps,requiredSecrets:d.requiredSecrets,workdir:d.workdir,branch:d.branch,publicUrl:d.publicUrl,cfg:t});v.sendEnvPreflightResult(d.requestId,g)},onSelfMigrationApply:async d=>{let m=x(d.projectId);if(!m){v.sendSelfMigrationApplyResult(d.requestId,{ok:!1,file:d.file,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project",fix:[]}],output:"",error:E(d.projectId)});return}y.info(`applying migration ${d.file} for "${d.environmentName}"`);let g=await Wd({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,file:d.file,urlSecret:d.urlSecret,cfg:t});y.info(g.ok?`migration ${d.file} applied`:`migration ${d.file} failed: ${g.error}`),v.sendSelfMigrationApplyResult(d.requestId,g)},onChatTurn:async d=>{let m=x(d.projectId);if(!m){v.sendChatTurnResult(d.requestId,{ok:!1,sessionId:d.sessionId??"",reply:"",error:E(d.projectId)});return}let g=d.sessionId||(0,Hs.randomUUID)(),C=!d.sessionId,M=C?0:Os(g)?.messages.length??0,V=!1,W=0,ee="";if(!C&&M>=Nd){let be=await Dd(m,g,t);if(be)V=!0,W=M,ee=be,g=(0,Hs.randomUUID)(),C=!0,y.info(`chat compacted: ${M} message(s) summarized into a fresh session`);else if(M>=Md){v.sendChatTurnResult(d.requestId,{ok:!1,sessionId:g,reply:"",error:"this chat is very long and could not be compacted automatically - start a new chat (it keeps the repo knowledge; only the conversation resets)."});return}}let D=d.files.length?nu(m.repoPath,d.requestId,d.files):null,U=(0,Ze.replyPreferenceAppendix)({language:d.replyLanguage,languageInstruction:d.replyLanguageInstruction,style:d.replyStyle})+(0,Ze.pendingMigrationsAppendix)(d.pendingMigrations),ne="```",de=C?`You are the project assistant for "${m.project.name}" - this working directory is its repository, and you have read-only access.
|
|
888
|
+
`);let n=s=>new Promise((i,o)=>{(0,tf.execFile)("git",["-C",t.repoPath,...s],{timeout:12e4},(l,u,c)=>l?o(new Error(c||l.message)):i())}),r="";try{await n(["add",e.rel]),await n(["-c","user.name=Allwright","-c","user.email=runner@allwright.local","commit","-m",t.commitMessage]);try{await n(["push"]),r="committed and pushed to the repo"}catch(s){r="committed locally, but push failed: "+(s instanceof Error?s.message.slice(0,200):"unknown")+" - push it from the server when convenient"}}catch(s){r="file written, but commit failed: "+(s instanceof Error?s.message.slice(0,200):"unknown")+" - commit it from the server when convenient"}return{ok:!0,note:r}}var Tr=I(require("node:fs"),1),vl=I(require("node:path"),1),uo=require("node:child_process"),rf=require("node:util");nr();wt();var sf=I(_e(),1),nf=(0,rf.promisify)(uo.execFile);function qv(t){try{return new URL(t).host}catch{return t}}function Fv(t){try{return(0,uo.execFileSync)("git",["-C",t,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim()}catch{return null}}async function co(t,e,n=[],r){let s=[],i=t.repos[e.repoName]?.jira,o=i??t.jira,l=(e.jiraSiteUrl??"").trim().toLowerCase();if(!o)s.push({name:"jira-credentials",ok:!1,detail:"no Jira credentials configured on this runner"});else if(!l)s.push({name:"jira-site",ok:!1,detail:"this project has not said which Atlassian site it is on, so nothing here can be verified - a credential that authenticates somewhere else would look like a pass.",fixNote:"This one is fixed in the dashboard, not on the server: open the project and fill in its Atlassian site (for example yourcompany.atlassian.net), then run this test again."});else{let p=qv(o.baseUrl),b=i?"this repo's own Jira credential":"the runner-wide Jira credential";if(p!==l)s.push({name:"jira-site",ok:!1,detail:`this project is on ${l}, but ${b} is for ${p}.`,fix:[`allwright jira set "${e.repoName}"`],fixNote:`"${e.repoName}" in that command is this project's REPO NAME - the label that ties the project here to a checkout on the server (the same one used with allwright repo add). Not the Jira key, not a folder path. The command asks for three things for ${l}: the base URL (https://${l}), your Jira account email, and an API token from id.atlassian.com/manage-profile/security/api-tokens. They are stored on this server only. Restart afterwards: allwright stop && allwright start`});else{let w=new Pe(o);try{let S=await w.myself();s.push({name:"jira-auth",ok:!0,detail:`authenticated as ${S.displayName} on ${p} (${b})`});try{await w.search(`project = "${e.jiraProjectKey}" ORDER BY created DESC`,1),s.push({name:"jira-project",ok:!0,detail:`project ${e.jiraProjectKey} is readable on ${p}`})}catch(x){s.push({name:"jira-project",ok:!1,detail:`cannot read project ${e.jiraProjectKey} on ${p}: ${Bs(x)}`})}}catch(S){s.push({name:"jira-auth",ok:!1,detail:`Jira auth failed on ${p}: ${Bs(S)}`})}}}let u=t.repos[e.repoName];if(u&&Tr.default.existsSync(u.path)){let p=vl.default.join(u.path,"CLAUDE.md"),b=Tr.default.existsSync(p)&&Tr.default.readFileSync(p,"utf8").trim().length>0;s.push({name:"memory-file",kind:"content",ok:b,detail:b?"CLAUDE.md present - the agent has project memory":"MISSING: CLAUDE.md at the repo root. Rules can't be enabled until the project has a memory file - it is what makes every run smarter than the last.",...b?{}:{fixNote:"No command needed: the setup step below this one drafts CLAUDE.md by reading the repo, shows it to you, and commits it when you approve. Writing it by hand works too - any honest description of what the project is and how it is built beats an empty file."}});let w=Fi(u.path);s.push({name:"deploy-doc",kind:"content",ok:w!==null,detail:w?`${w.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.",...w?{}:{fixNote:"Only needed if this project will deploy from Allwright. The setup wizard can draft DEPLOY.md the same way it drafts CLAUDE.md - describe how you deploy today (the commands you actually run), and the agent proposes steps a human saves. Skip it if you only want tickets to become pull requests."}})}if(!u)s.push({name:"repo-path",ok:!1,detail:`no local path mapped for repo "${e.repoName}" - run: allwright repo add "${e.repoName}" /path/to/checkout`});else if(!Tr.default.existsSync(u.path))s.push({name:"repo-path",ok:!1,detail:`path does not exist: ${u.path}`});else{let p=Tr.default.existsSync(vl.default.join(u.path,".git"));s.push({name:"repo-path",ok:!0,detail:`${u.path}${p?" (git checkout)":" (warning: not a git checkout)"}`})}let c=[...new Set([e.defaultAgent||"claude-code",...r??[]])];for(let p of c){let b=Ue(t,p),w=p==="claude-code"?"claude-code":`agent:${p}`;try{let{stdout:S}=await nf(b,["--version"],{timeout:15e3});s.push({name:w,ok:!0,detail:S.trim().slice(0,100)})}catch(S){s.push({name:w,ok:!1,detail:`cannot run "${b}" for agent "${p}": ${Bs(S)}`,fixNote:p==="claude-code"?"Install Claude Code on this server (npm install -g @anthropic-ai/claude-code) and log it in.":`Install the "${p}" CLI on this server, or point the runner at its binary in the config's agents section.`})}}try{let{stdout:p}=await nf("git",["--version"],{timeout:15e3});s.push({name:"git",ok:!0,detail:p.trim().slice(0,100)})}catch(p){s.push({name:"git",ok:!1,detail:`cannot run git: ${Bs(p)}`})}let f=Ae(t,e.repoName);if(!f)s.push({name:"github-token",ok:!1,detail:`no GitHub token applies to "${e.repoName}" - implement rules cannot push.`,fix:[`allwright github set "${e.repoName}"`,"allwright github set-token"],fixNote:`"${e.repoName}" is this project's REPO NAME - the same label used with allwright repo add, not a folder path. The first command stores a token for this repo alone (separately revocable); the second stores one shared by every repo on this server. Both print the exact permission checklist before asking. In short: create it at ${sf.GITHUB_TOKEN_PERMISSIONS.where}, with the RESOURCE OWNER set to the org that owns the repo (the usual mistake), Contents and Pull requests both Read and write.`});else try{let{GitHubClient:p}=await Promise.resolve().then(()=>(ut(),or)),b=new p(f),w=await b.whoami(),S=u&&Tr.default.existsSync(u.path)?Fv(u.path):null,x=S?at(S):null;if(!x)s.push({name:"github-token",ok:!0,detail:`authenticated as ${w} - repo access not checked (no local checkout yet)`});else{let A=await b.repoAccess(x.owner,x.repo);s.push({name:"github-token",ok:A.ok&&A.canPush,detail:A.ok?A.canPush?`${w} has push access to ${x.owner}/${x.repo}`:`${w} can read ${x.owner}/${x.repo} but NOT push to it - implement rules will fail at the push`:`${w} cannot see ${x.owner}/${x.repo}: ${A.error}`,...A.ok&&A.canPush?{}:{fix:[`allwright github set "${e.repoName}"`],fixNote:`Two ways: edit the existing PAT on GitHub and add ${x.owner}/${x.repo} to it with contents:write and pull_requests:write - or give this repo its own token with the command above. A fine-grained PAT only ever covers ONE organisation, so a repo in a different org than your other projects always needs its own.`}})}}catch(p){s.push({name:"github-token",ok:!1,detail:Bs(p)})}if(n.length){t.deploy.enabled?s.push({name:"deploy",ok:!0,detail:"deployments enabled on this runner"}):s.push({name:"deploy",ok:!1,detail:"deployments are disabled on this runner - run `allwright deploy enable` to allow it to execute your saved deploy steps"});for(let p of n){let b=Ot(t,e.repoName,p.name),w=p.requiredSecrets.filter(S=>!b[S]&&!process.env[S]);s.push({name:`env:${p.name}`,ok:w.length===0,detail:w.length?`missing secret(s): ${w.join(", ")} - allwright env set "${e.repoName}" "${p.name}" ${w[0]}=...`:`${p.steps.length} step(s), ${p.requiredSecrets.length} secret(s) present`+(p.branch?`, deploys origin/${p.branch}`:"")})}}return s}function Bs(t){return(t instanceof Error?t.message:String(t)).slice(0,300)}var Te=new Ll;Te.name("allwright").description("Allwright runner - runs on YOUR machine, holds YOUR credentials locally, connects outbound-only to the control plane. Your Jira token, Anthropic key and source code never leave this host.").version(yi);function hf(t){y.info(`Create the token at ${Ze.GITHUB_TOKEN_PERMISSIONS.where}`);for(let e of Ze.GITHUB_TOKEN_PERMISSIONS.steps)y.info(` - ${e}`);y.info(Ze.GITHUB_TOKEN_PERMISSIONS.note),y.info(`Then paste it below for ${t}.`)}Te.command("init").description("Interactive setup: enroll this runner and store credentials locally").option("--cp-url <url>","control plane URL").option("--enroll-token <token>","enrolment token from the Allwright UI").option("--name <name>","runner name",wl.default.hostname()).option("--jira-url <url>","Jira base URL, e.g. https://yourorg.atlassian.net").option("--jira-email <email>","Jira account email").option("--jira-token <token>","Jira API token (stored locally only)").action(async t=>{let e=yn.default.createInterface({input:process.stdin,output:process.stdout}),n=async(r,s,i=!1)=>{if(s)return s;let o=await e.question(`${r}: `);if(!o.trim())throw new Error(`${r} is required`);return o.trim()};try{let r=await n("Control plane URL",t.cpUrl),s=await n("Enrolment token (from the web UI)",t.enrollToken),i=await n("Jira base URL (https://yourorg.atlassian.net)",t.jiraUrl),o=await n("Jira account email",t.jiraEmail),l=await n("Jira API token (create at id.atlassian.com/manage-profile/security/api-tokens)",t.jiraToken,!0),u=jo.parse({controlPlaneUrl:r,runnerName:t.name,jira:{baseUrl:i,email:o,apiToken:l}}),c=await new Pe(u.jira).myself();y.info(`Jira credential OK - authenticated as ${c.displayName}`),u=await ju(u,s),y.info(`Enrolled as runner "${u.runnerName}" (${u.runnerId})`),y.info(`Credentials saved to ${jt()} (mode 600, this machine only)`),y.info("Next: map your repo with `allwright repo add <repoName> <localPath>`, then `allwright start`")}finally{e.close()}});var _l=Te.command("repo").description("Map control-plane repo names to local checkouts");_l.command("add <repoName> <localPath>").description("Map a repo name (as configured in the web UI) to a local checkout path").action(async(t,e)=>{let n=ie();n.repos[t]={path:e},ge(n),y.info(`mapped repo "${t}" -> ${e}`);try{let{originUrl:r}=await Promise.resolve().then(()=>(wt(),qu));y.info(` origin remote: ${await r(e)} - make sure this is the repo you meant`)}catch{y.warn(` could not read an origin remote at ${e} - is it a git checkout?`)}gn()||y.warn(`"${t}" is saved but NOT live yet - the running runner still does not know about it, and runs will keep saying it is not mapped until it reloads.`)});_l.command("list").description("Show configured repo mappings").action(()=>{let t=ie(),e=Object.entries(t.repos);if(!e.length)return y.info("no repos mapped yet");for(let[n,r]of e)y.info(`${n} -> ${r.path}`)});var ff=Te.command("claude").description("Per-user Claude login profiles - each teammate's runs bill their OWN Claude account");ff.command("login <profileName>").description("Create (or re-login) a named Claude profile. Opens Claude Code interactively with its own config directory - have the PERSON WHOSE ACCOUNT IT IS complete the /login flow with their credentials, then exit. Assign the profile to their user on the dashboard's Team page.").action(async t=>{if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new Error("profile name: letters, digits, dots, dashes and underscores only");let e=ie(),n=e.claudeProfiles[t]?.configDir??`${jt().replace(/runner\.json$/,"")}claude-profiles/${t}`;ft.default.mkdirSync(n,{recursive:!0,mode:448}),e.claudeProfiles[t]={configDir:n},ge(e),y.info(`profile "${t}" -> ${n}`),y.info("Opening Claude Code with this profile. In it: run /login, complete the browser flow"),y.info("with the account this profile belongs to, then exit Claude (ctrl+c twice or /exit).");let r=(0,Gt.spawn)(e.claudeBin,[],{env:{...process.env,CLAUDE_CONFIG_DIR:n},stdio:"inherit"});await new Promise(s=>r.on("exit",()=>s())),y.info(`Done. Assign it on the dashboard: Team -> the user -> Claude profile = "${t}".`),gn()});ff.command("list").description("Show configured Claude profiles and whether each looks logged in").action(()=>{let t=ie(),e=Object.entries(t.claudeProfiles);if(y.info("default: this OS user's own Claude login (no profile)"),!e.length)return y.info("no named profiles yet - allwright claude login <name>");for(let[n,r]of e){let s=ft.default.existsSync(r.configDir)&&ft.default.readdirSync(r.configDir).length>0;y.info(`${n} -> ${r.configDir} ${s?"(logged in)":"(NOT logged in yet)"}`)}});_l.command("remove <repoName>").description("Unmap a repo from this runner: removes the mapping plus its per-repo Jira/GitHub overrides and env secrets from the config. Does NOT touch the checkout on disk or anything in the control plane - delete the project on the dashboard separately.").action(t=>{let e=ie();if(!e.repos[t]){let i=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${t}" - mapped repos: ${i}`)}let n=e.repos[t].path;delete e.repos[t];let r=Object.keys(e.environments).filter(i=>i.startsWith(`${t}:`));for(let i of r)delete e.environments[i];let s=e.auditSchedules.length;e.auditSchedules=e.auditSchedules.filter(i=>i.repoName!==t),ge(e),y.info(`Removed "${t}" (was ${n})`),r.length&&y.info(`Also removed ${r.length} environment secret set(s): ${r.join(", ")}`),e.auditSchedules.length!==s&&y.info("Also removed its audit schedule(s)"),y.info("The checkout on disk was NOT touched - remove it yourself if you want it gone."),y.info("Restart the runner to apply. Dashboard project (if any) is deleted separately there.")});var kl=Te.command("service").description("Run the runner as a system service (starts on boot, restarts on crash)");kl.command("install").description("Install + start the systemd service - detects node, this script, your user and home; no hand-written unit files. Run with sudo. (--print shows the unit without installing.)").option("--print","print the generated unit file and exit").action(t=>{if(t.print){y.info(`
|
|
889
|
+
`+ua(la()));return}Vu(y)});kl.command("uninstall").description("Stop and remove the systemd service (config/credentials untouched)").action(()=>Wu(y));kl.command("status").description("systemctl status for the runner service").action(()=>{(0,Gt.spawn)("systemctl",["status","allwright","--no-pager"],{stdio:"inherit"}).on("exit",e=>process.exit(e??0))});Te.command("update").description("Update the runner to the latest published version (npm install -g allwright@latest). Restart the runner afterwards - and only when no runs are active.").action(async()=>{y.info("Updating: npm install -g allwright@latest");let t=(0,Gt.spawn)("npm",["install","-g","allwright@latest"],{stdio:"inherit"});await new Promise((e,n)=>{t.on("exit",r=>r===0?e():n(new Error(`npm exited with code ${r}`))),t.on("error",n)}),y.info("Updated. Restart the runner service to load the new version (check active runs first).")});var hs=Te.command("jira").description("Per-repo Jira site overrides - for projects living on a different Atlassian site");hs.command("set <repoName>").description("Store Jira credentials for ONE repo's project (e.g. a project on a different *.atlassian.net site than the runner's main credential). Prompts on stdin; stored locally only, like every other credential.").action(async t=>{let e=ie();if(!e.repos[t]){let l=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${t}" - mapped repos: ${l}. Run \`allwright repo add\` first.`)}let n=Gd(t),r=(n?.jiraSiteUrl??"").trim(),s=r?`https://${r}`:"",i=e.jira?.email??"";if(s&&i&&e.jira?.apiToken){let l={baseUrl:s,email:i,apiToken:e.jira.apiToken};try{let u=await new Pe(l).myself();if(e.repos[t].jira=l,ge(e),y.info(`The token already on this server works on ${r} - authenticated as ${u.displayName}. Saved it for "${t}"; nothing to type.`),n?.jiraProjectKey)try{await new Pe(l).search(`project = "${n.jiraProjectKey}"`,1),y.info(`Project ${n.jiraProjectKey} is readable with it.`)}catch{y.warn(`Authenticated, but project ${n.jiraProjectKey} is not readable with this account. Ask a Jira admin for access, or re-run this command to enter a different account's token.`)}gn();return}catch{y.info(`The token already on this server does not work on ${r} - asking for one that does.`)}}let o=yn.default.createInterface({input:process.stdin,output:process.stdout});try{let u=(await o.question(s?`Jira base URL [${s}]: `:"Jira base URL for this repo (https://yourorg.atlassian.net): ")).trim()||s,f=(await o.question(i?`Jira account email [${i}]: `:"Jira account email: ")).trim()||i,p=(await o.question("Jira API token (id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!u||!f||!p)throw new Error("all three values are required");let b={baseUrl:u,email:f,apiToken:p},w=await new Pe(b).myself();y.info(`Jira credential OK - authenticated as ${w.displayName} on ${u}`),e.repos[t].jira=b,ge(e),y.info(`Saved: repo "${t}" now polls ${u} (other repos keep the runner-wide credential)`),gn()}finally{o.close()}});hs.command("set-token").description("Replace the RUNNER-WIDE Jira credential (the one every repo without an override uses). Until now this was only set at init - and Atlassian API tokens expire, which surfaces as boards quietly going empty. Prompts on stdin; validated before saving; applies live, no restart.").action(async()=>{let t=ie(),e=yn.default.createInterface({input:process.stdin,output:process.stdout});try{let n=t.jira?.baseUrl??"",r=t.jira?.email??"",s=(await e.question(n?`Jira base URL [${n}]: `:"Jira base URL (https://yourorg.atlassian.net): ")).trim()||n,i=(await e.question(r?`Jira account email [${r}]: `:"Jira account email: ")).trim()||r,o=(await e.question("Jira API token (id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!s||!i||!o)throw new Error("all three values are required");let l={baseUrl:s,email:i,apiToken:o},u=await new Pe(l).myself();t.jira=l,ge(t),y.info(`Jira credential OK - authenticated as ${u.displayName} on ${s}`),y.info(`Saved to ${jt()} (mode 600, this machine only). Repo overrides are untouched.`),gn()}finally{e.close()}});hs.command("show").description("Show which Jira site each repo uses (never prints tokens)").action(()=>{let t=ie();y.info(`runner-wide: ${t.jira?`${t.jira.baseUrl} (${t.jira.email})`:"(not configured)"}`);for(let[e,n]of Object.entries(t.repos))y.info(`${e} -> ${n.jira?`${n.jira.baseUrl} (${n.jira.email})`:"(runner-wide credential)"}`)});hs.command("user-add <ticketpilotEmail>").description("Store a PERSON's own Jira credential, so board buttons and Compose tickets they click post to Jira under THEIR Atlassian identity instead of the runner's account. Keyed by their Allwright login email. Prompts on stdin; stored locally only. Picked up on the next click - no restart needed.").action(async t=>{let e=ie(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=yn.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await r.question(`Their ATLASSIAN account email [${n}]: `)).trim()||n,i=(await r.question("Their Jira API token (they create it at id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!i)throw new Error("API token is required");let o=[e.jira,...Object.values(e.repos).map(c=>c.jira)].filter(c=>!!c),l=new Set,u=!1;for(let c of o)if(!l.has(c.baseUrl)){l.add(c.baseUrl);try{let f=await new Pe({baseUrl:c.baseUrl,email:s,apiToken:i}).myself();y.info(`${c.baseUrl}: OK - authenticated as ${f.displayName}`),u=!0}catch{y.warn(`${c.baseUrl}: this credential does NOT work there (fine if they don't use that site)`)}}if(!u)throw new Error("credential failed on every configured Jira site - nothing saved");e.jiraUsers[n]={email:s,apiToken:i},ge(e),y.info(`Saved. Dashboard actions by ${n} now post to Jira as ${s}. No restart needed.`)}finally{r.close()}});hs.command("user-list").description("Show which Allwright users have their own Jira credential here (never prints tokens)").action(()=>{let t=ie(),e=Object.entries(t.jiraUsers);if(!e.length)return y.info("none yet - everyone's dashboard clicks require one: allwright jira user-add <their-ticketpilot-email>");for(let[n,r]of e)y.info(`${n} -> posts to Jira as ${r.email}`)});hs.command("user-remove <ticketpilotEmail>").description("Delete a person's stored Jira credential").action(t=>{let e=ie(),n=t.trim().toLowerCase();if(!e.jiraUsers[n])throw new Error(`no credential stored for ${n}`);delete e.jiraUsers[n],ge(e),y.info(`Removed. Dashboard actions by ${n} will now be refused until a new credential is added.`)});var fs=Te.command("github").description("GitHub credential for implement-mode rules");fs.command("set-token").description("Store a GitHub token for opening pull requests (implement rules). Stored locally only, like your Jira token. Recommended: a fine-grained PAT scoped to the repo with contents:write + pull_requests:write.").option("--token <token>","GitHub token (omit to be prompted)").action(async t=>{let e=yn.default.createInterface({input:process.stdin,output:process.stdout});try{let n=t.token??void hf("every repo on this server")??(await e.question("GitHub token: ")).trim();if(!n)throw new Error("token is required");let{GitHubClient:r}=await Promise.resolve().then(()=>(ut(),or)),s=await new r(n).whoami(),i=ie();i.github={token:n,login:s},ge(i),y.info(`GitHub token OK - authenticated as ${s}`),y.info(`Saved to ${jt()} (mode 600, this machine only)`)}finally{e.close()}});fs.command("set <repoName>").description("Store a GitHub token for ONE repo only - overrides the runner-wide token for that repo's PRs and PR-watching. Useful when projects need separately revocable access. Prompts on stdin; stored locally only.").action(async t=>{let e=ie();if(!e.repos[t]){let i=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${t}" - mapped repos: ${i}. Run \`allwright repo add\` first.`)}let n=e.github?.token,r=e.repos[t]?.path;if(n&&r&&ft.default.existsSync(r))try{let i=(0,Gt.execFileSync)("git",["-C",r,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim(),o=at(i);if(o){let{GitHubClient:l}=await Promise.resolve().then(()=>(ut(),or)),u=new l(n),c=await u.repoAccess(o.owner,o.repo);if(c.ok&&c.canPush){let f=await u.whoami();y.info(`The shared token on this server already has push access to ${o.owner}/${o.repo} as ${f} - "${t}" needs nothing of its own. Storing a second token here would only give you two to rotate.`),y.info("Want a separately revocable one anyway? Paste it at the prompt below; press Enter to leave things as they are.")}}}catch{}let s=yn.default.createInterface({input:process.stdin,output:process.stdout});try{hf(`"${t}"`);let i=(await s.question(`GitHub token for "${t}": `)).trim();if(!i&&n){y.info(`Nothing changed - "${t}" keeps using the shared token.`);return}if(!i)throw new Error("token is required");let{GitHubClient:o}=await Promise.resolve().then(()=>(ut(),or)),l=await new o(i).whoami();e.repos[t].github={token:i,login:l},ge(e),y.info(`GitHub token OK - authenticated as ${l}`),y.info(`Saved: repo "${t}" now uses its own token (other repos keep the runner-wide one)`)}finally{s.close()}});fs.command("user-add <ticketpilotEmail>").description("Store a PERSON's own GitHub token, so PRs from implement runs THEY trigger are authored by their GitHub account. Keyed by their Allwright login email. Optional - without it their runs fall back to the repo/runner-wide token. Needs contents:write + pull_requests:write on the repos they'll touch.").action(async t=>{let e=ie(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=yn.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await r.question(`GitHub token for ${n}: `)).trim();if(!s)throw new Error("token is required");let{GitHubClient:i}=await Promise.resolve().then(()=>(ut(),or)),o=await new i(s).whoami();e.githubUsers[n]={token:s,login:o},ge(e),y.info(`GitHub token OK - authenticated as ${o}`),y.info(`Saved. Implement runs triggered by ${n} now open PRs as ${o}. No restart needed.`)}finally{r.close()}});fs.command("user-list").description("Show which Allwright users have their own GitHub token here (never prints tokens)").action(()=>{let t=ie(),e=Object.entries(t.githubUsers);if(!e.length)return y.info("no per-user GitHub tokens - everyone's PRs use the repo/runner-wide token");for(let[n]of e)y.info(`${n} -> own GitHub token stored`)});fs.command("user-remove <ticketpilotEmail>").description("Delete a person's stored GitHub token (their runs fall back to the shared token)").action(t=>{let e=ie(),n=t.trim().toLowerCase();if(!e.githubUsers[n])throw new Error(`no GitHub token stored for ${n}`);delete e.githubUsers[n],ge(e),y.info(`Removed. ${n}'s runs use the repo/runner-wide token again.`)});fs.command("show").description("Show which GitHub token each repo and person would use (never prints tokens)").action(()=>{let t=ie();y.info(`runner-wide: ${t.github?.token?"token set":"(not configured)"}`);for(let[n,r]of Object.entries(t.repos))y.info(`${n} -> ${r.github?.token?"own repo token":"runner-wide token"}`);let e=Object.keys(t.githubUsers);y.info(e.length?`per-user tokens: ${e.join(", ")}`:"per-user tokens: (none)")});var Sl=Te.command("audit").description("Recurring specialist audits on this runner");Sl.command("schedule <repoName> <role> <intervalHours>").description("Audit this repo's project on a cadence (role: security|testing; interval in hours, min 6). Runs on the runner's own clock; reports land in the Audits page history, where the diff-vs-previous view shows drift. Advisory only - nothing blocks.").action((t,e,n)=>{let r=ie();if(!r.repos[t]){let i=Object.keys(r.repos).join(", ")||"(none)";throw new Error(`unknown repo "${t}" - mapped repos: ${i}`)}if(e!=="security"&&e!=="testing")throw new Error('role must be "security" or "testing"');let s=parseInt(n,10);if(!Number.isInteger(s)||s<6||s>720)throw new Error("intervalHours must be 6-720");r.auditSchedules=[...r.auditSchedules.filter(i=>!(i.repoName===t&&i.role===e)),{repoName:t,role:e,intervalHours:s}],ge(r),y.info(`Scheduled: ${e} audit of "${t}" every ${s}h. Restart the runner to apply.`)});Sl.command("schedules").description("List scheduled audits").action(()=>{let t=ie();if(!t.auditSchedules.length)return y.info("no scheduled audits - allwright audit schedule <repo> <role> <hours>");for(let e of t.auditSchedules)y.info(`${e.repoName} \xB7 ${e.role} \xB7 every ${e.intervalHours}h`)});Sl.command("unschedule <repoName> <role>").description("Remove a scheduled audit").action((t,e)=>{let n=ie(),r=n.auditSchedules.length;if(n.auditSchedules=n.auditSchedules.filter(s=>!(s.repoName===t&&s.role===e)),n.auditSchedules.length===r)throw new Error("no such schedule");ge(n),y.info("Removed. Restart the runner to apply.")});var Tl=Te.command("deploy").description("Deployment settings for this machine");Tl.command("enable").description("Allow this runner to execute the deploy steps saved in the dashboard. Those steps are shell commands that run here, as this user - so this switch lives on the machine, not in the web UI, and only someone with shell access can flip it.").action(()=>{let t=ie();t.deploy={enabled:!0},ge(t),y.info("deployments ENABLED on this runner"),y.info("This runner will now execute the deploy steps configured for your environments. Review them in the dashboard before shipping to production."),gn()});Tl.command("disable").description("Stop this runner from executing any deploy steps").action(()=>{let t=ie();t.deploy={enabled:!1},ge(t),y.info("deployments DISABLED on this runner"),gn()});Tl.command("status").description("Show whether deployments are enabled here, and which env secrets are stored").action(()=>{let t=ie();y.info(`deployments: ${t.deploy.enabled?"enabled":"disabled"}`);let e=Object.entries(t.environments);if(!e.length)return y.info("no environment secrets stored");for(let[n,r]of e){let s=Object.keys(r.secrets);y.info(`${n}: ${s.length?s.join(", "):"(no secrets)"}`)}});var xl=Te.command("env").description("Per-environment deploy secrets. Values stay on this machine, like your Jira token.");xl.command("set <repoName> <envName> <assignments...>").description('Store secrets for one environment, e.g. env set acme/api production "SSH_HOST=1.2.3.4" "SSH_USER=deploy". Your deploy steps reference these as $SSH_HOST. The control plane only ever learns the NAMES.').action((t,e,n)=>{let r=ie(),s=ri(t,e),i=r.environments[s]??{secrets:{}},o=[];for(let l of n){let u=l.indexOf("=");if(u<=0)throw new Error(`expected KEY=VALUE, got "${l}"`);let c=l.slice(0,u).trim();i.secrets[c]=l.slice(u+1),o.push(c)}r.environments[s]=i,ge(r),y.info(`stored ${o.length} secret(s) for ${s}: ${o.join(", ")}`),y.info(`Saved to ${jt()} (mode 600, this machine only)`),gn()});xl.command("unset <repoName> <envName> <names...>").description("Remove stored secrets for an environment").action((t,e,n)=>{let r=ie(),s=ri(t,e),i=r.environments[s];if(!i)return y.info(`nothing stored for ${s}`);for(let o of n)delete i.secrets[o];r.environments[s]=i,ge(r),y.info(`removed ${n.join(", ")} from ${s}`)});xl.command("list").description("Show which environments have secrets stored here (names only, never values)").action(()=>{let t=ie(),e=Object.entries(t.environments);if(!e.length)return y.info("no environment secrets stored");for(let[n,r]of e)y.info(`${n}: ${Object.keys(r.secrets).join(", ")||"(none)"}`)});Te.command("export [file]").description("Back up ALL runner state (config+secrets, knowledge, audits, chats) to one tarball").action(t=>{try{let e=Xl(t);y.info(`Backup written: ${e.file} (${e.entries.length} entries, mode 600)`),y.warn("This file CONTAINS YOUR SECRETS (Jira/GitHub tokens). Keep it private - anyone holding it can act as this runner."),y.info(`Restore on any machine with: allwright import ${ds.default.basename(e.file)}`)}catch(e){y.error(e instanceof Error?e.message:String(e)),process.exitCode=1}});Te.command("import <file>").description("Restore runner state from an `export` tarball (existing config is kept as a .bak dir)").action(t=>{let e=On();if(e&&Nn(e)){y.error("the runner is running - stop it first (systemctl stop allwright, or `allwright stop` for a pid-file daemon), then import."),process.exitCode=1;return}try{let n=Ql(t);y.info(`Restored ${n.restored.length} entries into ${se()}`),n.previousDir&&y.info(`Previous config kept at ${n.previousDir}`),y.info("Start the runner and it will reconnect with the restored identity.")}catch(n){y.error(n instanceof Error?n.message:String(n)),process.exitCode=1}});Te.command("test").description("Check local setup: Jira auth, repo mappings, Claude Code binary").action(async()=>{let t=ie(),e=Object.keys(t.repos);if(!t.jira){y.error("no Jira credentials configured - run `allwright init`"),process.exitCode=1;return}let n=e.length?e.map(s=>({jiraProjectKey:"*",repoName:s})):[{jiraProjectKey:"*",repoName:"(none mapped)"}],r=!0;for(let s of n){let i=await co(t,s);for(let o of i){if(s.jiraProjectKey==="*"&&o.name==="jira-project")continue;let l=o.ok?"PASS":"FAIL";(o.ok?y.info:y.error)(`[${l}] ${o.name}: ${o.detail}`),r&&=o.ok}}r||(process.exitCode=1)});function gn(){let t=On();if(t&&Nn(t)&&process.platform!=="win32")try{return process.kill(t,"SIGHUP"),y.info("running runner reloaded its config live - no restart needed"),!0}catch{}let e=t?au(t):null;return y.info(e?`No background runner found to reload, but a service named "${e}" exists here: sudo systemctl kill -s HUP ${e} - otherwise it applies on the next start.`:"No background runner found to reload. Under systemd: sudo systemctl kill -s HUP <your allwright service> (allwright service install names it 'allwright'; installs predating the rename use 'ticketpilot-runner') - otherwise it applies on the next allwright start."),!1}function Hv(t){if(!t.runnerToken)throw new Error("runner not enrolled - run `allwright init`");if(!t.jira)throw new Error("no Jira credentials - run `allwright init`");let e=ou();e.ok||(y.warn(`another runner is already running on this machine (pid ${e.pid}). Two runner processes with one identity kick each other off the control plane every second. Stop the other one first: \`allwright stop\` (background runner) or \`sudo systemctl stop allwright\` (service).`),process.exit(1)),process.on("exit",Mo);let n=new Pe(t.jira),r=new Map,s=d=>{let m=t.repos[d]?.jira;if(!m)return n;let g=r.get(d);return g||(g=new Pe(m),r.set(d,g)),g},i=new Map,o=(d,m)=>{let g=Ku(ye()??t,d,m);switch(g.kind){case"legacy":return{jira:s(d),authored:!1};case"self":return{jira:s(d),authored:!0};case"missing":return{error:g.error};case"user":{let C=`${g.creds.baseUrl}:${g.creds.email}:${g.creds.apiToken.slice(-6)}`,M=i.get(C);return M||(M=new Pe(g.creds),i.set(C,M)),{jira:M,authored:!0}}}},l=new URL("/api/runner/ws",t.controlPlaneUrl);l.protocol=l.protocol==="https:"?"wss:":"ws:";let u=[],c=[],f=[],p,b=null,w={cfg:t,jiraFor:s,transport:null},S=new Set,x=d=>{let m=u.find(C=>C.id===d),g=m&&t.repos[m.repoName];return m&&g?{project:m,repoPath:g.path}:null},A=d=>{let m=u.find(M=>M.id===d),g=t.runnerName?`This runner ("${t.runnerName}")`:"This runner";if(!m)return`${g} does not know that project at all - it may have been deleted, or this runner has not synced yet.`;let C=Object.keys(t.repos).join(", ")||"(none)";return`${g} has no local checkout for "${m.name}" (repo "${m.repoName}"). Repos mapped here: ${C}. Either pin the project to the runner that HAS that repo (Dashboard \u2192 the project \u2192 Edit \u2192 Runner) - do this when several runners are online and the project is unpinned, because then the request goes to whichever one answers first - or map the repo on this machine: allwright repo add ${m.repoName} /path/to/checkout`},j={cfg:t,jiraFor:s,get transport(){return w.transport},lookup:(d,m)=>{let g=x(d),C=f.find(M=>M.projectId===d&&M.name===m);return g&&C?{...g,environment:C}:null}},v=new ao(l.toString(),t.runnerToken,{runnerVersion:yi},{onConfig:d=>{u=d.projects,Zd(d.projects),c=d.rules,f=d.environments,p.setConfig(d.projects,d.rules,d.pollingPaused,d.environments)},onDeployFix:async d=>{let m=x(d.projectId);if(!m){v.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:A(d.projectId)});return}let g=Ke(t,m.project,"assist");if("error"in g){v.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:g.error});return}y.info(`investigating failed deploy of "${d.environmentName}" (step: ${d.failedStep||"?"})`);let C=await _d({agent:g,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,steps:d.steps,failedStep:d.failedStep,errorText:d.errorText,cfg:t});v.sendDeploySuggestResult(d.requestId,C)},onProjectTest:async d=>{let m=u.find(C=>C.id===d.projectId);if(!m){v.sendProjectTestResult(d.requestId,!1,[{name:"config",ok:!1,detail:"project not in this runner's synced config yet"}]);return}y.info(`running connection test for project "${m.name}"`);let g=await co(ye()??t,m,f.filter(C=>C.projectId===m.id),c.filter(C=>C.projectId===m.id).map(C=>"agent"in C.action?C.action.agent:"").filter(Boolean));v.sendProjectTestResult(d.requestId,g.every(C=>C.ok),g)},onRuleDiagnose:async d=>{let m=c.find(L=>L.id===d.ruleId),g=m&&u.find(L=>L.id===m.projectId);if(!m||!g){v.sendRuleDiagnoseResult(d.requestId,{checks:[{name:"config",ok:!1,detail:"rule not in this runner's synced config yet"}],matchedCount:0,excludedCount:0,excludedSample:[]});return}y.info(`diagnosing rule "${m.name}"`);let C=await co(ye()??t,g,m.action.type==="deploy"?f.filter(L=>L.projectId===g.id):[]),M=m.action.type==="implement"?C:C.filter(L=>L.name!=="github-token"),{matchedCount:V,excludedCount:W,excludedSample:ee}=await p.diagnoseRule(m,g);v.sendRuleDiagnoseResult(d.requestId,{checks:M,matchedCount:V,excludedCount:W,excludedSample:ee})},onCancel:d=>{Hc(d)?y.info(`run ${d} stopped from the dashboard`):y.warn(`cancel requested for run ${d}, but nothing is running under that id here - it likely finished already`)},onApproved:(d,m)=>{if(qa(d)){md(j,d).catch(g=>y.error(`deploy approval crashed for ${d}: ${g instanceof Error?g.stack:g}`));return}$s(w,d,m).catch(g=>y.error(`approval handling crashed for ${d}: ${g instanceof Error?g.stack:g}`))},onRetryPush:d=>{let m=Pi(d),g=()=>Qc(w,d).catch(C=>y.error(`retry push crashed for ${d}: ${C instanceof Error?C.stack:C}`));m?p.runOnRepoQueue(m.baseRepoPath,g):g()},onRejected:d=>{if(qa(d)){gd(j,d).catch(m=>y.error(`deploy rejection crashed for ${d}: ${m instanceof Error?m.stack:m}`));return}Xc(w,d).catch(m=>y.error(`rejection handling crashed for ${d}: ${m instanceof Error?m.stack:m}`))},onDeployStart:d=>{let m=`${d.runId}#${d.attempt}`;if(S.has(m))return;S.add(m);let g=x(d.projectId);if(!g){let C=A(d.projectId);y.error(`deploy ${d.runId}: ${C}`),v.send({type:"run.status",runId:d.runId,status:"failed",error:C});return}y.info(`deploy ${d.runId} requested from the dashboard: ${d.issueKey} \u2192 ${d.environment.name}`),p.runOnEnvironmentQueue(d.environment.id,()=>qi({runId:d.runId,project:g.project,environment:d.environment,issueKey:d.issueKey,issueSummary:d.issueSummary,repoPath:g.repoPath,cfg:t,jira:s(g.project.repoName),transport:v,requestedBy:d.requestedBy}).catch(C=>y.error(`deploy crashed for ${d.runId}: ${C instanceof Error?C.stack:C}`)))},onDeploySuggest:async d=>{let m=x(d.projectId);if(!m){v.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:A(d.projectId)});return}let g=Ke(t,m.project,"assist");if("error"in g){v.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:g.error});return}y.info(`asking ${g.adapter.displayName} for "${d.environmentName}" deploy steps in ${m.repoPath}`);let C=await kd({agent:g,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,notes:d.notes,timeoutSeconds:d.timeoutSeconds,cfg:t});v.sendDeploySuggestResult(d.requestId,C)},onEnvPreflight:async d=>{let m=x(d.projectId);if(!m){v.sendEnvPreflightResult(d.requestId,{ok:!1,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project"}]});return}let g=await wd({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,steps:d.steps,requiredSecrets:d.requiredSecrets,workdir:d.workdir,branch:d.branch,publicUrl:d.publicUrl,cfg:t});v.sendEnvPreflightResult(d.requestId,g)},onSelfMigrationApply:async d=>{let m=x(d.projectId);if(!m){v.sendSelfMigrationApplyResult(d.requestId,{ok:!1,file:d.file,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project",fix:[]}],output:"",error:A(d.projectId)});return}y.info(`applying migration ${d.file} for "${d.environmentName}"`);let g=await Wd({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,file:d.file,urlSecret:d.urlSecret,cfg:t});y.info(g.ok?`migration ${d.file} applied`:`migration ${d.file} failed: ${g.error}`),v.sendSelfMigrationApplyResult(d.requestId,g)},onChatTurn:async d=>{let m=x(d.projectId);if(!m){v.sendChatTurnResult(d.requestId,{ok:!1,sessionId:d.sessionId??"",reply:"",error:A(d.projectId)});return}let g=d.sessionId||(0,Hs.randomUUID)(),C=!d.sessionId,M=C?0:Os(g)?.messages.length??0,V=!1,W=0,ee="";if(!C&&M>=Nd){let be=await Dd(m,g,t);if(be)V=!0,W=M,ee=be,g=(0,Hs.randomUUID)(),C=!0,y.info(`chat compacted: ${M} message(s) summarized into a fresh session`);else if(M>=Md){v.sendChatTurnResult(d.requestId,{ok:!1,sessionId:g,reply:"",error:"this chat is very long and could not be compacted automatically - start a new chat (it keeps the repo knowledge; only the conversation resets)."});return}}let L=d.files.length?nu(m.repoPath,d.requestId,d.files):null,D=(0,Ze.replyPreferenceAppendix)({language:d.replyLanguage,languageInstruction:d.replyLanguageInstruction,style:d.replyStyle})+(0,Ze.pendingMigrationsAppendix)(d.pendingMigrations),ne="```",de=C?`You are the project assistant for "${m.project.name}" - this working directory is its repository, and you have read-only access.
|
|
890
890
|
|
|
891
891
|
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.
|
|
892
892
|
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.
|
|
@@ -912,12 +912,17 @@ EXCEPTION - big requirements: when the user asks for an epic with sub-tickets, o
|
|
|
912
912
|
|
|
913
913
|
This conversation was already running and has been compacted. Everything agreed so far, in summary form - treat it as established, do not re-ask:
|
|
914
914
|
${ee}
|
|
915
|
-
`:"")+
|
|
916
|
-
${d.userName||"The user"} says: ${d.message}`+(
|
|
915
|
+
`:"")+D+`
|
|
916
|
+
${d.userName||"The user"} says: ${d.message}`+(L?.section??""):D+`${d.userName||"The user"} says: ${d.message}`+(L?.section??""),he=0,Ne=[],pe;try{let be=Ke(t,m.project,"chat");if("error"in be){v.sendChatTurnResult(d.requestId,{ok:!1,sessionId:g,reply:"",error:be.error});return}pe=await be.adapter.run({repoPath:m.repoPath,prompt:de,timeoutSeconds:180,bin:be.bin,mode:"read_only",maxTurns:25,model:d.model||be.adapter.fastModel,sessionId:g,resume:!C,onLog:(ue,Ie)=>{ue==="agent"&&(Ne.push(Ie.slice(0,4e3)),v.send({type:"chat.stream",requestId:d.requestId,seq:he++,text:Ie.slice(0,8e3)}))},onUsage:ue=>{v.send({type:"chat.usage",requestId:d.requestId,inputTokens:Math.round(ue.inputTokens),outputTokens:Math.round(ue.outputTokens),cacheReadTokens:ue.cacheReadTokens===void 0?void 0:Math.round(ue.cacheReadTokens),turns:ue.turns})}})}finally{L&&ft.default.rmSync(L.dir,{recursive:!0,force:!0})}if(pe.ok){let be=Ne.filter(ue=>ue.trim()&&!pe.resultText.trim().startsWith(ue.trim()));jd(d.projectId,g,d.message,pe.resultText,be,d.files.map(ue=>ue.name))}let ve=(pe.inputTokens??0)+(pe.cacheReadTokens??0);v.sendChatTurnResult(d.requestId,{contextTokens:ve,contextLimit:zd(pe.model||d.model||""),compacted:V,compactedMessages:W,ok:pe.ok,sessionId:g,reply:pe.resultText,error:pe.ok?void 0:pe.error??"the agent produced no reply",inputTokens:pe.inputTokens,outputTokens:pe.outputTokens,cacheReadTokens:pe.cacheReadTokens,costUsd:pe.costUsd,model:pe.model??""})},onChatList:d=>{v.sendChatListResult(d.requestId,Od(d.projectId))},onRepoDocs:d=>{let m=x(d.projectId);if(!m){v.sendRepoDocsResult(d.requestId,{ok:!1,docs:[],error:A(d.projectId)});return}v.sendRepoDocsResult(d.requestId,{ok:!0,docs:Fd(m.repoPath)})},onRepoDocRead:d=>{let m=x(d.projectId);if(!m){v.sendRepoDocReadResult(d.requestId,{ok:!1,path:d.path,content:"",truncated:!1,error:A(d.projectId)});return}let g=Bd(m.repoPath,d.path);v.sendRepoDocReadResult(d.requestId,{ok:g.ok,path:g.ok?g.path:d.path,content:g.ok?g.content:"",truncated:g.ok?g.truncated:!1,error:g.ok?void 0:g.error})},onChatLoad:d=>{let m=Os(d.sessionId);v.sendChatLoadResult(d.requestId,{ok:m!==null,projectId:m?.projectId??"",messages:m?.messages??[],error:m?void 0:"chat not found on this runner (pruned or never existed)"})},onBoardFetch:async d=>{let m=x(d.projectId);if(!m){v.sendBoardFetchResult(d.requestId,{ok:!1,columns:[],error:A(d.projectId)});return}try{let g=s(m.project.repoName),C;try{C=await g.searchBoard(`project = "${m.project.jiraProjectKey}" ORDER BY Rank ASC`,100)}catch{C=await g.searchBoard(`project = "${m.project.jiraProjectKey}" ORDER BY updated DESC`,100)}let M=await g.boardColumns(m.project.jiraProjectKey),V;if(M){V=M.map(L=>({name:L.name,issues:[]}));let ee=new Map;for(let L of C){let D=M.findIndex(de=>de.statusIds.includes(L.statusId)),ne={key:L.key,summary:L.summary,labels:L.labels};if(D>=0)V[D].issues.push(ne);else{let de=ee.get(L.status)??[];de.push(ne),ee.set(L.status,de)}}for(let[L,D]of ee)V.push({name:L,issues:D})}else{let ee=he=>he.trim().toLowerCase(),L=new Map,D=new Map;for(let he of C){let Ne=ee(he.status);L.has(Ne)||L.set(Ne,he.status.trim());let pe=D.get(Ne)??[];pe.push({key:he.key,summary:he.summary,labels:he.labels}),D.set(Ne,pe)}let ne=[];try{ne=await g.projectStatuses(m.project.jiraProjectKey)}catch{}let de=[];for(let he of ne){let Ne=ee(he);!de.includes(Ne)&&D.has(Ne)&&de.push(Ne)}for(let he of D.keys())de.includes(he)||de.push(he);V=de.map(he=>({name:L.get(he)??he,issues:D.get(he)??[]}))}let W=t.repos[m.project.repoName]?.jira??t.jira;v.sendBoardFetchResult(d.requestId,{ok:!0,browseBaseUrl:(W?.baseUrl??"").replace(/\/+$/,""),columns:V})}catch(g){v.sendBoardFetchResult(d.requestId,{ok:!1,columns:[],error:g instanceof Error?g.message:String(g)})}},onBoardTrigger:async d=>{let m=x(d.projectId);if(!m){v.sendBoardTriggerResult(d.requestId,{ok:!1,error:A(d.projectId)});return}try{let g=s(m.project.repoName),C=d.comment.trim()?o(m.project.repoName,d.requestedByEmail):{jira:g,authored:!1};if(C.error!==void 0){v.sendBoardTriggerResult(d.requestId,{ok:!1,error:C.error});return}if(d.reimplement){let M=await g.getIssue(d.issueKey),V=M.comments.filter(L=>_t(L.body)),W=V.length?Math.max(...V.map(L=>new Date(L.created).getTime())):0;if(!M.comments.some(L=>!_t(L.body)&&new Date(L.created).getTime()>W)){v.sendBoardTriggerResult(d.requestId,{ok:!1,error:`${d.issueKey} has nothing new since the last implementation - add a comment describing what should change, then hit Implement again. Re-running with the same ticket would just rebuild the same thing.`});return}await g.editLabels(d.issueKey,{remove:["agent-implemented"]})}d.removeLabel.trim()&&await g.editLabels(d.issueKey,{remove:[d.removeLabel.trim()]}),d.comment.trim()&&await C.jira.addTriggerComment(d.issueKey,`${d.comment.trim()}`+(!C.authored&&d.requestedBy?`
|
|
917
917
|
|
|
918
|
-
_(requested by ${d.requestedBy} via Allwright)_`:"")),y.info(`Board action on ${d.issueKey}`+(d.comment?` comment "${d.comment.trim()}"`:"")+(d.removeLabel?` -label ${d.removeLabel}`:"")+(d.requestedBy?` by ${d.requestedBy}`:"")),v.sendBoardTriggerResult(d.requestId,{ok:!0})}catch(g){v.sendBoardTriggerResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onChatCreateTicket:async d=>{let m=x(d.projectId);if(!m){v.sendChatCreateTicketResult(d.requestId,{ok:!1,issueKey:"",error:
|
|
918
|
+
_(requested by ${d.requestedBy} via Allwright)_`:"")),y.info(`Board action on ${d.issueKey}`+(d.comment?` comment "${d.comment.trim()}"`:"")+(d.removeLabel?` -label ${d.removeLabel}`:"")+(d.requestedBy?` by ${d.requestedBy}`:"")),v.sendBoardTriggerResult(d.requestId,{ok:!0})}catch(g){v.sendBoardTriggerResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onChatCreateTicket:async d=>{let m=x(d.projectId);if(!m){v.sendChatCreateTicketResult(d.requestId,{ok:!1,issueKey:"",error:A(d.projectId)});return}try{let g=o(m.project.repoName,d.requestedByEmail);if(g.error!==void 0){v.sendChatCreateTicketResult(d.requestId,{ok:!1,issueKey:"",error:g.error});return}let C=`
|
|
919
919
|
|
|
920
920
|
---
|
|
921
|
-
_Created via Allwright Compose`+(!g.authored&&d.requestedBy?` by ${d.requestedBy}`:"")+", drafted with the project agent._";if(d.asEpic&&d.createAs!=="epic_with_children"&&d.children.length){let W=d.createAs==="separate_epics"?"Epic":"Task",ee=[];for(let
|
|
921
|
+
_Created via Allwright Compose`+(!g.authored&&d.requestedBy?` by ${d.requestedBy}`:"")+", drafted with the project agent._";if(d.asEpic&&d.createAs!=="epic_with_children"&&d.children.length){let W=d.createAs==="separate_epics"?"Epic":"Task",ee=[];for(let L of d.children){let D=await g.jira.createIssue(m.project.jiraProjectKey,L.summary,(L.description||"(no description)")+C,W);ee.push(D.key)}y.info(`Compose created ${ee.length} standalone ${W.toLowerCase()}(s)`),v.sendChatCreateTicketResult(d.requestId,{ok:!0,issueKey:ee[0]??"",childKeys:ee});return}let{key:M}=await g.jira.createIssue(m.project.jiraProjectKey,d.summary,(d.description||"(no description)")+C,d.asEpic?"Epic":"Task");d.files.length&&await g.jira.addAttachments(M,d.files.map(W=>({name:W.name,content:Buffer.from(W.contentBase64,"base64")}))).then(()=>y.info(`Compose attached ${d.files.length} file(s) to ${M}`)).catch(W=>y.warn(`Compose could not attach files to ${M}: ${W instanceof Error?W.message:W}`));let V=[];if(d.asEpic){for(let W of d.children){let ee=await g.jira.createIssue(m.project.jiraProjectKey,W.summary,W.description||"(no description)","Task",M);V.push(ee.key)}y.info(`Compose created epic ${M} with ${V.length} child ticket(s)`),v.sendChatCreateTicketResult(d.requestId,{ok:!0,issueKey:M,childKeys:V});return}d.triggerComment.trim()&&await g.jira.addTriggerComment(M,`${d.triggerComment.trim()}`+(!g.authored&&d.requestedBy?`
|
|
922
922
|
|
|
923
|
-
_(requested by ${d.requestedBy} via Allwright)_`:"")),y.info(`Compose created ${M}`+(d.requestedBy?` for ${d.requestedBy}`:"")+(d.triggerComment?` with trigger "${d.triggerComment.trim()}"`:"")),v.sendChatCreateTicketResult(d.requestId,{ok:!0,issueKey:M})}catch(g){v.sendChatCreateTicketResult(d.requestId,{ok:!1,issueKey:"",error:g instanceof Error?g.message:String(g)})}},onAuditStart:async d=>{let m=x(d.projectId);if(!m){v.sendAuditStartResult(d.requestId,{ok:!1,error:E(d.projectId)});return}try{y.info(`Audit (${d.role}) starting on ${m.project.repoName}`+(d.scope.kind!=="repo"?` scoped to ${d.scope.kind}:${d.scope.ref}`:""));let g=Ke(t,m.project,"assist");if("error"in g){v.sendAuditStartResult(d.requestId,{ok:!1,error:g.error});return}let C=await Yr({projectId:d.projectId,repoPath:m.repoPath,role:d.role,scope:d.scope,detailLevel:d.detailLevel,model:d.model,agent:g,jira:s(m.project.repoName)});if(!C.ok){v.sendAuditStartResult(d.requestId,{ok:!1,error:C.error});return}v.sendAuditStartResult(d.requestId,{ok:!0,audit:C.audit})}catch(g){v.sendAuditStartResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onAuditList:async d=>{try{v.sendAuditListResult(d.requestId,{ok:!0,audits:lc(d.projectId)})}catch(m){v.sendAuditListResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditGet:async d=>{try{let m=dc(d.projectId,d.auditId);if(!m){v.sendAuditGetResult(d.requestId,{ok:!1,error:"audit not found on this runner"});return}v.sendAuditGetResult(d.requestId,{ok:!0,audit:m})}catch(m){v.sendAuditGetResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditReview:async d=>{try{let m=ha(d.projectId,d.auditId,{selected:d.selected,ticketed:d.ticketed,verdicts:d.verdicts,verdictBy:d.verdictBy});if(!m){v.sendAuditReviewResult(d.requestId,{ok:!1,error:"audit not found on this runner"});return}let g=x(d.projectId);if(g&&d.verdicts.length){let C=[];for(let M of d.verdicts){if(M.verdict==="valid"||m.lessonsWritten.includes(M.findingId))continue;let V=m.findings.find(W=>W.id===M.findingId);V&&(ya(g.repoPath,m.role,bc(V,M.verdict,M.note,d.verdictBy)),C.push(M.findingId),y.info(`Lesson written (${m.role}): ${M.verdict} - ${V.title.slice(0,60)}`))}C.length&&(m=ha(d.projectId,d.auditId,{markLessonsWritten:C})??m)}v.sendAuditReviewResult(d.requestId,{ok:!0,audit:m})}catch(m){v.sendAuditReviewResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onKnowledgeList:async d=>{let m=x(d.projectId);if(!m){v.sendKnowledgeListResult(d.requestId,{ok:!1,error:E(d.projectId)});return}try{v.sendKnowledgeListResult(d.requestId,{ok:!0,files:wc(m.repoPath)})}catch(g){v.sendKnowledgeListResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onKnowledgeSave:async d=>{let m=x(d.projectId);if(!m){v.sendKnowledgeSaveResult(d.requestId,{ok:!1,error:E(d.projectId)});return}try{d.append?ya(m.repoPath,d.role,vc(d.content,d.by),d.level):_c(m.repoPath,d.role,d.level,d.source,d.name,d.content),y.info(`Knowledge ${d.append?"taught":"saved"}: ${d.role}/${d.level}/${d.name}`),v.sendKnowledgeSaveResult(d.requestId,{ok:!0})}catch(g){v.sendKnowledgeSaveResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onEpicList:async d=>{let m=x(d.projectId);if(!m){v.sendEpicListResult(d.requestId,{ok:!1,error:E(d.projectId)});return}try{let g=s(m.project.repoName);if(d.epicKey){let C=await g.epicChildren(d.epicKey);v.sendEpicListResult(d.requestId,{ok:!0,children:C})}else{let C=await g.searchEpics(m.project.jiraProjectKey);v.sendEpicListResult(d.requestId,{ok:!0,epics:C})}}catch(g){v.sendEpicListResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onEpicSuggest:async d=>{let m=x(d.projectId);if(!m){v.sendEpicSuggestResult(d.requestId,{ok:!1,error:E(d.projectId)});return}try{let g=s(m.project.repoName),C=await g.epicChildren(d.epicKey),M=Yu(C);if(!M.length){v.sendEpicSuggestResult(d.requestId,{ok:!1,error:`every child of ${d.epicKey} is already done or in an agent's hands - nothing to sequence`});return}if(M.length===1){v.sendEpicSuggestResult(d.requestId,{ok:!0,issueKey:M[0].key,reason:"It's the only pending ticket left in this epic.",considered:1});return}let V=await Promise.all(M.slice(0,12).map(async ne=>{try{let de=await g.getIssue(ne.key);return{...ne,description:de.description}}catch{return{...ne,description:""}}})),W=(await g.getIssue(d.epicKey).catch(()=>null))?.summary??"";y.info(`Epic suggest: weighing ${V.length} pending children of ${d.epicKey}`);let ee=Ke(t,m.project,"assist");if("error"in ee){v.sendEpicSuggestResult(d.requestId,{ok:!1,error:ee.error});return}let D=await ee.adapter.run({repoPath:m.repoPath,prompt:Xu(d.epicKey,W,V),timeoutSeconds:150,bin:ee.bin,mode:"read_only",maxTurns:20,sessionId:(0,Hs.randomUUID)(),model:d.model||"claude-sonnet-5",onLog:()=>{}}),U=Qu(D.resultText,V.map(ne=>ne.key));if("error"in U){v.sendEpicSuggestResult(d.requestId,{ok:!1,error:U.error});return}y.info(`Epic suggest: ${d.epicKey} -> do ${U.issueKey} first`),v.sendEpicSuggestResult(d.requestId,{ok:!0,issueKey:U.issueKey,reason:U.reason,considered:V.length})}catch(g){v.sendEpicSuggestResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onTeamCreds:async d=>{try{let m=ye()??t;if(m.github?.token&&!m.github.login)try{let{GitHubClient:C}=await Promise.resolve().then(()=>(ut(),or));m.github.login=await new C(m.github.token).whoami(),ge(m)}catch{}let g=Hu(m,d.emails);v.sendTeamCredsResult(d.requestId,{ok:!0,...g})}catch(m){v.sendTeamCredsResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupStatus:async d=>{try{let m=ye()??t,{buildSetupReport:g}=await Promise.resolve().then(()=>(df(),cf)),C=await g(m,d.repoNames);v.sendSetupStatusResult(d.requestId,{ok:!0,...C})}catch(m){v.sendSetupStatusResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdGenerate:async d=>{try{let m=x(d.projectId);if(!m){v.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=d.kind==="deploy"?"DEPLOY.md":d.kind==="design"?"DESIGN.md":"CLAUDE.md";y.info(`Setup: drafting ${g} for ${m.project.repoName}`);let C="Explore this repository and draft the content of a CLAUDE.md file for its repo root - the memory file AI agents read before working on tickets here. Cover: what the product does (one paragraph), the tech stack, how the code is organized (key directories and what lives in them), exact commands to install dependencies / build / run tests, code conventions worth following, and gotchas a newcomer would trip over. Under 150 lines, factual, no marketing language, nothing you cannot verify from the code. Reply with ONLY the file content - no preamble, no fences around the whole thing.",M='Inspect this repository (deploy scripts, CI files, server configs, package scripts) and draft the content of a DEPLOY.md deploy contract for its repo root. An automation tool will follow it LITERALLY, so only write what you can verify from the repo. IMPORTANT: you are running ON the machine where deploys will execute - commands are plain local commands, no ssh wrapper, unless the repo clearly documents a different target machine. For each environment that VERIFIABLY exists: name, branch, exact deploy commands, secrets as $NAMES only (never values), pre/post checks (post-restart checks must wait and retry - services report active before their port binds). Where you cannot verify something (hosts, service names, ports), write it with a clear "VERIFY:" marker so the human fills it in during review, instead of guessing. State explicitly which environments do NOT exist. Reply with ONLY the file content - no preamble, no fences around the whole thing.',V=`Explore this repository's UI code and draft the content of a DESIGN.md file for its repo root - the design guidelines AI agents will follow for anything user-facing here. This is a SEED DRAFT: extract only what the code proves, and leave taste to the humans. Cover, from real evidence (tailwind/theme configs, design tokens, CSS, component libraries, existing screens): the color palette actually in use (names + hex), typography (families, the size scale), spacing and layout conventions, the component idiom (which library, how buttons/forms/cards are built, naming), dark mode, responsive breakpoints, and accessibility patterns already present. For everything code cannot prove - brand intent, tone of voice, look-and-feel references, what to never do - write a line starting with "VERIFY:" phrased as a question for the human to answer during review, instead of guessing. If the project has no UI at all, say exactly that in one line and stop. Under 120 lines, factual, no marketing language. Reply with ONLY the file content - no preamble, no fences around the whole thing.`,W=Ke(t,m.project,"assist");if("error"in W){v.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,content:"",error:W.error});return}let D=(await W.adapter.run({repoPath:m.repoPath,prompt:d.kind==="deploy"?M:d.kind==="design"?V:C,timeoutSeconds:240,bin:W.bin,mode:"read_only",maxTurns:40,sessionId:(0,Hs.randomUUID)(),onLog:()=>{}})).resultText.trim();if(!D){v.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:"the agent returned no content - try again"});return}v.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!0,content:D})}catch(m){v.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdSave:async d=>{try{let m=x(d.projectId);if(!m){v.sendSetupClaudeMdSaveResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=d.kind==="deploy"?"DEPLOY.md":d.kind==="design"?"DESIGN.md":"CLAUDE.md",C=await bl({repoPath:m.repoPath,relPath:g,content:d.content,overwrite:d.overwrite,commitMessage:`Add ${g} (agent-drafted, human-approved via Allwright)`});C.ok&&y.info(`Setup: wrote human-approved ${g} to ${m.repoPath}`),v.sendSetupClaudeMdSaveResult(d.requestId,C)}catch(m){v.sendSetupClaudeMdSaveResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRepoDocSave:async d=>{try{let m=x(d.projectId);if(!m){v.sendRepoDocSaveResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=await bl({repoPath:m.repoPath,relPath:d.relPath,content:d.content,overwrite:d.overwrite,commitMessage:`Add ${d.relPath.trim()} (written in Allwright Compose, human-approved)`});g.ok&&y.info(`Saved approved doc ${d.relPath} into ${m.repoPath}`),v.sendRepoDocSaveResult(d.requestId,g)}catch(m){v.sendRepoDocSaveResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditStats:d=>{try{v.sendAuditStatsResult(d.requestId,{ok:!0,byProject:uc(d.projectIds,d.since)})}catch(m){v.sendAuditStatsResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRunnerUpdate:async d=>{if(!process.env.INVOCATION_ID){v.sendRunnerUpdateResult(d.requestId,{ok:!1,error:"this runner is not running as a systemd service, so it cannot restart itself after updating. On the machine run: allwright update && allwright stop && allwright start"});return}let m=()=>{y.info("Installing allwright@latest");let C=ds.default.dirname(process.execPath),M=ft.default.existsSync(ds.default.join(C,"npm"))?ds.default.join(C,"npm"):"npm";(0,Gt.execFile)(M,["install","-g","allwright@latest"],{timeout:18e4,env:{...process.env,PATH:`${C}:${process.env.PATH??""}`}},(V,W,ee)=>{if(V){v.sendRunnerUpdateResult(d.requestId,{ok:!1,error:`npm install failed: ${(ee||V.message).slice(0,300)} - on the machine run: allwright update && sudo systemctl restart allwright`});return}v.sendRunnerUpdateResult(d.requestId,{ok:!0,note:"updated - restarting now, back in a few seconds"}),y.info("Update installed; exiting so systemd restarts on the new version"),setTimeout(()=>process.exit(0),1500)})};if(p.idle){m();return}if(b){v.sendRunnerUpdateResult(d.requestId,{ok:!0,scheduled:!0,note:"an update is already scheduled and will install once the current work finishes"});return}let g=p.busyCount;v.sendRunnerUpdateResult(d.requestId,{ok:!0,scheduled:!0,note:`scheduled - ${g} run(s)/deploy(s) active right now. Nothing is refused meanwhile; the install runs automatically as soon as this machine goes idle.`}),y.info(`Update scheduled: waiting for ${g} active run(s)/deploy(s) to finish`),b=setInterval(()=>{p.idle&&(clearInterval(b),b=null,m())},5e3)},onTestFix:async d=>{let m=g=>v.sendTestFixResult(d.requestId,{ok:!1,note:g});try{let g=Qr(d.runId);if(!g){m("this runner no longer has that PR on file - it may have been decided already");return}let C=t.repos[g.repoName];if(!C){m(`no local checkout mapped for "${g.repoName}" on this machine`);return}let M=Ee(t,g.repoName);if(!M){m("no GitHub token on this runner for that repo");return}let V=await new $e(M).getPullRequest(g.owner,g.repo,g.prNumber);if(!V){m("that pull request no longer exists on GitHub");return}if(V.merged||V.state==="closed"){m("that pull request is already merged or closed - there is nothing left to fix");return}let W=u.find(ne=>ne.repoName===g.repoName),ee=g.nextDecisionSeq??1e5,D=(ne,de)=>{v.send({type:"run.log",runId:d.runId,seq:ee++,ts:new Date().toISOString(),level:ne,message:de}),g.nextDecisionSeq=ee,ct(g)},U=await Ad({cfg:t,repoPath:C.path,branch:g.branch,baseBranch:V.baseRef||"main",issueKey:g.issueKey,agentId:W?.defaultAgent||Ze.DEFAULT_AGENT_ID,configDir:g.agentConfigDir,failedTests:d.failedTests,timeoutSeconds:900,onLog:D});U.ok&&U.headSha&&(g.headSha=U.headSha,ct(g),v.send({type:"run.status",runId:d.runId,status:"awaiting_approval",headSha:U.headSha,failedTests:U.remaining??[],...U.testsPassed!==void 0?{testsPassed:U.testsPassed}:{},...U.testsTotal!==void 0?{testsTotal:U.testsTotal}:{},...U.costUsd!==void 0?{costUsd:U.costUsd}:{},...U.inputTokens!==void 0?{inputTokens:U.inputTokens}:{},...U.outputTokens!==void 0?{outputTokens:U.outputTokens}:{}})),lt(C.path,{issueKey:g.issueKey,runId:d.runId,title:U.ok?U.headSha?(U.remaining??[]).length?"dashboard test fix pushed, some commands still failing":"tests fixed from the dashboard":"dashboard test fix: agent changed nothing":"dashboard test fix failed",detail:U.note.slice(0,500)}),v.sendTestFixResult(d.requestId,U)}catch(g){m(g instanceof Error?g.message.slice(0,300):String(g))}},onRunAnswer:async d=>{try{let m=await p.answerPendingInput(d.runId,d.text,d.answeredBy);v.sendRunAnswerResult(d.requestId,m)}catch(m){v.sendRunAnswerResult(d.requestId,{ok:!1,error:m instanceof Error?m.message.slice(0,300):String(m)})}},onResolveConflict:async d=>{let m=g=>v.sendResolveConflictResult(d.requestId,{ok:!1,note:g});try{let g=Qr(d.runId);if(!g){m("this runner no longer has that PR on file - it may have been decided already");return}let C=t.repos[g.repoName];if(!C){m(`no local checkout mapped for "${g.repoName}" on this machine`);return}let M=Ee(t,g.repoName);if(!M){m("no GitHub token on this runner for that repo");return}let V=await new $e(M).getPullRequest(g.owner,g.repo,g.prNumber);if(!V){m("that pull request no longer exists on GitHub");return}if(!V.baseRef){m("GitHub did not report the PR's base branch, so there is nothing to merge in");return}let W=u.find(ne=>ne.repoName===g.repoName),ee=g.nextDecisionSeq??1e5,D=(ne,de)=>{v.send({type:"run.log",runId:d.runId,seq:ee++,ts:new Date().toISOString(),level:ne,message:de}),g.nextDecisionSeq=ee,ct(g)},U=await Id({cfg:t,repoPath:C.path,branch:g.branch,baseBranch:V.baseRef,issueKey:g.issueKey,agentId:W?.defaultAgent||Ze.DEFAULT_AGENT_ID,configDir:g.agentConfigDir,timeoutSeconds:900,onLog:D});U.ok&&U.headSha&&(g.headSha=U.headSha,g.conflictNotified=!1,ct(g),v.send({type:"run.pr.conflict",runId:d.runId,conflicted:!1}),v.send({type:"run.status",runId:d.runId,status:"awaiting_approval",headSha:U.headSha,...U.costUsd!==void 0?{costUsd:U.costUsd}:{},...U.inputTokens!==void 0?{inputTokens:U.inputTokens}:{},...U.outputTokens!==void 0?{outputTokens:U.outputTokens}:{}})),v.sendResolveConflictResult(d.requestId,U)}catch(g){m(g instanceof Error?g.message.slice(0,300):String(g))}},onAgentProfiles:d=>{try{let m=C=>{try{return ft.default.existsSync(C)&&ft.default.readdirSync(C).length>0}catch{return!1}},g=Object.entries(t.claudeProfiles).map(([C,M])=>({agent:"claude-code",name:C,loggedIn:m(M.configDir)}));v.sendAgentProfilesResult(d.requestId,{ok:!0,profiles:g,defaultLoggedIn:m(ds.default.join(wl.default.homedir(),".claude")),agentsWithoutProfiles:Ze.REGISTERED_AGENTS.filter(C=>!C.capabilities.loginProfiles).map(C=>C.id)})}catch(m){v.sendAgentProfilesResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onJiraUsers:async d=>{try{let m=await n.searchUsers(d.query);v.sendJiraUsersResult(d.requestId,{ok:!0,users:m})}catch(m){v.sendJiraUsersResult(d.requestId,{ok:!1,users:[],error:m instanceof Error?m.message:String(m)})}}});w.transport=v,p=new Hi(t,s,v);let O=Object.values(lr()).filter(d=>d.kind==="implement").map(d=>d.repoPath);Wo(Object.values(t.repos).map(d=>d.path),O).catch(()=>{}),v.start(),p.start();let H=()=>{y.info("shutting down"),b&&clearInterval(b),v.stop(),iu(process.pid),Mo(),process.exit(0)},z=!1,B=()=>{if(z){y.warn("second stop signal - exiting NOW; the interrupted run will be marked failed"),H();return}if(z=!0,p.stop(),p.idle){H();return}y.info(`stop requested - no new work will start; waiting for ${p.busyCount} active run(s)/deploy(s) to finish. Send the signal again to kill them immediately.`);let d=setInterval(()=>{p.idle&&(clearInterval(d),H())},3e3)};process.on("SIGINT",B),process.on("SIGTERM",B),process.on("SIGHUP",()=>{try{let d=ie();if(!d.jira)throw new Error("no Jira credentials in the reloaded config");for(let m of Object.keys(t))delete t[m];Object.assign(t,d),n=new Pe(d.jira),r.clear(),y.info("config reloaded live - new Jira tokens/repos/rules apply from the next poll. (Poll interval and control-plane URL still need a restart.)")}catch(d){y.error(`config reload failed - keeping the running config: ${d instanceof Error?d.message:String(d)}`)}})}Te.command("start").description("Start watching Jira. Runs in the background by default - close this terminal and it keeps going until you run `allwright stop`. Use --foreground to keep it attached (e.g. under systemd).").option("--foreground","run in this terminal instead of detaching to the background").action(async t=>{let e=ie();if(t.foreground){Hv(e);return}let n=On();if(n&&Nn(n)){y.info(`already running in the background (pid ${n}). Use \`allwright status\` or \`stop\`.`);return}let r=bs();if(r){y.info(`a runner is already running on this machine (pid ${r}) - most likely the systemd service. One machine runs ONE runner; nothing to do. (Service controls: sudo systemctl status|stop|restart allwright)`);return}let s=ru(),i=(0,Gt.spawn)(process.execPath,[process.argv[1],"start","--foreground"],{detached:!0,stdio:["ignore",s,s]});i.unref(),su(i.pid),y.info(`Runner started in the background (pid ${i.pid}).`),y.info(`Logs: ${ai()}`),y.info("It will keep polling Jira until you run `allwright stop` - closing this terminal is fine.")});Te.command("stop").description("Stop the background runner started by `start`. Graceful by default: it stops taking new work and exits once active runs and deploys finish - safe to use while customers' tickets are running.").option("--force","kill immediately - anything executing is interrupted and marked failed").action(t=>{let e=On();if(!e||!Nn(e)){y.info("no background runner is running"),e&&ft.default.rmSync(zr(),{force:!0});return}if(t.force){process.kill(e,"SIGKILL"),ft.default.rmSync(zr(),{force:!0}),y.info(`killed (pid ${e}) - any interrupted run will show as failed on the dashboard`);return}process.kill(e,"SIGTERM"),y.info(`stop signal sent (pid ${e}) - it stops polling now and exits once active work finishes (watch \`allwright status\`). Use --force to kill immediately.`)});Te.command("status").description("Check whether the background runner is running").action(()=>{let t=On();t&&Nn(t)?y.info(`running in the background (pid ${t})`):y.info("not running")});Te.parseAsync().catch(t=>{y.error(t instanceof Error?t.message:String(t)),process.exit(1)});
|
|
923
|
+
_(requested by ${d.requestedBy} via Allwright)_`:"")),y.info(`Compose created ${M}`+(d.requestedBy?` for ${d.requestedBy}`:"")+(d.triggerComment?` with trigger "${d.triggerComment.trim()}"`:"")),v.sendChatCreateTicketResult(d.requestId,{ok:!0,issueKey:M})}catch(g){v.sendChatCreateTicketResult(d.requestId,{ok:!1,issueKey:"",error:g instanceof Error?g.message:String(g)})}},onAuditStart:async d=>{let m=x(d.projectId);if(!m){v.sendAuditStartResult(d.requestId,{ok:!1,error:A(d.projectId)});return}try{y.info(`Audit (${d.role}) starting on ${m.project.repoName}`+(d.scope.kind!=="repo"?` scoped to ${d.scope.kind}:${d.scope.ref}`:""));let g=Ke(t,m.project,"assist");if("error"in g){v.sendAuditStartResult(d.requestId,{ok:!1,error:g.error});return}let C=await Yr({projectId:d.projectId,repoPath:m.repoPath,role:d.role,scope:d.scope,detailLevel:d.detailLevel,model:d.model,agent:g,jira:s(m.project.repoName)});if(!C.ok){v.sendAuditStartResult(d.requestId,{ok:!1,error:C.error});return}v.sendAuditStartResult(d.requestId,{ok:!0,audit:C.audit})}catch(g){v.sendAuditStartResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onAuditList:async d=>{try{v.sendAuditListResult(d.requestId,{ok:!0,audits:lc(d.projectId)})}catch(m){v.sendAuditListResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditGet:async d=>{try{let m=dc(d.projectId,d.auditId);if(!m){v.sendAuditGetResult(d.requestId,{ok:!1,error:"audit not found on this runner"});return}v.sendAuditGetResult(d.requestId,{ok:!0,audit:m})}catch(m){v.sendAuditGetResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditReview:async d=>{try{let m=ha(d.projectId,d.auditId,{selected:d.selected,ticketed:d.ticketed,verdicts:d.verdicts,verdictBy:d.verdictBy});if(!m){v.sendAuditReviewResult(d.requestId,{ok:!1,error:"audit not found on this runner"});return}let g=x(d.projectId);if(g&&d.verdicts.length){let C=[];for(let M of d.verdicts){if(M.verdict==="valid"||m.lessonsWritten.includes(M.findingId))continue;let V=m.findings.find(W=>W.id===M.findingId);V&&(ya(g.repoPath,m.role,bc(V,M.verdict,M.note,d.verdictBy)),C.push(M.findingId),y.info(`Lesson written (${m.role}): ${M.verdict} - ${V.title.slice(0,60)}`))}C.length&&(m=ha(d.projectId,d.auditId,{markLessonsWritten:C})??m)}v.sendAuditReviewResult(d.requestId,{ok:!0,audit:m})}catch(m){v.sendAuditReviewResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onKnowledgeList:async d=>{let m=x(d.projectId);if(!m){v.sendKnowledgeListResult(d.requestId,{ok:!1,error:A(d.projectId)});return}try{v.sendKnowledgeListResult(d.requestId,{ok:!0,files:wc(m.repoPath)})}catch(g){v.sendKnowledgeListResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onKnowledgeSave:async d=>{let m=x(d.projectId);if(!m){v.sendKnowledgeSaveResult(d.requestId,{ok:!1,error:A(d.projectId)});return}try{d.append?ya(m.repoPath,d.role,vc(d.content,d.by),d.level):_c(m.repoPath,d.role,d.level,d.source,d.name,d.content),y.info(`Knowledge ${d.append?"taught":"saved"}: ${d.role}/${d.level}/${d.name}`),v.sendKnowledgeSaveResult(d.requestId,{ok:!0})}catch(g){v.sendKnowledgeSaveResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onEpicList:async d=>{let m=x(d.projectId);if(!m){v.sendEpicListResult(d.requestId,{ok:!1,error:A(d.projectId)});return}try{let g=s(m.project.repoName);if(d.epicKey){let C=await g.epicChildren(d.epicKey);v.sendEpicListResult(d.requestId,{ok:!0,children:C})}else{let C=await g.searchEpics(m.project.jiraProjectKey);v.sendEpicListResult(d.requestId,{ok:!0,epics:C})}}catch(g){v.sendEpicListResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onEpicSuggest:async d=>{let m=x(d.projectId);if(!m){v.sendEpicSuggestResult(d.requestId,{ok:!1,error:A(d.projectId)});return}try{let g=s(m.project.repoName),C=await g.epicChildren(d.epicKey),M=Yu(C);if(!M.length){v.sendEpicSuggestResult(d.requestId,{ok:!1,error:`every child of ${d.epicKey} is already done or in an agent's hands - nothing to sequence`});return}if(M.length===1){v.sendEpicSuggestResult(d.requestId,{ok:!0,issueKey:M[0].key,reason:"It's the only pending ticket left in this epic.",considered:1});return}let V=await Promise.all(M.slice(0,12).map(async ne=>{try{let de=await g.getIssue(ne.key);return{...ne,description:de.description}}catch{return{...ne,description:""}}})),W=(await g.getIssue(d.epicKey).catch(()=>null))?.summary??"";y.info(`Epic suggest: weighing ${V.length} pending children of ${d.epicKey}`);let ee=Ke(t,m.project,"assist");if("error"in ee){v.sendEpicSuggestResult(d.requestId,{ok:!1,error:ee.error});return}let L=await ee.adapter.run({repoPath:m.repoPath,prompt:Xu(d.epicKey,W,V),timeoutSeconds:150,bin:ee.bin,mode:"read_only",maxTurns:20,sessionId:(0,Hs.randomUUID)(),model:d.model||"claude-sonnet-5",onLog:()=>{}}),D=Qu(L.resultText,V.map(ne=>ne.key));if("error"in D){v.sendEpicSuggestResult(d.requestId,{ok:!1,error:D.error});return}y.info(`Epic suggest: ${d.epicKey} -> do ${D.issueKey} first`),v.sendEpicSuggestResult(d.requestId,{ok:!0,issueKey:D.issueKey,reason:D.reason,considered:V.length})}catch(g){v.sendEpicSuggestResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onTeamCreds:async d=>{try{let m=ye()??t;if(m.github?.token&&!m.github.login)try{let{GitHubClient:C}=await Promise.resolve().then(()=>(ut(),or));m.github.login=await new C(m.github.token).whoami(),ge(m)}catch{}let g=Hu(m,d.emails);v.sendTeamCredsResult(d.requestId,{ok:!0,...g})}catch(m){v.sendTeamCredsResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupStatus:async d=>{try{let m=ye()??t,{buildSetupReport:g}=await Promise.resolve().then(()=>(df(),cf)),C=await g(m,d.repoNames,t);v.sendSetupStatusResult(d.requestId,{ok:!0,...C})}catch(m){v.sendSetupStatusResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdGenerate:async d=>{try{let m=x(d.projectId);if(!m){v.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=d.kind==="deploy"?"DEPLOY.md":d.kind==="design"?"DESIGN.md":"CLAUDE.md";y.info(`Setup: drafting ${g} for ${m.project.repoName}`);let C="Explore this repository and draft the content of a CLAUDE.md file for its repo root - the memory file AI agents read before working on tickets here. Cover: what the product does (one paragraph), the tech stack, how the code is organized (key directories and what lives in them), exact commands to install dependencies / build / run tests, code conventions worth following, and gotchas a newcomer would trip over. Under 150 lines, factual, no marketing language, nothing you cannot verify from the code. Reply with ONLY the file content - no preamble, no fences around the whole thing.",M='Inspect this repository (deploy scripts, CI files, server configs, package scripts) and draft the content of a DEPLOY.md deploy contract for its repo root. An automation tool will follow it LITERALLY, so only write what you can verify from the repo. IMPORTANT: you are running ON the machine where deploys will execute - commands are plain local commands, no ssh wrapper, unless the repo clearly documents a different target machine. For each environment that VERIFIABLY exists: name, branch, exact deploy commands, secrets as $NAMES only (never values), pre/post checks (post-restart checks must wait and retry - services report active before their port binds). Where you cannot verify something (hosts, service names, ports), write it with a clear "VERIFY:" marker so the human fills it in during review, instead of guessing. State explicitly which environments do NOT exist. Reply with ONLY the file content - no preamble, no fences around the whole thing.'+(d.environments.length?`
|
|
924
|
+
|
|
925
|
+
THESE ENVIRONMENTS ARE ALREADY DECLARED for this project - write a section for EACH one, no more and no fewer, and target each one's own health checks at its own URL:
|
|
926
|
+
`+d.environments.map(D=>`- ${D.name}`+(D.branch?` (branch ${D.branch})`:"")+(D.publicUrl?` serves ${D.publicUrl}`:" - no URL given")).join(`
|
|
927
|
+
`)+`
|
|
928
|
+
If the repo shows no evidence of how one of them deploys, still write its section with VERIFY: markers rather than dropping it.`:""),V=`Explore this repository's UI code and draft the content of a DESIGN.md file for its repo root - the design guidelines AI agents will follow for anything user-facing here. This is a SEED DRAFT: extract only what the code proves, and leave taste to the humans. Cover, from real evidence (tailwind/theme configs, design tokens, CSS, component libraries, existing screens): the color palette actually in use (names + hex), typography (families, the size scale), spacing and layout conventions, the component idiom (which library, how buttons/forms/cards are built, naming), dark mode, responsive breakpoints, and accessibility patterns already present. For everything code cannot prove - brand intent, tone of voice, look-and-feel references, what to never do - write a line starting with "VERIFY:" phrased as a question for the human to answer during review, instead of guessing. If the project has no UI at all, say exactly that in one line and stop. Under 120 lines, factual, no marketing language. Reply with ONLY the file content - no preamble, no fences around the whole thing.`,W=Ke(t,m.project,"assist");if("error"in W){v.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,content:"",error:W.error});return}let L=(await W.adapter.run({repoPath:m.repoPath,prompt:d.kind==="deploy"?M:d.kind==="design"?V:C,timeoutSeconds:240,bin:W.bin,mode:"read_only",maxTurns:40,sessionId:(0,Hs.randomUUID)(),onLog:()=>{}})).resultText.trim();if(!L){v.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:"the agent returned no content - try again"});return}v.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!0,content:L})}catch(m){v.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdSave:async d=>{try{let m=x(d.projectId);if(!m){v.sendSetupClaudeMdSaveResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=d.kind==="deploy"?"DEPLOY.md":d.kind==="design"?"DESIGN.md":"CLAUDE.md",C=await bl({repoPath:m.repoPath,relPath:g,content:d.content,overwrite:d.overwrite,commitMessage:`Add ${g} (agent-drafted, human-approved via Allwright)`});C.ok&&y.info(`Setup: wrote human-approved ${g} to ${m.repoPath}`),v.sendSetupClaudeMdSaveResult(d.requestId,C)}catch(m){v.sendSetupClaudeMdSaveResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRepoDocSave:async d=>{try{let m=x(d.projectId);if(!m){v.sendRepoDocSaveResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=await bl({repoPath:m.repoPath,relPath:d.relPath,content:d.content,overwrite:d.overwrite,commitMessage:`Add ${d.relPath.trim()} (written in Allwright Compose, human-approved)`});g.ok&&y.info(`Saved approved doc ${d.relPath} into ${m.repoPath}`),v.sendRepoDocSaveResult(d.requestId,g)}catch(m){v.sendRepoDocSaveResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditStats:d=>{try{v.sendAuditStatsResult(d.requestId,{ok:!0,byProject:uc(d.projectIds,d.since)})}catch(m){v.sendAuditStatsResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRunnerUpdate:async d=>{if(!process.env.INVOCATION_ID){v.sendRunnerUpdateResult(d.requestId,{ok:!1,error:"this runner is not running as a systemd service, so it cannot restart itself after updating. On the machine run: allwright update && allwright stop && allwright start"});return}let m=()=>{y.info("Installing allwright@latest");let C=ds.default.dirname(process.execPath),M=ft.default.existsSync(ds.default.join(C,"npm"))?ds.default.join(C,"npm"):"npm";(0,Gt.execFile)(M,["install","-g","allwright@latest"],{timeout:18e4,env:{...process.env,PATH:`${C}:${process.env.PATH??""}`}},(V,W,ee)=>{if(V){v.sendRunnerUpdateResult(d.requestId,{ok:!1,error:`npm install failed: ${(ee||V.message).slice(0,300)} - on the machine run: allwright update && sudo systemctl restart allwright`});return}v.sendRunnerUpdateResult(d.requestId,{ok:!0,note:"updated - restarting now, back in a few seconds"}),y.info("Update installed; exiting so systemd restarts on the new version"),setTimeout(()=>process.exit(0),1500)})};if(p.idle){m();return}if(b){v.sendRunnerUpdateResult(d.requestId,{ok:!0,scheduled:!0,note:"an update is already scheduled and will install once the current work finishes"});return}let g=p.busyCount;v.sendRunnerUpdateResult(d.requestId,{ok:!0,scheduled:!0,note:`scheduled - ${g} run(s)/deploy(s) active right now. Nothing is refused meanwhile; the install runs automatically as soon as this machine goes idle.`}),y.info(`Update scheduled: waiting for ${g} active run(s)/deploy(s) to finish`),b=setInterval(()=>{p.idle&&(clearInterval(b),b=null,m())},5e3)},onTestFix:async d=>{let m=g=>v.sendTestFixResult(d.requestId,{ok:!1,note:g});try{let g=Qr(d.runId);if(!g){m("this runner no longer has that PR on file - it may have been decided already");return}let C=t.repos[g.repoName];if(!C){m(`no local checkout mapped for "${g.repoName}" on this machine`);return}let M=Ae(t,g.repoName);if(!M){m("no GitHub token on this runner for that repo");return}let V=await new $e(M).getPullRequest(g.owner,g.repo,g.prNumber);if(!V){m("that pull request no longer exists on GitHub");return}if(V.merged||V.state==="closed"){m("that pull request is already merged or closed - there is nothing left to fix");return}let W=u.find(ne=>ne.repoName===g.repoName),ee=g.nextDecisionSeq??1e5,L=(ne,de)=>{v.send({type:"run.log",runId:d.runId,seq:ee++,ts:new Date().toISOString(),level:ne,message:de}),g.nextDecisionSeq=ee,ct(g)},D=await Ed({cfg:t,repoPath:C.path,branch:g.branch,baseBranch:V.baseRef||"main",issueKey:g.issueKey,agentId:W?.defaultAgent||Ze.DEFAULT_AGENT_ID,configDir:g.agentConfigDir,failedTests:d.failedTests,timeoutSeconds:900,onLog:L});D.ok&&D.headSha&&(g.headSha=D.headSha,ct(g),v.send({type:"run.status",runId:d.runId,status:"awaiting_approval",headSha:D.headSha,failedTests:D.remaining??[],...D.testsPassed!==void 0?{testsPassed:D.testsPassed}:{},...D.testsTotal!==void 0?{testsTotal:D.testsTotal}:{},...D.costUsd!==void 0?{costUsd:D.costUsd}:{},...D.inputTokens!==void 0?{inputTokens:D.inputTokens}:{},...D.outputTokens!==void 0?{outputTokens:D.outputTokens}:{}})),lt(C.path,{issueKey:g.issueKey,runId:d.runId,title:D.ok?D.headSha?(D.remaining??[]).length?"dashboard test fix pushed, some commands still failing":"tests fixed from the dashboard":"dashboard test fix: agent changed nothing":"dashboard test fix failed",detail:D.note.slice(0,500)}),v.sendTestFixResult(d.requestId,D)}catch(g){m(g instanceof Error?g.message.slice(0,300):String(g))}},onRunAnswer:async d=>{try{let m=await p.answerPendingInput(d.runId,d.text,d.answeredBy);v.sendRunAnswerResult(d.requestId,m)}catch(m){v.sendRunAnswerResult(d.requestId,{ok:!1,error:m instanceof Error?m.message.slice(0,300):String(m)})}},onResolveConflict:async d=>{let m=g=>v.sendResolveConflictResult(d.requestId,{ok:!1,note:g});try{let g=Qr(d.runId);if(!g){m("this runner no longer has that PR on file - it may have been decided already");return}let C=t.repos[g.repoName];if(!C){m(`no local checkout mapped for "${g.repoName}" on this machine`);return}let M=Ae(t,g.repoName);if(!M){m("no GitHub token on this runner for that repo");return}let V=await new $e(M).getPullRequest(g.owner,g.repo,g.prNumber);if(!V){m("that pull request no longer exists on GitHub");return}if(!V.baseRef){m("GitHub did not report the PR's base branch, so there is nothing to merge in");return}let W=u.find(ne=>ne.repoName===g.repoName),ee=g.nextDecisionSeq??1e5,L=(ne,de)=>{v.send({type:"run.log",runId:d.runId,seq:ee++,ts:new Date().toISOString(),level:ne,message:de}),g.nextDecisionSeq=ee,ct(g)},D=await Id({cfg:t,repoPath:C.path,branch:g.branch,baseBranch:V.baseRef,issueKey:g.issueKey,agentId:W?.defaultAgent||Ze.DEFAULT_AGENT_ID,configDir:g.agentConfigDir,timeoutSeconds:900,onLog:L});D.ok&&D.headSha&&(g.headSha=D.headSha,g.conflictNotified=!1,ct(g),v.send({type:"run.pr.conflict",runId:d.runId,conflicted:!1}),v.send({type:"run.status",runId:d.runId,status:"awaiting_approval",headSha:D.headSha,...D.costUsd!==void 0?{costUsd:D.costUsd}:{},...D.inputTokens!==void 0?{inputTokens:D.inputTokens}:{},...D.outputTokens!==void 0?{outputTokens:D.outputTokens}:{}})),v.sendResolveConflictResult(d.requestId,D)}catch(g){m(g instanceof Error?g.message.slice(0,300):String(g))}},onAgentProfiles:d=>{try{let m=C=>{try{return ft.default.existsSync(C)&&ft.default.readdirSync(C).length>0}catch{return!1}},g=Object.entries(t.claudeProfiles).map(([C,M])=>({agent:"claude-code",name:C,loggedIn:m(M.configDir)}));v.sendAgentProfilesResult(d.requestId,{ok:!0,profiles:g,defaultLoggedIn:m(ds.default.join(wl.default.homedir(),".claude")),agentsWithoutProfiles:Ze.REGISTERED_AGENTS.filter(C=>!C.capabilities.loginProfiles).map(C=>C.id)})}catch(m){v.sendAgentProfilesResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onJiraUsers:async d=>{try{let m=await n.searchUsers(d.query);v.sendJiraUsersResult(d.requestId,{ok:!0,users:m})}catch(m){v.sendJiraUsersResult(d.requestId,{ok:!1,users:[],error:m instanceof Error?m.message:String(m)})}}});w.transport=v,p=new Hi(t,s,v);let O=Object.values(lr()).filter(d=>d.kind==="implement").map(d=>d.repoPath);Wo(Object.values(t.repos).map(d=>d.path),O).catch(()=>{}),v.start(),p.start();let H=()=>{y.info("shutting down"),b&&clearInterval(b),v.stop(),iu(process.pid),Mo(),process.exit(0)},z=!1,B=()=>{if(z){y.warn("second stop signal - exiting NOW; the interrupted run will be marked failed"),H();return}if(z=!0,p.stop(),p.idle){H();return}y.info(`stop requested - no new work will start; waiting for ${p.busyCount} active run(s)/deploy(s) to finish. Send the signal again to kill them immediately.`);let d=setInterval(()=>{p.idle&&(clearInterval(d),H())},3e3)};process.on("SIGINT",B),process.on("SIGTERM",B),process.on("SIGHUP",()=>{try{let d=ie();if(!d.jira)throw new Error("no Jira credentials in the reloaded config");for(let m of Object.keys(t))delete t[m];Object.assign(t,d),n=new Pe(d.jira),r.clear(),y.info("config reloaded live - new Jira tokens/repos/rules apply from the next poll. (Poll interval and control-plane URL still need a restart.)")}catch(d){y.error(`config reload failed - keeping the running config: ${d instanceof Error?d.message:String(d)}`)}})}Te.command("start").description("Start watching Jira. Runs in the background by default - close this terminal and it keeps going until you run `allwright stop`. Use --foreground to keep it attached (e.g. under systemd).").option("--foreground","run in this terminal instead of detaching to the background").action(async t=>{let e=ie();if(t.foreground){Hv(e);return}let n=On();if(n&&Nn(n)){y.info(`already running in the background (pid ${n}). Use \`allwright status\` or \`stop\`.`);return}let r=bs();if(r){y.info(`a runner is already running on this machine (pid ${r}) - most likely the systemd service. One machine runs ONE runner; nothing to do. (Service controls: sudo systemctl status|stop|restart allwright)`);return}let s=ru(),i=(0,Gt.spawn)(process.execPath,[process.argv[1],"start","--foreground"],{detached:!0,stdio:["ignore",s,s]});i.unref(),su(i.pid),y.info(`Runner started in the background (pid ${i.pid}).`),y.info(`Logs: ${ai()}`),y.info("It will keep polling Jira until you run `allwright stop` - closing this terminal is fine.")});Te.command("stop").description("Stop the background runner started by `start`. Graceful by default: it stops taking new work and exits once active runs and deploys finish - safe to use while customers' tickets are running.").option("--force","kill immediately - anything executing is interrupted and marked failed").action(t=>{let e=On();if(!e||!Nn(e)){y.info("no background runner is running"),e&&ft.default.rmSync(zr(),{force:!0});return}if(t.force){process.kill(e,"SIGKILL"),ft.default.rmSync(zr(),{force:!0}),y.info(`killed (pid ${e}) - any interrupted run will show as failed on the dashboard`);return}process.kill(e,"SIGTERM"),y.info(`stop signal sent (pid ${e}) - it stops polling now and exits once active work finishes (watch \`allwright status\`). Use --force to kill immediately.`)});Te.command("status").description("Check whether the background runner is running").action(()=>{let t=On();t&&Nn(t)?y.info(`running in the background (pid ${t})`):y.info("not running")});Te.parseAsync().catch(t=>{y.error(t instanceof Error?t.message:String(t)),process.exit(1)});
|