allwright 1.19.0 → 1.21.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 +147 -133
- package/package.json +1 -1
package/bin/allwright.js
CHANGED
|
@@ -1,26 +1,26 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var
|
|
3
|
-
`).replace(/^/gm," ".repeat(i))}let c=[`Usage: ${t.commandUsage(e)}`,""],f=t.commandDescription(e);f.length>0&&(c=c.concat([t.wrap(f,s,0),""]));let p=t.visibleArguments(e).map(T=>a(t.argumentTerm(T),t.argumentDescription(T)));p.length>0&&(c=c.concat(["Arguments:",
|
|
4
|
-
`)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,n,s=40){let i=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",o=new RegExp(`[\\n][${i}]+`);if(e.match(o))return e;let a=t-n;if(a<s)return e;let
|
|
2
|
+
"use strict";var wh=Object.create;var Fi=Object.defineProperty;var _h=Object.getOwnPropertyDescriptor;var kh=Object.getOwnPropertyNames;var Sh=Object.getPrototypeOf,Th=Object.prototype.hasOwnProperty;var _s=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=[n],n}};var ee=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},ks=(r,e)=>{for(var t in e)Fi(r,t,{get:e[t],enumerable:!0})},xh=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of kh(e))!Th.call(r,s)&&s!==t&&Fi(r,s,{get:()=>e[s],enumerable:!(n=_h(e,s))||n.enumerable});return r};var E=(r,e,t)=>(t=r!=null?wh(Sh(r)):{},xh(e||!r||!r.__esModule?Fi(t,"default",{value:r,enumerable:!0}):t,r));var Bn=ee(Ki=>{var Ss=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},Bi=class extends Ss{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Ki.CommanderError=Ss;Ki.InvalidArgumentError=Bi});var Ts=ee(Gi=>{var{InvalidArgumentError:Ch}=Bn(),Zi=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new Ch(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Ih(r){let e=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+e+">":"["+e+"]"}Gi.Argument=Zi;Gi.humanReadableArgName=Ih});var Vi=ee(Wa=>{var{humanReadableArgName:Rh}=Ts(),Hi=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let t=e.commands.filter(s=>!s._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((s,i)=>s.name().localeCompare(i.name())),t}compareOptions(e,t){let n=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(s=>!s.hidden),n=e._getHelpOption();if(n&&!n.hidden){let s=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!s&&!i?t.push(n):n.long&&!i?t.push(e.createOption(n.long,n.description)):n.short&&!s&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let s=n.options.filter(i=>!i.hidden);t.push(...s)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(n=>Rh(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((n,s)=>Math.max(n,t.subcommandTerm(s).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((n,s)=>Math.max(n,t.optionTerm(s).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((n,s)=>Math.max(n,t.optionTerm(s).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((n,s)=>Math.max(n,t.argumentTerm(s).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let n="";for(let s=e.parent;s;s=s.parent)n=s.name()+" "+n;return n+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,t){let n=t.padWidth(e,t),s=t.helpWidth||80,i=2,o=2;function a(T,x){if(x){let P=`${T.padEnd(n+o)}${x}`;return t.wrap(P,s-i,n+o)}return T}function u(T){return T.join(`
|
|
3
|
+
`).replace(/^/gm," ".repeat(i))}let c=[`Usage: ${t.commandUsage(e)}`,""],f=t.commandDescription(e);f.length>0&&(c=c.concat([t.wrap(f,s,0),""]));let p=t.visibleArguments(e).map(T=>a(t.argumentTerm(T),t.argumentDescription(T)));p.length>0&&(c=c.concat(["Arguments:",u(p),""]));let v=t.visibleOptions(e).map(T=>a(t.optionTerm(T),t.optionDescription(T)));if(v.length>0&&(c=c.concat(["Options:",u(v),""])),this.showGlobalOptions){let T=t.visibleGlobalOptions(e).map(x=>a(t.optionTerm(x),t.optionDescription(x)));T.length>0&&(c=c.concat(["Global Options:",u(T),""]))}let S=t.visibleCommands(e).map(T=>a(t.subcommandTerm(T),t.subcommandDescription(T)));return S.length>0&&(c=c.concat(["Commands:",u(S),""])),c.join(`
|
|
4
|
+
`)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,n,s=40){let i=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",o=new RegExp(`[\\n][${i}]+`);if(e.match(o))return e;let a=t-n;if(a<s)return e;let u=e.slice(0,n),c=e.slice(n).replace(`\r
|
|
5
5
|
`,`
|
|
6
|
-
`),f=" ".repeat(n),v="\\s\u200B",
|
|
7
|
-
|.{1,${a-1}}([${v}]|$)|[^${v}]+?([${v}]|$)`,"g"),T=c.match(
|
|
8
|
-
`?"":(
|
|
9
|
-
`)}};
|
|
6
|
+
`),f=" ".repeat(n),v="\\s\u200B",S=new RegExp(`
|
|
7
|
+
|.{1,${a-1}}([${v}]|$)|[^${v}]+?([${v}]|$)`,"g"),T=c.match(S)||[];return u+T.map((x,P)=>x===`
|
|
8
|
+
`?"":(P>0?f:"")+x.trimEnd()).join(`
|
|
9
|
+
`)}};Wa.Help=Hi});var Xi=ee(Yi=>{var{InvalidArgumentError:Eh}=Bn(),Wi=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=$h(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new Eh(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return Ah(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Ji=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let s=this.negativeOptions.get(n).presetArg,i=s!==void 0?s:!1;return t.negate===(i===e)}};function Ah(r){return r.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function $h(r){let e,t,n=r.split(/[ |,]+/);return n.length>1&&!/^[[<]/.test(n[1])&&(e=n.shift()),t=n.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}Yi.Option=Wi;Yi.DualOptions=Ji});var Ya=ee(Ja=>{function Ph(r,e){if(Math.abs(r.length-e.length)>3)return Math.max(r.length,e.length);let t=[];for(let n=0;n<=r.length;n++)t[n]=[n];for(let n=0;n<=e.length;n++)t[0][n]=n;for(let n=1;n<=e.length;n++)for(let s=1;s<=r.length;s++){let i=1;r[s-1]===e[n-1]?i=0:i=1,t[s][n]=Math.min(t[s-1][n]+1,t[s][n-1]+1,t[s-1][n-1]+i),s>1&&n>1&&r[s-1]===e[n-2]&&r[s-2]===e[n-1]&&(t[s][n]=Math.min(t[s][n],t[s-2][n-2]+1))}return t[r.length][e.length]}function jh(r,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=r.startsWith("--");t&&(r=r.slice(2),e=e.map(o=>o.slice(2)));let n=[],s=3,i=.4;return e.forEach(o=>{if(o.length<=1)return;let a=Ph(r,o),u=Math.max(r.length,o.length);(u-a)/u>i&&(a<s?(s=a,n=[o]):a===s&&n.push(o))}),n.sort((o,a)=>o.localeCompare(a)),t&&(n=n.map(o=>`--${o}`)),n.length>1?`
|
|
10
10
|
(Did you mean one of ${n.join(", ")}?)`:n.length===1?`
|
|
11
|
-
(Did you mean ${n[0]}?)`:""}
|
|
12
|
-
- specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new
|
|
13
|
-
Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new
|
|
14
|
-
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=s=>[s.name()].concat(s.aliases()),n=t(e).find(s=>this._findCommand(s));if(n){let s=t(this._findCommand(n)).join("|"),i=t(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let s=(i,o,a)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let
|
|
11
|
+
(Did you mean ${n[0]}?)`:""}Ja.suggestSimilar=jh});var rl=ee(tl=>{var Oh=require("node:events").EventEmitter,Qi=require("node:child_process"),ht=require("node:path"),eo=require("node:fs"),de=require("node:process"),{Argument:Nh,humanReadableArgName:Mh}=Ts(),{CommanderError:to}=Bn(),{Help:zh}=Vi(),{Option:Xa,DualOptions:Dh}=Xi(),{suggestSimilar:Qa}=Ya(),ro=class r extends Oh{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:t=>de.stdout.write(t),writeErr:t=>de.stderr.write(t),getOutHelpWidth:()=>de.stdout.isTTY?de.stdout.columns:void 0,getErrHelpWidth:()=>de.stderr.isTTY?de.stderr.columns:void 0,outputError:(t,n)=>n(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let s=t,i=n;typeof s=="object"&&s!==null&&(i=s,s=null),i=i||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),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,a&&u.arguments(a),this._registerCommand(u),u.parent=this,u.copyInheritedSettings(this),s?this:u}createCommand(e){return new r(e)}createHelp(){return Object.assign(new zh,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
12
|
+
- specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new Nh(e,t)}argument(e,t,n,s){let i=this.createArgument(e,t);return typeof n=="function"?i.default(s).argParser(n):i.default(n),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,n,s]=e.match(/([^ ]+) *(.*)/),i=t??"display help for command",o=this.createCommand(n);return o.helpOption(!1),s&&o.arguments(s),i&&o.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
13
|
+
Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new to(e,t,n)),de.exit(e)}action(e){let t=n=>{let s=this.registeredArguments.length,i=n.slice(0,s);return this._storeOptionsAsProperties?i[s]=this:i[s]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=t,this}createOption(e,t){return new Xa(e,t)}_callParseArg(e,t,n,s){try{return e.parseArg(t,n)}catch(i){if(i.code==="commander.invalidArgument"){let o=`${s} ${i.message}`;this.error(o,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
|
|
14
|
+
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=s=>[s.name()].concat(s.aliases()),n=t(e).find(s=>this._findCommand(s));if(n){let s=t(this._findCommand(n)).join("|"),i=t(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let s=(i,o,a)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let u=this.getOptionValue(n);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(n,i,a)};return this.on("option:"+t,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;s(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+t,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;s(i,o,"env")}),this}_optionEx(e,t,n,s,i){if(typeof t=="object"&&t instanceof Xa)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(t,n);if(o.makeOptionMandatory(!!e.mandatory),typeof s=="function")o.default(i).argParser(s);else if(s instanceof RegExp){let a=s;s=(u,c)=>{let f=a.exec(u);return f?f[0]:c},o.default(i).argParser(s)}else o.default(s);return this.addOption(o)}option(e,t,n,s){return this._optionEx({},e,t,n,s)}requiredOption(e,t,n,s){return this._optionEx({mandatory:!0},e,t,n,s)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){de.versions?.electron&&(t.from="electron");let s=de.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(t.from="eval")}e===void 0&&(e=de.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":de.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,t){let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_executeSubCommand(e,t){t=t.slice();let n=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function i(f,p){let v=ht.resolve(f,p);if(eo.existsSync(v))return v;if(s.includes(ht.extname(p)))return;let S=s.find(T=>eo.existsSync(`${v}${T}`));if(S)return`${v}${S}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let f;try{f=eo.realpathSync(this._scriptPath)}catch{f=this._scriptPath}a=ht.resolve(ht.dirname(f),a)}if(a){let f=i(a,o);if(!f&&!e._executableFile&&this._scriptPath){let p=ht.basename(this._scriptPath,ht.extname(this._scriptPath));p!==this._name&&(f=i(a,`${p}-${e._name}`))}o=f||o}n=s.includes(ht.extname(o));let u;de.platform!=="win32"?n?(t.unshift(o),t=el(de.execArgv).concat(t),u=Qi.spawn(de.argv[0],t,{stdio:"inherit"})):u=Qi.spawn(o,t,{stdio:"inherit"}):(t.unshift(o),t=el(de.execArgv).concat(t),u=Qi.spawn(de.execPath,t,{stdio:"inherit"})),u.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(p=>{de.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 to(f,"commander.executeSubCommandAsync","(close)")):de.exit(f)}),u.on("error",f=>{if(f.code==="ENOENT"){let p=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",v=`'${o}' does not exist
|
|
15
15
|
- if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
16
16
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
17
|
-
- ${p}`;throw new Error(v)}else if(f.code==="EACCES")throw new Error(`'${o}' not executable`);if(!c)de.exit(1);else{let p=new
|
|
17
|
+
- ${p}`;throw new Error(v)}else if(f.code==="EACCES")throw new Error(`'${o}' not executable`);if(!c)de.exit(1);else{let p=new to(1,"commander.executeSubCommandAsync","(error)");p.nestedError=f,c(p)}}),this.runningCommand=u}_dispatchSubcommand(e,t,n){let s=this._findCommand(e);s||this.help({error:!0});let i;return i=this._chainOrCallSubCommandHook(i,s,"preSubcommand"),i=this._chainOrCall(i,()=>{if(s._executableHandler)this._executeSubCommand(s,t.concat(n));else return s._parseCommand(t,n)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(n,s,i)=>{let o=s;if(s!==null&&n.parseArg){let a=`error: command-argument value '${s}' is invalid for argument '${n.name()}'.`;o=this._callParseArg(n,s,i,a)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,s)=>{let i=n.defaultValue;n.variadic?s<this.args.length?(i=this.args.slice(s),n.parseArg&&(i=i.reduce((o,a)=>e(n,a,o),n.defaultValue))):i===void 0&&(i=[]):s<this.args.length&&(i=this.args[s],n.parseArg&&(i=e(n,i,n.defaultValue))),t[s]=i}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,s=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[t]!==void 0).forEach(i=>{i._lifeCycleHooks[t].forEach(o=>{s.push({hookedCommand:i,callback:o})})}),t==="postAction"&&s.reverse(),s.forEach(i=>{n=this._chainOrCall(n,()=>i.callback(i.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let s=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(i=>{s=this._chainOrCall(s,()=>i(this,t))}),s}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){s(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(i,e,t)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(i))s(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(n=>{let s=n.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let s=e.find(i=>n.conflictsWith.includes(i.attributeName()));s&&this._conflictingOption(n,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],s=t,i=e.slice();function o(u){return u.length>1&&u[0]==="-"}let a=null;for(;i.length;){let u=i.shift();if(u==="--"){s===n&&s.push(u),s.push(...i);break}if(a&&!o(u)){this.emit(`option:${a.name()}`,u);continue}if(a=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()}`);a=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=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(u)){t.push(u),i.length>0&&n.push(...i);break}else if(this._getHelpCommand()&&u===this._getHelpCommand().name()){t.push(u),i.length>0&&t.push(...i);break}else if(this._defaultCommandName){n.push(u),i.length>0&&n.push(...i);break}}if(this._passThroughOptions){s.push(u),i.length>0&&s.push(...i);break}s.push(u)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let s=this.options[n].attributeName();e[s]=s===this._versionOptionName?this._version:this[s]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
|
|
18
18
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
19
19
|
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
20
|
-
`),this.outputHelp({error:!0}));let n=t||{},s=n.exitCode||1,i=n.code||"commander.error";this._exit(s,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in de.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,de.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new
|
|
21
|
-
`),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let s=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(n=>
|
|
20
|
+
`),this.outputHelp({error:!0}));let n=t||{},s=n.exitCode||1,i=n.code||"commander.error";this._exit(s,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in de.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,de.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Dh(this.options),t=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(s=>!t(s)).forEach(s=>{this.setOptionValueWithSource(s,n.implied[s],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let n=o=>{let a=o.attributeName(),u=this.getOptionValue(a),c=this.options.find(p=>p.negate&&a===p.attributeName()),f=this.options.find(p=>!p.negate&&a===p.attributeName());return c&&(c.presetArg===void 0&&u===!1||c.presetArg!==void 0&&u===c.presetArg)?c:f||o},s=o=>{let a=n(o),u=a.attributeName();return this.getOptionValueSource(u)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},i=`error: ${s(e)} cannot be used with ${s(t)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],i=this;do{let o=i.createHelp().visibleOptions(i).filter(a=>a.long).map(a=>a.long);s=s.concat(o),i=i.parent}while(i&&!i._enablePositionalOptions);t=Qa(e,s)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(i=>{s.push(i.name()),i.alias()&&s.push(i.alias())}),t=Qa(e,s)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:"commander.unknownCommand"})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",n=n||"output the version number";let s=this.createOption(t,n);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
21
|
+
`),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let s=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(n=>Mh(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=ht.basename(e,ht.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};let t={error:!!e.error},n;return t.error?n=s=>this._outputConfiguration.writeErr(s):n=s=>this._outputConfiguration.writeOut(s),t.write=e.write||n,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let n=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let s=this.helpInformation(n);if(t&&(s=t(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",n))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=de.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
22
22
|
Expecting one of '${n.join("', '")}'`);let s=`${e}Help`;return this.on(s,i=>{let o;typeof t=="function"?o=t({error:i.error,command:i.command}):o=t,o&&i.write(`${o}
|
|
23
|
-
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(s=>t.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Za(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",s="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?t=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=i[1],/^\d+$/.test(i[3])?s=i[3]:n=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],s=i[4]),t&&s!=="0"?`${t}=${n}:${parseInt(s)+1}`:e})}Ga.Command=Ji});var Ya=ee(Oe=>{var{Argument:Ha}=gs(),{Command:Yi}=Va(),{CommanderError:Ah,InvalidArgumentError:Wa}=Nn(),{Help:$h}=Fi(),{Option:Ja}=Gi();Oe.program=new Yi;Oe.createCommand=r=>new Yi(r);Oe.createOption=(r,e)=>new Ja(r,e);Oe.createArgument=(r,e)=>new Ha(r,e);Oe.Command=Yi;Oe.Option=Ja;Oe.Argument=Ha;Oe.Help=$h;Oe.CommanderError=Ah;Oe.InvalidArgumentError=Wa;Oe.InvalidOptionArgumentError=Wa});var Un=ee(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.getParsedType=oe.ZodParsedType=oe.objectUtil=oe.util=void 0;var io;(function(r){r.assertEqual=s=>{};function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},r.getValidEnumValues=s=>{let i=r.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),o={};for(let a of i)o[a]=s[a];return r.objectValues(o)},r.objectValues=s=>r.objectKeys(s).map(function(i){return s[i]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},r.find=(s,i)=>{for(let o of s)if(i(o))return o},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}r.joinValues=n,r.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(io||(oe.util=io={}));var _u;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(_u||(oe.objectUtil=_u={}));oe.ZodParsedType=io.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var Jf=r=>{switch(typeof r){case"undefined":return oe.ZodParsedType.undefined;case"string":return oe.ZodParsedType.string;case"number":return Number.isNaN(r)?oe.ZodParsedType.nan:oe.ZodParsedType.number;case"boolean":return oe.ZodParsedType.boolean;case"function":return oe.ZodParsedType.function;case"bigint":return oe.ZodParsedType.bigint;case"symbol":return oe.ZodParsedType.symbol;case"object":return Array.isArray(r)?oe.ZodParsedType.array:r===null?oe.ZodParsedType.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?oe.ZodParsedType.promise:typeof Map<"u"&&r instanceof Map?oe.ZodParsedType.map:typeof Set<"u"&&r instanceof Set?oe.ZodParsedType.set:typeof Date<"u"&&r instanceof Date?oe.ZodParsedType.date:oe.ZodParsedType.object;default:return oe.ZodParsedType.unknown}};oe.getParsedType=Jf});var As=ee(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.ZodError=Nt.quotelessJson=Nt.ZodIssueCode=void 0;var ku=Un();Nt.ZodIssueCode=ku.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 Yf=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:");Nt.quotelessJson=Yf;var qn=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},n={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)n._errors.push(t(o));else{let a=n,l=0;for(;l<o.path.length;){let c=o.path[l];l===o.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(t(o))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return s(this),n}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ku.util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},n=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];t[i]=t[i]||[],t[i].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};Nt.ZodError=qn;qn.create=r=>new qn(r)});var ao=ee(oo=>{"use strict";Object.defineProperty(oo,"__esModule",{value:!0});var ke=As(),cr=Un(),Xf=(r,e)=>{let t;switch(r.code){case ke.ZodIssueCode.invalid_type:r.received===cr.ZodParsedType.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case ke.ZodIssueCode.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,cr.util.jsonStringifyReplacer)}`;break;case ke.ZodIssueCode.unrecognized_keys:t=`Unrecognized key(s) in object: ${cr.util.joinValues(r.keys,", ")}`;break;case ke.ZodIssueCode.invalid_union:t="Invalid input";break;case ke.ZodIssueCode.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${cr.util.joinValues(r.options)}`;break;case ke.ZodIssueCode.invalid_enum_value:t=`Invalid enum value. Expected ${cr.util.joinValues(r.options)}, received '${r.received}'`;break;case ke.ZodIssueCode.invalid_arguments:t="Invalid function arguments";break;case ke.ZodIssueCode.invalid_return_type:t="Invalid function return type";break;case ke.ZodIssueCode.invalid_date:t="Invalid date";break;case ke.ZodIssueCode.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:cr.util.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case ke.ZodIssueCode.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case ke.ZodIssueCode.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case ke.ZodIssueCode.custom:t="Invalid input";break;case ke.ZodIssueCode.invalid_intersection_types:t="Intersection results could not be merged";break;case ke.ZodIssueCode.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case ke.ZodIssueCode.not_finite:t="Number must be finite";break;default:t=e.defaultError,cr.util.assertNever(r)}return{message:t}};oo.default=Xf});var $s=ee(Mt=>{"use strict";var Qf=Mt&&Mt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Mt,"__esModule",{value:!0});Mt.defaultErrorMap=void 0;Mt.setErrorMap=ep;Mt.getErrorMap=tp;var Su=Qf(ao());Mt.defaultErrorMap=Su.default;var Tu=Su.default;function ep(r){Tu=r}function tp(){return Tu}});var lo=ee(ne=>{"use strict";var rp=ne&&ne.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ne,"__esModule",{value:!0});ne.isAsync=ne.isValid=ne.isDirty=ne.isAborted=ne.OK=ne.DIRTY=ne.INVALID=ne.ParseStatus=ne.EMPTY_PATH=ne.makeIssue=void 0;ne.addIssueToContext=ip;var np=$s(),xu=rp(ao()),sp=r=>{let{data:e,path:t,errorMaps:n,issueData:s}=r,i=[...t,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let a="",l=n.filter(c=>!!c).slice().reverse();for(let c of l)a=c(o,{data:e,defaultError:a}).message;return{...s,path:i,message:a}};ne.makeIssue=sp;ne.EMPTY_PATH=[];function ip(r,e){let t=(0,np.getErrorMap)(),n=(0,ne.makeIssue)({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===xu.default?void 0:xu.default].filter(s=>!!s)});r.common.issues.push(n)}var uo=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let s of t){if(s.status==="aborted")return ne.INVALID;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let s of t){let i=await s.key,o=await s.value;n.push({key:i,value:o})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let s of t){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return ne.INVALID;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(n[i.value]=o.value)}return{status:e.value,value:n}}};ne.ParseStatus=uo;ne.INVALID=Object.freeze({status:"aborted"});var op=r=>({status:"dirty",value:r});ne.DIRTY=op;var ap=r=>({status:"valid",value:r});ne.OK=ap;var up=r=>r.status==="aborted";ne.isAborted=up;var lp=r=>r.status==="dirty";ne.isDirty=lp;var cp=r=>r.status==="valid";ne.isValid=cp;var dp=r=>typeof Promise<"u"&&r instanceof Promise;ne.isAsync=dp});var Eu=ee(Cu=>{"use strict";Object.defineProperty(Cu,"__esModule",{value:!0})});var Ru=ee(Ps=>{"use strict";Object.defineProperty(Ps,"__esModule",{value:!0});Ps.errorUtil=void 0;var Iu;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(Iu||(Ps.errorUtil=Iu={}))});var qu=ee(y=>{"use strict";Object.defineProperty(y,"__esModule",{value:!0});y.discriminatedUnion=y.date=y.boolean=y.bigint=y.array=y.any=y.coerce=y.ZodFirstPartyTypeKind=y.late=y.ZodSchema=y.Schema=y.ZodReadonly=y.ZodPipeline=y.ZodBranded=y.BRAND=y.ZodNaN=y.ZodCatch=y.ZodDefault=y.ZodNullable=y.ZodOptional=y.ZodTransformer=y.ZodEffects=y.ZodPromise=y.ZodNativeEnum=y.ZodEnum=y.ZodLiteral=y.ZodLazy=y.ZodFunction=y.ZodSet=y.ZodMap=y.ZodRecord=y.ZodTuple=y.ZodIntersection=y.ZodDiscriminatedUnion=y.ZodUnion=y.ZodObject=y.ZodArray=y.ZodVoid=y.ZodNever=y.ZodUnknown=y.ZodAny=y.ZodNull=y.ZodUndefined=y.ZodSymbol=y.ZodDate=y.ZodBoolean=y.ZodBigInt=y.ZodNumber=y.ZodString=y.ZodType=void 0;y.NEVER=y.void=y.unknown=y.union=y.undefined=y.tuple=y.transformer=y.symbol=y.string=y.strictObject=y.set=y.record=y.promise=y.preprocess=y.pipeline=y.ostring=y.optional=y.onumber=y.oboolean=y.object=y.number=y.nullable=y.null=y.never=y.nativeEnum=y.nan=y.map=y.literal=y.lazy=y.intersection=y.instanceof=y.function=y.enum=y.effect=void 0;y.datetimeRegex=Ou;y.custom=Mu;var I=As(),js=$s(),N=Ru(),b=lo(),A=Un(),Le=class{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Au=(r,e)=>{if((0,b.isValid)(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new I.ZodError(r.common.issues);return this._error=t,this._error}}};function Z(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,a)=>{let{message:l}=r;return o.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??n??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:l??t??a.defaultError}},description:s}}var G=class{get description(){return this._def.description}_getType(e){return(0,A.getParsedType)(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:(0,A.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new b.ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:(0,A.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if((0,b.isAsync)(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,A.getParsedType)(e)},s=this._parseSync({data:e,path:n.path,parent:n});return Au(n,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,A.getParsedType)(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return(0,b.isValid)(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>(0,b.isValid)(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,A.getParsedType)(e)},s=this._parse({data:e,path:n.path,parent:n}),i=await((0,b.isAsync)(s)?s:Promise.resolve(s));return Au(n,i)}refine(e,t){let n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,i)=>{let o=e(s),a=()=>i.addIssue({code:I.ZodIssueCode.custom,...n(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new $e({schema:this,typeName:q.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return De.create(this,this._def)}nullable(){return rt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return yt.create(this)}promise(){return Lt.create(this,this._def)}or(e){return yr.create([this,e],this._def)}and(e){return vr.create(this,e,this._def)}transform(e){return new $e({...Z(this._def),schema:this,typeName:q.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Sr({...Z(this._def),innerType:this,defaultValue:t,typeName:q.ZodDefault})}brand(){return new Fn({typeName:q.ZodBranded,type:this,...Z(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Tr({...Z(this._def),innerType:this,catchValue:t,typeName:q.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Bn.create(this,e)}readonly(){return xr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};y.ZodType=G;y.Schema=G;y.ZodSchema=G;var hp=/^c[^\s-]{8,}$/i,fp=/^[0-9a-z]+$/,pp=/^[0-9A-HJKMNP-TV-Z]{26}$/i,mp=/^[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,gp=/^[a-z0-9_-]{21}$/i,yp=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,vp=/^[-+]?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)?)??$/,bp=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,wp="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",co,_p=/^(?:(?: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])$/,kp=/^(?:(?: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])$/,Sp=/^(([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]))$/,Tp=/^(([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])$/,xp=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Cp=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Pu="((\\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(`^${Pu}$`);function ju(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Ip(r){return new RegExp(`^${ju(r)}$`)}function Ou(r){let e=`${Pu}T${ju(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Rp(r,e){return!!((e==="v4"||!e)&&_p.test(r)||(e==="v6"||!e)&&Sp.test(r))}function Ap(r,e){if(!yp.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function $p(r,e){return!!((e==="v4"||!e)&&kp.test(r)||(e==="v6"||!e)&&Tp.test(r))}var zt=class r extends G{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==A.ZodParsedType.string){let i=this._getOrReturnCtx(e);return(0,b.addIssueToContext)(i,{code:I.ZodIssueCode.invalid_type,expected:A.ZodParsedType.string,received:i.parsedType}),b.INVALID}let n=new b.ParseStatus,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),(0,b.addIssueToContext)(s,{code:I.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),(0,b.addIssueToContext)(s,{code:I.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(s=this._getOrReturnCtx(e,s),o?(0,b.addIssueToContext)(s,{code:I.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&(0,b.addIssueToContext)(s,{code:I.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")bp.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,b.addIssueToContext)(s,{validation:"email",code:I.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")co||(co=new RegExp(wp,"u")),co.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,b.addIssueToContext)(s,{validation:"emoji",code:I.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")mp.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,b.addIssueToContext)(s,{validation:"uuid",code:I.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")gp.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,b.addIssueToContext)(s,{validation:"nanoid",code:I.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")hp.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,b.addIssueToContext)(s,{validation:"cuid",code:I.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")fp.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,b.addIssueToContext)(s,{validation:"cuid2",code:I.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")pp.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,b.addIssueToContext)(s,{validation:"ulid",code:I.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),(0,b.addIssueToContext)(s,{validation:"url",code:I.ZodIssueCode.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,b.addIssueToContext)(s,{validation:"regex",code:I.ZodIssueCode.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),(0,b.addIssueToContext)(s,{code:I.ZodIssueCode.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,b.addIssueToContext)(s,{code:I.ZodIssueCode.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,b.addIssueToContext)(s,{code:I.ZodIssueCode.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?Ou(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,b.addIssueToContext)(s,{code:I.ZodIssueCode.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?Ep.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,b.addIssueToContext)(s,{code:I.ZodIssueCode.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?Ip(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,b.addIssueToContext)(s,{code:I.ZodIssueCode.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?vp.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,b.addIssueToContext)(s,{validation:"duration",code:I.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?Rp(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,b.addIssueToContext)(s,{validation:"ip",code:I.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?Ap(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),(0,b.addIssueToContext)(s,{validation:"jwt",code:I.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?$p(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,b.addIssueToContext)(s,{validation:"cidr",code:I.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?xp.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,b.addIssueToContext)(s,{validation:"base64",code:I.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?Cp.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,b.addIssueToContext)(s,{validation:"base64url",code:I.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):A.util.assertNever(i);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:I.ZodIssueCode.invalid_string,...N.errorUtil.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...N.errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...N.errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...N.errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...N.errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...N.errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...N.errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...N.errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...N.errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...N.errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...N.errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...N.errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...N.errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...N.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,...N.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,...N.errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...N.errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...N.errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...N.errorUtil.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...N.errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...N.errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...N.errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...N.errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...N.errorUtil.errToObj(t)})}nonempty(e){return this.min(1,N.errorUtil.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};y.ZodString=zt;zt.create=r=>new zt({checks:[],typeName:q.ZodString,coerce:r?.coerce??!1,...Z(r)});function Pp(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,i=Number.parseInt(r.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var dr=class r extends G{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)!==A.ZodParsedType.number){let i=this._getOrReturnCtx(e);return(0,b.addIssueToContext)(i,{code:I.ZodIssueCode.invalid_type,expected:A.ZodParsedType.number,received:i.parsedType}),b.INVALID}let n,s=new b.ParseStatus;for(let i of this._def.checks)i.kind==="int"?A.util.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),(0,b.addIssueToContext)(n,{code:I.ZodIssueCode.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),(0,b.addIssueToContext)(n,{code:I.ZodIssueCode.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),(0,b.addIssueToContext)(n,{code:I.ZodIssueCode.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Pp(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),(0,b.addIssueToContext)(n,{code:I.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),(0,b.addIssueToContext)(n,{code:I.ZodIssueCode.not_finite,message:i.message}),s.dirty()):A.util.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,N.errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,N.errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,N.errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,N.errorUtil.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:N.errorUtil.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:N.errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:N.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:N.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:N.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:N.errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:N.errorUtil.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:N.errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:N.errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:N.errorUtil.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&A.util.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};y.ZodNumber=dr;dr.create=r=>new dr({checks:[],typeName:q.ZodNumber,coerce:r?.coerce||!1,...Z(r)});var hr=class r extends G{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)!==A.ZodParsedType.bigint)return this._getInvalidInput(e);let n,s=new b.ParseStatus;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),(0,b.addIssueToContext)(n,{code:I.ZodIssueCode.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),(0,b.addIssueToContext)(n,{code:I.ZodIssueCode.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),(0,b.addIssueToContext)(n,{code:I.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):A.util.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return(0,b.addIssueToContext)(t,{code:I.ZodIssueCode.invalid_type,expected:A.ZodParsedType.bigint,received:t.parsedType}),b.INVALID}gte(e,t){return this.setLimit("min",e,!0,N.errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,N.errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,N.errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,N.errorUtil.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:N.errorUtil.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:N.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:N.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:N.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:N.errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:N.errorUtil.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};y.ZodBigInt=hr;hr.create=r=>new hr({checks:[],typeName:q.ZodBigInt,coerce:r?.coerce??!1,...Z(r)});var fr=class extends G{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==A.ZodParsedType.boolean){let n=this._getOrReturnCtx(e);return(0,b.addIssueToContext)(n,{code:I.ZodIssueCode.invalid_type,expected:A.ZodParsedType.boolean,received:n.parsedType}),b.INVALID}return(0,b.OK)(e.data)}};y.ZodBoolean=fr;fr.create=r=>new fr({typeName:q.ZodBoolean,coerce:r?.coerce||!1,...Z(r)});var pr=class r extends G{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==A.ZodParsedType.date){let i=this._getOrReturnCtx(e);return(0,b.addIssueToContext)(i,{code:I.ZodIssueCode.invalid_type,expected:A.ZodParsedType.date,received:i.parsedType}),b.INVALID}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return(0,b.addIssueToContext)(i,{code:I.ZodIssueCode.invalid_date}),b.INVALID}let n=new b.ParseStatus,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),(0,b.addIssueToContext)(s,{code:I.ZodIssueCode.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),(0,b.addIssueToContext)(s,{code:I.ZodIssueCode.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):A.util.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:N.errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:N.errorUtil.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};y.ZodDate=pr;pr.create=r=>new pr({checks:[],coerce:r?.coerce||!1,typeName:q.ZodDate,...Z(r)});var un=class extends G{_parse(e){if(this._getType(e)!==A.ZodParsedType.symbol){let n=this._getOrReturnCtx(e);return(0,b.addIssueToContext)(n,{code:I.ZodIssueCode.invalid_type,expected:A.ZodParsedType.symbol,received:n.parsedType}),b.INVALID}return(0,b.OK)(e.data)}};y.ZodSymbol=un;un.create=r=>new un({typeName:q.ZodSymbol,...Z(r)});var mr=class extends G{_parse(e){if(this._getType(e)!==A.ZodParsedType.undefined){let n=this._getOrReturnCtx(e);return(0,b.addIssueToContext)(n,{code:I.ZodIssueCode.invalid_type,expected:A.ZodParsedType.undefined,received:n.parsedType}),b.INVALID}return(0,b.OK)(e.data)}};y.ZodUndefined=mr;mr.create=r=>new mr({typeName:q.ZodUndefined,...Z(r)});var gr=class extends G{_parse(e){if(this._getType(e)!==A.ZodParsedType.null){let n=this._getOrReturnCtx(e);return(0,b.addIssueToContext)(n,{code:I.ZodIssueCode.invalid_type,expected:A.ZodParsedType.null,received:n.parsedType}),b.INVALID}return(0,b.OK)(e.data)}};y.ZodNull=gr;gr.create=r=>new gr({typeName:q.ZodNull,...Z(r)});var Dt=class extends G{constructor(){super(...arguments),this._any=!0}_parse(e){return(0,b.OK)(e.data)}};y.ZodAny=Dt;Dt.create=r=>new Dt({typeName:q.ZodAny,...Z(r)});var gt=class extends G{constructor(){super(...arguments),this._unknown=!0}_parse(e){return(0,b.OK)(e.data)}};y.ZodUnknown=gt;gt.create=r=>new gt({typeName:q.ZodUnknown,...Z(r)});var Ve=class extends G{_parse(e){let t=this._getOrReturnCtx(e);return(0,b.addIssueToContext)(t,{code:I.ZodIssueCode.invalid_type,expected:A.ZodParsedType.never,received:t.parsedType}),b.INVALID}};y.ZodNever=Ve;Ve.create=r=>new Ve({typeName:q.ZodNever,...Z(r)});var ln=class extends G{_parse(e){if(this._getType(e)!==A.ZodParsedType.undefined){let n=this._getOrReturnCtx(e);return(0,b.addIssueToContext)(n,{code:I.ZodIssueCode.invalid_type,expected:A.ZodParsedType.void,received:n.parsedType}),b.INVALID}return(0,b.OK)(e.data)}};y.ZodVoid=ln;ln.create=r=>new ln({typeName:q.ZodVoid,...Z(r)});var yt=class r extends G{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==A.ZodParsedType.array)return(0,b.addIssueToContext)(t,{code:I.ZodIssueCode.invalid_type,expected:A.ZodParsedType.array,received:t.parsedType}),b.INVALID;if(s.exactLength!==null){let o=t.data.length>s.exactLength.value,a=t.data.length<s.exactLength.value;(o||a)&&((0,b.addIssueToContext)(t,{code:o?I.ZodIssueCode.too_big:I.ZodIssueCode.too_small,minimum:a?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&((0,b.addIssueToContext)(t,{code:I.ZodIssueCode.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&((0,b.addIssueToContext)(t,{code:I.ZodIssueCode.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>s.type._parseAsync(new Le(t,o,t.path,a)))).then(o=>b.ParseStatus.mergeArray(n,o));let i=[...t.data].map((o,a)=>s.type._parseSync(new Le(t,o,t.path,a)));return b.ParseStatus.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:N.errorUtil.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:N.errorUtil.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:N.errorUtil.toString(t)}})}nonempty(e){return this.min(1,e)}};y.ZodArray=yt;yt.create=(r,e)=>new yt({type:r,minLength:null,maxLength:null,exactLength:null,typeName:q.ZodArray,...Z(e)});function an(r){if(r instanceof Ee){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=De.create(an(n))}return new Ee({...r._def,shape:()=>e})}else return r instanceof yt?new yt({...r._def,type:an(r.element)}):r instanceof De?De.create(an(r.unwrap())):r instanceof rt?rt.create(an(r.unwrap())):r instanceof tt?tt.create(r.items.map(e=>an(e))):r}var Ee=class r extends G{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=A.util.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==A.ZodParsedType.object){let c=this._getOrReturnCtx(e);return(0,b.addIssueToContext)(c,{code:I.ZodIssueCode.invalid_type,expected:A.ZodParsedType.object,received:c.parsedType}),b.INVALID}let{status:n,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ve&&this._def.unknownKeys==="strip"))for(let c in s.data)o.includes(c)||a.push(c);let l=[];for(let c of o){let f=i[c],p=s.data[c];l.push({key:{status:"valid",value:c},value:f._parse(new Le(s,p,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof Ve){let c=this._def.unknownKeys;if(c==="passthrough")for(let f of a)l.push({key:{status:"valid",value:f},value:{status:"valid",value:s.data[f]}});else if(c==="strict")a.length>0&&((0,b.addIssueToContext)(s,{code:I.ZodIssueCode.unrecognized_keys,keys:a}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let f of a){let p=s.data[f];l.push({key:{status:"valid",value:f},value:c._parse(new Le(s,p,s.path,f)),alwaysSet:f in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let c=[];for(let f of l){let p=await f.key,v=await f.value;c.push({key:p,value:v,alwaysSet:f.alwaysSet})}return c}).then(c=>b.ParseStatus.mergeObjectSync(n,c)):b.ParseStatus.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return N.errorUtil.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let s=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:N.errorUtil.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:q.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let n of A.util.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let n of A.util.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return an(this)}partial(e){let t={};for(let n of A.util.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let n of A.util.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof De;)i=i._def.innerType;t[n]=i}return new r({...this._def,shape:()=>t})}keyof(){return Nu(A.util.objectKeys(this.shape))}};y.ZodObject=Ee;Ee.create=(r,e)=>new Ee({shape:()=>r,unknownKeys:"strip",catchall:Ve.create(),typeName:q.ZodObject,...Z(e)});Ee.strictCreate=(r,e)=>new Ee({shape:()=>r,unknownKeys:"strict",catchall:Ve.create(),typeName:q.ZodObject,...Z(e)});Ee.lazycreate=(r,e)=>new Ee({shape:r,unknownKeys:"strip",catchall:Ve.create(),typeName:q.ZodObject,...Z(e)});var yr=class extends G{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function s(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return t.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(a=>new I.ZodError(a.ctx.common.issues));return(0,b.addIssueToContext)(t,{code:I.ZodIssueCode.invalid_union,unionErrors:o}),b.INVALID}if(t.common.async)return Promise.all(n.map(async i=>{let o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let l of n){let c={...t,common:{...t.common,issues:[]},parent:null},f=l._parseSync({data:t.data,path:t.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 t.common.issues.push(...i.ctx.common.issues),i.result;let a=o.map(l=>new I.ZodError(l));return(0,b.addIssueToContext)(t,{code:I.ZodIssueCode.invalid_union,unionErrors:a}),b.INVALID}}get options(){return this._def.options}};y.ZodUnion=yr;yr.create=(r,e)=>new yr({options:r,typeName:q.ZodUnion,...Z(e)});var mt=r=>r instanceof br?mt(r.schema):r instanceof $e?mt(r.innerType()):r instanceof wr?[r.value]:r instanceof _r?r.options:r instanceof kr?A.util.objectValues(r.enum):r instanceof Sr?mt(r._def.innerType):r instanceof mr?[void 0]:r instanceof gr?[null]:r instanceof De?[void 0,...mt(r.unwrap())]:r instanceof rt?[null,...mt(r.unwrap())]:r instanceof Fn||r instanceof xr?mt(r.unwrap()):r instanceof Tr?mt(r._def.innerType):[],Os=class r extends G{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==A.ZodParsedType.object)return(0,b.addIssueToContext)(t,{code:I.ZodIssueCode.invalid_type,expected:A.ZodParsedType.object,received:t.parsedType}),b.INVALID;let n=this.discriminator,s=t.data[n],i=this.optionsMap.get(s);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):((0,b.addIssueToContext)(t,{code:I.ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),b.INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let s=new Map;for(let i of t){let o=mt(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of o){if(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,i)}}return new r({typeName:q.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...Z(n)})}};y.ZodDiscriminatedUnion=Os;function ho(r,e){let t=(0,A.getParsedType)(r),n=(0,A.getParsedType)(e);if(r===e)return{valid:!0,data:r};if(t===A.ZodParsedType.object&&n===A.ZodParsedType.object){let s=A.util.objectKeys(e),i=A.util.objectKeys(r).filter(a=>s.indexOf(a)!==-1),o={...r,...e};for(let a of i){let l=ho(r[a],e[a]);if(!l.valid)return{valid:!1};o[a]=l.data}return{valid:!0,data:o}}else if(t===A.ZodParsedType.array&&n===A.ZodParsedType.array){if(r.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<r.length;i++){let o=r[i],a=e[i],l=ho(o,a);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return t===A.ZodParsedType.date&&n===A.ZodParsedType.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var vr=class extends G{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=(i,o)=>{if((0,b.isAborted)(i)||(0,b.isAborted)(o))return b.INVALID;let a=ho(i.value,o.value);return a.valid?(((0,b.isDirty)(i)||(0,b.isDirty)(o))&&t.dirty(),{status:t.value,value:a.data}):((0,b.addIssueToContext)(n,{code:I.ZodIssueCode.invalid_intersection_types}),b.INVALID)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};y.ZodIntersection=vr;vr.create=(r,e,t)=>new vr({left:r,right:e,typeName:q.ZodIntersection,...Z(t)});var tt=class r extends G{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==A.ZodParsedType.array)return(0,b.addIssueToContext)(n,{code:I.ZodIssueCode.invalid_type,expected:A.ZodParsedType.array,received:n.parsedType}),b.INVALID;if(n.data.length<this._def.items.length)return(0,b.addIssueToContext)(n,{code:I.ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),b.INVALID;!this._def.rest&&n.data.length>this._def.items.length&&((0,b.addIssueToContext)(n,{code:I.ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...n.data].map((o,a)=>{let l=this._def.items[a]||this._def.rest;return l?l._parse(new Le(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(i).then(o=>b.ParseStatus.mergeArray(t,o)):b.ParseStatus.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};y.ZodTuple=tt;tt.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new tt({items:r,typeName:q.ZodTuple,rest:null,...Z(e)})};var Ns=class r extends G{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==A.ZodParsedType.object)return(0,b.addIssueToContext)(n,{code:I.ZodIssueCode.invalid_type,expected:A.ZodParsedType.object,received:n.parsedType}),b.INVALID;let s=[],i=this._def.keyType,o=this._def.valueType;for(let a in n.data)s.push({key:i._parse(new Le(n,a,n.path,a)),value:o._parse(new Le(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?b.ParseStatus.mergeObjectAsync(t,s):b.ParseStatus.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof G?new r({keyType:e,valueType:t,typeName:q.ZodRecord,...Z(n)}):new r({keyType:zt.create(),valueType:e,typeName:q.ZodRecord,...Z(t)})}};y.ZodRecord=Ns;var cn=class extends G{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==A.ZodParsedType.map)return(0,b.addIssueToContext)(n,{code:I.ZodIssueCode.invalid_type,expected:A.ZodParsedType.map,received:n.parsedType}),b.INVALID;let s=this._def.keyType,i=this._def.valueType,o=[...n.data.entries()].map(([a,l],c)=>({key:s._parse(new Le(n,a,n.path,[c,"key"])),value:i._parse(new Le(n,l,n.path,[c,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let l of o){let c=await l.key,f=await l.value;if(c.status==="aborted"||f.status==="aborted")return b.INVALID;(c.status==="dirty"||f.status==="dirty")&&t.dirty(),a.set(c.value,f.value)}return{status:t.value,value:a}})}else{let a=new Map;for(let l of o){let c=l.key,f=l.value;if(c.status==="aborted"||f.status==="aborted")return b.INVALID;(c.status==="dirty"||f.status==="dirty")&&t.dirty(),a.set(c.value,f.value)}return{status:t.value,value:a}}}};y.ZodMap=cn;cn.create=(r,e,t)=>new cn({valueType:e,keyType:r,typeName:q.ZodMap,...Z(t)});var dn=class r extends G{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==A.ZodParsedType.set)return(0,b.addIssueToContext)(n,{code:I.ZodIssueCode.invalid_type,expected:A.ZodParsedType.set,received:n.parsedType}),b.INVALID;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&((0,b.addIssueToContext)(n,{code:I.ZodIssueCode.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&((0,b.addIssueToContext)(n,{code:I.ZodIssueCode.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let i=this._def.valueType;function o(l){let c=new Set;for(let f of l){if(f.status==="aborted")return b.INVALID;f.status==="dirty"&&t.dirty(),c.add(f.value)}return{status:t.value,value:c}}let a=[...n.data.values()].map((l,c)=>i._parse(new Le(n,l,n.path,c)));return n.common.async?Promise.all(a).then(l=>o(l)):o(a)}min(e,t){return new r({...this._def,minSize:{value:e,message:N.errorUtil.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:N.errorUtil.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};y.ZodSet=dn;dn.create=(r,e)=>new dn({valueType:r,minSize:null,maxSize:null,typeName:q.ZodSet,...Z(e)});var Ms=class r extends G{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==A.ZodParsedType.function)return(0,b.addIssueToContext)(t,{code:I.ZodIssueCode.invalid_type,expected:A.ZodParsedType.function,received:t.parsedType}),b.INVALID;function n(a,l){return(0,b.makeIssue)({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,(0,js.getErrorMap)(),js.defaultErrorMap].filter(c=>!!c),issueData:{code:I.ZodIssueCode.invalid_arguments,argumentsError:l}})}function s(a,l){return(0,b.makeIssue)({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,(0,js.getErrorMap)(),js.defaultErrorMap].filter(c=>!!c),issueData:{code:I.ZodIssueCode.invalid_return_type,returnTypeError:l}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof Lt){let a=this;return(0,b.OK)(async function(...l){let c=new I.ZodError([]),f=await a._def.args.parseAsync(l,i).catch(k=>{throw c.addIssue(n(l,k)),c}),p=await Reflect.apply(o,this,f);return await a._def.returns._def.type.parseAsync(p,i).catch(k=>{throw c.addIssue(s(p,k)),c})})}else{let a=this;return(0,b.OK)(function(...l){let c=a._def.args.safeParse(l,i);if(!c.success)throw new I.ZodError([n(l,c.error)]);let f=Reflect.apply(o,this,c.data),p=a._def.returns.safeParse(f,i);if(!p.success)throw new I.ZodError([s(f,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:tt.create(e).rest(gt.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||tt.create([]).rest(gt.create()),returns:t||gt.create(),typeName:q.ZodFunction,...Z(n)})}};y.ZodFunction=Ms;var br=class extends G{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};y.ZodLazy=br;br.create=(r,e)=>new br({getter:r,typeName:q.ZodLazy,...Z(e)});var wr=class extends G{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return(0,b.addIssueToContext)(t,{received:t.data,code:I.ZodIssueCode.invalid_literal,expected:this._def.value}),b.INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}};y.ZodLiteral=wr;wr.create=(r,e)=>new wr({value:r,typeName:q.ZodLiteral,...Z(e)});function Nu(r,e){return new _r({values:r,typeName:q.ZodEnum,...Z(e)})}var _r=class r extends G{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return(0,b.addIssueToContext)(t,{expected:A.util.joinValues(n),received:t.parsedType,code:I.ZodIssueCode.invalid_type}),b.INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return(0,b.addIssueToContext)(t,{received:t.data,code:I.ZodIssueCode.invalid_enum_value,options:n}),b.INVALID}return(0,b.OK)(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};y.ZodEnum=_r;_r.create=Nu;var kr=class extends G{_parse(e){let t=A.util.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==A.ZodParsedType.string&&n.parsedType!==A.ZodParsedType.number){let s=A.util.objectValues(t);return(0,b.addIssueToContext)(n,{expected:A.util.joinValues(s),received:n.parsedType,code:I.ZodIssueCode.invalid_type}),b.INVALID}if(this._cache||(this._cache=new Set(A.util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=A.util.objectValues(t);return(0,b.addIssueToContext)(n,{received:n.data,code:I.ZodIssueCode.invalid_enum_value,options:s}),b.INVALID}return(0,b.OK)(e.data)}get enum(){return this._def.values}};y.ZodNativeEnum=kr;kr.create=(r,e)=>new kr({values:r,typeName:q.ZodNativeEnum,...Z(e)});var Lt=class extends G{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==A.ZodParsedType.promise&&t.common.async===!1)return(0,b.addIssueToContext)(t,{code:I.ZodIssueCode.invalid_type,expected:A.ZodParsedType.promise,received:t.parsedType}),b.INVALID;let n=t.parsedType===A.ZodParsedType.promise?t.data:Promise.resolve(t.data);return(0,b.OK)(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};y.ZodPromise=Lt;Lt.create=(r,e)=>new Lt({type:r,typeName:q.ZodPromise,...Z(e)});var $e=class extends G{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===q.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{(0,b.addIssueToContext)(n,o),o.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(n.data,i);if(n.common.async)return Promise.resolve(o).then(async a=>{if(t.value==="aborted")return b.INVALID;let l=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return l.status==="aborted"?b.INVALID:l.status==="dirty"||t.value==="dirty"?(0,b.DIRTY)(l.value):l});{if(t.value==="aborted")return b.INVALID;let a=this._def.schema._parseSync({data:o,path:n.path,parent:n});return a.status==="aborted"?b.INVALID:a.status==="dirty"||t.value==="dirty"?(0,b.DIRTY)(a.value):a}}if(s.type==="refinement"){let o=a=>{let l=s.refinement(a,i);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?b.INVALID:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?b.INVALID:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.value,value:a.value}))))}if(s.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!(0,b.isValid)(o))return b.INVALID;let a=s.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>(0,b.isValid)(o)?Promise.resolve(s.transform(o.value,i)).then(a=>({status:t.value,value:a})):b.INVALID);A.util.assertNever(s)}};y.ZodEffects=$e;y.ZodTransformer=$e;$e.create=(r,e,t)=>new $e({schema:r,typeName:q.ZodEffects,effect:e,...Z(t)});$e.createWithPreprocess=(r,e,t)=>new $e({schema:e,effect:{type:"preprocess",transform:r},typeName:q.ZodEffects,...Z(t)});var De=class extends G{_parse(e){return this._getType(e)===A.ZodParsedType.undefined?(0,b.OK)(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};y.ZodOptional=De;De.create=(r,e)=>new De({innerType:r,typeName:q.ZodOptional,...Z(e)});var rt=class extends G{_parse(e){return this._getType(e)===A.ZodParsedType.null?(0,b.OK)(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};y.ZodNullable=rt;rt.create=(r,e)=>new rt({innerType:r,typeName:q.ZodNullable,...Z(e)});var Sr=class extends G{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===A.ZodParsedType.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};y.ZodDefault=Sr;Sr.create=(r,e)=>new Sr({innerType:r,typeName:q.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Z(e)});var Tr=class extends G{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return(0,b.isAsync)(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new I.ZodError(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new I.ZodError(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};y.ZodCatch=Tr;Tr.create=(r,e)=>new Tr({innerType:r,typeName:q.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Z(e)});var hn=class extends G{_parse(e){if(this._getType(e)!==A.ZodParsedType.nan){let n=this._getOrReturnCtx(e);return(0,b.addIssueToContext)(n,{code:I.ZodIssueCode.invalid_type,expected:A.ZodParsedType.nan,received:n.parsedType}),b.INVALID}return{status:"valid",value:e.data}}};y.ZodNaN=hn;hn.create=r=>new hn({typeName:q.ZodNaN,...Z(r)});y.BRAND=Symbol("zod_brand");var Fn=class extends G{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}};y.ZodBranded=Fn;var Bn=class r extends G{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?b.INVALID:i.status==="dirty"?(t.dirty(),(0,b.DIRTY)(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?b.INVALID:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:q.ZodPipeline})}};y.ZodPipeline=Bn;var xr=class extends G{_parse(e){let t=this._def.innerType._parse(e),n=s=>((0,b.isValid)(s)&&(s.value=Object.freeze(s.value)),s);return(0,b.isAsync)(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}};y.ZodReadonly=xr;xr.create=(r,e)=>new xr({innerType:r,typeName:q.ZodReadonly,...Z(e)});function $u(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function Mu(r,e={},t){return r?Dt.create().superRefine((n,s)=>{let i=r(n);if(i instanceof Promise)return i.then(o=>{if(!o){let a=$u(e,n),l=a.fatal??t??!0;s.addIssue({code:"custom",...a,fatal:l})}});if(!i){let o=$u(e,n),a=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:a})}}):Dt.create()}y.late={object:Ee.lazycreate};var q;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(q||(y.ZodFirstPartyTypeKind=q={}));var jp=(r,e={message:`Input not instance of ${r.name}`})=>Mu(t=>t instanceof r,e);y.instanceof=jp;var zu=zt.create;y.string=zu;var Du=dr.create;y.number=Du;var Op=hn.create;y.nan=Op;var Np=hr.create;y.bigint=Np;var Lu=fr.create;y.boolean=Lu;var Mp=pr.create;y.date=Mp;var zp=un.create;y.symbol=zp;var Dp=mr.create;y.undefined=Dp;var Lp=gr.create;y.null=Lp;var Up=Dt.create;y.any=Up;var qp=gt.create;y.unknown=qp;var Fp=Ve.create;y.never=Fp;var Bp=ln.create;y.void=Bp;var Kp=yt.create;y.array=Kp;var Zp=Ee.create;y.object=Zp;var Gp=Ee.strictCreate;y.strictObject=Gp;var Vp=yr.create;y.union=Vp;var Hp=Os.create;y.discriminatedUnion=Hp;var Wp=vr.create;y.intersection=Wp;var Jp=tt.create;y.tuple=Jp;var Yp=Ns.create;y.record=Yp;var Xp=cn.create;y.map=Xp;var Qp=dn.create;y.set=Qp;var em=Ms.create;y.function=em;var tm=br.create;y.lazy=tm;var rm=wr.create;y.literal=rm;var nm=_r.create;y.enum=nm;var sm=kr.create;y.nativeEnum=sm;var im=Lt.create;y.promise=im;var Uu=$e.create;y.effect=Uu;y.transformer=Uu;var om=De.create;y.optional=om;var am=rt.create;y.nullable=am;var um=$e.createWithPreprocess;y.preprocess=um;var lm=Bn.create;y.pipeline=lm;var cm=()=>zu().optional();y.ostring=cm;var dm=()=>Du().optional();y.onumber=dm;var hm=()=>Lu().optional();y.oboolean=hm;y.coerce={string:(r=>zt.create({...r,coerce:!0})),number:(r=>dr.create({...r,coerce:!0})),boolean:(r=>fr.create({...r,coerce:!0})),bigint:(r=>hr.create({...r,coerce:!0})),date:(r=>pr.create({...r,coerce:!0}))};y.NEVER=b.INVALID});var fo=ee(Ue=>{"use strict";var fm=Ue&&Ue.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),fn=Ue&&Ue.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&fm(e,r,t)};Object.defineProperty(Ue,"__esModule",{value:!0});fn($s(),Ue);fn(lo(),Ue);fn(Eu(),Ue);fn(Un(),Ue);fn(qu(),Ue);fn(As(),Ue)});var Ku=ee(Ie=>{"use strict";var Fu=Ie&&Ie.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),pm=Ie&&Ie.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),mm=Ie&&Ie.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&Fu(e,r,t);return pm(e,r),e},gm=Ie&&Ie.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Fu(e,r,t)};Object.defineProperty(Ie,"__esModule",{value:!0});Ie.z=void 0;var Bu=mm(fo());Ie.z=Bu;gm(fo(),Ie);Ie.default=Bu});var ve=ee(d=>{"use strict";Object.defineProperty(d,"__esModule",{value:!0});d.RepoDocReadResultMsg=d.RepoDocReadMsg=d.RepoDocsResultMsg=d.RepoDocsMsg=d.ChatLoadResultMsg=d.ChatLoadMsg=d.ChatListResultMsg=d.ChatListMsg=d.ChatUsageMsg=d.ChatStreamMsg=d.JiraUsersResultMsg=d.DeployClaimResultMsg=d.DeployClaimMsg=d.RuleDiagnoseResultMsg=d.ProjectTestResultMsg=d.RunStatusMsg=d.RunUsageMsg=d.RunLogMsg=d.RunClaimMsg=d.HeartbeatMsg=d.HelloMsg=d.RuleConfig=d.ProjectConfig=d.ActionConfig=d.DeployAction=d.EnvironmentConfig=d.PromotionMode=d.DeployStep=d.RespondAction=d.ImplementAction=d.PlanOnlyAction=d.TriggerConfig=d.StatusChangedTrigger=d.CommentKeywordTrigger=d.LabelAddedTrigger=d.ActionType=d.TriggerType=d.ACTIVE_RUN_STATUSES=d.RunStatus=d.needsInputMarkerIn=d.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=d.NEEDS_INPUT_COMMENT_MARKER=d.NEEDS_INPUT_LABEL=d.NEEDS_INPUT_MARKER=d.BRANCH_DEPLOY_ISSUE_KEY=d.REQUIRED_AGENT_CAPABILITIES=d.DEFAULT_AGENT_ID=d.REGISTERED_AGENTS=d.PROTOCOL_VERSION=d.GITHUB_TOKEN_PERMISSIONS=void 0;d.AutopilotNextMsg=d.RunnerUpdateResultMsg=d.RunnerUpdateMsg=d.RepoDocSaveResultMsg=d.RepoDocSaveMsg=d.SetupClaudeMdSaveResultMsg=d.SetupClaudeMdSaveMsg=d.SetupClaudeMdGenerateResultMsg=d.SetupClaudeMdGenerateMsg=d.SetupStatusResultMsg=d.SetupStatusMsg=d.DeploySuggestResultMsg=d.EnvPreflightResultMsg=d.EnvPreflightMsg=d.ChatCreateTicketResultMsg=d.ChatCreateTicketMsg=d.ChatTurnResultMsg=d.ChatTurnMsg=d.ChatFile=d.TeamCredsResultMsg=d.TeamCredsMsg=d.KnowledgeSaveResultMsg=d.KnowledgeSaveMsg=d.KnowledgeListResultMsg=d.KnowledgeFile=d.KnowledgeListMsg=d.AuditReviewResultMsg=d.AuditReviewMsg=d.AuditGetResultMsg=d.AuditGetMsg=d.AuditListResultMsg=d.AuditStatsResultMsg=d.AuditStatsMsg=d.AuditListMsg=d.AuditStartResultMsg=d.AuditStartMsg=d.AuditRecord=d.AuditFinding=d.AuditScope=d.AuditSeverity=d.AuditRole=d.EpicSuggestResultMsg=d.EpicSuggestMsg=d.EpicListResultMsg=d.EpicChild=d.EpicListMsg=d.BoardTriggerResultMsg=d.BoardTriggerMsg=d.BoardFetchResultMsg=d.BoardFetchMsg=void 0;d.DEFAULT_DEPLOY_SUGGEST_PROMPT_TEMPLATE=d.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE=d.DEPLOY_FIX_PROMPT_TEMPLATE=d.PROMPT_PRESETS=d.DEFAULT_RESPOND_PROMPT_TEMPLATE=d.BUGFIX_IMPLEMENT_PROMPT_TEMPLATE=d.BUG_INVESTIGATION_PROMPT_TEMPLATE=d.TECHNICAL_PLAN_PROMPT_TEMPLATE=d.MEMORY_UPDATE_PROMPT=d.DEFAULT_IMPLEMENT_PROMPT_TEMPLATE=d.WRITE_TESTS_PROMPT=d.DEFAULT_PLAN_PROMPT_TEMPLATE=d.EnrollResponse=d.EnrollRequest=d.ServerToRunnerMsg=d.JiraUsersMsg=d.DeploySuggestMsg=d.DeployFixMsg=d.DeployStartMsg=d.RunRetryPushMsg=d.RunRejectedMsg=d.RunApprovedMsg=d.RunCancelMsg=d.RuleDiagnoseMsg=d.ProjectTestMsg=d.RunClaimResultMsg=d.ConfigMsg=d.HelloAckMsg=d.RunnerToServerMsg=d.AutopilotReportMsg=d.AutopilotNextResultMsg=void 0;d.missingAgentCapabilities=ym;d.parseRunnerMsg=bm;d.parseServerMsg=wm;var u=Ku();d.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."};d.PROTOCOL_VERSION="1.37";d.REGISTERED_AGENTS=[{id:"claude-code",displayName:"Claude Code",capabilities:{readOnlyJail:!0,editNoShellJail:!0,sessionResume:!0,costReporting:!0,modelSelection:!0,loginProfiles:!0},suggestedModels:["claude-fable-5","claude-opus-5","claude-sonnet-5","claude-haiku-4-5-20251001"],experimental:!1},{id:"codex",displayName:"OpenAI Codex CLI (experimental)",capabilities:{readOnlyJail:!0,editNoShellJail:!1,sessionResume:!1,costReporting:!1,modelSelection:!0,loginProfiles:!1},suggestedModels:[],experimental:!0}];d.DEFAULT_AGENT_ID="claude-code";d.REQUIRED_AGENT_CAPABILITIES={plan_only:["readOnlyJail","sessionResume"],respond:["readOnlyJail"],implement:["editNoShellJail","sessionResume"],deploy:[],chat:["readOnlyJail","sessionResume"],assist:["readOnlyJail"]};function ym(r,e){let t=d.REGISTERED_AGENTS.find(n=>n.id===r);return t?(d.REQUIRED_AGENT_CAPABILITIES[e]??[]).filter(n=>!t.capabilities[n]):null}d.BRANCH_DEPLOY_ISSUE_KEY="(branch deploy)";d.NEEDS_INPUT_MARKER="NEEDS-INPUT";d.NEEDS_INPUT_LABEL="agent-needs-input";d.NEEDS_INPUT_COMMENT_MARKER="Allwright needs your input";d.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=["TicketPilot needs your input"];var vm=r=>r.includes(d.NEEDS_INPUT_COMMENT_MARKER)||d.LEGACY_NEEDS_INPUT_COMMENT_MARKERS.some(e=>r.includes(e));d.needsInputMarkerIn=vm;d.RunStatus=u.z.enum(["queued","running","posting","awaiting_approval","needs_input","succeeded","failed","timed_out"]);d.ACTIVE_RUN_STATUSES=["queued","running","posting","awaiting_approval"];d.TriggerType=u.z.enum(["label_added","comment_keyword","status_changed"]);d.ActionType=u.z.enum(["plan_only","implement","respond","deploy"]);d.LabelAddedTrigger=u.z.object({type:u.z.literal("label_added"),label:u.z.string().min(1),doneLabel:u.z.string().min(1).default("agent-planned"),failedLabel:u.z.string().min(1).default("agent-failed")});d.CommentKeywordTrigger=u.z.object({type:u.z.literal("comment_keyword"),keyword:u.z.string().min(1),doneLabel:u.z.string().min(1).default("agent-implemented"),failedLabel:u.z.string().min(1).default("agent-failed")});d.StatusChangedTrigger=u.z.object({type:u.z.literal("status_changed"),status:u.z.string().min(1),doneLabel:u.z.string().min(1).default("agent-deployed"),failedLabel:u.z.string().min(1).default("agent-failed")});d.TriggerConfig=u.z.discriminatedUnion("type",[d.LabelAddedTrigger,d.CommentKeywordTrigger,d.StatusChangedTrigger]);d.PlanOnlyAction=u.z.object({type:u.z.literal("plan_only"),promptTemplate:u.z.string().min(1),timeoutSeconds:u.z.number().int().positive().max(3600).default(900),agent:u.z.string().default(d.DEFAULT_AGENT_ID),model:u.z.string().default("")});d.ImplementAction=u.z.object({type:u.z.literal("implement"),promptTemplate:u.z.string().min(1),timeoutSeconds:u.z.number().int().positive().max(7200).default(1800),maxTurns:u.z.number().int().positive().max(500).default(120),requireApproval:u.z.boolean().default(!0),branchTemplate:u.z.string().min(1).default("agent/{{issueKey}}").refine(r=>r.includes("{{issueKey}}"),{message:"branchTemplate must contain {{issueKey}}"}),baseBranch:u.z.string().min(1).default("main"),jiraTransition:u.z.string().optional(),jiraTransitionOnStart:u.z.string().optional(),jiraTransitionOnMerge:u.z.string().optional(),agent:u.z.string().default(d.DEFAULT_AGENT_ID),model:u.z.string().default(""),updateMemory:u.z.boolean().default(!1),writeTests:u.z.boolean().default(!0),runTests:u.z.boolean().default(!0),mergeOnApprove:u.z.boolean().default(!0),mergeMethod:u.z.enum(["squash","merge","rebase"]).default("squash")});d.RespondAction=u.z.object({type:u.z.literal("respond"),promptTemplate:u.z.string().min(1),timeoutSeconds:u.z.number().int().positive().max(3600).default(600),agent:u.z.string().default(d.DEFAULT_AGENT_ID),model:u.z.string().default("")});d.DeployStep=u.z.object({name:u.z.string().min(1).max(120),run:u.z.string().min(1).max(4e3),continueOnError:u.z.boolean().default(!1)});d.PromotionMode=u.z.enum(["deploy_only","merge_and_deploy"]);d.EnvironmentConfig=u.z.object({id:u.z.string(),projectId:u.z.string(),name:u.z.string(),rank:u.z.number().int().nonnegative(),auditBeforeDeploy:u.z.enum(["","security","testing"]).default(""),branch:u.z.string().default(""),publicUrl:u.z.string().default(""),useDedicatedCheckout:u.z.boolean().default(!1),promotionMode:d.PromotionMode.default("deploy_only"),ticketBranchTemplate:u.z.string().default("agent/{{issueKey}}"),steps:u.z.array(d.DeployStep).default([]),workdir:u.z.string().default(""),timeoutSeconds:u.z.number().int().positive().max(21600).default(1800),requiredSecrets:u.z.array(u.z.string()).default([]),requireApproval:u.z.boolean().default(!1),requireSyncCheck:u.z.boolean().default(!1),previousEnvBranch:u.z.string().optional(),deployFromColumn:u.z.string().default(""),deployToColumn:u.z.string().default("")});d.DeployAction=u.z.object({type:u.z.literal("deploy"),envSelection:u.z.enum(["fixed","from_comment"]).default("from_comment"),environmentId:u.z.string().optional(),requireStatus:u.z.string().optional()});d.ActionConfig=u.z.discriminatedUnion("type",[d.PlanOnlyAction,d.ImplementAction,d.RespondAction,d.DeployAction]);d.ProjectConfig=u.z.object({id:u.z.string(),name:u.z.string(),jiraProjectKey:u.z.string(),repoName:u.z.string(),jiraSiteUrl:u.z.string().default(""),defaultAgent:u.z.string().default("claude-code"),componentRoutes:u.z.array(u.z.object({component:u.z.string().min(1),repoName:u.z.string().min(1)})).default([])});d.RuleConfig=u.z.object({id:u.z.string(),projectId:u.z.string(),name:u.z.string(),enabled:u.z.boolean(),trigger:d.TriggerConfig,action:d.ActionConfig});d.HelloMsg=u.z.object({type:u.z.literal("hello"),protocolVersion:u.z.string(),runnerVersion:u.z.string(),platform:u.z.string(),justBooted:u.z.boolean().optional()});d.HeartbeatMsg=u.z.object({type:u.z.literal("heartbeat"),ts:u.z.string()});d.RunClaimMsg=u.z.object({type:u.z.literal("run.claim"),requestId:u.z.string(),ruleId:u.z.string(),issueKey:u.z.string(),issueSummary:u.z.string().default(""),triggerFingerprint:u.z.string(),dedupKey:u.z.string().optional(),triggeredByAccountId:u.z.string().optional()});d.RunLogMsg=u.z.object({type:u.z.literal("run.log"),runId:u.z.string(),seq:u.z.number().int().nonnegative(),ts:u.z.string(),level:u.z.enum(["info","warn","error","agent"]),message:u.z.string().max(16384)});d.RunUsageMsg=u.z.object({type:u.z.literal("run.usage"),runId:u.z.string(),inputTokens:u.z.number().int().nonnegative(),outputTokens:u.z.number().int().nonnegative(),cacheReadTokens:u.z.number().int().nonnegative().optional(),costUsd:u.z.number().nonnegative().optional(),turns:u.z.number().int().nonnegative().optional()});d.RunStatusMsg=u.z.object({type:u.z.literal("run.status"),runId:u.z.string(),status:d.RunStatus,error:u.z.string().optional(),errorKind:u.z.enum(["guard"]).optional(),costUsd:u.z.number().nonnegative().optional(),inputTokens:u.z.number().int().nonnegative().optional(),outputTokens:u.z.number().int().nonnegative().optional(),resultSummary:u.z.string().max(2e3).optional(),billingMode:u.z.enum(["subscription","api","unknown"]).optional(),model:u.z.string().max(200).optional(),prUrl:u.z.string().optional(),headSha:u.z.string().optional(),deployedRef:u.z.string().optional(),retryAvailable:u.z.boolean().optional()});d.ProjectTestResultMsg=u.z.object({type:u.z.literal("project.test.result"),requestId:u.z.string(),ok:u.z.boolean(),checks:u.z.array(u.z.object({name:u.z.string(),ok:u.z.boolean(),detail:u.z.string(),kind:u.z.enum(["connection","content"]).default("connection"),fix:u.z.array(u.z.string()).default([]),fixNote:u.z.string().default("")}))});d.RuleDiagnoseResultMsg=u.z.object({type:u.z.literal("rule.diagnose.result"),requestId:u.z.string(),checks:u.z.array(u.z.object({name:u.z.string(),ok:u.z.boolean(),detail:u.z.string(),kind:u.z.enum(["connection","content"]).default("connection"),fix:u.z.array(u.z.string()).default([]),fixNote:u.z.string().default("")})),matchedCount:u.z.number().int().nonnegative(),excludedCount:u.z.number().int().nonnegative(),excludedSample:u.z.array(u.z.string()).max(5)});d.DeployClaimMsg=u.z.object({type:u.z.literal("deploy.claim"),requestId:u.z.string(),projectId:u.z.string(),ruleId:u.z.string(),issueKey:u.z.string(),issueSummary:u.z.string().default(""),environmentName:u.z.string(),requestedByAccountId:u.z.string().optional(),requestedByDisplayName:u.z.string().default(""),dedupKey:u.z.string(),triggerFingerprint:u.z.string()});d.DeployClaimResultMsg=u.z.object({type:u.z.literal("deploy.claim.result"),requestId:u.z.string(),accepted:u.z.boolean(),runId:u.z.string().optional(),environment:d.EnvironmentConfig.optional(),reason:u.z.string().optional(),code:u.z.enum(["ok","duplicate","unknown_environment","not_permitted","unlinked_jira_account","promotion_order","jira_disabled","rule_disabled","cap"]).optional()});d.JiraUsersResultMsg=u.z.object({type:u.z.literal("jira.users.result"),requestId:u.z.string(),ok:u.z.boolean(),users:u.z.array(u.z.object({accountId:u.z.string(),displayName:u.z.string(),email:u.z.string().default(""),active:u.z.boolean().default(!0)})).default([]),error:u.z.string().optional()});d.ChatStreamMsg=u.z.object({type:u.z.literal("chat.stream"),requestId:u.z.string(),seq:u.z.number().int().nonnegative(),text:u.z.string().max(8e3)});d.ChatUsageMsg=u.z.object({type:u.z.literal("chat.usage"),requestId:u.z.string(),inputTokens:u.z.number().int().nonnegative(),outputTokens:u.z.number().int().nonnegative(),cacheReadTokens:u.z.number().int().nonnegative().optional(),turns:u.z.number().int().nonnegative().optional()});d.ChatListMsg=u.z.object({type:u.z.literal("chat.list"),requestId:u.z.string(),projectId:u.z.string()});d.ChatListResultMsg=u.z.object({type:u.z.literal("chat.list.result"),requestId:u.z.string(),sessions:u.z.array(u.z.object({sessionId:u.z.string(),title:u.z.string().default(""),updatedAt:u.z.string().default(""),messageCount:u.z.number().int().nonnegative().default(0)})).default([])});d.ChatLoadMsg=u.z.object({type:u.z.literal("chat.load"),requestId:u.z.string(),sessionId:u.z.string()});d.ChatLoadResultMsg=u.z.object({type:u.z.literal("chat.load.result"),requestId:u.z.string(),ok:u.z.boolean(),projectId:u.z.string().default(""),messages:u.z.array(u.z.object({role:u.z.enum(["user","agent"]),text:u.z.string()})).default([]),error:u.z.string().optional()});d.RepoDocsMsg=u.z.object({type:u.z.literal("repo.docs"),requestId:u.z.string(),projectId:u.z.string()});d.RepoDocsResultMsg=u.z.object({type:u.z.literal("repo.docs.result"),requestId:u.z.string(),ok:u.z.boolean(),docs:u.z.array(u.z.object({path:u.z.string(),sizeBytes:u.z.number().int().nonnegative().default(0),updatedAt:u.z.string().default("")})).default([]),error:u.z.string().optional()});d.RepoDocReadMsg=u.z.object({type:u.z.literal("repo.doc.read"),requestId:u.z.string(),projectId:u.z.string(),path:u.z.string().max(400)});d.RepoDocReadResultMsg=u.z.object({type:u.z.literal("repo.doc.read.result"),requestId:u.z.string(),ok:u.z.boolean(),path:u.z.string().default(""),content:u.z.string().default(""),truncated:u.z.boolean().default(!1),error:u.z.string().optional()});d.BoardFetchMsg=u.z.object({type:u.z.literal("board.fetch"),requestId:u.z.string(),projectId:u.z.string()});d.BoardFetchResultMsg=u.z.object({type:u.z.literal("board.fetch.result"),requestId:u.z.string(),ok:u.z.boolean(),browseBaseUrl:u.z.string().default(""),columns:u.z.array(u.z.object({name:u.z.string(),issues:u.z.array(u.z.object({key:u.z.string(),summary:u.z.string(),labels:u.z.array(u.z.string()).default([])})).default([])})).default([]),error:u.z.string().optional()});d.BoardTriggerMsg=u.z.object({type:u.z.literal("board.trigger"),requestId:u.z.string(),projectId:u.z.string(),issueKey:u.z.string(),comment:u.z.string().max(2e3).default(""),removeLabel:u.z.string().default(""),requestedBy:u.z.string().default(""),requestedByEmail:u.z.string().default(""),reimplement:u.z.boolean().default(!1)});d.BoardTriggerResultMsg=u.z.object({type:u.z.literal("board.trigger.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional()});d.EpicListMsg=u.z.object({type:u.z.literal("epic.list"),requestId:u.z.string(),projectId:u.z.string(),epicKey:u.z.string().default("")});d.EpicChild=u.z.object({key:u.z.string(),summary:u.z.string(),status:u.z.string(),statusCategory:u.z.string(),labels:u.z.array(u.z.string()).default([])});d.EpicListResultMsg=u.z.object({type:u.z.literal("epic.list.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),epics:u.z.array(u.z.object({key:u.z.string(),summary:u.z.string(),status:u.z.string()})).default([]),children:u.z.array(d.EpicChild).default([])});d.EpicSuggestMsg=u.z.object({type:u.z.literal("epic.suggest"),requestId:u.z.string(),projectId:u.z.string(),epicKey:u.z.string().min(1),model:u.z.string().default("")});d.EpicSuggestResultMsg=u.z.object({type:u.z.literal("epic.suggest.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),issueKey:u.z.string().default(""),reason:u.z.string().default(""),considered:u.z.number().int().default(0)});d.AuditRole=u.z.enum(["security","testing","architecture"]);d.AuditSeverity=u.z.enum(["critical","high","medium","low","info"]);d.AuditScope=u.z.object({kind:u.z.enum(["repo","ticket","branch"]).default("repo"),ref:u.z.string().default("")});d.AuditFinding=u.z.object({id:u.z.string().min(1),title:u.z.string().min(1),ruleId:u.z.string().max(20).default(""),severity:d.AuditSeverity,area:u.z.string().default(""),evidence:u.z.array(u.z.object({file:u.z.string().min(1),line:u.z.number().int().positive().optional(),note:u.z.string().default("")})).min(1),fix:u.z.string().default("")});d.AuditRecord=u.z.object({id:u.z.string(),role:d.AuditRole,createdAt:u.z.string(),model:u.z.string().default(""),summary:u.z.string().default(""),packNames:u.z.array(u.z.string()).default([]),findings:u.z.array(d.AuditFinding).default([]),costUsd:u.z.number().default(0),review:u.z.object({selected:u.z.array(u.z.string()),updatedAt:u.z.string()}).optional(),verdicts:u.z.record(u.z.object({verdict:u.z.enum(["valid","false-positive","wont-fix"]),note:u.z.string().default(""),by:u.z.string().default(""),at:u.z.string().default("")})).default({}),lessonsWritten:u.z.array(u.z.string()).default([]),ticketed:u.z.record(u.z.string()).default({}),scope:d.AuditScope.default({kind:"repo",ref:""}),testRun:u.z.array(u.z.object({command:u.z.string(),exitCode:u.z.number().int(),durationMs:u.z.number().int().default(0),tail:u.z.string().default("")})).optional()});d.AuditStartMsg=u.z.object({type:u.z.literal("audit.start"),requestId:u.z.string(),projectId:u.z.string(),role:d.AuditRole,model:u.z.string().default(""),scope:d.AuditScope.default({kind:"repo",ref:""})});d.AuditStartResultMsg=u.z.object({type:u.z.literal("audit.start.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),audit:d.AuditRecord.optional()});d.AuditListMsg=u.z.object({type:u.z.literal("audit.list"),requestId:u.z.string(),projectId:u.z.string()});d.AuditStatsMsg=u.z.object({type:u.z.literal("audit.stats"),requestId:u.z.string(),projectIds:u.z.array(u.z.string()).max(200).default([]),since:u.z.string().default("")});d.AuditStatsResultMsg=u.z.object({type:u.z.literal("audit.stats.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),byProject:u.z.record(u.z.object({audits:u.z.number().int().default(0),findings:u.z.number().int().default(0),valid:u.z.number().int().default(0),falsePositive:u.z.number().int().default(0),wontFix:u.z.number().int().default(0),unreviewed:u.z.number().int().default(0)})).default({})});d.AuditListResultMsg=u.z.object({type:u.z.literal("audit.list.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),audits:u.z.array(u.z.object({id:u.z.string(),role:d.AuditRole,createdAt:u.z.string(),findingCount:u.z.number().int(),bySeverity:u.z.record(u.z.number().int()).default({})})).default([])});d.AuditGetMsg=u.z.object({type:u.z.literal("audit.get"),requestId:u.z.string(),projectId:u.z.string(),auditId:u.z.string()});d.AuditGetResultMsg=u.z.object({type:u.z.literal("audit.get.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),audit:d.AuditRecord.optional()});d.AuditReviewMsg=u.z.object({type:u.z.literal("audit.review"),requestId:u.z.string(),projectId:u.z.string(),auditId:u.z.string(),selected:u.z.array(u.z.string()).optional(),ticketed:u.z.array(u.z.object({findingId:u.z.string(),issueKey:u.z.string()})).default([]),verdicts:u.z.array(u.z.object({findingId:u.z.string(),verdict:u.z.enum(["valid","false-positive","wont-fix"]),note:u.z.string().max(2e3).default("")})).default([]),verdictBy:u.z.string().default("")});d.AuditReviewResultMsg=u.z.object({type:u.z.literal("audit.review.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),audit:d.AuditRecord.optional()});d.KnowledgeListMsg=u.z.object({type:u.z.literal("knowledge.list"),requestId:u.z.string(),projectId:u.z.string()});d.KnowledgeFile=u.z.object({role:d.AuditRole,level:u.z.enum(["global","org","project"]),source:u.z.enum(["pack","lessons"]),name:u.z.string(),content:u.z.string(),editable:u.z.boolean().default(!1)});d.KnowledgeListResultMsg=u.z.object({type:u.z.literal("knowledge.list.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),files:u.z.array(d.KnowledgeFile).default([])});d.KnowledgeSaveMsg=u.z.object({type:u.z.literal("knowledge.save"),requestId:u.z.string(),projectId:u.z.string(),role:d.AuditRole,level:u.z.enum(["org","project"]),source:u.z.enum(["pack","lessons"]),name:u.z.string().min(1).max(100),content:u.z.string().max(6e4),append:u.z.boolean().default(!1),by:u.z.string().default("")});d.KnowledgeSaveResultMsg=u.z.object({type:u.z.literal("knowledge.save.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional()});d.TeamCredsMsg=u.z.object({type:u.z.literal("team.creds"),requestId:u.z.string(),emails:u.z.array(u.z.string()).max(200)});d.TeamCredsResultMsg=u.z.object({type:u.z.literal("team.creds.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),githubShared:u.z.boolean().default(!1),sharedGithubLogin:u.z.string().default(""),entries:u.z.array(u.z.object({email:u.z.string(),jira:u.z.enum(["own","runner-account","missing"]),jiraAs:u.z.string().default(""),github:u.z.enum(["own","shared","missing"]),githubAs:u.z.string().default("")})).default([])});d.ChatFile=u.z.object({name:u.z.string().min(1).max(255),contentBase64:u.z.string().min(1).max(6e6)});d.ChatTurnMsg=u.z.object({type:u.z.literal("chat.turn"),requestId:u.z.string(),projectId:u.z.string(),sessionId:u.z.string().optional(),message:u.z.string().min(1).max(2e4),userName:u.z.string().default(""),model:u.z.string().default(""),files:u.z.array(d.ChatFile).max(8).default([])});d.ChatTurnResultMsg=u.z.object({type:u.z.literal("chat.turn.result"),requestId:u.z.string(),ok:u.z.boolean(),sessionId:u.z.string().default(""),reply:u.z.string().default(""),error:u.z.string().optional(),inputTokens:u.z.number().int().nonnegative().default(0),outputTokens:u.z.number().int().nonnegative().default(0),cacheReadTokens:u.z.number().int().nonnegative().default(0),costUsd:u.z.number().nonnegative().default(0),model:u.z.string().max(200).default("")});d.ChatCreateTicketMsg=u.z.object({type:u.z.literal("chat.create.ticket"),requestId:u.z.string(),projectId:u.z.string(),summary:u.z.string().min(1).max(250),description:u.z.string().default(""),triggerComment:u.z.string().default(""),requestedBy:u.z.string().default(""),requestedByEmail:u.z.string().default(""),asEpic:u.z.boolean().default(!1),children:u.z.array(u.z.object({summary:u.z.string().min(1),description:u.z.string().default("")})).max(20).default([]),files:u.z.array(d.ChatFile).max(8).default([])});d.ChatCreateTicketResultMsg=u.z.object({type:u.z.literal("chat.create.ticket.result"),requestId:u.z.string(),ok:u.z.boolean(),issueKey:u.z.string().default(""),error:u.z.string().optional(),childKeys:u.z.array(u.z.string()).default([])});d.EnvPreflightMsg=u.z.object({type:u.z.literal("env.preflight"),requestId:u.z.string(),projectId:u.z.string(),environmentName:u.z.string().default(""),steps:u.z.array(d.DeployStep).default([]),requiredSecrets:u.z.array(u.z.string()).default([]),workdir:u.z.string().default(""),branch:u.z.string().default(""),publicUrl:u.z.string().default("")});d.EnvPreflightResultMsg=u.z.object({type:u.z.literal("env.preflight.result"),requestId:u.z.string(),ok:u.z.boolean(),checks:u.z.array(u.z.object({name:u.z.string(),ok:u.z.boolean(),detail:u.z.string().default(""),kind:u.z.enum(["connection","content"]).default("connection"),fix:u.z.array(u.z.string()).default([]),fixNote:u.z.string().default("")})).default([])});d.DeploySuggestResultMsg=u.z.object({type:u.z.literal("deploy.suggest.result"),requestId:u.z.string(),ok:u.z.boolean(),steps:u.z.array(d.DeployStep).default([]),requiredSecrets:u.z.array(u.z.string()).default([]),notes:u.z.string().default(""),error:u.z.string().optional(),docPath:u.z.string().default(""),docContent:u.z.string().max(1e5).default("")});d.SetupStatusMsg=u.z.object({type:u.z.literal("setup.status"),requestId:u.z.string(),repoNames:u.z.array(u.z.string()).max(100).default([])});d.SetupStatusResultMsg=u.z.object({type:u.z.literal("setup.status.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),jiraConfigured:u.z.boolean().default(!1),jiraEmail:u.z.string().default(""),claude:u.z.object({installed:u.z.boolean(),version:u.z.string().default(""),loggedIn:u.z.boolean()}).optional(),githubTokenSet:u.z.boolean().default(!1),githubLogin:u.z.string().default(""),deploysEnabled:u.z.boolean().default(!1),jiraUserCount:u.z.number().int().default(0),repos:u.z.array(u.z.object({repoName:u.z.string(),mapped:u.z.boolean(),pathExists:u.z.boolean().default(!1),isGit:u.z.boolean().default(!1),claudeMd:u.z.boolean().default(!1),deployMd:u.z.boolean().default(!1),testMd:u.z.boolean().default(!1),defaultBranch:u.z.string().default(""),githubToken:u.z.boolean().default(!1),githubTokenOwn:u.z.boolean().default(!1)})).default([])});d.SetupClaudeMdGenerateMsg=u.z.object({type:u.z.literal("setup.claudemd.generate"),requestId:u.z.string(),projectId:u.z.string(),kind:u.z.enum(["claude","deploy","design"]).default("claude"),streamId:u.z.string().default("")});d.SetupClaudeMdGenerateResultMsg=u.z.object({type:u.z.literal("setup.claudemd.generate.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),content:u.z.string().default("")});d.SetupClaudeMdSaveMsg=u.z.object({type:u.z.literal("setup.claudemd.save"),requestId:u.z.string(),projectId:u.z.string(),kind:u.z.enum(["claude","deploy","design"]).default("claude"),overwrite:u.z.boolean().default(!1),content:u.z.string().max(1e5)});d.SetupClaudeMdSaveResultMsg=u.z.object({type:u.z.literal("setup.claudemd.save.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),note:u.z.string().default("")});d.RepoDocSaveMsg=u.z.object({type:u.z.literal("repo.doc.save"),requestId:u.z.string(),projectId:u.z.string(),relPath:u.z.string().min(1).max(200),overwrite:u.z.boolean().default(!1),content:u.z.string().max(2e5)});d.RepoDocSaveResultMsg=u.z.object({type:u.z.literal("repo.doc.save.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),note:u.z.string().default("")});d.RunnerUpdateMsg=u.z.object({type:u.z.literal("runner.update"),requestId:u.z.string()});d.RunnerUpdateResultMsg=u.z.object({type:u.z.literal("runner.update.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),note:u.z.string().default(""),scheduled:u.z.boolean().default(!1)});d.AutopilotNextMsg=u.z.object({type:u.z.literal("autopilot.next"),requestId:u.z.string()});d.AutopilotNextResultMsg=u.z.object({type:u.z.literal("autopilot.next.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),item:u.z.object({id:u.z.string(),projectId:u.z.string(),issueKey:u.z.string(),ruleId:u.z.string(),baseOverride:u.z.string().default(""),branchOverride:u.z.string().default(""),continueBranch:u.z.boolean().default(!1)}).nullable().default(null),pausedUntil:u.z.string().default("")});d.AutopilotReportMsg=u.z.object({type:u.z.literal("autopilot.report"),requestId:u.z.string(),itemId:u.z.string(),outcome:u.z.enum(["claimed","failed","paused"]),runId:u.z.string().default(""),error:u.z.string().default("")});d.RunnerToServerMsg=u.z.discriminatedUnion("type",[d.HelloMsg,d.HeartbeatMsg,d.RunClaimMsg,d.RunLogMsg,d.RunUsageMsg,d.RunStatusMsg,d.ProjectTestResultMsg,d.RuleDiagnoseResultMsg,d.DeployClaimMsg,d.DeploySuggestResultMsg,d.EnvPreflightResultMsg,d.ChatTurnResultMsg,d.ChatStreamMsg,d.ChatUsageMsg,d.ChatCreateTicketResultMsg,d.ChatListResultMsg,d.RepoDocsResultMsg,d.RepoDocReadResultMsg,d.ChatLoadResultMsg,d.BoardFetchResultMsg,d.BoardTriggerResultMsg,d.TeamCredsResultMsg,d.AuditStartResultMsg,d.AuditListResultMsg,d.AuditGetResultMsg,d.AuditReviewResultMsg,d.KnowledgeListResultMsg,d.KnowledgeSaveResultMsg,d.EpicListResultMsg,d.EpicSuggestResultMsg,d.JiraUsersResultMsg,d.SetupStatusResultMsg,d.SetupClaudeMdGenerateResultMsg,d.SetupClaudeMdSaveResultMsg,d.RepoDocSaveResultMsg,d.RunnerUpdateResultMsg,d.AuditStatsResultMsg,d.AutopilotNextMsg,d.AutopilotReportMsg]);d.HelloAckMsg=u.z.object({type:u.z.literal("hello.ack"),runnerId:u.z.string(),runnerName:u.z.string(),serverTime:u.z.string()});d.ConfigMsg=u.z.object({type:u.z.literal("config"),projects:u.z.array(d.ProjectConfig),rules:u.z.array(d.RuleConfig),environments:u.z.array(d.EnvironmentConfig).default([]),pollingPaused:u.z.boolean().default(!1)});d.RunClaimResultMsg=u.z.object({type:u.z.literal("run.claim.result"),requestId:u.z.string(),accepted:u.z.boolean(),runId:u.z.string().optional(),reason:u.z.string().optional(),claudeProfile:u.z.string().optional(),actorEmail:u.z.string().optional()});d.ProjectTestMsg=u.z.object({type:u.z.literal("project.test"),requestId:u.z.string(),projectId:u.z.string()});d.RuleDiagnoseMsg=u.z.object({type:u.z.literal("rule.diagnose"),requestId:u.z.string(),ruleId:u.z.string()});d.RunCancelMsg=u.z.object({type:u.z.literal("run.cancel"),runId:u.z.string()});d.RunApprovedMsg=u.z.object({type:u.z.literal("run.approved"),runId:u.z.string(),headSha:u.z.string().optional()});d.RunRejectedMsg=u.z.object({type:u.z.literal("run.rejected"),runId:u.z.string()});d.RunRetryPushMsg=u.z.object({type:u.z.literal("run.retryPush"),runId:u.z.string()});d.DeployStartMsg=u.z.object({type:u.z.literal("deploy.start"),runId:u.z.string(),projectId:u.z.string(),issueKey:u.z.string(),issueSummary:u.z.string().default(""),environment:d.EnvironmentConfig,requestedBy:u.z.string().default(""),attempt:u.z.number().int().positive().default(1)});d.DeployFixMsg=u.z.object({type:u.z.literal("deploy.fix"),requestId:u.z.string(),projectId:u.z.string(),environmentName:u.z.string(),steps:u.z.array(u.z.object({name:u.z.string(),run:u.z.string(),continueOnError:u.z.boolean().default(!1)})),failedStep:u.z.string().default(""),errorText:u.z.string().max(8e3).default("")});d.DeploySuggestMsg=u.z.object({type:u.z.literal("deploy.suggest"),requestId:u.z.string(),projectId:u.z.string(),environmentName:u.z.string(),notes:u.z.string().default(""),timeoutSeconds:u.z.number().int().positive().max(1800).default(300)});d.JiraUsersMsg=u.z.object({type:u.z.literal("jira.users"),requestId:u.z.string(),query:u.z.string().default("")});d.ServerToRunnerMsg=u.z.discriminatedUnion("type",[d.HelloAckMsg,d.ConfigMsg,d.RunClaimResultMsg,d.ProjectTestMsg,d.RuleDiagnoseMsg,d.RunCancelMsg,d.RunApprovedMsg,d.RunRejectedMsg,d.RunRetryPushMsg,d.DeployClaimResultMsg,d.DeployStartMsg,d.DeploySuggestMsg,d.DeployFixMsg,d.EnvPreflightMsg,d.ChatTurnMsg,d.ChatCreateTicketMsg,d.ChatListMsg,d.RepoDocsMsg,d.RepoDocReadMsg,d.ChatLoadMsg,d.BoardFetchMsg,d.BoardTriggerMsg,d.TeamCredsMsg,d.AuditStartMsg,d.AuditListMsg,d.AuditGetMsg,d.AuditReviewMsg,d.KnowledgeListMsg,d.KnowledgeSaveMsg,d.EpicListMsg,d.EpicSuggestMsg,d.JiraUsersMsg,d.SetupStatusMsg,d.SetupClaudeMdGenerateMsg,d.SetupClaudeMdSaveMsg,d.RepoDocSaveMsg,d.RunnerUpdateMsg,d.AuditStatsMsg,d.AutopilotNextResultMsg]);d.EnrollRequest=u.z.object({enrollToken:u.z.string().min(10),name:u.z.string().min(1).max(100),platform:u.z.string(),runnerVersion:u.z.string()});d.EnrollResponse=u.z.object({runnerId:u.z.string(),runnerToken:u.z.string(),controlPlaneWsUrl:u.z.string()});function bm(r){return d.RunnerToServerMsg.parse(r)}function wm(r){return d.ServerToRunnerMsg.parse(r)}d.DEFAULT_PLAN_PROMPT_TEMPLATE=`You are a senior engineer asked to assess a Jira ticket. You have read-only access to the repository - do not attempt to modify anything.
|
|
23
|
+
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(s=>t.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function el(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",s="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?t=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=i[1],/^\d+$/.test(i[3])?s=i[3]:n=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],s=i[4]),t&&s!=="0"?`${t}=${n}:${parseInt(s)+1}`:e})}tl.Command=ro});var ol=ee(Me=>{var{Argument:nl}=Ts(),{Command:no}=rl(),{CommanderError:Lh,InvalidArgumentError:sl}=Bn(),{Help:Uh}=Vi(),{Option:il}=Xi();Me.program=new no;Me.createCommand=r=>new no(r);Me.createOption=(r,e)=>new il(r,e);Me.createArgument=(r,e)=>new nl(r,e);Me.Command=no;Me.Option=il;Me.Argument=nl;Me.Help=Uh;Me.CommanderError=Lh;Me.InvalidArgumentError=sl;Me.InvalidOptionArgumentError=sl});var Vn=ee(ae=>{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});ae.getParsedType=ae.ZodParsedType=ae.objectUtil=ae.util=void 0;var ho;(function(r){r.assertEqual=s=>{};function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},r.getValidEnumValues=s=>{let i=r.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),o={};for(let a of i)o[a]=s[a];return r.objectValues(o)},r.objectValues=s=>r.objectKeys(s).map(function(i){return s[i]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},r.find=(s,i)=>{for(let o of s)if(i(o))return o},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}r.joinValues=n,r.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(ho||(ae.util=ho={}));var Al;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(Al||(ae.objectUtil=Al={}));ae.ZodParsedType=ho.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var ip=r=>{switch(typeof r){case"undefined":return ae.ZodParsedType.undefined;case"string":return ae.ZodParsedType.string;case"number":return Number.isNaN(r)?ae.ZodParsedType.nan:ae.ZodParsedType.number;case"boolean":return ae.ZodParsedType.boolean;case"function":return ae.ZodParsedType.function;case"bigint":return ae.ZodParsedType.bigint;case"symbol":return ae.ZodParsedType.symbol;case"object":return Array.isArray(r)?ae.ZodParsedType.array:r===null?ae.ZodParsedType.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?ae.ZodParsedType.promise:typeof Map<"u"&&r instanceof Map?ae.ZodParsedType.map:typeof Set<"u"&&r instanceof Set?ae.ZodParsedType.set:typeof Date<"u"&&r instanceof Date?ae.ZodParsedType.date:ae.ZodParsedType.object;default:return ae.ZodParsedType.unknown}};ae.getParsedType=ip});var Ds=ee(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.ZodError=zt.quotelessJson=zt.ZodIssueCode=void 0;var $l=Vn();zt.ZodIssueCode=$l.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 op=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:");zt.quotelessJson=op;var Wn=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},n={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)n._errors.push(t(o));else{let a=n,u=0;for(;u<o.path.length;){let c=o.path[u];u===o.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(t(o))):a[c]=a[c]||{_errors:[]},a=a[c],u++}}};return s(this),n}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,$l.util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},n=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];t[i]=t[i]||[],t[i].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};zt.ZodError=Wn;Wn.create=r=>new Wn(r)});var po=ee(fo=>{"use strict";Object.defineProperty(fo,"__esModule",{value:!0});var ke=Ds(),fr=Vn(),ap=(r,e)=>{let t;switch(r.code){case ke.ZodIssueCode.invalid_type:r.received===fr.ZodParsedType.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case ke.ZodIssueCode.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,fr.util.jsonStringifyReplacer)}`;break;case ke.ZodIssueCode.unrecognized_keys:t=`Unrecognized key(s) in object: ${fr.util.joinValues(r.keys,", ")}`;break;case ke.ZodIssueCode.invalid_union:t="Invalid input";break;case ke.ZodIssueCode.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${fr.util.joinValues(r.options)}`;break;case ke.ZodIssueCode.invalid_enum_value:t=`Invalid enum value. Expected ${fr.util.joinValues(r.options)}, received '${r.received}'`;break;case ke.ZodIssueCode.invalid_arguments:t="Invalid function arguments";break;case ke.ZodIssueCode.invalid_return_type:t="Invalid function return type";break;case ke.ZodIssueCode.invalid_date:t="Invalid date";break;case ke.ZodIssueCode.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:fr.util.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case ke.ZodIssueCode.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case ke.ZodIssueCode.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case ke.ZodIssueCode.custom:t="Invalid input";break;case ke.ZodIssueCode.invalid_intersection_types:t="Intersection results could not be merged";break;case ke.ZodIssueCode.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case ke.ZodIssueCode.not_finite:t="Number must be finite";break;default:t=e.defaultError,fr.util.assertNever(r)}return{message:t}};fo.default=ap});var Ls=ee(Dt=>{"use strict";var lp=Dt&&Dt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Dt,"__esModule",{value:!0});Dt.defaultErrorMap=void 0;Dt.setErrorMap=up;Dt.getErrorMap=cp;var Pl=lp(po());Dt.defaultErrorMap=Pl.default;var jl=Pl.default;function up(r){jl=r}function cp(){return jl}});var go=ee(se=>{"use strict";var dp=se&&se.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(se,"__esModule",{value:!0});se.isAsync=se.isValid=se.isDirty=se.isAborted=se.OK=se.DIRTY=se.INVALID=se.ParseStatus=se.EMPTY_PATH=se.makeIssue=void 0;se.addIssueToContext=pp;var hp=Ls(),Ol=dp(po()),fp=r=>{let{data:e,path:t,errorMaps:n,issueData:s}=r,i=[...t,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let a="",u=n.filter(c=>!!c).slice().reverse();for(let c of u)a=c(o,{data:e,defaultError:a}).message;return{...s,path:i,message:a}};se.makeIssue=fp;se.EMPTY_PATH=[];function pp(r,e){let t=(0,hp.getErrorMap)(),n=(0,se.makeIssue)({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===Ol.default?void 0:Ol.default].filter(s=>!!s)});r.common.issues.push(n)}var mo=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let s of t){if(s.status==="aborted")return se.INVALID;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let s of t){let i=await s.key,o=await s.value;n.push({key:i,value:o})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let s of t){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return se.INVALID;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(n[i.value]=o.value)}return{status:e.value,value:n}}};se.ParseStatus=mo;se.INVALID=Object.freeze({status:"aborted"});var mp=r=>({status:"dirty",value:r});se.DIRTY=mp;var gp=r=>({status:"valid",value:r});se.OK=gp;var yp=r=>r.status==="aborted";se.isAborted=yp;var vp=r=>r.status==="dirty";se.isDirty=vp;var bp=r=>r.status==="valid";se.isValid=bp;var wp=r=>typeof Promise<"u"&&r instanceof Promise;se.isAsync=wp});var Ml=ee(Nl=>{"use strict";Object.defineProperty(Nl,"__esModule",{value:!0})});var Dl=ee(Us=>{"use strict";Object.defineProperty(Us,"__esModule",{value:!0});Us.errorUtil=void 0;var zl;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(zl||(Us.errorUtil=zl={}))});var Jl=ee(b=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});b.discriminatedUnion=b.date=b.boolean=b.bigint=b.array=b.any=b.coerce=b.ZodFirstPartyTypeKind=b.late=b.ZodSchema=b.Schema=b.ZodReadonly=b.ZodPipeline=b.ZodBranded=b.BRAND=b.ZodNaN=b.ZodCatch=b.ZodDefault=b.ZodNullable=b.ZodOptional=b.ZodTransformer=b.ZodEffects=b.ZodPromise=b.ZodNativeEnum=b.ZodEnum=b.ZodLiteral=b.ZodLazy=b.ZodFunction=b.ZodSet=b.ZodMap=b.ZodRecord=b.ZodTuple=b.ZodIntersection=b.ZodDiscriminatedUnion=b.ZodUnion=b.ZodObject=b.ZodArray=b.ZodVoid=b.ZodNever=b.ZodUnknown=b.ZodAny=b.ZodNull=b.ZodUndefined=b.ZodSymbol=b.ZodDate=b.ZodBoolean=b.ZodBigInt=b.ZodNumber=b.ZodString=b.ZodType=void 0;b.NEVER=b.void=b.unknown=b.union=b.undefined=b.tuple=b.transformer=b.symbol=b.string=b.strictObject=b.set=b.record=b.promise=b.preprocess=b.pipeline=b.ostring=b.optional=b.onumber=b.oboolean=b.object=b.number=b.nullable=b.null=b.never=b.nativeEnum=b.nan=b.map=b.literal=b.lazy=b.intersection=b.instanceof=b.function=b.enum=b.effect=void 0;b.datetimeRegex=Bl;b.custom=Zl;var R=Ds(),qs=Ls(),z=Dl(),w=go(),A=Vn(),qe=class{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Ll=(r,e)=>{if((0,w.isValid)(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new R.ZodError(r.common.issues);return this._error=t,this._error}}};function G(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,a)=>{let{message:u}=r;return o.code==="invalid_enum_value"?{message:u??a.defaultError}:typeof a.data>"u"?{message:u??n??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:u??t??a.defaultError}},description:s}}var H=class{get description(){return this._def.description}_getType(e){return(0,A.getParsedType)(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:(0,A.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new w.ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:(0,A.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if((0,w.isAsync)(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,A.getParsedType)(e)},s=this._parseSync({data:e,path:n.path,parent:n});return Ll(n,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,A.getParsedType)(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return(0,w.isValid)(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>(0,w.isValid)(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,A.getParsedType)(e)},s=this._parse({data:e,path:n.path,parent:n}),i=await((0,w.isAsync)(s)?s:Promise.resolve(s));return Ll(n,i)}refine(e,t){let n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,i)=>{let o=e(s),a=()=>i.addIssue({code:R.ZodIssueCode.custom,...n(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(u=>u?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new je({schema:this,typeName:B.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return Ue.create(this,this._def)}nullable(){return it.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return wt.create(this)}promise(){return qt.create(this,this._def)}or(e){return wr.create([this,e],this._def)}and(e){return _r.create(this,e,this._def)}transform(e){return new je({...G(this._def),schema:this,typeName:B.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Cr({...G(this._def),innerType:this,defaultValue:t,typeName:B.ZodDefault})}brand(){return new Jn({typeName:B.ZodBranded,type:this,...G(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Ir({...G(this._def),innerType:this,catchValue:t,typeName:B.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Yn.create(this,e)}readonly(){return Rr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};b.ZodType=H;b.Schema=H;b.ZodSchema=H;var _p=/^c[^\s-]{8,}$/i,kp=/^[0-9a-z]+$/,Sp=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Tp=/^[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,xp=/^[a-z0-9_-]{21}$/i,Cp=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ip=/^[-+]?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)?)??$/,Rp=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ep="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",yo,Ap=/^(?:(?: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])$/,$p=/^(?:(?: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])$/,Pp=/^(([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]))$/,jp=/^(([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])$/,Op=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Np=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ql="((\\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])))",Mp=new RegExp(`^${ql}$`);function Fl(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function zp(r){return new RegExp(`^${Fl(r)}$`)}function Bl(r){let e=`${ql}T${Fl(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Dp(r,e){return!!((e==="v4"||!e)&&Ap.test(r)||(e==="v6"||!e)&&Pp.test(r))}function Lp(r,e){if(!Cp.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function Up(r,e){return!!((e==="v4"||!e)&&$p.test(r)||(e==="v6"||!e)&&jp.test(r))}var Lt=class r extends H{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==A.ZodParsedType.string){let i=this._getOrReturnCtx(e);return(0,w.addIssueToContext)(i,{code:R.ZodIssueCode.invalid_type,expected:A.ZodParsedType.string,received:i.parsedType}),w.INVALID}let n=new w.ParseStatus,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),(0,w.addIssueToContext)(s,{code:R.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),(0,w.addIssueToContext)(s,{code:R.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(s=this._getOrReturnCtx(e,s),o?(0,w.addIssueToContext)(s,{code:R.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&(0,w.addIssueToContext)(s,{code:R.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")Rp.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,w.addIssueToContext)(s,{validation:"email",code:R.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")yo||(yo=new RegExp(Ep,"u")),yo.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,w.addIssueToContext)(s,{validation:"emoji",code:R.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")Tp.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,w.addIssueToContext)(s,{validation:"uuid",code:R.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")xp.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,w.addIssueToContext)(s,{validation:"nanoid",code:R.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")_p.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,w.addIssueToContext)(s,{validation:"cuid",code:R.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")kp.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,w.addIssueToContext)(s,{validation:"cuid2",code:R.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")Sp.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,w.addIssueToContext)(s,{validation:"ulid",code:R.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),(0,w.addIssueToContext)(s,{validation:"url",code:R.ZodIssueCode.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,w.addIssueToContext)(s,{validation:"regex",code:R.ZodIssueCode.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),(0,w.addIssueToContext)(s,{code:R.ZodIssueCode.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,w.addIssueToContext)(s,{code:R.ZodIssueCode.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,w.addIssueToContext)(s,{code:R.ZodIssueCode.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?Bl(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,w.addIssueToContext)(s,{code:R.ZodIssueCode.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?Mp.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,w.addIssueToContext)(s,{code:R.ZodIssueCode.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?zp(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,w.addIssueToContext)(s,{code:R.ZodIssueCode.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?Ip.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,w.addIssueToContext)(s,{validation:"duration",code:R.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?Dp(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,w.addIssueToContext)(s,{validation:"ip",code:R.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?Lp(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),(0,w.addIssueToContext)(s,{validation:"jwt",code:R.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?Up(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,w.addIssueToContext)(s,{validation:"cidr",code:R.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?Op.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,w.addIssueToContext)(s,{validation:"base64",code:R.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?Np.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,w.addIssueToContext)(s,{validation:"base64url",code:R.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):A.util.assertNever(i);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:R.ZodIssueCode.invalid_string,...z.errorUtil.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...z.errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...z.errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...z.errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...z.errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...z.errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...z.errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...z.errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...z.errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...z.errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...z.errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...z.errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...z.errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...z.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,...z.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,...z.errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...z.errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...z.errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...z.errorUtil.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...z.errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...z.errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...z.errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...z.errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...z.errorUtil.errToObj(t)})}nonempty(e){return this.min(1,z.errorUtil.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};b.ZodString=Lt;Lt.create=r=>new Lt({checks:[],typeName:B.ZodString,coerce:r?.coerce??!1,...G(r)});function qp(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,i=Number.parseInt(r.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var pr=class r extends H{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==A.ZodParsedType.number){let i=this._getOrReturnCtx(e);return(0,w.addIssueToContext)(i,{code:R.ZodIssueCode.invalid_type,expected:A.ZodParsedType.number,received:i.parsedType}),w.INVALID}let n,s=new w.ParseStatus;for(let i of this._def.checks)i.kind==="int"?A.util.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),(0,w.addIssueToContext)(n,{code:R.ZodIssueCode.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),(0,w.addIssueToContext)(n,{code:R.ZodIssueCode.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),(0,w.addIssueToContext)(n,{code:R.ZodIssueCode.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?qp(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),(0,w.addIssueToContext)(n,{code:R.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),(0,w.addIssueToContext)(n,{code:R.ZodIssueCode.not_finite,message:i.message}),s.dirty()):A.util.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,z.errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,z.errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,z.errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,z.errorUtil.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:z.errorUtil.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:z.errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:z.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:z.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:z.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:z.errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:z.errorUtil.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:z.errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:z.errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:z.errorUtil.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&A.util.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};b.ZodNumber=pr;pr.create=r=>new pr({checks:[],typeName:B.ZodNumber,coerce:r?.coerce||!1,...G(r)});var mr=class r extends H{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==A.ZodParsedType.bigint)return this._getInvalidInput(e);let n,s=new w.ParseStatus;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),(0,w.addIssueToContext)(n,{code:R.ZodIssueCode.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),(0,w.addIssueToContext)(n,{code:R.ZodIssueCode.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),(0,w.addIssueToContext)(n,{code:R.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):A.util.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return(0,w.addIssueToContext)(t,{code:R.ZodIssueCode.invalid_type,expected:A.ZodParsedType.bigint,received:t.parsedType}),w.INVALID}gte(e,t){return this.setLimit("min",e,!0,z.errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,z.errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,z.errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,z.errorUtil.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:z.errorUtil.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:z.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:z.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:z.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:z.errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:z.errorUtil.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};b.ZodBigInt=mr;mr.create=r=>new mr({checks:[],typeName:B.ZodBigInt,coerce:r?.coerce??!1,...G(r)});var gr=class extends H{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==A.ZodParsedType.boolean){let n=this._getOrReturnCtx(e);return(0,w.addIssueToContext)(n,{code:R.ZodIssueCode.invalid_type,expected:A.ZodParsedType.boolean,received:n.parsedType}),w.INVALID}return(0,w.OK)(e.data)}};b.ZodBoolean=gr;gr.create=r=>new gr({typeName:B.ZodBoolean,coerce:r?.coerce||!1,...G(r)});var yr=class r extends H{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==A.ZodParsedType.date){let i=this._getOrReturnCtx(e);return(0,w.addIssueToContext)(i,{code:R.ZodIssueCode.invalid_type,expected:A.ZodParsedType.date,received:i.parsedType}),w.INVALID}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return(0,w.addIssueToContext)(i,{code:R.ZodIssueCode.invalid_date}),w.INVALID}let n=new w.ParseStatus,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),(0,w.addIssueToContext)(s,{code:R.ZodIssueCode.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),(0,w.addIssueToContext)(s,{code:R.ZodIssueCode.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):A.util.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:z.errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:z.errorUtil.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};b.ZodDate=yr;yr.create=r=>new yr({checks:[],coerce:r?.coerce||!1,typeName:B.ZodDate,...G(r)});var pn=class extends H{_parse(e){if(this._getType(e)!==A.ZodParsedType.symbol){let n=this._getOrReturnCtx(e);return(0,w.addIssueToContext)(n,{code:R.ZodIssueCode.invalid_type,expected:A.ZodParsedType.symbol,received:n.parsedType}),w.INVALID}return(0,w.OK)(e.data)}};b.ZodSymbol=pn;pn.create=r=>new pn({typeName:B.ZodSymbol,...G(r)});var vr=class extends H{_parse(e){if(this._getType(e)!==A.ZodParsedType.undefined){let n=this._getOrReturnCtx(e);return(0,w.addIssueToContext)(n,{code:R.ZodIssueCode.invalid_type,expected:A.ZodParsedType.undefined,received:n.parsedType}),w.INVALID}return(0,w.OK)(e.data)}};b.ZodUndefined=vr;vr.create=r=>new vr({typeName:B.ZodUndefined,...G(r)});var br=class extends H{_parse(e){if(this._getType(e)!==A.ZodParsedType.null){let n=this._getOrReturnCtx(e);return(0,w.addIssueToContext)(n,{code:R.ZodIssueCode.invalid_type,expected:A.ZodParsedType.null,received:n.parsedType}),w.INVALID}return(0,w.OK)(e.data)}};b.ZodNull=br;br.create=r=>new br({typeName:B.ZodNull,...G(r)});var Ut=class extends H{constructor(){super(...arguments),this._any=!0}_parse(e){return(0,w.OK)(e.data)}};b.ZodAny=Ut;Ut.create=r=>new Ut({typeName:B.ZodAny,...G(r)});var bt=class extends H{constructor(){super(...arguments),this._unknown=!0}_parse(e){return(0,w.OK)(e.data)}};b.ZodUnknown=bt;bt.create=r=>new bt({typeName:B.ZodUnknown,...G(r)});var He=class extends H{_parse(e){let t=this._getOrReturnCtx(e);return(0,w.addIssueToContext)(t,{code:R.ZodIssueCode.invalid_type,expected:A.ZodParsedType.never,received:t.parsedType}),w.INVALID}};b.ZodNever=He;He.create=r=>new He({typeName:B.ZodNever,...G(r)});var mn=class extends H{_parse(e){if(this._getType(e)!==A.ZodParsedType.undefined){let n=this._getOrReturnCtx(e);return(0,w.addIssueToContext)(n,{code:R.ZodIssueCode.invalid_type,expected:A.ZodParsedType.void,received:n.parsedType}),w.INVALID}return(0,w.OK)(e.data)}};b.ZodVoid=mn;mn.create=r=>new mn({typeName:B.ZodVoid,...G(r)});var wt=class r extends H{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==A.ZodParsedType.array)return(0,w.addIssueToContext)(t,{code:R.ZodIssueCode.invalid_type,expected:A.ZodParsedType.array,received:t.parsedType}),w.INVALID;if(s.exactLength!==null){let o=t.data.length>s.exactLength.value,a=t.data.length<s.exactLength.value;(o||a)&&((0,w.addIssueToContext)(t,{code:o?R.ZodIssueCode.too_big:R.ZodIssueCode.too_small,minimum:a?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&((0,w.addIssueToContext)(t,{code:R.ZodIssueCode.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&((0,w.addIssueToContext)(t,{code:R.ZodIssueCode.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>s.type._parseAsync(new qe(t,o,t.path,a)))).then(o=>w.ParseStatus.mergeArray(n,o));let i=[...t.data].map((o,a)=>s.type._parseSync(new qe(t,o,t.path,a)));return w.ParseStatus.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:z.errorUtil.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:z.errorUtil.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:z.errorUtil.toString(t)}})}nonempty(e){return this.min(1,e)}};b.ZodArray=wt;wt.create=(r,e)=>new wt({type:r,minLength:null,maxLength:null,exactLength:null,typeName:B.ZodArray,...G(e)});function fn(r){if(r instanceof Ie){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=Ue.create(fn(n))}return new Ie({...r._def,shape:()=>e})}else return r instanceof wt?new wt({...r._def,type:fn(r.element)}):r instanceof Ue?Ue.create(fn(r.unwrap())):r instanceof it?it.create(fn(r.unwrap())):r instanceof st?st.create(r.items.map(e=>fn(e))):r}var Ie=class r extends H{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=A.util.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==A.ZodParsedType.object){let c=this._getOrReturnCtx(e);return(0,w.addIssueToContext)(c,{code:R.ZodIssueCode.invalid_type,expected:A.ZodParsedType.object,received:c.parsedType}),w.INVALID}let{status:n,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof He&&this._def.unknownKeys==="strip"))for(let c in s.data)o.includes(c)||a.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 He){let c=this._def.unknownKeys;if(c==="passthrough")for(let f of a)u.push({key:{status:"valid",value:f},value:{status:"valid",value:s.data[f]}});else if(c==="strict")a.length>0&&((0,w.addIssueToContext)(s,{code:R.ZodIssueCode.unrecognized_keys,keys:a}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let f of a){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,v=await f.value;c.push({key:p,value:v,alwaysSet:f.alwaysSet})}return c}).then(c=>w.ParseStatus.mergeObjectSync(n,c)):w.ParseStatus.mergeObjectSync(n,u)}get shape(){return this._def.shape()}strict(e){return z.errorUtil.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let s=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:z.errorUtil.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:B.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let n of A.util.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let n of A.util.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return fn(this)}partial(e){let t={};for(let n of A.util.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let n of A.util.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof Ue;)i=i._def.innerType;t[n]=i}return new r({...this._def,shape:()=>t})}keyof(){return Kl(A.util.objectKeys(this.shape))}};b.ZodObject=Ie;Ie.create=(r,e)=>new Ie({shape:()=>r,unknownKeys:"strip",catchall:He.create(),typeName:B.ZodObject,...G(e)});Ie.strictCreate=(r,e)=>new Ie({shape:()=>r,unknownKeys:"strict",catchall:He.create(),typeName:B.ZodObject,...G(e)});Ie.lazycreate=(r,e)=>new Ie({shape:r,unknownKeys:"strip",catchall:He.create(),typeName:B.ZodObject,...G(e)});var wr=class extends H{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function s(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return t.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(a=>new R.ZodError(a.ctx.common.issues));return(0,w.addIssueToContext)(t,{code:R.ZodIssueCode.invalid_union,unionErrors:o}),w.INVALID}if(t.common.async)return Promise.all(n.map(async i=>{let o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let u of n){let c={...t,common:{...t.common,issues:[]},parent:null},f=u._parseSync({data:t.data,path:t.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 t.common.issues.push(...i.ctx.common.issues),i.result;let a=o.map(u=>new R.ZodError(u));return(0,w.addIssueToContext)(t,{code:R.ZodIssueCode.invalid_union,unionErrors:a}),w.INVALID}}get options(){return this._def.options}};b.ZodUnion=wr;wr.create=(r,e)=>new wr({options:r,typeName:B.ZodUnion,...G(e)});var vt=r=>r instanceof kr?vt(r.schema):r instanceof je?vt(r.innerType()):r instanceof Sr?[r.value]:r instanceof Tr?r.options:r instanceof xr?A.util.objectValues(r.enum):r instanceof Cr?vt(r._def.innerType):r instanceof vr?[void 0]:r instanceof br?[null]:r instanceof Ue?[void 0,...vt(r.unwrap())]:r instanceof it?[null,...vt(r.unwrap())]:r instanceof Jn||r instanceof Rr?vt(r.unwrap()):r instanceof Ir?vt(r._def.innerType):[],Fs=class r extends H{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==A.ZodParsedType.object)return(0,w.addIssueToContext)(t,{code:R.ZodIssueCode.invalid_type,expected:A.ZodParsedType.object,received:t.parsedType}),w.INVALID;let n=this.discriminator,s=t.data[n],i=this.optionsMap.get(s);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):((0,w.addIssueToContext)(t,{code:R.ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),w.INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let s=new Map;for(let i of t){let o=vt(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of o){if(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,i)}}return new r({typeName:B.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...G(n)})}};b.ZodDiscriminatedUnion=Fs;function vo(r,e){let t=(0,A.getParsedType)(r),n=(0,A.getParsedType)(e);if(r===e)return{valid:!0,data:r};if(t===A.ZodParsedType.object&&n===A.ZodParsedType.object){let s=A.util.objectKeys(e),i=A.util.objectKeys(r).filter(a=>s.indexOf(a)!==-1),o={...r,...e};for(let a of i){let u=vo(r[a],e[a]);if(!u.valid)return{valid:!1};o[a]=u.data}return{valid:!0,data:o}}else if(t===A.ZodParsedType.array&&n===A.ZodParsedType.array){if(r.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<r.length;i++){let o=r[i],a=e[i],u=vo(o,a);if(!u.valid)return{valid:!1};s.push(u.data)}return{valid:!0,data:s}}else return t===A.ZodParsedType.date&&n===A.ZodParsedType.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var _r=class extends H{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=(i,o)=>{if((0,w.isAborted)(i)||(0,w.isAborted)(o))return w.INVALID;let a=vo(i.value,o.value);return a.valid?(((0,w.isDirty)(i)||(0,w.isDirty)(o))&&t.dirty(),{status:t.value,value:a.data}):((0,w.addIssueToContext)(n,{code:R.ZodIssueCode.invalid_intersection_types}),w.INVALID)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};b.ZodIntersection=_r;_r.create=(r,e,t)=>new _r({left:r,right:e,typeName:B.ZodIntersection,...G(t)});var st=class r extends H{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==A.ZodParsedType.array)return(0,w.addIssueToContext)(n,{code:R.ZodIssueCode.invalid_type,expected:A.ZodParsedType.array,received:n.parsedType}),w.INVALID;if(n.data.length<this._def.items.length)return(0,w.addIssueToContext)(n,{code:R.ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),w.INVALID;!this._def.rest&&n.data.length>this._def.items.length&&((0,w.addIssueToContext)(n,{code:R.ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...n.data].map((o,a)=>{let u=this._def.items[a]||this._def.rest;return u?u._parse(new qe(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(i).then(o=>w.ParseStatus.mergeArray(t,o)):w.ParseStatus.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};b.ZodTuple=st;st.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new st({items:r,typeName:B.ZodTuple,rest:null,...G(e)})};var Bs=class r extends H{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==A.ZodParsedType.object)return(0,w.addIssueToContext)(n,{code:R.ZodIssueCode.invalid_type,expected:A.ZodParsedType.object,received:n.parsedType}),w.INVALID;let s=[],i=this._def.keyType,o=this._def.valueType;for(let a in n.data)s.push({key:i._parse(new qe(n,a,n.path,a)),value:o._parse(new qe(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?w.ParseStatus.mergeObjectAsync(t,s):w.ParseStatus.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof H?new r({keyType:e,valueType:t,typeName:B.ZodRecord,...G(n)}):new r({keyType:Lt.create(),valueType:e,typeName:B.ZodRecord,...G(t)})}};b.ZodRecord=Bs;var gn=class extends H{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==A.ZodParsedType.map)return(0,w.addIssueToContext)(n,{code:R.ZodIssueCode.invalid_type,expected:A.ZodParsedType.map,received:n.parsedType}),w.INVALID;let s=this._def.keyType,i=this._def.valueType,o=[...n.data.entries()].map(([a,u],c)=>({key:s._parse(new qe(n,a,n.path,[c,"key"])),value:i._parse(new qe(n,u,n.path,[c,"value"]))}));if(n.common.async){let a=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 w.INVALID;(c.status==="dirty"||f.status==="dirty")&&t.dirty(),a.set(c.value,f.value)}return{status:t.value,value:a}})}else{let a=new Map;for(let u of o){let c=u.key,f=u.value;if(c.status==="aborted"||f.status==="aborted")return w.INVALID;(c.status==="dirty"||f.status==="dirty")&&t.dirty(),a.set(c.value,f.value)}return{status:t.value,value:a}}}};b.ZodMap=gn;gn.create=(r,e,t)=>new gn({valueType:e,keyType:r,typeName:B.ZodMap,...G(t)});var yn=class r extends H{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==A.ZodParsedType.set)return(0,w.addIssueToContext)(n,{code:R.ZodIssueCode.invalid_type,expected:A.ZodParsedType.set,received:n.parsedType}),w.INVALID;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&((0,w.addIssueToContext)(n,{code:R.ZodIssueCode.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&((0,w.addIssueToContext)(n,{code:R.ZodIssueCode.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let i=this._def.valueType;function o(u){let c=new Set;for(let f of u){if(f.status==="aborted")return w.INVALID;f.status==="dirty"&&t.dirty(),c.add(f.value)}return{status:t.value,value:c}}let a=[...n.data.values()].map((u,c)=>i._parse(new qe(n,u,n.path,c)));return n.common.async?Promise.all(a).then(u=>o(u)):o(a)}min(e,t){return new r({...this._def,minSize:{value:e,message:z.errorUtil.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:z.errorUtil.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};b.ZodSet=yn;yn.create=(r,e)=>new yn({valueType:r,minSize:null,maxSize:null,typeName:B.ZodSet,...G(e)});var Ks=class r extends H{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==A.ZodParsedType.function)return(0,w.addIssueToContext)(t,{code:R.ZodIssueCode.invalid_type,expected:A.ZodParsedType.function,received:t.parsedType}),w.INVALID;function n(a,u){return(0,w.makeIssue)({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,(0,qs.getErrorMap)(),qs.defaultErrorMap].filter(c=>!!c),issueData:{code:R.ZodIssueCode.invalid_arguments,argumentsError:u}})}function s(a,u){return(0,w.makeIssue)({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,(0,qs.getErrorMap)(),qs.defaultErrorMap].filter(c=>!!c),issueData:{code:R.ZodIssueCode.invalid_return_type,returnTypeError:u}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof qt){let a=this;return(0,w.OK)(async function(...u){let c=new R.ZodError([]),f=await a._def.args.parseAsync(u,i).catch(S=>{throw c.addIssue(n(u,S)),c}),p=await Reflect.apply(o,this,f);return await a._def.returns._def.type.parseAsync(p,i).catch(S=>{throw c.addIssue(s(p,S)),c})})}else{let a=this;return(0,w.OK)(function(...u){let c=a._def.args.safeParse(u,i);if(!c.success)throw new R.ZodError([n(u,c.error)]);let f=Reflect.apply(o,this,c.data),p=a._def.returns.safeParse(f,i);if(!p.success)throw new R.ZodError([s(f,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:st.create(e).rest(bt.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||st.create([]).rest(bt.create()),returns:t||bt.create(),typeName:B.ZodFunction,...G(n)})}};b.ZodFunction=Ks;var kr=class extends H{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};b.ZodLazy=kr;kr.create=(r,e)=>new kr({getter:r,typeName:B.ZodLazy,...G(e)});var Sr=class extends H{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return(0,w.addIssueToContext)(t,{received:t.data,code:R.ZodIssueCode.invalid_literal,expected:this._def.value}),w.INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}};b.ZodLiteral=Sr;Sr.create=(r,e)=>new Sr({value:r,typeName:B.ZodLiteral,...G(e)});function Kl(r,e){return new Tr({values:r,typeName:B.ZodEnum,...G(e)})}var Tr=class r extends H{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return(0,w.addIssueToContext)(t,{expected:A.util.joinValues(n),received:t.parsedType,code:R.ZodIssueCode.invalid_type}),w.INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return(0,w.addIssueToContext)(t,{received:t.data,code:R.ZodIssueCode.invalid_enum_value,options:n}),w.INVALID}return(0,w.OK)(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};b.ZodEnum=Tr;Tr.create=Kl;var xr=class extends H{_parse(e){let t=A.util.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==A.ZodParsedType.string&&n.parsedType!==A.ZodParsedType.number){let s=A.util.objectValues(t);return(0,w.addIssueToContext)(n,{expected:A.util.joinValues(s),received:n.parsedType,code:R.ZodIssueCode.invalid_type}),w.INVALID}if(this._cache||(this._cache=new Set(A.util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=A.util.objectValues(t);return(0,w.addIssueToContext)(n,{received:n.data,code:R.ZodIssueCode.invalid_enum_value,options:s}),w.INVALID}return(0,w.OK)(e.data)}get enum(){return this._def.values}};b.ZodNativeEnum=xr;xr.create=(r,e)=>new xr({values:r,typeName:B.ZodNativeEnum,...G(e)});var qt=class extends H{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==A.ZodParsedType.promise&&t.common.async===!1)return(0,w.addIssueToContext)(t,{code:R.ZodIssueCode.invalid_type,expected:A.ZodParsedType.promise,received:t.parsedType}),w.INVALID;let n=t.parsedType===A.ZodParsedType.promise?t.data:Promise.resolve(t.data);return(0,w.OK)(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};b.ZodPromise=qt;qt.create=(r,e)=>new qt({type:r,typeName:B.ZodPromise,...G(e)});var je=class extends H{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===B.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{(0,w.addIssueToContext)(n,o),o.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(n.data,i);if(n.common.async)return Promise.resolve(o).then(async a=>{if(t.value==="aborted")return w.INVALID;let u=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return u.status==="aborted"?w.INVALID:u.status==="dirty"||t.value==="dirty"?(0,w.DIRTY)(u.value):u});{if(t.value==="aborted")return w.INVALID;let a=this._def.schema._parseSync({data:o,path:n.path,parent:n});return a.status==="aborted"?w.INVALID:a.status==="dirty"||t.value==="dirty"?(0,w.DIRTY)(a.value):a}}if(s.type==="refinement"){let o=a=>{let u=s.refinement(a,i);if(n.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?w.INVALID:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?w.INVALID:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.value,value:a.value}))))}if(s.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!(0,w.isValid)(o))return w.INVALID;let a=s.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>(0,w.isValid)(o)?Promise.resolve(s.transform(o.value,i)).then(a=>({status:t.value,value:a})):w.INVALID);A.util.assertNever(s)}};b.ZodEffects=je;b.ZodTransformer=je;je.create=(r,e,t)=>new je({schema:r,typeName:B.ZodEffects,effect:e,...G(t)});je.createWithPreprocess=(r,e,t)=>new je({schema:e,effect:{type:"preprocess",transform:r},typeName:B.ZodEffects,...G(t)});var Ue=class extends H{_parse(e){return this._getType(e)===A.ZodParsedType.undefined?(0,w.OK)(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};b.ZodOptional=Ue;Ue.create=(r,e)=>new Ue({innerType:r,typeName:B.ZodOptional,...G(e)});var it=class extends H{_parse(e){return this._getType(e)===A.ZodParsedType.null?(0,w.OK)(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};b.ZodNullable=it;it.create=(r,e)=>new it({innerType:r,typeName:B.ZodNullable,...G(e)});var Cr=class extends H{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===A.ZodParsedType.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};b.ZodDefault=Cr;Cr.create=(r,e)=>new Cr({innerType:r,typeName:B.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...G(e)});var Ir=class extends H{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return(0,w.isAsync)(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new R.ZodError(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new R.ZodError(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};b.ZodCatch=Ir;Ir.create=(r,e)=>new Ir({innerType:r,typeName:B.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...G(e)});var vn=class extends H{_parse(e){if(this._getType(e)!==A.ZodParsedType.nan){let n=this._getOrReturnCtx(e);return(0,w.addIssueToContext)(n,{code:R.ZodIssueCode.invalid_type,expected:A.ZodParsedType.nan,received:n.parsedType}),w.INVALID}return{status:"valid",value:e.data}}};b.ZodNaN=vn;vn.create=r=>new vn({typeName:B.ZodNaN,...G(r)});b.BRAND=Symbol("zod_brand");var Jn=class extends H{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}};b.ZodBranded=Jn;var Yn=class r extends H{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?w.INVALID:i.status==="dirty"?(t.dirty(),(0,w.DIRTY)(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?w.INVALID:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:B.ZodPipeline})}};b.ZodPipeline=Yn;var Rr=class extends H{_parse(e){let t=this._def.innerType._parse(e),n=s=>((0,w.isValid)(s)&&(s.value=Object.freeze(s.value)),s);return(0,w.isAsync)(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}};b.ZodReadonly=Rr;Rr.create=(r,e)=>new Rr({innerType:r,typeName:B.ZodReadonly,...G(e)});function Ul(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function Zl(r,e={},t){return r?Ut.create().superRefine((n,s)=>{let i=r(n);if(i instanceof Promise)return i.then(o=>{if(!o){let a=Ul(e,n),u=a.fatal??t??!0;s.addIssue({code:"custom",...a,fatal:u})}});if(!i){let o=Ul(e,n),a=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:a})}}):Ut.create()}b.late={object:Ie.lazycreate};var B;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(B||(b.ZodFirstPartyTypeKind=B={}));var Fp=(r,e={message:`Input not instance of ${r.name}`})=>Zl(t=>t instanceof r,e);b.instanceof=Fp;var Gl=Lt.create;b.string=Gl;var Hl=pr.create;b.number=Hl;var Bp=vn.create;b.nan=Bp;var Kp=mr.create;b.bigint=Kp;var Vl=gr.create;b.boolean=Vl;var Zp=yr.create;b.date=Zp;var Gp=pn.create;b.symbol=Gp;var Hp=vr.create;b.undefined=Hp;var Vp=br.create;b.null=Vp;var Wp=Ut.create;b.any=Wp;var Jp=bt.create;b.unknown=Jp;var Yp=He.create;b.never=Yp;var Xp=mn.create;b.void=Xp;var Qp=wt.create;b.array=Qp;var em=Ie.create;b.object=em;var tm=Ie.strictCreate;b.strictObject=tm;var rm=wr.create;b.union=rm;var nm=Fs.create;b.discriminatedUnion=nm;var sm=_r.create;b.intersection=sm;var im=st.create;b.tuple=im;var om=Bs.create;b.record=om;var am=gn.create;b.map=am;var lm=yn.create;b.set=lm;var um=Ks.create;b.function=um;var cm=kr.create;b.lazy=cm;var dm=Sr.create;b.literal=dm;var hm=Tr.create;b.enum=hm;var fm=xr.create;b.nativeEnum=fm;var pm=qt.create;b.promise=pm;var Wl=je.create;b.effect=Wl;b.transformer=Wl;var mm=Ue.create;b.optional=mm;var gm=it.create;b.nullable=gm;var ym=je.createWithPreprocess;b.preprocess=ym;var vm=Yn.create;b.pipeline=vm;var bm=()=>Gl().optional();b.ostring=bm;var wm=()=>Hl().optional();b.onumber=wm;var _m=()=>Vl().optional();b.oboolean=_m;b.coerce={string:(r=>Lt.create({...r,coerce:!0})),number:(r=>pr.create({...r,coerce:!0})),boolean:(r=>gr.create({...r,coerce:!0})),bigint:(r=>mr.create({...r,coerce:!0})),date:(r=>yr.create({...r,coerce:!0}))};b.NEVER=w.INVALID});var bo=ee(Fe=>{"use strict";var km=Fe&&Fe.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),bn=Fe&&Fe.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&km(e,r,t)};Object.defineProperty(Fe,"__esModule",{value:!0});bn(Ls(),Fe);bn(go(),Fe);bn(Ml(),Fe);bn(Vn(),Fe);bn(Jl(),Fe);bn(Ds(),Fe)});var Ql=ee(Re=>{"use strict";var Yl=Re&&Re.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),Sm=Re&&Re.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Tm=Re&&Re.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&Yl(e,r,t);return Sm(e,r),e},xm=Re&&Re.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Yl(e,r,t)};Object.defineProperty(Re,"__esModule",{value:!0});Re.z=void 0;var Xl=Tm(bo());Re.z=Xl;xm(bo(),Re);Re.default=Xl});var be=ee(d=>{"use strict";Object.defineProperty(d,"__esModule",{value:!0});d.RepoDocReadResultMsg=d.RepoDocReadMsg=d.RepoDocsResultMsg=d.RepoDocsMsg=d.ChatLoadResultMsg=d.ChatLoadMsg=d.ChatListResultMsg=d.ChatListMsg=d.ChatUsageMsg=d.ChatStreamMsg=d.JiraUsersResultMsg=d.DeployClaimResultMsg=d.DeployClaimMsg=d.RuleDiagnoseResultMsg=d.ProjectTestResultMsg=d.RunStatusMsg=d.RunUsageMsg=d.RunLogMsg=d.RunClaimMsg=d.HeartbeatMsg=d.HelloMsg=d.RuleConfig=d.ProjectConfig=d.ActionConfig=d.DeployAction=d.EnvironmentConfig=d.PromotionMode=d.DeployStep=d.RespondAction=d.ImplementAction=d.PlanOnlyAction=d.TriggerConfig=d.StatusChangedTrigger=d.CommentKeywordTrigger=d.LabelAddedTrigger=d.ActionType=d.TriggerType=d.ACTIVE_RUN_STATUSES=d.RunStatus=d.needsInputMarkerIn=d.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=d.NEEDS_INPUT_COMMENT_MARKER=d.NEEDS_INPUT_LABEL=d.NEEDS_INPUT_MARKER=d.BRANCH_DEPLOY_ISSUE_KEY=d.REQUIRED_AGENT_CAPABILITIES=d.DEFAULT_AGENT_ID=d.REGISTERED_AGENTS=d.PROTOCOL_VERSION=d.GITHUB_TOKEN_PERMISSIONS=void 0;d.RunResolveConflictResultMsg=d.RunResolveConflictMsg=d.RunnerUpdateMsg=d.RepoDocSaveResultMsg=d.RepoDocSaveMsg=d.SetupClaudeMdSaveResultMsg=d.SetupClaudeMdSaveMsg=d.SetupClaudeMdGenerateResultMsg=d.SetupClaudeMdGenerateMsg=d.SetupStatusResultMsg=d.SetupStatusMsg=d.DeploySuggestResultMsg=d.EnvPreflightResultMsg=d.EnvPreflightMsg=d.ChatCreateTicketResultMsg=d.ChatCreateTicketMsg=d.ChatTurnResultMsg=d.ChatTurnMsg=d.ChatFile=d.TeamCredsResultMsg=d.TeamCredsMsg=d.KnowledgeSaveResultMsg=d.KnowledgeSaveMsg=d.KnowledgeListResultMsg=d.KnowledgeFile=d.KnowledgeListMsg=d.AuditReviewResultMsg=d.AuditReviewMsg=d.AuditGetResultMsg=d.AuditGetMsg=d.AuditListResultMsg=d.AuditStatsResultMsg=d.AuditStatsMsg=d.AuditListMsg=d.AuditStartResultMsg=d.AuditStartMsg=d.AuditRecord=d.AuditFinding=d.AuditScope=d.AuditSeverity=d.AuditRole=d.EpicSuggestResultMsg=d.EpicSuggestMsg=d.EpicListResultMsg=d.EpicChild=d.EpicListMsg=d.BoardTriggerResultMsg=d.BoardTriggerMsg=d.BoardFetchResultMsg=d.BoardFetchMsg=void 0;d.DEFAULT_DEPLOY_SUGGEST_PROMPT_TEMPLATE=d.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE=d.DEPLOY_FIX_PROMPT_TEMPLATE=d.PROMPT_PRESETS=d.DEFAULT_RESPOND_PROMPT_TEMPLATE=d.BUGFIX_IMPLEMENT_PROMPT_TEMPLATE=d.BUG_INVESTIGATION_PROMPT_TEMPLATE=d.TECHNICAL_PLAN_PROMPT_TEMPLATE=d.MEMORY_UPDATE_PROMPT=d.DEFAULT_IMPLEMENT_PROMPT_TEMPLATE=d.WRITE_TESTS_PROMPT=d.DEFAULT_PLAN_PROMPT_TEMPLATE=d.EnrollResponse=d.EnrollRequest=d.ServerToRunnerMsg=d.JiraUsersMsg=d.DeploySuggestMsg=d.DeployFixMsg=d.DeployStartMsg=d.RunRetryPushMsg=d.RunRejectedMsg=d.RunApprovedMsg=d.RunCancelMsg=d.RuleDiagnoseMsg=d.ProjectTestMsg=d.RunClaimResultMsg=d.ConfigMsg=d.HelloAckMsg=d.RunnerToServerMsg=d.AutopilotReportMsg=d.AutopilotNextResultMsg=d.AutopilotNextMsg=d.RunnerUpdateResultMsg=d.AgentProfilesResultMsg=d.AgentProfilesMsg=d.RunPrConflictMsg=void 0;d.missingAgentCapabilities=Cm;d.parseRunnerMsg=Rm;d.parseServerMsg=Em;var l=Ql();d.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."};d.PROTOCOL_VERSION="1.40";d.REGISTERED_AGENTS=[{id:"claude-code",displayName:"Claude Code",capabilities:{readOnlyJail:!0,editNoShellJail:!0,sessionResume:!0,costReporting:!0,modelSelection:!0,loginProfiles:!0},suggestedModels:["claude-fable-5","claude-opus-5","claude-sonnet-5","claude-haiku-4-5-20251001"],experimental:!1},{id:"codex",displayName:"OpenAI Codex CLI (experimental)",capabilities:{readOnlyJail:!0,editNoShellJail:!1,sessionResume:!1,costReporting:!1,modelSelection:!0,loginProfiles:!1},suggestedModels:[],experimental:!0}];d.DEFAULT_AGENT_ID="claude-code";d.REQUIRED_AGENT_CAPABILITIES={plan_only:["readOnlyJail","sessionResume"],respond:["readOnlyJail"],implement:["editNoShellJail","sessionResume"],deploy:[],chat:["readOnlyJail","sessionResume"],assist:["readOnlyJail"]};function Cm(r,e){let t=d.REGISTERED_AGENTS.find(n=>n.id===r);return t?(d.REQUIRED_AGENT_CAPABILITIES[e]??[]).filter(n=>!t.capabilities[n]):null}d.BRANCH_DEPLOY_ISSUE_KEY="(branch deploy)";d.NEEDS_INPUT_MARKER="NEEDS-INPUT";d.NEEDS_INPUT_LABEL="agent-needs-input";d.NEEDS_INPUT_COMMENT_MARKER="Allwright needs your input";d.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=["TicketPilot needs your input"];var Im=r=>r.includes(d.NEEDS_INPUT_COMMENT_MARKER)||d.LEGACY_NEEDS_INPUT_COMMENT_MARKERS.some(e=>r.includes(e));d.needsInputMarkerIn=Im;d.RunStatus=l.z.enum(["queued","running","posting","awaiting_approval","needs_input","succeeded","failed","timed_out"]);d.ACTIVE_RUN_STATUSES=["queued","running","posting","awaiting_approval"];d.TriggerType=l.z.enum(["label_added","comment_keyword","status_changed"]);d.ActionType=l.z.enum(["plan_only","implement","respond","deploy"]);d.LabelAddedTrigger=l.z.object({type:l.z.literal("label_added"),label:l.z.string().min(1),doneLabel:l.z.string().min(1).default("agent-planned"),failedLabel:l.z.string().min(1).default("agent-failed")});d.CommentKeywordTrigger=l.z.object({type:l.z.literal("comment_keyword"),keyword:l.z.string().min(1),doneLabel:l.z.string().min(1).default("agent-implemented"),failedLabel:l.z.string().min(1).default("agent-failed")});d.StatusChangedTrigger=l.z.object({type:l.z.literal("status_changed"),status:l.z.string().min(1),doneLabel:l.z.string().min(1).default("agent-deployed"),failedLabel:l.z.string().min(1).default("agent-failed")});d.TriggerConfig=l.z.discriminatedUnion("type",[d.LabelAddedTrigger,d.CommentKeywordTrigger,d.StatusChangedTrigger]);d.PlanOnlyAction=l.z.object({type:l.z.literal("plan_only"),promptTemplate:l.z.string().min(1),timeoutSeconds:l.z.number().int().positive().max(3600).default(900),agent:l.z.string().default(d.DEFAULT_AGENT_ID),model:l.z.string().default("")});d.ImplementAction=l.z.object({type:l.z.literal("implement"),promptTemplate:l.z.string().min(1),timeoutSeconds:l.z.number().int().positive().max(7200).default(1800),maxTurns:l.z.number().int().positive().max(500).default(120),requireApproval:l.z.boolean().default(!0),branchTemplate:l.z.string().min(1).default("agent/{{issueKey}}").refine(r=>r.includes("{{issueKey}}"),{message:"branchTemplate must contain {{issueKey}}"}),baseBranch:l.z.string().min(1).default("main"),jiraTransition:l.z.string().optional(),jiraTransitionOnStart:l.z.string().optional(),jiraTransitionOnMerge:l.z.string().optional(),agent:l.z.string().default(d.DEFAULT_AGENT_ID),model:l.z.string().default(""),updateMemory:l.z.boolean().default(!1),writeTests:l.z.boolean().default(!0),runTests:l.z.boolean().default(!0),mergeOnApprove:l.z.boolean().default(!0),mergeMethod:l.z.enum(["squash","merge","rebase"]).default("squash")});d.RespondAction=l.z.object({type:l.z.literal("respond"),promptTemplate:l.z.string().min(1),timeoutSeconds:l.z.number().int().positive().max(3600).default(600),agent:l.z.string().default(d.DEFAULT_AGENT_ID),model:l.z.string().default("")});d.DeployStep=l.z.object({name:l.z.string().min(1).max(120),run:l.z.string().min(1).max(4e3),continueOnError:l.z.boolean().default(!1)});d.PromotionMode=l.z.enum(["deploy_only","merge_and_deploy"]);d.EnvironmentConfig=l.z.object({id:l.z.string(),projectId:l.z.string(),name:l.z.string(),rank:l.z.number().int().nonnegative(),auditBeforeDeploy:l.z.enum(["","security","testing"]).default(""),branch:l.z.string().default(""),publicUrl:l.z.string().default(""),useDedicatedCheckout:l.z.boolean().default(!1),promotionMode:d.PromotionMode.default("deploy_only"),ticketBranchTemplate:l.z.string().default("agent/{{issueKey}}"),steps:l.z.array(d.DeployStep).default([]),workdir:l.z.string().default(""),timeoutSeconds:l.z.number().int().positive().max(21600).default(1800),requiredSecrets:l.z.array(l.z.string()).default([]),requireApproval:l.z.boolean().default(!1),requireSyncCheck:l.z.boolean().default(!1),previousEnvBranch:l.z.string().optional(),deployFromColumn:l.z.string().default(""),deployToColumn:l.z.string().default("")});d.DeployAction=l.z.object({type:l.z.literal("deploy"),envSelection:l.z.enum(["fixed","from_comment"]).default("from_comment"),environmentId:l.z.string().optional(),requireStatus:l.z.string().optional()});d.ActionConfig=l.z.discriminatedUnion("type",[d.PlanOnlyAction,d.ImplementAction,d.RespondAction,d.DeployAction]);d.ProjectConfig=l.z.object({id:l.z.string(),name:l.z.string(),jiraProjectKey:l.z.string(),repoName:l.z.string(),jiraSiteUrl:l.z.string().default(""),defaultAgent:l.z.string().default("claude-code"),componentRoutes:l.z.array(l.z.object({component:l.z.string().min(1),repoName:l.z.string().min(1)})).default([])});d.RuleConfig=l.z.object({id:l.z.string(),projectId:l.z.string(),name:l.z.string(),enabled:l.z.boolean(),trigger:d.TriggerConfig,action:d.ActionConfig});d.HelloMsg=l.z.object({type:l.z.literal("hello"),protocolVersion:l.z.string(),runnerVersion:l.z.string(),platform:l.z.string(),justBooted:l.z.boolean().optional()});d.HeartbeatMsg=l.z.object({type:l.z.literal("heartbeat"),ts:l.z.string()});d.RunClaimMsg=l.z.object({type:l.z.literal("run.claim"),requestId:l.z.string(),ruleId:l.z.string(),issueKey:l.z.string(),issueSummary:l.z.string().default(""),triggerFingerprint:l.z.string(),dedupKey:l.z.string().optional(),triggeredByAccountId:l.z.string().optional()});d.RunLogMsg=l.z.object({type:l.z.literal("run.log"),runId:l.z.string(),seq:l.z.number().int().nonnegative(),ts:l.z.string(),level:l.z.enum(["info","warn","error","agent"]),message:l.z.string().max(16384)});d.RunUsageMsg=l.z.object({type:l.z.literal("run.usage"),runId:l.z.string(),inputTokens:l.z.number().int().nonnegative(),outputTokens:l.z.number().int().nonnegative(),cacheReadTokens:l.z.number().int().nonnegative().optional(),costUsd:l.z.number().nonnegative().optional(),turns:l.z.number().int().nonnegative().optional()});d.RunStatusMsg=l.z.object({type:l.z.literal("run.status"),runId:l.z.string(),status:d.RunStatus,error:l.z.string().optional(),errorKind:l.z.enum(["guard"]).optional(),costUsd:l.z.number().nonnegative().optional(),inputTokens:l.z.number().int().nonnegative().optional(),outputTokens:l.z.number().int().nonnegative().optional(),resultSummary:l.z.string().max(2e3).optional(),billingMode:l.z.enum(["subscription","api","unknown"]).optional(),model:l.z.string().max(200).optional(),prUrl:l.z.string().optional(),headSha:l.z.string().optional(),deployedRef:l.z.string().optional(),retryAvailable:l.z.boolean().optional()});d.ProjectTestResultMsg=l.z.object({type:l.z.literal("project.test.result"),requestId:l.z.string(),ok:l.z.boolean(),checks:l.z.array(l.z.object({name:l.z.string(),ok:l.z.boolean(),detail:l.z.string(),kind:l.z.enum(["connection","content"]).default("connection"),fix:l.z.array(l.z.string()).default([]),fixNote:l.z.string().default("")}))});d.RuleDiagnoseResultMsg=l.z.object({type:l.z.literal("rule.diagnose.result"),requestId:l.z.string(),checks:l.z.array(l.z.object({name:l.z.string(),ok:l.z.boolean(),detail:l.z.string(),kind:l.z.enum(["connection","content"]).default("connection"),fix:l.z.array(l.z.string()).default([]),fixNote:l.z.string().default("")})),matchedCount:l.z.number().int().nonnegative(),excludedCount:l.z.number().int().nonnegative(),excludedSample:l.z.array(l.z.string()).max(5)});d.DeployClaimMsg=l.z.object({type:l.z.literal("deploy.claim"),requestId:l.z.string(),projectId:l.z.string(),ruleId:l.z.string(),issueKey:l.z.string(),issueSummary:l.z.string().default(""),environmentName:l.z.string(),requestedByAccountId:l.z.string().optional(),requestedByDisplayName:l.z.string().default(""),dedupKey:l.z.string(),triggerFingerprint:l.z.string()});d.DeployClaimResultMsg=l.z.object({type:l.z.literal("deploy.claim.result"),requestId:l.z.string(),accepted:l.z.boolean(),runId:l.z.string().optional(),environment:d.EnvironmentConfig.optional(),reason:l.z.string().optional(),code:l.z.enum(["ok","duplicate","unknown_environment","not_permitted","unlinked_jira_account","promotion_order","jira_disabled","rule_disabled","cap"]).optional()});d.JiraUsersResultMsg=l.z.object({type:l.z.literal("jira.users.result"),requestId:l.z.string(),ok:l.z.boolean(),users:l.z.array(l.z.object({accountId:l.z.string(),displayName:l.z.string(),email:l.z.string().default(""),active:l.z.boolean().default(!0)})).default([]),error:l.z.string().optional()});d.ChatStreamMsg=l.z.object({type:l.z.literal("chat.stream"),requestId:l.z.string(),seq:l.z.number().int().nonnegative(),text:l.z.string().max(8e3)});d.ChatUsageMsg=l.z.object({type:l.z.literal("chat.usage"),requestId:l.z.string(),inputTokens:l.z.number().int().nonnegative(),outputTokens:l.z.number().int().nonnegative(),cacheReadTokens:l.z.number().int().nonnegative().optional(),turns:l.z.number().int().nonnegative().optional()});d.ChatListMsg=l.z.object({type:l.z.literal("chat.list"),requestId:l.z.string(),projectId:l.z.string()});d.ChatListResultMsg=l.z.object({type:l.z.literal("chat.list.result"),requestId:l.z.string(),sessions:l.z.array(l.z.object({sessionId:l.z.string(),title:l.z.string().default(""),updatedAt:l.z.string().default(""),messageCount:l.z.number().int().nonnegative().default(0)})).default([])});d.ChatLoadMsg=l.z.object({type:l.z.literal("chat.load"),requestId:l.z.string(),sessionId:l.z.string()});d.ChatLoadResultMsg=l.z.object({type:l.z.literal("chat.load.result"),requestId:l.z.string(),ok:l.z.boolean(),projectId:l.z.string().default(""),messages:l.z.array(l.z.object({role:l.z.enum(["user","agent"]),text:l.z.string()})).default([]),error:l.z.string().optional()});d.RepoDocsMsg=l.z.object({type:l.z.literal("repo.docs"),requestId:l.z.string(),projectId:l.z.string()});d.RepoDocsResultMsg=l.z.object({type:l.z.literal("repo.docs.result"),requestId:l.z.string(),ok:l.z.boolean(),docs:l.z.array(l.z.object({path:l.z.string(),sizeBytes:l.z.number().int().nonnegative().default(0),updatedAt:l.z.string().default("")})).default([]),error:l.z.string().optional()});d.RepoDocReadMsg=l.z.object({type:l.z.literal("repo.doc.read"),requestId:l.z.string(),projectId:l.z.string(),path:l.z.string().max(400)});d.RepoDocReadResultMsg=l.z.object({type:l.z.literal("repo.doc.read.result"),requestId:l.z.string(),ok:l.z.boolean(),path:l.z.string().default(""),content:l.z.string().default(""),truncated:l.z.boolean().default(!1),error:l.z.string().optional()});d.BoardFetchMsg=l.z.object({type:l.z.literal("board.fetch"),requestId:l.z.string(),projectId:l.z.string()});d.BoardFetchResultMsg=l.z.object({type:l.z.literal("board.fetch.result"),requestId:l.z.string(),ok:l.z.boolean(),browseBaseUrl:l.z.string().default(""),columns:l.z.array(l.z.object({name:l.z.string(),issues:l.z.array(l.z.object({key:l.z.string(),summary:l.z.string(),labels:l.z.array(l.z.string()).default([])})).default([])})).default([]),error:l.z.string().optional()});d.BoardTriggerMsg=l.z.object({type:l.z.literal("board.trigger"),requestId:l.z.string(),projectId:l.z.string(),issueKey:l.z.string(),comment:l.z.string().max(2e3).default(""),removeLabel:l.z.string().default(""),requestedBy:l.z.string().default(""),requestedByEmail:l.z.string().default(""),reimplement:l.z.boolean().default(!1)});d.BoardTriggerResultMsg=l.z.object({type:l.z.literal("board.trigger.result"),requestId:l.z.string(),ok:l.z.boolean(),error:l.z.string().optional()});d.EpicListMsg=l.z.object({type:l.z.literal("epic.list"),requestId:l.z.string(),projectId:l.z.string(),epicKey:l.z.string().default("")});d.EpicChild=l.z.object({key:l.z.string(),summary:l.z.string(),status:l.z.string(),statusCategory:l.z.string(),labels:l.z.array(l.z.string()).default([])});d.EpicListResultMsg=l.z.object({type:l.z.literal("epic.list.result"),requestId:l.z.string(),ok:l.z.boolean(),error:l.z.string().optional(),epics:l.z.array(l.z.object({key:l.z.string(),summary:l.z.string(),status:l.z.string()})).default([]),children:l.z.array(d.EpicChild).default([])});d.EpicSuggestMsg=l.z.object({type:l.z.literal("epic.suggest"),requestId:l.z.string(),projectId:l.z.string(),epicKey:l.z.string().min(1),model:l.z.string().default("")});d.EpicSuggestResultMsg=l.z.object({type:l.z.literal("epic.suggest.result"),requestId:l.z.string(),ok:l.z.boolean(),error:l.z.string().optional(),issueKey:l.z.string().default(""),reason:l.z.string().default(""),considered:l.z.number().int().default(0)});d.AuditRole=l.z.enum(["security","testing","architecture"]);d.AuditSeverity=l.z.enum(["critical","high","medium","low","info"]);d.AuditScope=l.z.object({kind:l.z.enum(["repo","ticket","branch"]).default("repo"),ref:l.z.string().default("")});d.AuditFinding=l.z.object({id:l.z.string().min(1),title:l.z.string().min(1),ruleId:l.z.string().max(20).default(""),severity:d.AuditSeverity,area:l.z.string().default(""),evidence:l.z.array(l.z.object({file:l.z.string().min(1),line:l.z.number().int().positive().optional(),note:l.z.string().default("")})).min(1),fix:l.z.string().default("")});d.AuditRecord=l.z.object({id:l.z.string(),role:d.AuditRole,createdAt:l.z.string(),model:l.z.string().default(""),summary:l.z.string().default(""),packNames:l.z.array(l.z.string()).default([]),findings:l.z.array(d.AuditFinding).default([]),costUsd:l.z.number().default(0),review:l.z.object({selected:l.z.array(l.z.string()),updatedAt:l.z.string()}).optional(),verdicts:l.z.record(l.z.object({verdict:l.z.enum(["valid","false-positive","wont-fix"]),note:l.z.string().default(""),by:l.z.string().default(""),at:l.z.string().default("")})).default({}),lessonsWritten:l.z.array(l.z.string()).default([]),ticketed:l.z.record(l.z.string()).default({}),scope:d.AuditScope.default({kind:"repo",ref:""}),testRun:l.z.array(l.z.object({command:l.z.string(),exitCode:l.z.number().int(),durationMs:l.z.number().int().default(0),tail:l.z.string().default("")})).optional()});d.AuditStartMsg=l.z.object({type:l.z.literal("audit.start"),requestId:l.z.string(),projectId:l.z.string(),role:d.AuditRole,model:l.z.string().default(""),scope:d.AuditScope.default({kind:"repo",ref:""})});d.AuditStartResultMsg=l.z.object({type:l.z.literal("audit.start.result"),requestId:l.z.string(),ok:l.z.boolean(),error:l.z.string().optional(),audit:d.AuditRecord.optional()});d.AuditListMsg=l.z.object({type:l.z.literal("audit.list"),requestId:l.z.string(),projectId:l.z.string()});d.AuditStatsMsg=l.z.object({type:l.z.literal("audit.stats"),requestId:l.z.string(),projectIds:l.z.array(l.z.string()).max(200).default([]),since:l.z.string().default("")});d.AuditStatsResultMsg=l.z.object({type:l.z.literal("audit.stats.result"),requestId:l.z.string(),ok:l.z.boolean(),error:l.z.string().optional(),byProject:l.z.record(l.z.object({audits:l.z.number().int().default(0),findings:l.z.number().int().default(0),valid:l.z.number().int().default(0),falsePositive:l.z.number().int().default(0),wontFix:l.z.number().int().default(0),unreviewed:l.z.number().int().default(0)})).default({})});d.AuditListResultMsg=l.z.object({type:l.z.literal("audit.list.result"),requestId:l.z.string(),ok:l.z.boolean(),error:l.z.string().optional(),audits:l.z.array(l.z.object({id:l.z.string(),role:d.AuditRole,createdAt:l.z.string(),findingCount:l.z.number().int(),bySeverity:l.z.record(l.z.number().int()).default({})})).default([])});d.AuditGetMsg=l.z.object({type:l.z.literal("audit.get"),requestId:l.z.string(),projectId:l.z.string(),auditId:l.z.string()});d.AuditGetResultMsg=l.z.object({type:l.z.literal("audit.get.result"),requestId:l.z.string(),ok:l.z.boolean(),error:l.z.string().optional(),audit:d.AuditRecord.optional()});d.AuditReviewMsg=l.z.object({type:l.z.literal("audit.review"),requestId:l.z.string(),projectId:l.z.string(),auditId:l.z.string(),selected:l.z.array(l.z.string()).optional(),ticketed:l.z.array(l.z.object({findingId:l.z.string(),issueKey:l.z.string()})).default([]),verdicts:l.z.array(l.z.object({findingId:l.z.string(),verdict:l.z.enum(["valid","false-positive","wont-fix"]),note:l.z.string().max(2e3).default("")})).default([]),verdictBy:l.z.string().default("")});d.AuditReviewResultMsg=l.z.object({type:l.z.literal("audit.review.result"),requestId:l.z.string(),ok:l.z.boolean(),error:l.z.string().optional(),audit:d.AuditRecord.optional()});d.KnowledgeListMsg=l.z.object({type:l.z.literal("knowledge.list"),requestId:l.z.string(),projectId:l.z.string()});d.KnowledgeFile=l.z.object({role:d.AuditRole,level:l.z.enum(["global","org","project"]),source:l.z.enum(["pack","lessons"]),name:l.z.string(),content:l.z.string(),editable:l.z.boolean().default(!1)});d.KnowledgeListResultMsg=l.z.object({type:l.z.literal("knowledge.list.result"),requestId:l.z.string(),ok:l.z.boolean(),error:l.z.string().optional(),files:l.z.array(d.KnowledgeFile).default([])});d.KnowledgeSaveMsg=l.z.object({type:l.z.literal("knowledge.save"),requestId:l.z.string(),projectId:l.z.string(),role:d.AuditRole,level:l.z.enum(["org","project"]),source:l.z.enum(["pack","lessons"]),name:l.z.string().min(1).max(100),content:l.z.string().max(6e4),append:l.z.boolean().default(!1),by:l.z.string().default("")});d.KnowledgeSaveResultMsg=l.z.object({type:l.z.literal("knowledge.save.result"),requestId:l.z.string(),ok:l.z.boolean(),error:l.z.string().optional()});d.TeamCredsMsg=l.z.object({type:l.z.literal("team.creds"),requestId:l.z.string(),emails:l.z.array(l.z.string()).max(200)});d.TeamCredsResultMsg=l.z.object({type:l.z.literal("team.creds.result"),requestId:l.z.string(),ok:l.z.boolean(),error:l.z.string().optional(),githubShared:l.z.boolean().default(!1),sharedGithubLogin:l.z.string().default(""),entries:l.z.array(l.z.object({email:l.z.string(),jira:l.z.enum(["own","runner-account","missing"]),jiraAs:l.z.string().default(""),github:l.z.enum(["own","shared","missing"]),githubAs:l.z.string().default("")})).default([])});d.ChatFile=l.z.object({name:l.z.string().min(1).max(255),contentBase64:l.z.string().min(1).max(6e6)});d.ChatTurnMsg=l.z.object({type:l.z.literal("chat.turn"),requestId:l.z.string(),projectId:l.z.string(),sessionId:l.z.string().optional(),message:l.z.string().min(1).max(2e4),userName:l.z.string().default(""),model:l.z.string().default(""),files:l.z.array(d.ChatFile).max(8).default([])});d.ChatTurnResultMsg=l.z.object({type:l.z.literal("chat.turn.result"),requestId:l.z.string(),ok:l.z.boolean(),sessionId:l.z.string().default(""),reply:l.z.string().default(""),error:l.z.string().optional(),inputTokens:l.z.number().int().nonnegative().default(0),outputTokens:l.z.number().int().nonnegative().default(0),cacheReadTokens:l.z.number().int().nonnegative().default(0),costUsd:l.z.number().nonnegative().default(0),model:l.z.string().max(200).default("")});d.ChatCreateTicketMsg=l.z.object({type:l.z.literal("chat.create.ticket"),requestId:l.z.string(),projectId:l.z.string(),summary:l.z.string().min(1).max(250),description:l.z.string().default(""),triggerComment:l.z.string().default(""),requestedBy:l.z.string().default(""),requestedByEmail:l.z.string().default(""),asEpic:l.z.boolean().default(!1),children:l.z.array(l.z.object({summary:l.z.string().min(1),description:l.z.string().default("")})).max(20).default([]),files:l.z.array(d.ChatFile).max(8).default([])});d.ChatCreateTicketResultMsg=l.z.object({type:l.z.literal("chat.create.ticket.result"),requestId:l.z.string(),ok:l.z.boolean(),issueKey:l.z.string().default(""),error:l.z.string().optional(),childKeys:l.z.array(l.z.string()).default([])});d.EnvPreflightMsg=l.z.object({type:l.z.literal("env.preflight"),requestId:l.z.string(),projectId:l.z.string(),environmentName:l.z.string().default(""),steps:l.z.array(d.DeployStep).default([]),requiredSecrets:l.z.array(l.z.string()).default([]),workdir:l.z.string().default(""),branch:l.z.string().default(""),publicUrl:l.z.string().default("")});d.EnvPreflightResultMsg=l.z.object({type:l.z.literal("env.preflight.result"),requestId:l.z.string(),ok:l.z.boolean(),checks:l.z.array(l.z.object({name:l.z.string(),ok:l.z.boolean(),detail:l.z.string().default(""),kind:l.z.enum(["connection","content"]).default("connection"),fix:l.z.array(l.z.string()).default([]),fixNote:l.z.string().default("")})).default([])});d.DeploySuggestResultMsg=l.z.object({type:l.z.literal("deploy.suggest.result"),requestId:l.z.string(),ok:l.z.boolean(),steps:l.z.array(d.DeployStep).default([]),requiredSecrets:l.z.array(l.z.string()).default([]),notes:l.z.string().default(""),error:l.z.string().optional(),docPath:l.z.string().default(""),docContent:l.z.string().max(1e5).default("")});d.SetupStatusMsg=l.z.object({type:l.z.literal("setup.status"),requestId:l.z.string(),repoNames:l.z.array(l.z.string()).max(100).default([])});d.SetupStatusResultMsg=l.z.object({type:l.z.literal("setup.status.result"),requestId:l.z.string(),ok:l.z.boolean(),error:l.z.string().optional(),jiraConfigured:l.z.boolean().default(!1),jiraEmail:l.z.string().default(""),claude:l.z.object({installed:l.z.boolean(),version:l.z.string().default(""),loggedIn:l.z.boolean()}).optional(),githubTokenSet:l.z.boolean().default(!1),githubLogin:l.z.string().default(""),deploysEnabled:l.z.boolean().default(!1),jiraUserCount:l.z.number().int().default(0),repos:l.z.array(l.z.object({repoName:l.z.string(),mapped:l.z.boolean(),pathExists:l.z.boolean().default(!1),isGit:l.z.boolean().default(!1),claudeMd:l.z.boolean().default(!1),deployMd:l.z.boolean().default(!1),testMd:l.z.boolean().default(!1),defaultBranch:l.z.string().default(""),githubToken:l.z.boolean().default(!1),githubTokenOwn:l.z.boolean().default(!1)})).default([])});d.SetupClaudeMdGenerateMsg=l.z.object({type:l.z.literal("setup.claudemd.generate"),requestId:l.z.string(),projectId:l.z.string(),kind:l.z.enum(["claude","deploy","design"]).default("claude"),streamId:l.z.string().default("")});d.SetupClaudeMdGenerateResultMsg=l.z.object({type:l.z.literal("setup.claudemd.generate.result"),requestId:l.z.string(),ok:l.z.boolean(),error:l.z.string().optional(),content:l.z.string().default("")});d.SetupClaudeMdSaveMsg=l.z.object({type:l.z.literal("setup.claudemd.save"),requestId:l.z.string(),projectId:l.z.string(),kind:l.z.enum(["claude","deploy","design"]).default("claude"),overwrite:l.z.boolean().default(!1),content:l.z.string().max(1e5)});d.SetupClaudeMdSaveResultMsg=l.z.object({type:l.z.literal("setup.claudemd.save.result"),requestId:l.z.string(),ok:l.z.boolean(),error:l.z.string().optional(),note:l.z.string().default("")});d.RepoDocSaveMsg=l.z.object({type:l.z.literal("repo.doc.save"),requestId:l.z.string(),projectId:l.z.string(),relPath:l.z.string().min(1).max(200),overwrite:l.z.boolean().default(!1),content:l.z.string().max(2e5)});d.RepoDocSaveResultMsg=l.z.object({type:l.z.literal("repo.doc.save.result"),requestId:l.z.string(),ok:l.z.boolean(),error:l.z.string().optional(),note:l.z.string().default("")});d.RunnerUpdateMsg=l.z.object({type:l.z.literal("runner.update"),requestId:l.z.string()});d.RunResolveConflictMsg=l.z.object({type:l.z.literal("run.resolve.conflict"),requestId:l.z.string(),runId:l.z.string()});d.RunResolveConflictResultMsg=l.z.object({type:l.z.literal("run.resolve.conflict.result"),requestId:l.z.string(),ok:l.z.boolean(),note:l.z.string().default(""),freeOfCharge:l.z.boolean().default(!1),headSha:l.z.string().default(""),costUsd:l.z.number().nonnegative().optional(),inputTokens:l.z.number().int().nonnegative().optional(),outputTokens:l.z.number().int().nonnegative().optional()});d.RunPrConflictMsg=l.z.object({type:l.z.literal("run.pr.conflict"),runId:l.z.string(),conflicted:l.z.boolean()});d.AgentProfilesMsg=l.z.object({type:l.z.literal("agent.profiles"),requestId:l.z.string()});d.AgentProfilesResultMsg=l.z.object({type:l.z.literal("agent.profiles.result"),requestId:l.z.string(),ok:l.z.boolean(),error:l.z.string().optional(),profiles:l.z.array(l.z.object({agent:l.z.string(),name:l.z.string(),loggedIn:l.z.boolean()})).max(200).default([]),defaultLoggedIn:l.z.boolean().default(!1),agentsWithoutProfiles:l.z.array(l.z.string()).max(20).default([])});d.RunnerUpdateResultMsg=l.z.object({type:l.z.literal("runner.update.result"),requestId:l.z.string(),ok:l.z.boolean(),error:l.z.string().optional(),note:l.z.string().default(""),scheduled:l.z.boolean().default(!1)});d.AutopilotNextMsg=l.z.object({type:l.z.literal("autopilot.next"),requestId:l.z.string()});d.AutopilotNextResultMsg=l.z.object({type:l.z.literal("autopilot.next.result"),requestId:l.z.string(),ok:l.z.boolean(),error:l.z.string().optional(),item:l.z.object({id:l.z.string(),projectId:l.z.string(),issueKey:l.z.string(),ruleId:l.z.string(),baseOverride:l.z.string().default(""),branchOverride:l.z.string().default(""),continueBranch:l.z.boolean().default(!1)}).nullable().default(null),pausedUntil:l.z.string().default("")});d.AutopilotReportMsg=l.z.object({type:l.z.literal("autopilot.report"),requestId:l.z.string(),itemId:l.z.string(),outcome:l.z.enum(["claimed","failed","paused"]),runId:l.z.string().default(""),error:l.z.string().default("")});d.RunnerToServerMsg=l.z.discriminatedUnion("type",[d.HelloMsg,d.HeartbeatMsg,d.RunClaimMsg,d.RunLogMsg,d.RunUsageMsg,d.RunStatusMsg,d.ProjectTestResultMsg,d.RuleDiagnoseResultMsg,d.DeployClaimMsg,d.DeploySuggestResultMsg,d.EnvPreflightResultMsg,d.ChatTurnResultMsg,d.ChatStreamMsg,d.ChatUsageMsg,d.ChatCreateTicketResultMsg,d.ChatListResultMsg,d.RepoDocsResultMsg,d.RepoDocReadResultMsg,d.ChatLoadResultMsg,d.BoardFetchResultMsg,d.BoardTriggerResultMsg,d.TeamCredsResultMsg,d.AuditStartResultMsg,d.AuditListResultMsg,d.AuditGetResultMsg,d.AuditReviewResultMsg,d.KnowledgeListResultMsg,d.KnowledgeSaveResultMsg,d.EpicListResultMsg,d.EpicSuggestResultMsg,d.JiraUsersResultMsg,d.SetupStatusResultMsg,d.SetupClaudeMdGenerateResultMsg,d.SetupClaudeMdSaveResultMsg,d.RepoDocSaveResultMsg,d.RunnerUpdateResultMsg,d.AgentProfilesResultMsg,d.RunPrConflictMsg,d.RunResolveConflictResultMsg,d.AuditStatsResultMsg,d.AutopilotNextMsg,d.AutopilotReportMsg]);d.HelloAckMsg=l.z.object({type:l.z.literal("hello.ack"),runnerId:l.z.string(),runnerName:l.z.string(),serverTime:l.z.string()});d.ConfigMsg=l.z.object({type:l.z.literal("config"),projects:l.z.array(d.ProjectConfig),rules:l.z.array(d.RuleConfig),environments:l.z.array(d.EnvironmentConfig).default([]),pollingPaused:l.z.boolean().default(!1)});d.RunClaimResultMsg=l.z.object({type:l.z.literal("run.claim.result"),requestId:l.z.string(),accepted:l.z.boolean(),runId:l.z.string().optional(),reason:l.z.string().optional(),claudeProfile:l.z.string().optional(),actorEmail:l.z.string().optional()});d.ProjectTestMsg=l.z.object({type:l.z.literal("project.test"),requestId:l.z.string(),projectId:l.z.string()});d.RuleDiagnoseMsg=l.z.object({type:l.z.literal("rule.diagnose"),requestId:l.z.string(),ruleId:l.z.string()});d.RunCancelMsg=l.z.object({type:l.z.literal("run.cancel"),runId:l.z.string()});d.RunApprovedMsg=l.z.object({type:l.z.literal("run.approved"),runId:l.z.string(),headSha:l.z.string().optional()});d.RunRejectedMsg=l.z.object({type:l.z.literal("run.rejected"),runId:l.z.string()});d.RunRetryPushMsg=l.z.object({type:l.z.literal("run.retryPush"),runId:l.z.string()});d.DeployStartMsg=l.z.object({type:l.z.literal("deploy.start"),runId:l.z.string(),projectId:l.z.string(),issueKey:l.z.string(),issueSummary:l.z.string().default(""),environment:d.EnvironmentConfig,requestedBy:l.z.string().default(""),attempt:l.z.number().int().positive().default(1)});d.DeployFixMsg=l.z.object({type:l.z.literal("deploy.fix"),requestId:l.z.string(),projectId:l.z.string(),environmentName:l.z.string(),steps:l.z.array(l.z.object({name:l.z.string(),run:l.z.string(),continueOnError:l.z.boolean().default(!1)})),failedStep:l.z.string().default(""),errorText:l.z.string().max(8e3).default("")});d.DeploySuggestMsg=l.z.object({type:l.z.literal("deploy.suggest"),requestId:l.z.string(),projectId:l.z.string(),environmentName:l.z.string(),notes:l.z.string().default(""),timeoutSeconds:l.z.number().int().positive().max(1800).default(300)});d.JiraUsersMsg=l.z.object({type:l.z.literal("jira.users"),requestId:l.z.string(),query:l.z.string().default("")});d.ServerToRunnerMsg=l.z.discriminatedUnion("type",[d.HelloAckMsg,d.ConfigMsg,d.RunClaimResultMsg,d.ProjectTestMsg,d.RuleDiagnoseMsg,d.RunCancelMsg,d.RunApprovedMsg,d.RunRejectedMsg,d.RunRetryPushMsg,d.DeployClaimResultMsg,d.DeployStartMsg,d.DeploySuggestMsg,d.DeployFixMsg,d.EnvPreflightMsg,d.ChatTurnMsg,d.ChatCreateTicketMsg,d.ChatListMsg,d.RepoDocsMsg,d.RepoDocReadMsg,d.ChatLoadMsg,d.BoardFetchMsg,d.BoardTriggerMsg,d.TeamCredsMsg,d.AuditStartMsg,d.AuditListMsg,d.AuditGetMsg,d.AuditReviewMsg,d.KnowledgeListMsg,d.KnowledgeSaveMsg,d.EpicListMsg,d.EpicSuggestMsg,d.JiraUsersMsg,d.SetupStatusMsg,d.SetupClaudeMdGenerateMsg,d.SetupClaudeMdSaveMsg,d.RepoDocSaveMsg,d.RunnerUpdateMsg,d.AgentProfilesMsg,d.RunResolveConflictMsg,d.AuditStatsMsg,d.AutopilotNextResultMsg]);d.EnrollRequest=l.z.object({enrollToken:l.z.string().min(10),name:l.z.string().min(1).max(100),platform:l.z.string(),runnerVersion:l.z.string()});d.EnrollResponse=l.z.object({runnerId:l.z.string(),runnerToken:l.z.string(),controlPlaneWsUrl:l.z.string()});function Rm(r){return d.RunnerToServerMsg.parse(r)}function Em(r){return d.ServerToRunnerMsg.parse(r)}d.DEFAULT_PLAN_PROMPT_TEMPLATE=`You are a senior engineer asked to assess a Jira ticket. You have read-only access to the repository - do not attempt to modify anything.
|
|
24
24
|
|
|
25
25
|
Ticket {{issueKey}}: {{summary}}
|
|
26
26
|
|
|
@@ -234,54 +234,56 @@ Rules for the steps:
|
|
|
234
234
|
- Reference secrets as environment variables ($DEPLOY_HOST), never literal values, and list every variable you use in "requiredSecrets".
|
|
235
235
|
- Prefer commands that are safe to re-run; a deploy may be retried.
|
|
236
236
|
- Order matters: install, build, test (if cheap), then release.
|
|
237
|
-
- If you genuinely cannot tell how this repo is deployed, return an empty "steps" array and explain what is missing in "notes".`});var
|
|
238
|
-
`).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#"));for(let i of s.slice(0,200)){if(
|
|
239
|
-
`).filter(s=>s.startsWith("??")).map(s=>s.slice(3).trim()).slice(0,500).map(s=>{try{let i=
|
|
237
|
+
- If you genuinely cannot tell how this repo is deployed, return an empty "steps" array and explain what is missing in "notes".`});var uu={};ks(uu,{DELETE_MANIFEST_FILE:()=>wn,MAX_CHANGED_FILES:()=>_n,MAX_CHANGED_LINES:()=>kn,abortMerge:()=>Pr,applyDeleteManifest:()=>wo,branchForIssue:()=>Co,branchSha:()=>Ys,branchesDiffer:()=>Oo,checkDiffSafety:()=>Qn,commitAll:()=>Js,commitMergeResolution:()=>Ao,deleteStaleBranch:()=>So,diffAgainstDefault:()=>Xs,envCheckoutPath:()=>lu,envCheckoutsRoot:()=>au,fetchBase:()=>Sn,findConflictMarkers:()=>$o,headSha:()=>$r,mergeBaseIntoWorktree:()=>Eo,mergeTicketBranch:()=>Ro,originUrl:()=>jr,parseOwnerRepo:()=>Ve,prepareEnvCheckout:()=>Io,pruneWorktrees:()=>xo,pushBranch:()=>es,pushEnvBranch:()=>jo,pushWipBranch:()=>_o,removeWorktree:()=>Ft,statusSnapshot:()=>ko,worktreeAdd:()=>To,worktreeAddExisting:()=>Po,worktreeFingerprint:()=>Ws,worktreesRoot:()=>Ar});async function U(r,e,t={}){try{let{stdout:n}=await iu("git",["-C",r,...e],{timeout:t.timeoutMs??12e4,maxBuffer:16777216,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});return n}catch(n){let s=n;throw new Error(`git ${e[0]} failed: ${(s.stderr||s.message||"").trim().slice(0,500)}`)}}async function wo(r){let e={deleted:[],refused:[]},t=le.default.join(r,wn);if(!me.default.existsSync(t))return e;let n=le.default.resolve(r),s=me.default.readFileSync(t,"utf8").split(`
|
|
238
|
+
`).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#"));for(let i of s.slice(0,200)){if(le.default.isAbsolute(i)){e.refused.push(`${i} - absolute paths are not allowed`);continue}let o=le.default.resolve(n,i);if(o!==n&&!o.startsWith(n+le.default.sep)){e.refused.push(`${i} - escapes the worktree`);continue}let a=le.default.relative(n,o).split(le.default.sep).join("/");if(a===wn)continue;if(ou.some(c=>c.test(a))){e.refused.push(`${i} - protected path (CI/hook files are never touched)`);continue}let u;try{u=me.default.lstatSync(o)}catch{e.refused.push(`${i} - no such file`);continue}if(u.isDirectory()){e.refused.push(`${i} - is a directory (list the files inside it instead)`);continue}try{me.default.rmSync(o),e.deleted.push(a)}catch(c){e.refused.push(`${i} - ${c instanceof Error?c.message:"delete failed"}`)}}return me.default.rmSync(t,{force:!0}),e}async function _o(r,e){await U(r,["push","--force","origin",`HEAD:refs/heads/${e}`],{timeoutMs:3e5})}async function Ws(r){let e=await U(r,["status","--porcelain"]),t=await U(r,["diff","--numstat"]),n=e.split(`
|
|
239
|
+
`).filter(s=>s.startsWith("??")).map(s=>s.slice(3).trim()).slice(0,500).map(s=>{try{let i=me.default.statSync(le.default.join(r,s));return`${s}:${i.size}:${i.mtimeMs}`}catch{return s}}).join(`
|
|
240
240
|
`);return`${e}
|
|
241
241
|
--
|
|
242
242
|
${t}
|
|
243
243
|
--
|
|
244
|
-
${n}`}async function
|
|
244
|
+
${n}`}async function ko(r){let e=(await U(r,["rev-parse","--abbrev-ref","HEAD"])).trim(),t=(await U(r,["log","--oneline","-1"])).trim(),n=(await U(r,["status","--porcelain"])).trim(),s=n?n.split(`
|
|
245
245
|
`):[],i=s.slice(0,15).join(`
|
|
246
246
|
`),o=s.length>15?`
|
|
247
247
|
(\u2026 ${s.length-15} more)`:"";return`branch ${e} @ ${t}
|
|
248
248
|
working tree: ${s.length?`
|
|
249
|
-
${i}${o}`:"clean"}`}function
|
|
250
|
-
`))i.startsWith("worktree ")&&(s=i.slice(9).trim()),i===`branch refs/heads/${e}`&&s&&s.startsWith(n)&&await
|
|
251
|
-
`).filter(Boolean),s=n.filter(c=>
|
|
252
|
-
`).map(s=>s.trim()).filter(s=>s&&!s.includes("->"))[0]??null}async function Ks(r,e,t=6e4){let s=(await V(r,["symbolic-ref","refs/remotes/origin/HEAD"]).catch(()=>"")).trim().replace("refs/remotes/","")||"origin/main",i=await V(r,["diff","--stat",`${s}...${e}`]),o=await V(r,["diff",`${s}...${e}`]);return{base:s,stat:i.slice(0,4e3),diff:o.slice(0,t)}}function el(){let r=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(be.default.existsSync(ue.default.join(Cr.default.homedir(),".cache","ticketpilot"))?ue.default.join(Cr.default.homedir(),".cache","ticketpilot"):ue.default.join(Cr.default.homedir(),".cache","allwright"));return ue.default.join(r,"env-checkouts")}function Vu(r){return r.replace(/[^\w.-]+/g,"_")}function tl(r,e){return ue.default.join(el(),Vu(r),Vu(e))}async function So(r){let e=tl(r.repoName,r.envName);return await V(r.repoPath,["fetch","origin",r.branch],{timeoutMs:3e5}),be.default.existsSync(ue.default.join(e,".git"))?await V(e,["fetch","origin",r.branch],{timeoutMs:3e5}):(be.default.rmSync(e,{recursive:!0,force:!0}),be.default.mkdirSync(ue.default.dirname(e),{recursive:!0,mode:448}),await V(r.repoPath,["worktree","prune"]).catch(()=>{}),await V(r.repoPath,["worktree","add","--detach",e,`origin/${r.branch}`])),r.attached?await V(e,["checkout","-B",r.branch,`origin/${r.branch}`]):await V(e,["checkout","--force","--detach",`origin/${r.branch}`]),e}async function To(r,e,t){try{await V(r,["fetch","origin",e],{timeoutMs:3e5})}catch{return{ok:!1,reason:`branch "${e}" does not exist on origin - nothing to promote. Check the environment's ticket branch template against the branch your implement rule creates.`}}try{return await V(r,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyMerged:!0}}catch{}try{return await V(r,["-c",`user.name=${Yu}`,"-c",`user.email=${Xu}`,"merge","--no-ff","-m",t,`origin/${e}`]),{ok:!0}}catch(n){return await V(r,["merge","--abort"]).catch(()=>{}),{ok:!1,reason:`could not merge "${e}" into the environment branch - ${n instanceof Error?n.message:n}. Resolve it manually and deploy again.`}}}async function xo(r,e){try{await V(r,["push","origin",e],{timeoutMs:3e5})}catch(t){throw new Error(`could not push "${e}" - ${t instanceof Error?t.message:t}. Someone may have pushed to it since this deploy started; retry.`)}}async function Co(r,e,t){try{return await Ju("git",["-C",r,"diff","--quiet",e,t,"--"],{timeout:12e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),!1}catch(n){let s=n;if(s.code===1)return!0;throw new Error(`git diff failed comparing ${e}..${t}: ${(s.stderr||s.message||"").trim().slice(0,500)}`)}}async function Er(r){return(await V(r,["config","--get","remote.origin.url"])).trim()}function He(r){let e=/^git@github\.com(?:-[\w.-]+)?:([^/]+)\/(.+?)(\.git)?$/.exec(r)??/^https:\/\/github\.com\/([^/]+)\/(.+?)(\.git)?\/?$/.exec(r)??/^ssh:\/\/git@github\.com(?:-[\w.-]+)?\/([^/]+)\/(.+?)(\.git)?$/.exec(r);return e?{owner:e[1],repo:e[2]}:null}var be,Cr,ue,Hu,Wu,Ju,Yu,Xu,Ls,Us,Qu,pn,Ut=fs(()=>{"use strict";be=R(require("node:fs"),1),Cr=R(require("node:os"),1),ue=R(require("node:path"),1),Hu=require("node:child_process"),Wu=require("node:util"),Ju=(0,Wu.promisify)(Hu.execFile),Yu="Allwright Agent",Xu="agent@ticketpilot.local",Ls=200,Us=2e4,Qu=[/^\.github\/workflows\//,/^\.git\b/,/(^|\/)\.githooks\//];pn=".ticketpilot-delete"});function Zs(r,e,t){let n=(t??"").trim().toLowerCase(),s=n?r.githubUsers[n]?.token:void 0;if(s)return{token:s,source:"user"};let i=r.repos[e]?.github?.token;return i?{token:i,source:"repo"}:r.github?.token?{token:r.github.token,source:"global"}:null}function qe(r,e){return r.repos[e]?.github?.token??r.github?.token??null}function ol(r,e){let t=[r.jira,...Object.values(r.repos).map(a=>a.jira)].filter(a=>!!a),n=new Set(t.map(a=>a.email.toLowerCase())),s=!!r.github?.token||Object.values(r.repos).some(a=>a.github?.token),i=r.github?.login??Object.values(r.repos).find(a=>a.github?.login)?.github?.login??"",o=e.map(a=>{let l=a.trim().toLowerCase(),c=r.jiraUsers[l]?"own":n.has(l)?"runner-account":"missing",f=c==="own"?r.jiraUsers[l].email:c==="runner-account"?l:"",p=r.githubUsers[l]?"own":s?"shared":"missing",v=p==="own"?r.githubUsers[l].login??"":p==="shared"?i:"";return{email:l,jira:c,jiraAs:f,github:p,githubAs:v}});return{githubShared:s,sharedGithubLogin:i,entries:o}}var Ir=fs(()=>{"use strict"});var $r={};ps($r,{GitHubClient:()=>Fe});var Lm,Fe,it=fs(()=>{"use strict";Lm=process.env.TICKETPILOT_GITHUB_API??"https://api.github.com",Fe=class{constructor(e){this.token=e}token;async request(e,t,n){let s=await fetch(`${Lm}${t}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"allwright",...n!==void 0?{"Content-Type":"application/json"}:{}},body:n===void 0?void 0:JSON.stringify(n)}),i=await s.text(),o=null;try{o=i?JSON.parse(i):null}catch{}if(s.status===401)throw new Error("GitHub rejected the token (401) - expired or revoked? Run `allwright github set-token`");if(!s.ok&&s.status!==422){let a=o?.message??i.slice(0,300);throw new Error(`GitHub ${e} ${t} -> ${s.status}: ${a}`)}return{status:s.status,data:o}}async whoami(){let{data:e}=await this.request("GET","/user");return e.login}async createPullRequest(e,t,n){let{status:s,data:i}=await this.request("POST",`/repos/${e}/${t}/pulls`,n);if(s===422){let{data:o}=await this.request("GET",`/repos/${e}/${t}/pulls?head=${encodeURIComponent(`${e}:${n.head}`)}&state=open`);if(o?.length){let a=o[0];return{number:a.number,url:a.html_url,state:a.state,merged:a.merged??!1,headSha:a.head.sha,mergeableState:null}}throw new Error(`GitHub refused the PR (422): ${i?.message??"validation failed"}`)}return{number:i.number,url:i.html_url,state:i.state,merged:i.merged??!1,headSha:i.head.sha,mergeableState:null}}async getReviews(e,t,n){let{data:s}=await this.request("GET",`/repos/${e}/${t}/pulls/${n}/reviews?per_page=100`);return(s??[]).map(i=>({state:i.state??"",commitId:i.commit_id??"",user:i.user?.login??"",submittedAt:i.submitted_at??""}))}async getPullRequest(e,t,n){try{let{data:s}=await this.request("GET",`/repos/${e}/${t}/pulls/${n}`);return{number:s.number,url:s.html_url,state:s.state,merged:s.merged,headSha:s.head.sha,mergeableState:s.mergeable_state??null}}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return null;throw s}}async mergePullRequest(e,t,n,s,i={}){try{return await this.request("PUT",`/repos/${e}/${t}/pulls/${n}/merge`,{merge_method:s,...i.sha?{sha:i.sha}:{},...i.title?{commit_title:i.title}:{}}),{merged:!0}}catch(o){let a=o instanceof Error?o.message:String(o);return a.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.`}:a.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."}:a.includes("-> 403")?{merged:!1,reason:`this runner's GitHub token is not allowed to merge in ${e}/${t}. It needs write access to the repository - or merge the PR yourself.`}:{merged:!1,reason:a}}}async repoAccess(e,t){try{let{data:n}=await this.request("GET",`/repos/${e}/${t}`);return{ok:!0,canPush:!!(n.permissions?.push||n.permissions?.admin)}}catch(n){let s=n instanceof Error?n.message:String(n);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,t,n){await this.request("PATCH",`/repos/${e}/${t}/pulls/${n}`,{state:"closed"})}async deleteBranch(e,t,n){try{await this.request("DELETE",`/repos/${e}/${t}/git/refs/heads/${encodeURIComponent(n)}`)}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return;throw s}}}});var kt=ee((Xw,Wc)=>{"use strict";var Vc=["nodebuffer","arraybuffer","fragments"],Hc=typeof Blob<"u";Hc&&Vc.push("blob");Wc.exports={BINARY_TYPES:Vc,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Hc,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var ts=ee((Qw,mi)=>{"use strict";var{EMPTY_BUFFER:Pg}=kt(),la=Buffer[Symbol.species];function jg(r,e){if(r.length===0)return Pg;if(r.length===1)return r[0];let t=Buffer.allocUnsafe(e),n=0;for(let s=0;s<r.length;s++){let i=r[s];t.set(i,n),n+=i.length}return n<e?new la(t.buffer,t.byteOffset,n):t}function Jc(r,e,t,n,s){for(let i=0;i<s;i++)t[n+i]=r[i]^e[i&3]}function Yc(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function Og(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function ca(r){if(ca.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new la(r):ArrayBuffer.isView(r)?e=new la(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),ca.readOnly=!1),e}mi.exports={concat:jg,mask:Jc,toArrayBuffer:Og,toBuffer:ca,unmask:Yc};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=require("bufferutil");mi.exports.mask=function(e,t,n,s,i){i<48?Jc(e,t,n,s,i):r.mask(e,t,n,s,i)},mi.exports.unmask=function(e,t){e.length<32?Yc(e,t):r.unmask(e,t)}}catch{}});var ed=ee((e_,Qc)=>{"use strict";var Xc=Symbol("kDone"),da=Symbol("kRun"),ha=class{constructor(e){this[Xc]=()=>{this.pending--,this[da]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[da]()}[da](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Xc])}}};Qc.exports=ha});var Cn=ee((t_,sd)=>{"use strict";var rs=require("zlib"),td=ts(),Ng=ed(),{kStatusCode:rd}=kt(),Mg=Buffer[Symbol.species],zg=Buffer.from([0,0,255,255]),yi=Symbol("permessage-deflate"),St=Symbol("total-length"),Tn=Symbol("callback"),Ft=Symbol("buffers"),xn=Symbol("error"),gi,fa=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,!gi){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;gi=new Ng(t)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Tn];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,n=e.find(s=>!(t.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>s.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(n=>{let s=t[n];if(s.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(s=s[0],n==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else if(n==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else throw new Error(`Unknown parameter "${n}"`);t[n]=s})}),e}decompress(e,t,n){gi.add(s=>{this._decompress(e,t,(i,o)=>{s(),n(i,o)})})}compress(e,t,n){gi.add(s=>{this._compress(e,t,(i,o)=>{s(),n(i,o)})})}_decompress(e,t,n){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?rs.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=rs.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[yi]=this,this._inflate[St]=0,this._inflate[Ft]=[],this._inflate.on("error",Lg),this._inflate.on("data",nd)}this._inflate[Tn]=n,this._inflate.write(e),t&&this._inflate.write(zg),this._inflate.flush(()=>{let i=this._inflate[xn];if(i){this._inflate.close(),this._inflate=null,n(i);return}let o=td.concat(this._inflate[Ft],this._inflate[St]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[St]=0,this._inflate[Ft]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),n(null,o)})}_compress(e,t,n){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?rs.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=rs.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[St]=0,this._deflate[Ft]=[],this._deflate.on("data",Dg)}this._deflate[Tn]=n,this._deflate.write(e),this._deflate.flush(rs.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=td.concat(this._deflate[Ft],this._deflate[St]);t&&(i=new Mg(i.buffer,i.byteOffset,i.length-4)),this._deflate[Tn]=null,this._deflate[St]=0,this._deflate[Ft]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),n(null,i)})}};sd.exports=fa;function Dg(r){this[Ft].push(r),this[St]+=r.length}function nd(r){if(this[St]+=r.length,this[yi]._maxPayload<1||this[St]<=this[yi]._maxPayload){this[Ft].push(r);return}this[xn]=new RangeError("Max payload size exceeded"),this[xn].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[xn][rd]=1009,this.removeListener("data",nd),this.reset()}function Lg(r){if(this[yi]._inflate=null,this[xn]){this[Tn](this[xn]);return}r[rd]=1007,this[Tn](r)}});var En=ee((r_,vi)=>{"use strict";var{isUtf8:id}=require("buffer"),{hasBlob:Ug}=kt(),qg=[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 Fg(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function pa(r){let e=r.length,t=0;for(;t<e;)if((r[t]&128)===0)t++;else if((r[t]&224)===192){if(t+1===e||(r[t+1]&192)!==128||(r[t]&254)===192)return!1;t+=2}else if((r[t]&240)===224){if(t+2>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||r[t]===224&&(r[t+1]&224)===128||r[t]===237&&(r[t+1]&224)===160)return!1;t+=3}else if((r[t]&248)===240){if(t+3>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||(r[t+3]&192)!==128||r[t]===240&&(r[t+1]&240)===128||r[t]===244&&r[t+1]>143||r[t]>244)return!1;t+=4}else return!1;return!0}function Bg(r){return Ug&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}vi.exports={isBlob:Bg,isValidStatusCode:Fg,isValidUTF8:pa,tokenChars:qg};if(id)vi.exports.isValidUTF8=function(r){return r.length<24?pa(r):id(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=require("utf-8-validate");vi.exports.isValidUTF8=function(e){return e.length<32?pa(e):r(e)}}catch{}});var ba=ee((n_,hd)=>{"use strict";var{Writable:Kg}=require("stream"),od=Cn(),{BINARY_TYPES:Zg,EMPTY_BUFFER:ad,kStatusCode:Gg,kWebSocket:Vg}=kt(),{concat:ma,toArrayBuffer:Hg,unmask:Wg}=ts(),{isValidStatusCode:Jg,isValidUTF8:ud}=En(),bi=Buffer[Symbol.species],Ke=0,ld=1,cd=2,dd=3,ga=4,ya=5,wi=6,va=class extends Kg{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Zg[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[Vg]=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=Ke}_write(e,t,n){if(this._opcode===8&&this._state==Ke)return n();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){n(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new bi(n.buffer,n.byteOffset+e,n.length-e),new bi(n.buffer,n.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],s=t.length-e;e>=n.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),s),this._buffers[0]=new bi(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case Ke:this.getInfo(e);break;case ld:this.getPayloadLength16(e);break;case cd:this.getPayloadLength64(e);break;case dd:this.getMask();break;case ga:this.getData(e);break;case ya:case wi:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((t[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let n=(t[0]&64)===64;if(n&&!this._extensions[od.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=ld:this._payloadLength===127?this._state=cd:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=n*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=dd:this._state=ga}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=ga}getData(e){let t=ad;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Wg(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let n=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(n);return}if(this._compressed){this._state=ya,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[od.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return t(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(o);return}this._fragments.push(i)}this.dataMessage(t),this._state===Ke&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=Ke;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=ma(n,t):this._binaryType==="arraybuffer"?s=Hg(ma(n,t)):this._binaryType==="blob"?s=new Blob(n):s=n,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=Ke):(this._state=wi,setImmediate(()=>{this.emit("message",s,!0),this._state=Ke,this.startLoop(e)}))}else{let s=ma(n,t);if(!this._skipUTF8Validation&&!ud(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===ya||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=Ke):(this._state=wi,setImmediate(()=>{this.emit("message",s,!1),this._state=Ke,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,ad),this.end();else{let n=e.readUInt16BE(0);if(!Jg(n)){let i=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new bi(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!ud(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(i);return}this._loop=!1,this.emit("conclude",n,s),this.end()}this._state=Ke;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Ke):(this._state=wi,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Ke,this.startLoop(t)}))}createError(e,t,n,s,i){this._loop=!1,this._errored=!0;let o=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[Gg]=s,o}};hd.exports=va});var ka=ee((i_,md)=>{"use strict";var{Duplex:s_}=require("stream"),{randomFillSync:Yg}=require("crypto"),{types:{isUint8Array:Xg}}=require("util"),fd=Cn(),{EMPTY_BUFFER:Qg,kWebSocket:ey,NOOP:ty}=kt(),{isBlob:In,isValidStatusCode:ry}=En(),{mask:pd,toBuffer:qr}=ts(),Ze=Symbol("kByteLength"),ny=Buffer.alloc(4),_i=8*1024,Fr,Rn=_i,Ye=0,sy=1,iy=2,wa=class r{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Ye,this.onerror=ty,this[ey]=void 0}static frame(e,t){let n,s=!1,i=2,o=!1;t.mask&&(n=t.maskBuffer||ny,t.generateMask?t.generateMask(n):(Rn===_i&&(Fr===void 0&&(Fr=Buffer.alloc(_i)),Yg(Fr,0,_i),Rn=0),n[0]=Fr[Rn++],n[1]=Fr[Rn++],n[2]=Fr[Rn++],n[3]=Fr[Rn++]),o=(n[0]|n[1]|n[2]|n[3])===0,i=6);let a;typeof e=="string"?(!t.mask||o)&&t[Ze]!==void 0?a=t[Ze]:(e=Buffer.from(e),a=e.length):(a=e.length,s=t.mask&&t.readOnly&&!o);let l=a;a>=65536?(i+=8,l=127):a>125&&(i+=2,l=126);let c=Buffer.allocUnsafe(s?a+i:i);return c[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(c[0]|=64),c[1]=l,l===126?c.writeUInt16BE(a,2):l===127&&(c[2]=c[3]=0,c.writeUIntBE(a,4,6)),t.mask?(c[1]|=128,c[i-4]=n[0],c[i-3]=n[1],c[i-2]=n[2],c[i-1]=n[3],o?[c,e]:s?(pd(e,n,c,i,a),[c]):(pd(e,n,e,0,a),[c,e])):[c,e]}close(e,t,n,s){let i;if(e===void 0)i=Qg;else{if(typeof e!="number"||!ry(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(t);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");if(i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof t=="string")i.write(t,2);else if(Xg(t))i.set(t,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[Ze]:i.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Ye?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(r.frame(i,o),s)}ping(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):In(e)?(s=e.size,i=!1):(e=qr(e),s=e.length,i=qr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Ze]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};In(e)?this._state!==Ye?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==Ye?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(r.frame(e,o),n)}pong(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):In(e)?(s=e.size,i=!1):(e=qr(e),s=e.length,i=qr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Ze]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};In(e)?this._state!==Ye?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==Ye?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(r.frame(e,o),n)}send(e,t,n){let s=this._extensions[fd.extensionName],i=t.binary?2:1,o=t.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):In(e)?(a=e.size,l=!1):(e=qr(e),a=e.length,l=qr.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=s._threshold),this._compress=o):(o=!1,i=0),t.fin&&(this._firstFragment=!0);let c={[Ze]:a,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:l,rsv1:o};In(e)?this._state!==Ye?this.enqueue([this.getBlobData,e,this._compress,c,n]):this.getBlobData(e,this._compress,c,n):this._state!==Ye?this.enqueue([this.dispatch,e,this._compress,c,n]):this.dispatch(e,this._compress,c,n)}getBlobData(e,t,n,s){this._bufferedBytes+=n[Ze],this._state=iy,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(_a,this,a,s);return}this._bufferedBytes-=n[Ze];let o=qr(i);t?this.dispatch(o,t,n,s):(this._state=Ye,this.sendFrame(r.frame(o,n),s),this.dequeue())}).catch(i=>{process.nextTick(oy,this,i,s)})}dispatch(e,t,n,s){if(!t){this.sendFrame(r.frame(e,n),s);return}let i=this._extensions[fd.extensionName];this._bufferedBytes+=n[Ze],this._state=sy,i.compress(e,n.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");_a(this,l,s);return}this._bufferedBytes-=n[Ze],this._state=Ye,n.readOnly=!1,this.sendFrame(r.frame(a,n),s),this.dequeue()})}dequeue(){for(;this._state===Ye&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Ze],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Ze],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};md.exports=wa;function _a(r,e,t){typeof t=="function"&&t(e);for(let n=0;n<r._queue.length;n++){let s=r._queue[n],i=s[s.length-1];typeof i=="function"&&i(e)}}function oy(r,e,t){_a(r,e,t),r.onerror(e)}});var Td=ee((o_,Sd)=>{"use strict";var{kForOnEventAttribute:ns,kListener:Sa}=kt(),gd=Symbol("kCode"),yd=Symbol("kData"),vd=Symbol("kError"),bd=Symbol("kMessage"),wd=Symbol("kReason"),An=Symbol("kTarget"),_d=Symbol("kType"),kd=Symbol("kWasClean"),Tt=class{constructor(e){this[An]=null,this[_d]=e}get target(){return this[An]}get type(){return this[_d]}};Object.defineProperty(Tt.prototype,"target",{enumerable:!0});Object.defineProperty(Tt.prototype,"type",{enumerable:!0});var Br=class extends Tt{constructor(e,t={}){super(e),this[gd]=t.code===void 0?0:t.code,this[wd]=t.reason===void 0?"":t.reason,this[kd]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[gd]}get reason(){return this[wd]}get wasClean(){return this[kd]}};Object.defineProperty(Br.prototype,"code",{enumerable:!0});Object.defineProperty(Br.prototype,"reason",{enumerable:!0});Object.defineProperty(Br.prototype,"wasClean",{enumerable:!0});var $n=class extends Tt{constructor(e,t={}){super(e),this[vd]=t.error===void 0?null:t.error,this[bd]=t.message===void 0?"":t.message}get error(){return this[vd]}get message(){return this[bd]}};Object.defineProperty($n.prototype,"error",{enumerable:!0});Object.defineProperty($n.prototype,"message",{enumerable:!0});var ss=class extends Tt{constructor(e,t={}){super(e),this[yd]=t.data===void 0?null:t.data}get data(){return this[yd]}};Object.defineProperty(ss.prototype,"data",{enumerable:!0});var ay={addEventListener(r,e,t={}){for(let s of this.listeners(r))if(!t[ns]&&s[Sa]===e&&!s[ns])return;let n;if(r==="message")n=function(i,o){let a=new ss("message",{data:o?i:i.toString()});a[An]=this,ki(e,this,a)};else if(r==="close")n=function(i,o){let a=new Br("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[An]=this,ki(e,this,a)};else if(r==="error")n=function(i){let o=new $n("error",{error:i,message:i.message});o[An]=this,ki(e,this,o)};else if(r==="open")n=function(){let i=new Tt("open");i[An]=this,ki(e,this,i)};else return;n[ns]=!!t[ns],n[Sa]=e,t.once?this.once(r,n):this.on(r,n)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[Sa]===e&&!t[ns]){this.removeListener(r,t);break}}};Sd.exports={CloseEvent:Br,ErrorEvent:$n,Event:Tt,EventTarget:ay,MessageEvent:ss};function ki(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var Si=ee((a_,xd)=>{"use strict";var{tokenChars:is}=En();function at(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function uy(r){let e=Object.create(null),t=Object.create(null),n=!1,s=!1,i=!1,o,a,l=-1,c=-1,f=-1,p=0;for(;p<r.length;p++)if(c=r.charCodeAt(p),o===void 0)if(f===-1&&is[c]===1)l===-1&&(l=p);else if(p!==0&&(c===32||c===9))f===-1&&l!==-1&&(f=p);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let k=r.slice(l,f);c===44?(at(e,k,t),t=Object.create(null)):o=k,l=f=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(a===void 0)if(f===-1&&is[c]===1)l===-1&&(l=p);else if(c===32||c===9)f===-1&&l!==-1&&(f=p);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),at(t,r.slice(l,f),!0),c===44&&(at(e,o,t),t=Object.create(null),o=void 0),l=f=-1}else if(c===61&&l!==-1&&f===-1)a=r.slice(l,p),l=f=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(s){if(is[c]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);l===-1?l=p:n||(n=!0),s=!1}else if(i)if(is[c]===1)l===-1&&(l=p);else if(c===34&&l!==-1)i=!1,f=p;else if(c===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(c===34&&r.charCodeAt(p-1)===61)i=!0;else if(f===-1&&is[c]===1)l===-1&&(l=p);else if(l!==-1&&(c===32||c===9))f===-1&&(f=p);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let k=r.slice(l,f);n&&(k=k.replace(/\\/g,""),n=!1),at(t,a,k),c===44&&(at(e,o,t),t=Object.create(null),o=void 0),a=void 0,l=f=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(l===-1||i||c===32||c===9)throw new SyntaxError("Unexpected end of input");f===-1&&(f=p);let v=r.slice(l,f);return o===void 0?at(e,v,t):(a===void 0?at(t,v,!0):n?at(t,a,v.replace(/\\/g,"")):at(t,a,v),at(e,o,t)),e}function ly(r){return Object.keys(r).map(e=>{let t=r[e];return Array.isArray(t)||(t=[t]),t.map(n=>[e].concat(Object.keys(n).map(s=>{let i=n[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}xd.exports={format:ly,parse:uy}});var Ei=ee((c_,zd)=>{"use strict";var cy=require("events"),dy=require("https"),hy=require("http"),Id=require("net"),fy=require("tls"),{randomBytes:py,createHash:my}=require("crypto"),{Duplex:u_,Readable:l_}=require("stream"),{URL:Ta}=require("url"),Bt=Cn(),gy=ba(),yy=ka(),{isBlob:vy}=En(),{BINARY_TYPES:Cd,CLOSE_TIMEOUT:by,EMPTY_BUFFER:Ti,GUID:wy,kForOnEventAttribute:xa,kListener:_y,kStatusCode:ky,kWebSocket:me,NOOP:Rd}=kt(),{EventTarget:{addEventListener:Sy,removeEventListener:Ty}}=Td(),{format:xy,parse:Cy}=Si(),{toBuffer:Ey}=ts(),Ad=Symbol("kAborted"),Ca=[8,13],xt=["CONNECTING","OPEN","CLOSING","CLOSED"],Iy=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,le=class r extends cy{constructor(e,t,n){super(),this._binaryType=Cd[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Ti,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=r.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(n=t,t=[]):t=[t]),$d(this,e,t,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Cd.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,n){let s=new gy({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:n.maxBufferedChunks,maxFragments:n.maxFragments,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),i=new yy(e,this._extensions,n.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[me]=this,i[me]=this,e[me]=this,s.on("conclude",$y),s.on("drain",Py),s.on("error",jy),s.on("message",Oy),s.on("ping",Ny),s.on("pong",My),i.onerror=zy,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Od),e.on("data",Ci),e.on("end",Nd),e.on("error",Md),this._readyState=r.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Bt.extensionName]&&this._extensions[Bt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){je(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===r.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=r.CLOSING,this._sender.close(e,t,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),jd(this)}}pause(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Ea(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Ti,t,n)}pong(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Ea(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Ti,t,n)}resume(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(n=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Ea(this,e,n);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Bt.extensionName]||(s.compress=!1),this._sender.send(e||Ti,s,n)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){je(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(le,"CONNECTING",{enumerable:!0,value:xt.indexOf("CONNECTING")});Object.defineProperty(le.prototype,"CONNECTING",{enumerable:!0,value:xt.indexOf("CONNECTING")});Object.defineProperty(le,"OPEN",{enumerable:!0,value:xt.indexOf("OPEN")});Object.defineProperty(le.prototype,"OPEN",{enumerable:!0,value:xt.indexOf("OPEN")});Object.defineProperty(le,"CLOSING",{enumerable:!0,value:xt.indexOf("CLOSING")});Object.defineProperty(le.prototype,"CLOSING",{enumerable:!0,value:xt.indexOf("CLOSING")});Object.defineProperty(le,"CLOSED",{enumerable:!0,value:xt.indexOf("CLOSED")});Object.defineProperty(le.prototype,"CLOSED",{enumerable:!0,value:xt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(le.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(le.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[xa])return e[_y];return null},set(e){for(let t of this.listeners(r))if(t[xa]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[xa]:!0})}})});le.prototype.addEventListener=Sy;le.prototype.removeEventListener=Ty;zd.exports=le;function $d(r,e,t,n){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:by,protocolVersion:Ca[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(r._autoPong=s.autoPong,r._closeTimeout=s.closeTimeout,!Ca.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Ca.join(", ")})`);let i;if(e instanceof Ta)i=e;else try{i=new Ta(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),r._url=i.href;let o=i.protocol==="wss:",a=i.protocol==="ws+unix:",l;if(i.protocol!=="ws:"&&!o&&!a?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?l="The URL's pathname is empty":i.hash&&(l="The URL contains a fragment identifier"),l){let x=new SyntaxError(l);if(r._redirects===0)throw x;xi(r,x);return}let c=o?443:80,f=py(16).toString("base64"),p=o?dy.request:hy.request,v=new Set,k;if(s.createConnection=s.createConnection||(o?Ay:Ry),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&&(k=new Bt({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=xy({[Bt.extensionName]:k.offer()})),t.length){for(let x of t){if(typeof x!="string"||!Iy.test(x)||v.has(x))throw new SyntaxError("An invalid or duplicated subprotocol was specified");v.add(x)}s.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){let x=s.path.split(":");s.socketPath=x[0],s.path=x[1]}let T;if(s.followRedirects){if(r._redirects===0){r._originalIpc=a,r._originalSecure=o,r._originalHostOrSocketPath=a?s.socketPath:i.host;let x=n&&n.headers;if(n={...n,headers:{}},x)for(let[j,S]of Object.entries(x))n.headers[j.toLowerCase()]=S}else if(r.listenerCount("redirect")===0){let x=a?r._originalIpc?s.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:i.host===r._originalHostOrSocketPath;(!x||r._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,x||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),T=r._req=p(s),r._redirects&&r.emit("redirect",r.url,T)}else T=r._req=p(s);s.timeout&&T.on("timeout",()=>{je(r,T,"Opening handshake has timed out")}),T.on("error",x=>{T===null||T[Ad]||(T=r._req=null,xi(r,x))}),T.on("response",x=>{let j=x.headers.location,S=x.statusCode;if(j&&s.followRedirects&&S>=300&&S<400){if(++r._redirects>s.maxRedirects){je(r,T,"Maximum redirects exceeded");return}T.abort();let J;try{J=new Ta(j,e)}catch{let z=new SyntaxError(`Invalid URL: ${j}`);xi(r,z);return}$d(r,J,t,n)}else r.emit("unexpected-response",T,x)||je(r,T,`Unexpected server response: ${x.statusCode}`)}),T.on("upgrade",(x,j,S)=>{if(r.emit("upgrade",x),r.readyState!==le.CONNECTING)return;T=r._req=null;let J=x.headers.upgrade;if(J===void 0||J.toLowerCase()!=="websocket"){je(r,j,"Invalid Upgrade header");return}let M=my("sha1").update(f+wy).digest("base64");if(x.headers["sec-websocket-accept"]!==M){je(r,j,"Invalid Sec-WebSocket-Accept header");return}let z=x.headers["sec-websocket-protocol"],Q;if(z!==void 0?v.size?v.has(z)||(Q="Server sent an invalid subprotocol"):Q="Server sent a subprotocol but none was requested":v.size&&(Q="Server sent no subprotocol"),Q){je(r,j,Q);return}z&&(r._protocol=z);let h=x.headers["sec-websocket-extensions"];if(h!==void 0){if(!k){je(r,j,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let g;try{g=Cy(h)}catch{je(r,j,"Invalid Sec-WebSocket-Extensions header");return}let w=Object.keys(g);if(w.length!==1||w[0]!==Bt.extensionName){je(r,j,"Server indicated an extension that was not requested");return}try{k.accept(g[Bt.extensionName])}catch{je(r,j,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[Bt.extensionName]=k}r.setSocket(j,S,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(T,r):T.end()}function xi(r,e){r._readyState=le.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function Ry(r){return r.path=r.socketPath,Id.connect(r)}function Ay(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=Id.isIP(r.host)?"":r.host),fy.connect(r)}function je(r,e,t){r._readyState=le.CLOSING;let n=new Error(t);Error.captureStackTrace(n,je),e.setHeader?(e[Ad]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(xi,r,n)):(e.destroy(n),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function Ea(r,e,t){if(e){let n=vy(e)?e.size:Ey(e).length;r._socket?r._sender._bufferedBytes+=n:r._bufferedAmount+=n}if(t){let n=new Error(`WebSocket is not open: readyState ${r.readyState} (${xt[r.readyState]})`);process.nextTick(t,n)}}function $y(r,e){let t=this[me];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[me]!==void 0&&(t._socket.removeListener("data",Ci),process.nextTick(Pd,t._socket),r===1005?t.close():t.close(r,e))}function Py(){let r=this[me];r.isPaused||r._socket.resume()}function jy(r){let e=this[me];e._socket[me]!==void 0&&(e._socket.removeListener("data",Ci),process.nextTick(Pd,e._socket),e.close(r[ky])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function Ed(){this[me].emitClose()}function Oy(r,e){this[me].emit("message",r,e)}function Ny(r){let e=this[me];e._autoPong&&e.pong(r,!this._isServer,Rd),e.emit("ping",r)}function My(r){this[me].emit("pong",r)}function Pd(r){r.resume()}function zy(r){let e=this[me];e.readyState!==le.CLOSED&&(e.readyState===le.OPEN&&(e._readyState=le.CLOSING,jd(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function jd(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),r._closeTimeout)}function Od(){let r=this[me];if(this.removeListener("close",Od),this.removeListener("data",Ci),this.removeListener("end",Nd),r._readyState=le.CLOSING,!this._readableState.endEmitted&&!r._closeFrameReceived&&!r._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);r._receiver.write(e)}r._receiver.end(),this[me]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",Ed),r._receiver.on("finish",Ed))}function Ci(r){this[me]._receiver.write(r)||this.pause()}function Nd(){let r=this[me];r._readyState=le.CLOSING,r._receiver.end(),this.end()}function Md(){let r=this[me];this.removeListener("error",Md),this.on("error",Rd),r&&(r._readyState=le.CLOSING,this.destroy())}});var qd=ee((h_,Ud)=>{"use strict";var d_=Ei(),{Duplex:Dy}=require("stream");function Dd(r){r.emit("close")}function Ly(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Ld(r){this.removeListener("error",Ld),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function Uy(r,e){let t=!0,n=new Dy({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(i,o){let a=!o&&n._readableState.objectMode?i.toString():i;n.push(a)||r.pause()}),r.once("error",function(i){n.destroyed||(t=!1,n.destroy(i))}),r.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(s,i){if(r.readyState===r.CLOSED){i(s),process.nextTick(Dd,n);return}let o=!1;r.once("error",function(l){o=!0,i(l)}),r.once("close",function(){o||i(s),process.nextTick(Dd,n)}),t&&r.terminate()},n._final=function(s){if(r.readyState===r.CONNECTING){r.once("open",function(){n._final(s)});return}r._socket!==null&&(r._socket._writableState.finished?(s(),n._readableState.endEmitted&&n.destroy()):(r._socket.once("finish",function(){s()}),r.close()))},n._read=function(){r.isPaused&&r.resume()},n._write=function(s,i,o){if(r.readyState===r.CONNECTING){r.once("open",function(){n._write(s,i,o)});return}r.send(s,o)},n.on("end",Ly),n.on("error",Ld),n}Ud.exports=Uy});var Ia=ee((f_,Fd)=>{"use strict";var{tokenChars:qy}=En();function Fy(r){let e=new Set,t=-1,n=-1,s=0;for(s;s<r.length;s++){let o=r.charCodeAt(s);if(n===-1&&qy[o]===1)t===-1&&(t=s);else if(s!==0&&(o===32||o===9))n===-1&&t!==-1&&(n=s);else if(o===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${s}`);n===-1&&(n=s);let a=r.slice(t,n);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),t=n=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(t===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let i=r.slice(t,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}Fd.exports={parse:Fy}});var Wd=ee((m_,Hd)=>{"use strict";var By=require("events"),Ii=require("http"),{Duplex:p_}=require("stream"),{createHash:Ky}=require("crypto"),Bd=Si(),Kr=Cn(),Zy=Ia(),Gy=Ei(),{CLOSE_TIMEOUT:Vy,GUID:Hy,kWebSocket:Wy}=kt(),Jy=/^[+/0-9A-Za-z]{22}==$/,Kd=0,Zd=1,Vd=2,Ra=class extends By{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Vy,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Gy,...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=Ii.createServer((n,s)=>{let i=Ii.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=Yy(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Kd}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===Vd){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(os,this);return}if(e&&this.once("close",e),this._state!==Zd)if(this._state=Zd,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(os,this):process.nextTick(os,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{os(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,s){t.on("error",Gd);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Zr(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Zr(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!Jy.test(i)){Zr(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Zr(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){as(t,400);return}let l=e.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=Zy.parse(l)}catch{Zr(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let f=e.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&f!==void 0){let v=new Kr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let k=Bd.parse(f);k[Kr.extensionName]&&(v.accept(k[Kr.extensionName]),p[Kr.extensionName]=v)}catch{Zr(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let v={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(v,(k,T,x,j)=>{if(!k)return as(t,T||401,x,j);this.completeUpgrade(p,i,c,e,t,n,s)});return}if(!this.options.verifyClient(v))return as(t,401)}this.completeUpgrade(p,i,c,e,t,n,s)}completeUpgrade(e,t,n,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[Wy])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Kd)return as(i,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Ky("sha1").update(t+Hy).digest("base64")}`],f=new this.options.WebSocket(null,void 0,this.options);if(n.size){let p=this.options.handleProtocols?this.options.handleProtocols(n,s):n.values().next().value;p&&(c.push(`Sec-WebSocket-Protocol: ${p}`),f._protocol=p)}if(e[Kr.extensionName]){let p=e[Kr.extensionName].params,v=Bd.format({[Kr.extensionName]:[p]});c.push(`Sec-WebSocket-Extensions: ${v}`),f._extensions=e}this.emit("headers",c,s),i.write(c.concat(`\r
|
|
249
|
+
${i}${o}`:"clean"}`}function Ar(){let r=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(me.default.existsSync(le.default.join(Er.default.homedir(),".cache","ticketpilot"))?le.default.join(Er.default.homedir(),".cache","ticketpilot"):le.default.join(Er.default.homedir(),".cache","allwright"));return le.default.join(r,"worktrees")}async function Sn(r,e){try{await U(r,["fetch","origin",e])}catch(t){throw new Error(`could not fetch base branch "${e}" from origin - check the rule's base branch and that this machine can reach the remote (${t instanceof Error?t.message:t})`)}}async function So(r,e){try{let t=await U(r,["worktree","list","--porcelain"]),n=Ar(),s=null;for(let i of t.split(`
|
|
250
|
+
`))i.startsWith("worktree ")&&(s=i.slice(9).trim()),i===`branch refs/heads/${e}`&&s&&s.startsWith(n)&&await U(r,["worktree","remove","--force",s]);await U(r,["worktree","prune"])}catch{}try{await U(r,["branch","-D",e])}catch{}}async function To(r,e,t,n){me.default.mkdirSync(le.default.dirname(e),{recursive:!0,mode:448}),await U(r,["worktree","add","-b",t,e,`origin/${n}`])}async function Js(r,e){if(await U(r,["add","-A"]),!(await U(r,["status","--porcelain"])).trim())throw new Error("Claude wrote no changes - nothing to commit");await U(r,["-c",`user.name=${Hs}`,"-c",`user.email=${Vs}`,"commit","-m",e])}async function Qn(r,e){let n=(await U(r,["diff","--name-only",`origin/${e}...HEAD`])).split(`
|
|
251
|
+
`).filter(Boolean),s=n.filter(c=>ou.some(f=>f.test(c))),i=await U(r,["diff","--shortstat",`origin/${e}...HEAD`]),o=Number(/(\d+) insertion/.exec(i)?.[1]??0),a=Number(/(\d+) deletion/.exec(i)?.[1]??0);return{ok:s.length===0&&n.length<=_n&&o+a<=kn,files:n.length,insertions:o,deletions:a,forbidden:s}}async function es(r,e){await U(r,["fetch","--prune","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],{timeoutMs:12e4}).catch(()=>U(r,["update-ref","-d",`refs/remotes/origin/${e}`]).catch(()=>{})),await U(r,["push","--force-with-lease","-u","origin",e],{timeoutMs:3e5})}async function $r(r){return(await U(r,["rev-parse","HEAD"])).trim()}async function Ys(r,e){try{return(await U(r,["rev-parse","--verify",`refs/heads/${e}`])).trim()}catch{return null}}async function Ft(r,e){try{await U(r,["worktree","remove","--force",e])}catch{me.default.rmSync(e,{recursive:!0,force:!0})}}async function xo(r,e=[]){let t=new Set(e.map(s=>le.default.basename(le.default.resolve(s))).filter(s=>s.length>0)),n=Ar();if(me.default.existsSync(n))for(let s of me.default.readdirSync(n))t.has(s)||me.default.rmSync(le.default.join(n,s),{recursive:!0,force:!0});for(let s of r)try{await U(s,["worktree","prune"])}catch{}}async function Co(r,e){return await U(r,["fetch","origin","--prune"]).catch(()=>{}),(await U(r,["branch","-r","--list",`*${e}*`])).split(`
|
|
252
|
+
`).map(s=>s.trim()).filter(s=>s&&!s.includes("->"))[0]??null}async function Xs(r,e,t=6e4){let s=(await U(r,["symbolic-ref","refs/remotes/origin/HEAD"]).catch(()=>"")).trim().replace("refs/remotes/","")||"origin/main",i=await U(r,["diff","--stat",`${s}...${e}`]),o=await U(r,["diff",`${s}...${e}`]);return{base:s,stat:i.slice(0,4e3),diff:o.slice(0,t)}}function au(){let r=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(me.default.existsSync(le.default.join(Er.default.homedir(),".cache","ticketpilot"))?le.default.join(Er.default.homedir(),".cache","ticketpilot"):le.default.join(Er.default.homedir(),".cache","allwright"));return le.default.join(r,"env-checkouts")}function ru(r){return r.replace(/[^\w.-]+/g,"_")}function lu(r,e){return le.default.join(au(),ru(r),ru(e))}async function Io(r){let e=lu(r.repoName,r.envName);return await U(r.repoPath,["fetch","origin",r.branch],{timeoutMs:3e5}),me.default.existsSync(le.default.join(e,".git"))?await U(e,["fetch","origin",r.branch],{timeoutMs:3e5}):(me.default.rmSync(e,{recursive:!0,force:!0}),me.default.mkdirSync(le.default.dirname(e),{recursive:!0,mode:448}),await U(r.repoPath,["worktree","prune"]).catch(()=>{}),await U(r.repoPath,["worktree","add","--detach",e,`origin/${r.branch}`])),r.attached?await U(e,["checkout","-B",r.branch,`origin/${r.branch}`]):await U(e,["checkout","--force","--detach",`origin/${r.branch}`]),e}async function Ro(r,e,t){try{await U(r,["fetch","origin",e],{timeoutMs:3e5})}catch{return{ok:!1,reason:`branch "${e}" does not exist on origin - nothing to promote. Check the environment's ticket branch template against the branch your implement rule creates.`}}try{return await U(r,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyMerged:!0}}catch{}try{return await U(r,["-c",`user.name=${Hs}`,"-c",`user.email=${Vs}`,"merge","--no-ff","-m",t,`origin/${e}`]),{ok:!0}}catch(n){return await U(r,["merge","--abort"]).catch(()=>{}),{ok:!1,reason:`could not merge "${e}" into the environment branch - ${n instanceof Error?n.message:n}. Resolve it manually and deploy again.`}}}async function Eo(r,e){await U(r,["fetch","origin",e],{timeoutMs:3e5});try{return await U(r,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyUpToDate:!0}}catch{}try{return await U(r,["-c",`user.name=${Hs}`,"-c",`user.email=${Vs}`,"merge","--no-edit",`origin/${e}`]),{ok:!0,alreadyUpToDate:!1}}catch(t){let s=(await U(r,["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
|
|
253
|
+
`).filter(Boolean);return s.length?{ok:!1,conflicts:s}:(await U(r,["merge","--abort"]).catch(()=>{}),{ok:!1,conflicts:null,reason:t instanceof Error?t.message.slice(0,300):String(t)})}}async function Pr(r){await U(r,["merge","--abort"]).catch(()=>{})}async function Ao(r,e){await U(r,["add","-A"]),await U(r,["-c",`user.name=${Hs}`,"-c",`user.email=${Vs}`,"commit","--no-edit","-m",e])}async function $o(r){try{return(await U(r,["grep","-l","-I","-E","^(<{7}|={7}|>{7})( |$)"])).split(`
|
|
254
|
+
`).filter(Boolean)}catch{return[]}}async function Po(r,e,t){me.default.mkdirSync(le.default.dirname(e),{recursive:!0,mode:448}),await U(r,["fetch","origin",t],{timeoutMs:3e5}),await U(r,["worktree","add","--detach",e,`origin/${t}`]),await U(e,["checkout","-B",t,`origin/${t}`])}async function jo(r,e){try{await U(r,["push","origin",e],{timeoutMs:3e5})}catch(t){throw new Error(`could not push "${e}" - ${t instanceof Error?t.message:t}. Someone may have pushed to it since this deploy started; retry.`)}}async function Oo(r,e,t){try{return await iu("git",["-C",r,"diff","--quiet",e,t,"--"],{timeout:12e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),!1}catch(n){let s=n;if(s.code===1)return!0;throw new Error(`git diff failed comparing ${e}..${t}: ${(s.stderr||s.message||"").trim().slice(0,500)}`)}}async function jr(r){return(await U(r,["config","--get","remote.origin.url"])).trim()}function Ve(r){let e=/^git@github\.com(?:-[\w.-]+)?:([^/]+)\/(.+?)(\.git)?$/.exec(r)??/^https:\/\/github\.com\/([^/]+)\/(.+?)(\.git)?\/?$/.exec(r)??/^ssh:\/\/git@github\.com(?:-[\w.-]+)?\/([^/]+)\/(.+?)(\.git)?$/.exec(r);return e?{owner:e[1],repo:e[2]}:null}var me,Er,le,nu,su,iu,Hs,Vs,_n,kn,ou,wn,_t=_s(()=>{"use strict";me=E(require("node:fs"),1),Er=E(require("node:os"),1),le=E(require("node:path"),1),nu=require("node:child_process"),su=require("node:util"),iu=(0,su.promisify)(nu.execFile),Hs="Allwright Agent",Vs="agent@ticketpilot.local",_n=200,kn=2e4,ou=[/^\.github\/workflows\//,/^\.git\b/,/(^|\/)\.githooks\//];wn=".ticketpilot-delete"});function Qs(r,e,t){let n=(t??"").trim().toLowerCase(),s=n?r.githubUsers[n]?.token:void 0;if(s)return{token:s,source:"user"};let i=r.repos[e]?.github?.token;return i?{token:i,source:"repo"}:r.github?.token?{token:r.github.token,source:"global"}:null}function Ae(r,e){return r.repos[e]?.github?.token??r.github?.token??null}function fu(r,e){let t=[r.jira,...Object.values(r.repos).map(a=>a.jira)].filter(a=>!!a),n=new Set(t.map(a=>a.email.toLowerCase())),s=!!r.github?.token||Object.values(r.repos).some(a=>a.github?.token),i=r.github?.login??Object.values(r.repos).find(a=>a.github?.login)?.github?.login??"",o=e.map(a=>{let u=a.trim().toLowerCase(),c=r.jiraUsers[u]?"own":n.has(u)?"runner-account":"missing",f=c==="own"?r.jiraUsers[u].email:c==="runner-account"?u:"",p=r.githubUsers[u]?"own":s?"shared":"missing",v=p==="own"?r.githubUsers[u].login??"":p==="shared"?i:"";return{email:u,jira:c,jiraAs:f,github:p,githubAs:v}});return{githubShared:s,sharedGithubLogin:i,entries:o}}var Or=_s(()=>{"use strict"});var zr={};ks(zr,{GitHubClient:()=>$e});var Vm,$e,Ye=_s(()=>{"use strict";Vm=process.env.TICKETPILOT_GITHUB_API??"https://api.github.com",$e=class{constructor(e){this.token=e}token;async request(e,t,n){let s=await fetch(`${Vm}${t}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"allwright",...n!==void 0?{"Content-Type":"application/json"}:{}},body:n===void 0?void 0:JSON.stringify(n)}),i=await s.text(),o=null;try{o=i?JSON.parse(i):null}catch{}if(s.status===401)throw new Error("GitHub rejected the token (401) - expired or revoked? Run `allwright github set-token`");if(!s.ok&&s.status!==422){let a=o?.message??i.slice(0,300);throw new Error(`GitHub ${e} ${t} -> ${s.status}: ${a}`)}return{status:s.status,data:o}}async whoami(){let{data:e}=await this.request("GET","/user");return e.login}async createPullRequest(e,t,n){let{status:s,data:i}=await this.request("POST",`/repos/${e}/${t}/pulls`,n);if(s===422){let{data:o}=await this.request("GET",`/repos/${e}/${t}/pulls?head=${encodeURIComponent(`${e}:${n.head}`)}&state=open`);if(o?.length){let a=o[0];return{number:a.number,url:a.html_url,state:a.state,merged:a.merged??!1,headSha:a.head.sha,mergeableState:null,baseRef:a.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:n.base}}async getReviews(e,t,n){let{data:s}=await this.request("GET",`/repos/${e}/${t}/pulls/${n}/reviews?per_page=100`);return(s??[]).map(i=>({state:i.state??"",commitId:i.commit_id??"",user:i.user?.login??"",submittedAt:i.submitted_at??""}))}async getPullRequest(e,t,n){try{let{data:s}=await this.request("GET",`/repos/${e}/${t}/pulls/${n}`);return{number:s.number,url:s.html_url,state:s.state,merged:s.merged,headSha:s.head.sha,mergeableState:s.mergeable_state??null,baseRef:s.base?.ref??""}}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return null;throw s}}async mergePullRequest(e,t,n,s,i={}){try{return await this.request("PUT",`/repos/${e}/${t}/pulls/${n}/merge`,{merge_method:s,...i.sha?{sha:i.sha}:{},...i.title?{commit_title:i.title}:{}}),{merged:!0}}catch(o){let a=o instanceof Error?o.message:String(o);return a.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.`}:a.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."}:a.includes("-> 403")?{merged:!1,reason:`this runner's GitHub token is not allowed to merge in ${e}/${t}. It needs write access to the repository - or merge the PR yourself.`}:{merged:!1,reason:a}}}async repoAccess(e,t){try{let{data:n}=await this.request("GET",`/repos/${e}/${t}`);return{ok:!0,canPush:!!(n.permissions?.push||n.permissions?.admin)}}catch(n){let s=n instanceof Error?n.message:String(n);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,t,n){await this.request("PATCH",`/repos/${e}/${t}/pulls/${n}`,{state:"closed"})}async deleteBranch(e,t,n){try{await this.request("DELETE",`/repos/${e}/${t}/git/refs/heads/${encodeURIComponent(n)}`)}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return;throw s}}}});var xt=ee((d_,id)=>{"use strict";var nd=["nodebuffer","arraybuffer","fragments"],sd=typeof Blob<"u";sd&&nd.push("blob");id.exports={BINARY_TYPES:nd,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:sd,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var cs=ee((h_,ki)=>{"use strict";var{EMPTY_BUFFER:Fg}=xt(),ya=Buffer[Symbol.species];function Bg(r,e){if(r.length===0)return Fg;if(r.length===1)return r[0];let t=Buffer.allocUnsafe(e),n=0;for(let s=0;s<r.length;s++){let i=r[s];t.set(i,n),n+=i.length}return n<e?new ya(t.buffer,t.byteOffset,n):t}function od(r,e,t,n,s){for(let i=0;i<s;i++)t[n+i]=r[i]^e[i&3]}function ad(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function Kg(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function va(r){if(va.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new ya(r):ArrayBuffer.isView(r)?e=new ya(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),va.readOnly=!1),e}ki.exports={concat:Bg,mask:od,toArrayBuffer:Kg,toBuffer:va,unmask:ad};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=require("bufferutil");ki.exports.mask=function(e,t,n,s,i){i<48?od(e,t,n,s,i):r.mask(e,t,n,s,i)},ki.exports.unmask=function(e,t){e.length<32?ad(e,t):r.unmask(e,t)}}catch{}});var cd=ee((f_,ud)=>{"use strict";var ld=Symbol("kDone"),ba=Symbol("kRun"),wa=class{constructor(e){this[ld]=()=>{this.pending--,this[ba]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[ba]()}[ba](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[ld])}}};ud.exports=wa});var jn=ee((p_,pd)=>{"use strict";var ds=require("zlib"),dd=cs(),Zg=cd(),{kStatusCode:hd}=xt(),Gg=Buffer[Symbol.species],Hg=Buffer.from([0,0,255,255]),Ti=Symbol("permessage-deflate"),Ct=Symbol("total-length"),$n=Symbol("callback"),Kt=Symbol("buffers"),Pn=Symbol("error"),Si,_a=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,!Si){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Si=new Zg(t)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[$n];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,n=e.find(s=>!(t.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>s.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(n=>{let s=t[n];if(s.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(s=s[0],n==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else if(n==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else throw new Error(`Unknown parameter "${n}"`);t[n]=s})}),e}decompress(e,t,n){Si.add(s=>{this._decompress(e,t,(i,o)=>{s(),n(i,o)})})}compress(e,t,n){Si.add(s=>{this._compress(e,t,(i,o)=>{s(),n(i,o)})})}_decompress(e,t,n){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?ds.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=ds.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Ti]=this,this._inflate[Ct]=0,this._inflate[Kt]=[],this._inflate.on("error",Wg),this._inflate.on("data",fd)}this._inflate[$n]=n,this._inflate.write(e),t&&this._inflate.write(Hg),this._inflate.flush(()=>{let i=this._inflate[Pn];if(i){this._inflate.close(),this._inflate=null,n(i);return}let o=dd.concat(this._inflate[Kt],this._inflate[Ct]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Ct]=0,this._inflate[Kt]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),n(null,o)})}_compress(e,t,n){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?ds.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=ds.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[Ct]=0,this._deflate[Kt]=[],this._deflate.on("data",Vg)}this._deflate[$n]=n,this._deflate.write(e),this._deflate.flush(ds.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=dd.concat(this._deflate[Kt],this._deflate[Ct]);t&&(i=new Gg(i.buffer,i.byteOffset,i.length-4)),this._deflate[$n]=null,this._deflate[Ct]=0,this._deflate[Kt]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),n(null,i)})}};pd.exports=_a;function Vg(r){this[Kt].push(r),this[Ct]+=r.length}function fd(r){if(this[Ct]+=r.length,this[Ti]._maxPayload<1||this[Ct]<=this[Ti]._maxPayload){this[Kt].push(r);return}this[Pn]=new RangeError("Max payload size exceeded"),this[Pn].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Pn][hd]=1009,this.removeListener("data",fd),this.reset()}function Wg(r){if(this[Ti]._inflate=null,this[Pn]){this[$n](this[Pn]);return}r[hd]=1007,this[$n](r)}});var On=ee((m_,xi)=>{"use strict";var{isUtf8:md}=require("buffer"),{hasBlob:Jg}=xt(),Yg=[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 Xg(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function ka(r){let e=r.length,t=0;for(;t<e;)if((r[t]&128)===0)t++;else if((r[t]&224)===192){if(t+1===e||(r[t+1]&192)!==128||(r[t]&254)===192)return!1;t+=2}else if((r[t]&240)===224){if(t+2>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||r[t]===224&&(r[t+1]&224)===128||r[t]===237&&(r[t+1]&224)===160)return!1;t+=3}else if((r[t]&248)===240){if(t+3>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||(r[t+3]&192)!==128||r[t]===240&&(r[t+1]&240)===128||r[t]===244&&r[t+1]>143||r[t]>244)return!1;t+=4}else return!1;return!0}function Qg(r){return Jg&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}xi.exports={isBlob:Qg,isValidStatusCode:Xg,isValidUTF8:ka,tokenChars:Yg};if(md)xi.exports.isValidUTF8=function(r){return r.length<24?ka(r):md(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=require("utf-8-validate");xi.exports.isValidUTF8=function(e){return e.length<32?ka(e):r(e)}}catch{}});var Ia=ee((g_,kd)=>{"use strict";var{Writable:ey}=require("stream"),gd=jn(),{BINARY_TYPES:ty,EMPTY_BUFFER:yd,kStatusCode:ry,kWebSocket:ny}=xt(),{concat:Sa,toArrayBuffer:sy,unmask:iy}=cs(),{isValidStatusCode:oy,isValidUTF8:vd}=On(),Ci=Buffer[Symbol.species],Ke=0,bd=1,wd=2,_d=3,Ta=4,xa=5,Ii=6,Ca=class extends ey{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||ty[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[ny]=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=Ke}_write(e,t,n){if(this._opcode===8&&this._state==Ke)return n();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){n(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new Ci(n.buffer,n.byteOffset+e,n.length-e),new Ci(n.buffer,n.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],s=t.length-e;e>=n.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),s),this._buffers[0]=new Ci(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case Ke:this.getInfo(e);break;case bd:this.getPayloadLength16(e);break;case wd:this.getPayloadLength64(e);break;case _d:this.getMask();break;case Ta:this.getData(e);break;case xa:case Ii:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((t[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let n=(t[0]&64)===64;if(n&&!this._extensions[gd.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=bd:this._payloadLength===127?this._state=wd:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=n*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=_d:this._state=Ta}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Ta}getData(e){let t=yd;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&iy(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let n=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(n);return}if(this._compressed){this._state=xa,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[gd.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return t(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(o);return}this._fragments.push(i)}this.dataMessage(t),this._state===Ke&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=Ke;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=Sa(n,t):this._binaryType==="arraybuffer"?s=sy(Sa(n,t)):this._binaryType==="blob"?s=new Blob(n):s=n,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=Ke):(this._state=Ii,setImmediate(()=>{this.emit("message",s,!0),this._state=Ke,this.startLoop(e)}))}else{let s=Sa(n,t);if(!this._skipUTF8Validation&&!vd(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===xa||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=Ke):(this._state=Ii,setImmediate(()=>{this.emit("message",s,!1),this._state=Ke,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,yd),this.end();else{let n=e.readUInt16BE(0);if(!oy(n)){let i=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new Ci(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!vd(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(i);return}this._loop=!1,this.emit("conclude",n,s),this.end()}this._state=Ke;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Ke):(this._state=Ii,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Ke,this.startLoop(t)}))}createError(e,t,n,s,i){this._loop=!1,this._errored=!0;let o=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[ry]=s,o}};kd.exports=Ca});var Aa=ee((v_,xd)=>{"use strict";var{Duplex:y_}=require("stream"),{randomFillSync:ay}=require("crypto"),{types:{isUint8Array:ly}}=require("util"),Sd=jn(),{EMPTY_BUFFER:uy,kWebSocket:cy,NOOP:dy}=xt(),{isBlob:Nn,isValidStatusCode:hy}=On(),{mask:Td,toBuffer:Hr}=cs(),Ze=Symbol("kByteLength"),fy=Buffer.alloc(4),Ri=8*1024,Vr,Mn=Ri,Qe=0,py=1,my=2,Ra=class r{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Qe,this.onerror=dy,this[cy]=void 0}static frame(e,t){let n,s=!1,i=2,o=!1;t.mask&&(n=t.maskBuffer||fy,t.generateMask?t.generateMask(n):(Mn===Ri&&(Vr===void 0&&(Vr=Buffer.alloc(Ri)),ay(Vr,0,Ri),Mn=0),n[0]=Vr[Mn++],n[1]=Vr[Mn++],n[2]=Vr[Mn++],n[3]=Vr[Mn++]),o=(n[0]|n[1]|n[2]|n[3])===0,i=6);let a;typeof e=="string"?(!t.mask||o)&&t[Ze]!==void 0?a=t[Ze]:(e=Buffer.from(e),a=e.length):(a=e.length,s=t.mask&&t.readOnly&&!o);let u=a;a>=65536?(i+=8,u=127):a>125&&(i+=2,u=126);let c=Buffer.allocUnsafe(s?a+i:i);return c[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(c[0]|=64),c[1]=u,u===126?c.writeUInt16BE(a,2):u===127&&(c[2]=c[3]=0,c.writeUIntBE(a,4,6)),t.mask?(c[1]|=128,c[i-4]=n[0],c[i-3]=n[1],c[i-2]=n[2],c[i-1]=n[3],o?[c,e]:s?(Td(e,n,c,i,a),[c]):(Td(e,n,e,0,a),[c,e])):[c,e]}close(e,t,n,s){let i;if(e===void 0)i=uy;else{if(typeof e!="number"||!hy(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(t);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");if(i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof t=="string")i.write(t,2);else if(ly(t))i.set(t,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[Ze]:i.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Qe?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(r.frame(i,o),s)}ping(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):Nn(e)?(s=e.size,i=!1):(e=Hr(e),s=e.length,i=Hr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Ze]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Nn(e)?this._state!==Qe?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==Qe?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(r.frame(e,o),n)}pong(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):Nn(e)?(s=e.size,i=!1):(e=Hr(e),s=e.length,i=Hr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Ze]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Nn(e)?this._state!==Qe?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==Qe?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(r.frame(e,o),n)}send(e,t,n){let s=this._extensions[Sd.extensionName],i=t.binary?2:1,o=t.compress,a,u;typeof e=="string"?(a=Buffer.byteLength(e),u=!1):Nn(e)?(a=e.size,u=!1):(e=Hr(e),a=e.length,u=Hr.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=s._threshold),this._compress=o):(o=!1,i=0),t.fin&&(this._firstFragment=!0);let c={[Ze]:a,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:u,rsv1:o};Nn(e)?this._state!==Qe?this.enqueue([this.getBlobData,e,this._compress,c,n]):this.getBlobData(e,this._compress,c,n):this._state!==Qe?this.enqueue([this.dispatch,e,this._compress,c,n]):this.dispatch(e,this._compress,c,n)}getBlobData(e,t,n,s){this._bufferedBytes+=n[Ze],this._state=my,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Ea,this,a,s);return}this._bufferedBytes-=n[Ze];let o=Hr(i);t?this.dispatch(o,t,n,s):(this._state=Qe,this.sendFrame(r.frame(o,n),s),this.dequeue())}).catch(i=>{process.nextTick(gy,this,i,s)})}dispatch(e,t,n,s){if(!t){this.sendFrame(r.frame(e,n),s);return}let i=this._extensions[Sd.extensionName];this._bufferedBytes+=n[Ze],this._state=py,i.compress(e,n.fin,(o,a)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");Ea(this,u,s);return}this._bufferedBytes-=n[Ze],this._state=Qe,n.readOnly=!1,this.sendFrame(r.frame(a,n),s),this.dequeue()})}dequeue(){for(;this._state===Qe&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Ze],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Ze],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};xd.exports=Ra;function Ea(r,e,t){typeof t=="function"&&t(e);for(let n=0;n<r._queue.length;n++){let s=r._queue[n],i=s[s.length-1];typeof i=="function"&&i(e)}}function gy(r,e,t){Ea(r,e,t),r.onerror(e)}});var Od=ee((b_,jd)=>{"use strict";var{kForOnEventAttribute:hs,kListener:$a}=xt(),Cd=Symbol("kCode"),Id=Symbol("kData"),Rd=Symbol("kError"),Ed=Symbol("kMessage"),Ad=Symbol("kReason"),zn=Symbol("kTarget"),$d=Symbol("kType"),Pd=Symbol("kWasClean"),It=class{constructor(e){this[zn]=null,this[$d]=e}get target(){return this[zn]}get type(){return this[$d]}};Object.defineProperty(It.prototype,"target",{enumerable:!0});Object.defineProperty(It.prototype,"type",{enumerable:!0});var Wr=class extends It{constructor(e,t={}){super(e),this[Cd]=t.code===void 0?0:t.code,this[Ad]=t.reason===void 0?"":t.reason,this[Pd]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Cd]}get reason(){return this[Ad]}get wasClean(){return this[Pd]}};Object.defineProperty(Wr.prototype,"code",{enumerable:!0});Object.defineProperty(Wr.prototype,"reason",{enumerable:!0});Object.defineProperty(Wr.prototype,"wasClean",{enumerable:!0});var Dn=class extends It{constructor(e,t={}){super(e),this[Rd]=t.error===void 0?null:t.error,this[Ed]=t.message===void 0?"":t.message}get error(){return this[Rd]}get message(){return this[Ed]}};Object.defineProperty(Dn.prototype,"error",{enumerable:!0});Object.defineProperty(Dn.prototype,"message",{enumerable:!0});var fs=class extends It{constructor(e,t={}){super(e),this[Id]=t.data===void 0?null:t.data}get data(){return this[Id]}};Object.defineProperty(fs.prototype,"data",{enumerable:!0});var yy={addEventListener(r,e,t={}){for(let s of this.listeners(r))if(!t[hs]&&s[$a]===e&&!s[hs])return;let n;if(r==="message")n=function(i,o){let a=new fs("message",{data:o?i:i.toString()});a[zn]=this,Ei(e,this,a)};else if(r==="close")n=function(i,o){let a=new Wr("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[zn]=this,Ei(e,this,a)};else if(r==="error")n=function(i){let o=new Dn("error",{error:i,message:i.message});o[zn]=this,Ei(e,this,o)};else if(r==="open")n=function(){let i=new It("open");i[zn]=this,Ei(e,this,i)};else return;n[hs]=!!t[hs],n[$a]=e,t.once?this.once(r,n):this.on(r,n)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[$a]===e&&!t[hs]){this.removeListener(r,t);break}}};jd.exports={CloseEvent:Wr,ErrorEvent:Dn,Event:It,EventTarget:yy,MessageEvent:fs};function Ei(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var Ai=ee((w_,Nd)=>{"use strict";var{tokenChars:ps}=On();function ct(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function vy(r){let e=Object.create(null),t=Object.create(null),n=!1,s=!1,i=!1,o,a,u=-1,c=-1,f=-1,p=0;for(;p<r.length;p++)if(c=r.charCodeAt(p),o===void 0)if(f===-1&&ps[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 S=r.slice(u,f);c===44?(ct(e,S,t),t=Object.create(null)):o=S,u=f=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(a===void 0)if(f===-1&&ps[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),ct(t,r.slice(u,f),!0),c===44&&(ct(e,o,t),t=Object.create(null),o=void 0),u=f=-1}else if(c===61&&u!==-1&&f===-1)a=r.slice(u,p),u=f=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(s){if(ps[c]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:n||(n=!0),s=!1}else if(i)if(ps[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&&r.charCodeAt(p-1)===61)i=!0;else if(f===-1&&ps[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 S=r.slice(u,f);n&&(S=S.replace(/\\/g,""),n=!1),ct(t,a,S),c===44&&(ct(e,o,t),t=Object.create(null),o=void 0),a=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 v=r.slice(u,f);return o===void 0?ct(e,v,t):(a===void 0?ct(t,v,!0):n?ct(t,a,v.replace(/\\/g,"")):ct(t,a,v),ct(e,o,t)),e}function by(r){return Object.keys(r).map(e=>{let t=r[e];return Array.isArray(t)||(t=[t]),t.map(n=>[e].concat(Object.keys(n).map(s=>{let i=n[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Nd.exports={format:by,parse:vy}});var Oi=ee((S_,Hd)=>{"use strict";var wy=require("events"),_y=require("https"),ky=require("http"),Dd=require("net"),Sy=require("tls"),{randomBytes:Ty,createHash:xy}=require("crypto"),{Duplex:__,Readable:k_}=require("stream"),{URL:Pa}=require("url"),Zt=jn(),Cy=Ia(),Iy=Aa(),{isBlob:Ry}=On(),{BINARY_TYPES:Md,CLOSE_TIMEOUT:Ey,EMPTY_BUFFER:$i,GUID:Ay,kForOnEventAttribute:ja,kListener:$y,kStatusCode:Py,kWebSocket:ge,NOOP:Ld}=xt(),{EventTarget:{addEventListener:jy,removeEventListener:Oy}}=Od(),{format:Ny,parse:My}=Ai(),{toBuffer:zy}=cs(),Ud=Symbol("kAborted"),Oa=[8,13],Rt=["CONNECTING","OPEN","CLOSING","CLOSED"],Dy=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ue=class r extends wy{constructor(e,t,n){super(),this._binaryType=Md[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=$i,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=r.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(n=t,t=[]):t=[t]),qd(this,e,t,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Md.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,n){let s=new Cy({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:n.maxBufferedChunks,maxFragments:n.maxFragments,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),i=new Iy(e,this._extensions,n.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[ge]=this,i[ge]=this,e[ge]=this,s.on("conclude",qy),s.on("drain",Fy),s.on("error",By),s.on("message",Ky),s.on("ping",Zy),s.on("pong",Gy),i.onerror=Hy,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Kd),e.on("data",ji),e.on("end",Zd),e.on("error",Gd),this._readyState=r.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Zt.extensionName]&&this._extensions[Zt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){Ne(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===r.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=r.CLOSING,this._sender.close(e,t,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Bd(this)}}pause(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Na(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||$i,t,n)}pong(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Na(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||$i,t,n)}resume(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(n=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Na(this,e,n);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Zt.extensionName]||(s.compress=!1),this._sender.send(e||$i,s,n)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){Ne(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(ue,"CONNECTING",{enumerable:!0,value:Rt.indexOf("CONNECTING")});Object.defineProperty(ue.prototype,"CONNECTING",{enumerable:!0,value:Rt.indexOf("CONNECTING")});Object.defineProperty(ue,"OPEN",{enumerable:!0,value:Rt.indexOf("OPEN")});Object.defineProperty(ue.prototype,"OPEN",{enumerable:!0,value:Rt.indexOf("OPEN")});Object.defineProperty(ue,"CLOSING",{enumerable:!0,value:Rt.indexOf("CLOSING")});Object.defineProperty(ue.prototype,"CLOSING",{enumerable:!0,value:Rt.indexOf("CLOSING")});Object.defineProperty(ue,"CLOSED",{enumerable:!0,value:Rt.indexOf("CLOSED")});Object.defineProperty(ue.prototype,"CLOSED",{enumerable:!0,value:Rt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(ue.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(ue.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[ja])return e[$y];return null},set(e){for(let t of this.listeners(r))if(t[ja]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[ja]:!0})}})});ue.prototype.addEventListener=jy;ue.prototype.removeEventListener=Oy;Hd.exports=ue;function qd(r,e,t,n){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Ey,protocolVersion:Oa[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(r._autoPong=s.autoPong,r._closeTimeout=s.closeTimeout,!Oa.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Oa.join(", ")})`);let i;if(e instanceof Pa)i=e;else try{i=new Pa(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),r._url=i.href;let o=i.protocol==="wss:",a=i.protocol==="ws+unix:",u;if(i.protocol!=="ws:"&&!o&&!a?u=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!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(r._redirects===0)throw x;Pi(r,x);return}let c=o?443:80,f=Ty(16).toString("base64"),p=o?_y.request:ky.request,v=new Set,S;if(s.createConnection=s.createConnection||(o?Uy:Ly),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&&(S=new Zt({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=Ny({[Zt.extensionName]:S.offer()})),t.length){for(let x of t){if(typeof x!="string"||!Dy.test(x)||v.has(x))throw new SyntaxError("An invalid or duplicated subprotocol was specified");v.add(x)}s.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){let x=s.path.split(":");s.socketPath=x[0],s.path=x[1]}let T;if(s.followRedirects){if(r._redirects===0){r._originalIpc=a,r._originalSecure=o,r._originalHostOrSocketPath=a?s.socketPath:i.host;let x=n&&n.headers;if(n={...n,headers:{}},x)for(let[P,_]of Object.entries(x))n.headers[P.toLowerCase()]=_}else if(r.listenerCount("redirect")===0){let x=a?r._originalIpc?s.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:i.host===r._originalHostOrSocketPath;(!x||r._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,x||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),T=r._req=p(s),r._redirects&&r.emit("redirect",r.url,T)}else T=r._req=p(s);s.timeout&&T.on("timeout",()=>{Ne(r,T,"Opening handshake has timed out")}),T.on("error",x=>{T===null||T[Ud]||(T=r._req=null,Pi(r,x))}),T.on("response",x=>{let P=x.headers.location,_=x.statusCode;if(P&&s.followRedirects&&_>=300&&_<400){if(++r._redirects>s.maxRedirects){Ne(r,T,"Maximum redirects exceeded");return}T.abort();let J;try{J=new Pa(P,e)}catch{let L=new SyntaxError(`Invalid URL: ${P}`);Pi(r,L);return}qd(r,J,t,n)}else r.emit("unexpected-response",T,x)||Ne(r,T,`Unexpected server response: ${x.statusCode}`)}),T.on("upgrade",(x,P,_)=>{if(r.emit("upgrade",x),r.readyState!==ue.CONNECTING)return;T=r._req=null;let J=x.headers.upgrade;if(J===void 0||J.toLowerCase()!=="websocket"){Ne(r,P,"Invalid Upgrade header");return}let O=xy("sha1").update(f+Ay).digest("base64");if(x.headers["sec-websocket-accept"]!==O){Ne(r,P,"Invalid Sec-WebSocket-Accept header");return}let L=x.headers["sec-websocket-protocol"],Q;if(L!==void 0?v.size?v.has(L)||(Q="Server sent an invalid subprotocol"):Q="Server sent a subprotocol but none was requested":v.size&&(Q="Server sent no subprotocol"),Q){Ne(r,P,Q);return}L&&(r._protocol=L);let h=x.headers["sec-websocket-extensions"];if(h!==void 0){if(!S){Ne(r,P,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let m;try{m=My(h)}catch{Ne(r,P,"Invalid Sec-WebSocket-Extensions header");return}let y=Object.keys(m);if(y.length!==1||y[0]!==Zt.extensionName){Ne(r,P,"Server indicated an extension that was not requested");return}try{S.accept(m[Zt.extensionName])}catch{Ne(r,P,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[Zt.extensionName]=S}r.setSocket(P,_,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(T,r):T.end()}function Pi(r,e){r._readyState=ue.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function Ly(r){return r.path=r.socketPath,Dd.connect(r)}function Uy(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=Dd.isIP(r.host)?"":r.host),Sy.connect(r)}function Ne(r,e,t){r._readyState=ue.CLOSING;let n=new Error(t);Error.captureStackTrace(n,Ne),e.setHeader?(e[Ud]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Pi,r,n)):(e.destroy(n),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function Na(r,e,t){if(e){let n=Ry(e)?e.size:zy(e).length;r._socket?r._sender._bufferedBytes+=n:r._bufferedAmount+=n}if(t){let n=new Error(`WebSocket is not open: readyState ${r.readyState} (${Rt[r.readyState]})`);process.nextTick(t,n)}}function qy(r,e){let t=this[ge];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[ge]!==void 0&&(t._socket.removeListener("data",ji),process.nextTick(Fd,t._socket),r===1005?t.close():t.close(r,e))}function Fy(){let r=this[ge];r.isPaused||r._socket.resume()}function By(r){let e=this[ge];e._socket[ge]!==void 0&&(e._socket.removeListener("data",ji),process.nextTick(Fd,e._socket),e.close(r[Py])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function zd(){this[ge].emitClose()}function Ky(r,e){this[ge].emit("message",r,e)}function Zy(r){let e=this[ge];e._autoPong&&e.pong(r,!this._isServer,Ld),e.emit("ping",r)}function Gy(r){this[ge].emit("pong",r)}function Fd(r){r.resume()}function Hy(r){let e=this[ge];e.readyState!==ue.CLOSED&&(e.readyState===ue.OPEN&&(e._readyState=ue.CLOSING,Bd(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function Bd(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),r._closeTimeout)}function Kd(){let r=this[ge];if(this.removeListener("close",Kd),this.removeListener("data",ji),this.removeListener("end",Zd),r._readyState=ue.CLOSING,!this._readableState.endEmitted&&!r._closeFrameReceived&&!r._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);r._receiver.write(e)}r._receiver.end(),this[ge]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",zd),r._receiver.on("finish",zd))}function ji(r){this[ge]._receiver.write(r)||this.pause()}function Zd(){let r=this[ge];r._readyState=ue.CLOSING,r._receiver.end(),this.end()}function Gd(){let r=this[ge];this.removeListener("error",Gd),this.on("error",Ld),r&&(r._readyState=ue.CLOSING,this.destroy())}});var Yd=ee((x_,Jd)=>{"use strict";var T_=Oi(),{Duplex:Vy}=require("stream");function Vd(r){r.emit("close")}function Wy(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Wd(r){this.removeListener("error",Wd),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function Jy(r,e){let t=!0,n=new Vy({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(i,o){let a=!o&&n._readableState.objectMode?i.toString():i;n.push(a)||r.pause()}),r.once("error",function(i){n.destroyed||(t=!1,n.destroy(i))}),r.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(s,i){if(r.readyState===r.CLOSED){i(s),process.nextTick(Vd,n);return}let o=!1;r.once("error",function(u){o=!0,i(u)}),r.once("close",function(){o||i(s),process.nextTick(Vd,n)}),t&&r.terminate()},n._final=function(s){if(r.readyState===r.CONNECTING){r.once("open",function(){n._final(s)});return}r._socket!==null&&(r._socket._writableState.finished?(s(),n._readableState.endEmitted&&n.destroy()):(r._socket.once("finish",function(){s()}),r.close()))},n._read=function(){r.isPaused&&r.resume()},n._write=function(s,i,o){if(r.readyState===r.CONNECTING){r.once("open",function(){n._write(s,i,o)});return}r.send(s,o)},n.on("end",Wy),n.on("error",Wd),n}Jd.exports=Jy});var Ma=ee((C_,Xd)=>{"use strict";var{tokenChars:Yy}=On();function Xy(r){let e=new Set,t=-1,n=-1,s=0;for(s;s<r.length;s++){let o=r.charCodeAt(s);if(n===-1&&Yy[o]===1)t===-1&&(t=s);else if(s!==0&&(o===32||o===9))n===-1&&t!==-1&&(n=s);else if(o===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${s}`);n===-1&&(n=s);let a=r.slice(t,n);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),t=n=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(t===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let i=r.slice(t,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}Xd.exports={parse:Xy}});var ih=ee((R_,sh)=>{"use strict";var Qy=require("events"),Ni=require("http"),{Duplex:I_}=require("stream"),{createHash:ev}=require("crypto"),Qd=Ai(),Jr=jn(),tv=Ma(),rv=Oi(),{CLOSE_TIMEOUT:nv,GUID:sv,kWebSocket:iv}=xt(),ov=/^[+/0-9A-Za-z]{22}==$/,eh=0,th=1,nh=2,za=class extends Qy{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:nv,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:rv,...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=Ni.createServer((n,s)=>{let i=Ni.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=av(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=eh}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===nh){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(ms,this);return}if(e&&this.once("close",e),this._state!==th)if(this._state=th,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(ms,this):process.nextTick(ms,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{ms(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,s){t.on("error",rh);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Yr(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Yr(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!ov.test(i)){Yr(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Yr(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){gs(t,400);return}let u=e.headers["sec-websocket-protocol"],c=new Set;if(u!==void 0)try{c=tv.parse(u)}catch{Yr(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let f=e.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&f!==void 0){let v=new Jr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let S=Qd.parse(f);S[Jr.extensionName]&&(v.accept(S[Jr.extensionName]),p[Jr.extensionName]=v)}catch{Yr(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let v={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(v,(S,T,x,P)=>{if(!S)return gs(t,T||401,x,P);this.completeUpgrade(p,i,c,e,t,n,s)});return}if(!this.options.verifyClient(v))return gs(t,401)}this.completeUpgrade(p,i,c,e,t,n,s)}completeUpgrade(e,t,n,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[iv])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>eh)return gs(i,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${ev("sha1").update(t+sv).digest("base64")}`],f=new this.options.WebSocket(null,void 0,this.options);if(n.size){let p=this.options.handleProtocols?this.options.handleProtocols(n,s):n.values().next().value;p&&(c.push(`Sec-WebSocket-Protocol: ${p}`),f._protocol=p)}if(e[Jr.extensionName]){let p=e[Jr.extensionName].params,v=Qd.format({[Jr.extensionName]:[p]});c.push(`Sec-WebSocket-Extensions: ${v}`),f._extensions=e}this.emit("headers",c,s),i.write(c.concat(`\r
|
|
253
255
|
`).join(`\r
|
|
254
|
-
`)),i.removeListener("error",
|
|
256
|
+
`)),i.removeListener("error",rh),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(ms,this)})),a(f,s)}};sh.exports=za;function av(r,e){for(let t of Object.keys(e))r.on(t,e[t]);return function(){for(let n of Object.keys(e))r.removeListener(n,e[n])}}function ms(r){r._state=nh,r.emit("close")}function rh(){this.destroy()}function gs(r,e,t,n){t=t||Ni.STATUS_CODES[e],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...n},r.once("finish",r.destroy),r.end(`HTTP/1.1 ${e} ${Ni.STATUS_CODES[e]}\r
|
|
255
257
|
`+Object.keys(n).map(s=>`${s}: ${n[s]}`).join(`\r
|
|
256
258
|
`)+`\r
|
|
257
259
|
\r
|
|
258
|
-
`+t)}function Zr(r,e,t,n,s,i){if(r.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,Zr),r.emit("wsClientError",o,t,e)}else as(t,n,s,i)}});var oh={};ps(oh,{buildSetupReport:()=>gv,claudeLoggedIn:()=>ih,repoDefaultBranch:()=>sh});function sh(r){let e=(...s)=>{try{return(0,ji.execFileSync)("git",["-C",r,...s],{encoding:"utf8",timeout:1e4}).trim()}catch{return null}},t=e("symbolic-ref","--short","refs/remotes/origin/HEAD");if(t?.startsWith("origin/"))return t.slice(7);let n=e("rev-parse","--abbrev-ref","HEAD");return n&&n!=="HEAD"?n:""}function ih(r=rh.default.homedir()){if(Kt.default.existsSync(Vr.default.join(r,".claude",".credentials.json")))return!0;try{return!!JSON.parse(Kt.default.readFileSync(Vr.default.join(r,".claude.json"),"utf8")).oauthAccount}catch{return!1}}async function gv(r,e){let t=!1,n="";if(cs&&Date.now()-cs.at<6e4)t=cs.installed,n=cs.version;else{try{let{stdout:o}=await mv(r.claudeBin,["--version"],{timeout:1e4});t=!0,n=o.trim().slice(0,60)}catch{t=!1}cs={at:Date.now(),installed:t,version:n}}let s=e.map(o=>{let a=r.repos[o];if(!a)return{repoName:o,mapped:!1,pathExists:!1,isGit:!1,claudeMd:!1,deployMd:!1,testMd:!1,githubToken:!1,githubTokenOwn:!1,defaultBranch:""};let l=Kt.default.existsSync(a.path);return{repoName:o,mapped:!0,pathExists:l,isGit:l&&Kt.default.existsSync(Vr.default.join(a.path,".git")),claudeMd:l&&Kt.default.existsSync(Vr.default.join(a.path,"CLAUDE.md")),deployMd:l&&Kt.default.existsSync(Vr.default.join(a.path,"DEPLOY.md")),testMd:l&&Kt.default.existsSync(Vr.default.join(a.path,"TEST.md")),githubToken:!!qe(r,o),githubTokenOwn:!!a.github?.token,defaultBranch:l?sh(a.path):""}}),i=Object.values(r.repos).find(o=>o.github?.token);return{jiraConfigured:!!r.jira,jiraEmail:r.jira?.email??"",claude:{installed:t,version:n,loggedIn:ih()},githubTokenSet:!!(r.github?.token||i),githubLogin:r.github?.login??i?.github?.login??"",deploysEnabled:r.deploy.enabled,jiraUserCount:Object.keys(r.jiraUsers).length,repos:s}}var ji,Kt,rh,Vr,nh,mv,cs,ah=fs(()=>{"use strict";ji=require("node:child_process"),Kt=R(require("node:fs"),1),rh=R(require("node:os"),1),Vr=R(require("node:path"),1),nh=require("node:util");Ir();mv=(0,nh.promisify)(ji.execFile);cs=null});var Ct=R(require("node:fs"),1),uh=R(require("node:os"),1),ds=R(require("node:path"),1),Et=require("node:child_process"),Oi=require("node:crypto"),Hr=R(require("node:readline/promises"),1);var Xa=R(Ya(),1),{program:Cv,createCommand:Ev,createArgument:Iv,createOption:Rv,CommanderError:Av,InvalidArgumentError:$v,InvalidOptionArgumentError:Pv,Command:Qa,Argument:jv,Option:Ov,Help:Nv}=Xa.default;var pt=R(require("node:fs"),1),ks=R(require("node:os"),1),Ss=R(require("node:path"),1);var _={};ps(_,{BRAND:()=>nf,DIRTY:()=>Zt,EMPTY_PATH:()=>Nh,INVALID:()=>L,NEVER:()=>Ff,OK:()=>we,ParseStatus:()=>ye,Schema:()=>H,ZodAny:()=>At,ZodArray:()=>ft,ZodBigInt:()=>Vt,ZodBoolean:()=>Ht,ZodBranded:()=>zn,ZodCatch:()=>ir,ZodDate:()=>Wt,ZodDefault:()=>sr,ZodDiscriminatedUnion:()=>bs,ZodEffects:()=>ze,ZodEnum:()=>rr,ZodError:()=>xe,ZodFirstPartyTypeKind:()=>U,ZodFunction:()=>_s,ZodIntersection:()=>Qt,ZodIssueCode:()=>E,ZodLazy:()=>er,ZodLiteral:()=>tr,ZodMap:()=>en,ZodNaN:()=>rn,ZodNativeEnum:()=>nr,ZodNever:()=>Ge,ZodNull:()=>Yt,ZodNullable:()=>et,ZodNumber:()=>Gt,ZodObject:()=>Ce,ZodOptional:()=>Ne,ZodParsedType:()=>P,ZodPipeline:()=>Dn,ZodPromise:()=>$t,ZodReadonly:()=>or,ZodRecord:()=>ws,ZodSchema:()=>H,ZodSet:()=>tn,ZodString:()=>Rt,ZodSymbol:()=>Xr,ZodTransformer:()=>ze,ZodTuple:()=>Qe,ZodType:()=>H,ZodUndefined:()=>Jt,ZodUnion:()=>Xt,ZodUnknown:()=>ht,ZodVoid:()=>Qr,addIssueToContext:()=>$,any:()=>ff,array:()=>yf,bigint:()=>uf,boolean:()=>cu,coerce:()=>qf,custom:()=>au,date:()=>lf,datetimeRegex:()=>iu,defaultErrorMap:()=>ct,discriminatedUnion:()=>_f,effect:()=>jf,enum:()=>Af,function:()=>Ef,getErrorMap:()=>Wr,getParsedType:()=>Xe,instanceof:()=>of,intersection:()=>kf,isAborted:()=>ys,isAsync:()=>Jr,isDirty:()=>vs,isValid:()=>It,late:()=>sf,lazy:()=>If,literal:()=>Rf,makeIssue:()=>Mn,map:()=>xf,nan:()=>af,nativeEnum:()=>$f,never:()=>mf,null:()=>hf,nullable:()=>Nf,number:()=>lu,object:()=>vf,objectUtil:()=>Xi,oboolean:()=>Uf,onumber:()=>Lf,optional:()=>Of,ostring:()=>Df,pipeline:()=>zf,preprocess:()=>Mf,promise:()=>Pf,quotelessJson:()=>Ph,record:()=>Tf,set:()=>Cf,setErrorMap:()=>Oh,strictObject:()=>bf,string:()=>uu,symbol:()=>cf,transformer:()=>jf,tuple:()=>Sf,undefined:()=>df,union:()=>wf,unknown:()=>pf,util:()=>X,void:()=>gf});var X;(function(r){r.assertEqual=s=>{};function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},r.getValidEnumValues=s=>{let i=r.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),o={};for(let a of i)o[a]=s[a];return r.objectValues(o)},r.objectValues=s=>r.objectKeys(s).map(function(i){return s[i]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},r.find=(s,i)=>{for(let o of s)if(i(o))return o},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}r.joinValues=n,r.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(X||(X={}));var Xi;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(Xi||(Xi={}));var P=X.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Xe=r=>{switch(typeof r){case"undefined":return P.undefined;case"string":return P.string;case"number":return Number.isNaN(r)?P.nan:P.number;case"boolean":return P.boolean;case"function":return P.function;case"bigint":return P.bigint;case"symbol":return P.symbol;case"object":return Array.isArray(r)?P.array:r===null?P.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?P.promise:typeof Map<"u"&&r instanceof Map?P.map:typeof Set<"u"&&r instanceof Set?P.set:typeof Date<"u"&&r instanceof Date?P.date:P.object;default:return P.unknown}};var E=X.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"]),Ph=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),xe=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},n={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)n._errors.push(t(o));else{let a=n,l=0;for(;l<o.path.length;){let c=o.path[l];l===o.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(t(o))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return s(this),n}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,X.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},n=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];t[i]=t[i]||[],t[i].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};xe.create=r=>new xe(r);var jh=(r,e)=>{let t;switch(r.code){case E.invalid_type:r.received===P.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case E.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,X.jsonStringifyReplacer)}`;break;case E.unrecognized_keys:t=`Unrecognized key(s) in object: ${X.joinValues(r.keys,", ")}`;break;case E.invalid_union:t="Invalid input";break;case E.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${X.joinValues(r.options)}`;break;case E.invalid_enum_value:t=`Invalid enum value. Expected ${X.joinValues(r.options)}, received '${r.received}'`;break;case E.invalid_arguments:t="Invalid function arguments";break;case E.invalid_return_type:t="Invalid function return type";break;case E.invalid_date:t="Invalid date";break;case E.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:X.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case E.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case E.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case E.custom:t="Invalid input";break;case E.invalid_intersection_types:t="Intersection results could not be merged";break;case E.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case E.not_finite:t="Number must be finite";break;default:t=e.defaultError,X.assertNever(r)}return{message:t}},ct=jh;var eu=ct;function Oh(r){eu=r}function Wr(){return eu}var Mn=r=>{let{data:e,path:t,errorMaps:n,issueData:s}=r,i=[...t,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let a="",l=n.filter(c=>!!c).slice().reverse();for(let c of l)a=c(o,{data:e,defaultError:a}).message;return{...s,path:i,message:a}},Nh=[];function $(r,e){let t=Wr(),n=Mn({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===ct?void 0:ct].filter(s=>!!s)});r.common.issues.push(n)}var ye=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let s of t){if(s.status==="aborted")return L;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let s of t){let i=await s.key,o=await s.value;n.push({key:i,value:o})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let s of t){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return L;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(n[i.value]=o.value)}return{status:e.value,value:n}}},L=Object.freeze({status:"aborted"}),Zt=r=>({status:"dirty",value:r}),we=r=>({status:"valid",value:r}),ys=r=>r.status==="aborted",vs=r=>r.status==="dirty",It=r=>r.status==="valid",Jr=r=>typeof Promise<"u"&&r instanceof Promise;var O;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(O||(O={}));var Me=class{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},tu=(r,e)=>{if(It(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new xe(r.common.issues);return this._error=t,this._error}}};function K(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,a)=>{let{message:l}=r;return o.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??n??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:l??t??a.defaultError}},description:s}}var H=class{get description(){return this._def.description}_getType(e){return Xe(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Xe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ye,ctx:{common:e.parent.common,data:e.data,parsedType:Xe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Jr(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Xe(e)},s=this._parseSync({data:e,path:n.path,parent:n});return tu(n,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Xe(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return It(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>It(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Xe(e)},s=this._parse({data:e,path:n.path,parent:n}),i=await(Jr(s)?s:Promise.resolve(s));return tu(n,i)}refine(e,t){let n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,i)=>{let o=e(s),a=()=>i.addIssue({code:E.custom,...n(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new ze({schema:this,typeName:U.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return Ne.create(this,this._def)}nullable(){return et.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ft.create(this)}promise(){return $t.create(this,this._def)}or(e){return Xt.create([this,e],this._def)}and(e){return Qt.create(this,e,this._def)}transform(e){return new ze({...K(this._def),schema:this,typeName:U.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new sr({...K(this._def),innerType:this,defaultValue:t,typeName:U.ZodDefault})}brand(){return new zn({typeName:U.ZodBranded,type:this,...K(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new ir({...K(this._def),innerType:this,catchValue:t,typeName:U.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Dn.create(this,e)}readonly(){return or.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Mh=/^c[^\s-]{8,}$/i,zh=/^[0-9a-z]+$/,Dh=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Lh=/^[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,Uh=/^[a-z0-9_-]{21}$/i,qh=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Fh=/^[-+]?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)?)??$/,Bh=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Kh="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Qi,Zh=/^(?:(?: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])$/,Gh=/^(?:(?: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])$/,Vh=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Hh=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Wh=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Jh=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nu="((\\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])))",Yh=new RegExp(`^${nu}$`);function su(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Xh(r){return new RegExp(`^${su(r)}$`)}function iu(r){let e=`${nu}T${su(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Qh(r,e){return!!((e==="v4"||!e)&&Zh.test(r)||(e==="v6"||!e)&&Vh.test(r))}function ef(r,e){if(!qh.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function tf(r,e){return!!((e==="v4"||!e)&&Gh.test(r)||(e==="v6"||!e)&&Hh.test(r))}var Rt=class r extends H{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==P.string){let i=this._getOrReturnCtx(e);return $(i,{code:E.invalid_type,expected:P.string,received:i.parsedType}),L}let n=new ye,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),$(s,{code:E.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),$(s,{code:E.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(s=this._getOrReturnCtx(e,s),o?$(s,{code:E.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&$(s,{code:E.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")Bh.test(e.data)||(s=this._getOrReturnCtx(e,s),$(s,{validation:"email",code:E.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")Qi||(Qi=new RegExp(Kh,"u")),Qi.test(e.data)||(s=this._getOrReturnCtx(e,s),$(s,{validation:"emoji",code:E.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")Lh.test(e.data)||(s=this._getOrReturnCtx(e,s),$(s,{validation:"uuid",code:E.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")Uh.test(e.data)||(s=this._getOrReturnCtx(e,s),$(s,{validation:"nanoid",code:E.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")Mh.test(e.data)||(s=this._getOrReturnCtx(e,s),$(s,{validation:"cuid",code:E.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")zh.test(e.data)||(s=this._getOrReturnCtx(e,s),$(s,{validation:"cuid2",code:E.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")Dh.test(e.data)||(s=this._getOrReturnCtx(e,s),$(s,{validation:"ulid",code:E.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),$(s,{validation:"url",code:E.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),$(s,{validation:"regex",code:E.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),$(s,{code:E.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),$(s,{code:E.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),$(s,{code:E.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?iu(i).test(e.data)||(s=this._getOrReturnCtx(e,s),$(s,{code:E.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?Yh.test(e.data)||(s=this._getOrReturnCtx(e,s),$(s,{code:E.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?Xh(i).test(e.data)||(s=this._getOrReturnCtx(e,s),$(s,{code:E.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?Fh.test(e.data)||(s=this._getOrReturnCtx(e,s),$(s,{validation:"duration",code:E.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?Qh(e.data,i.version)||(s=this._getOrReturnCtx(e,s),$(s,{validation:"ip",code:E.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?ef(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),$(s,{validation:"jwt",code:E.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?tf(e.data,i.version)||(s=this._getOrReturnCtx(e,s),$(s,{validation:"cidr",code:E.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?Wh.test(e.data)||(s=this._getOrReturnCtx(e,s),$(s,{validation:"base64",code:E.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?Jh.test(e.data)||(s=this._getOrReturnCtx(e,s),$(s,{validation:"base64url",code:E.invalid_string,message:i.message}),n.dirty()):X.assertNever(i);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:E.invalid_string,...O.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...O.errToObj(e)})}url(e){return this._addCheck({kind:"url",...O.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...O.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...O.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...O.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...O.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...O.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...O.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...O.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...O.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...O.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...O.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...O.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...O.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...O.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...O.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...O.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...O.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...O.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...O.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...O.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...O.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...O.errToObj(t)})}nonempty(e){return this.min(1,O.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Rt.create=r=>new Rt({checks:[],typeName:U.ZodString,coerce:r?.coerce??!1,...K(r)});function rf(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,i=Number.parseInt(r.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var Gt=class r extends H{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==P.number){let i=this._getOrReturnCtx(e);return $(i,{code:E.invalid_type,expected:P.number,received:i.parsedType}),L}let n,s=new ye;for(let i of this._def.checks)i.kind==="int"?X.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),$(n,{code:E.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),$(n,{code:E.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),$(n,{code:E.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?rf(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),$(n,{code:E.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),$(n,{code:E.not_finite,message:i.message}),s.dirty()):X.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,O.toString(t))}gt(e,t){return this.setLimit("min",e,!1,O.toString(t))}lte(e,t){return this.setLimit("max",e,!0,O.toString(t))}lt(e,t){return this.setLimit("max",e,!1,O.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:O.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:O.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:O.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:O.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:O.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:O.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:O.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:O.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:O.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:O.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&X.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};Gt.create=r=>new Gt({checks:[],typeName:U.ZodNumber,coerce:r?.coerce||!1,...K(r)});var Vt=class r extends H{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==P.bigint)return this._getInvalidInput(e);let n,s=new ye;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),$(n,{code:E.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),$(n,{code:E.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),$(n,{code:E.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):X.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return $(t,{code:E.invalid_type,expected:P.bigint,received:t.parsedType}),L}gte(e,t){return this.setLimit("min",e,!0,O.toString(t))}gt(e,t){return this.setLimit("min",e,!1,O.toString(t))}lte(e,t){return this.setLimit("max",e,!0,O.toString(t))}lt(e,t){return this.setLimit("max",e,!1,O.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:O.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:O.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:O.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:O.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:O.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:O.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Vt.create=r=>new Vt({checks:[],typeName:U.ZodBigInt,coerce:r?.coerce??!1,...K(r)});var Ht=class extends H{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==P.boolean){let n=this._getOrReturnCtx(e);return $(n,{code:E.invalid_type,expected:P.boolean,received:n.parsedType}),L}return we(e.data)}};Ht.create=r=>new Ht({typeName:U.ZodBoolean,coerce:r?.coerce||!1,...K(r)});var Wt=class r extends H{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==P.date){let i=this._getOrReturnCtx(e);return $(i,{code:E.invalid_type,expected:P.date,received:i.parsedType}),L}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return $(i,{code:E.invalid_date}),L}let n=new ye,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),$(s,{code:E.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),$(s,{code:E.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):X.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:O.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:O.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};Wt.create=r=>new Wt({checks:[],coerce:r?.coerce||!1,typeName:U.ZodDate,...K(r)});var Xr=class extends H{_parse(e){if(this._getType(e)!==P.symbol){let n=this._getOrReturnCtx(e);return $(n,{code:E.invalid_type,expected:P.symbol,received:n.parsedType}),L}return we(e.data)}};Xr.create=r=>new Xr({typeName:U.ZodSymbol,...K(r)});var Jt=class extends H{_parse(e){if(this._getType(e)!==P.undefined){let n=this._getOrReturnCtx(e);return $(n,{code:E.invalid_type,expected:P.undefined,received:n.parsedType}),L}return we(e.data)}};Jt.create=r=>new Jt({typeName:U.ZodUndefined,...K(r)});var Yt=class extends H{_parse(e){if(this._getType(e)!==P.null){let n=this._getOrReturnCtx(e);return $(n,{code:E.invalid_type,expected:P.null,received:n.parsedType}),L}return we(e.data)}};Yt.create=r=>new Yt({typeName:U.ZodNull,...K(r)});var At=class extends H{constructor(){super(...arguments),this._any=!0}_parse(e){return we(e.data)}};At.create=r=>new At({typeName:U.ZodAny,...K(r)});var ht=class extends H{constructor(){super(...arguments),this._unknown=!0}_parse(e){return we(e.data)}};ht.create=r=>new ht({typeName:U.ZodUnknown,...K(r)});var Ge=class extends H{_parse(e){let t=this._getOrReturnCtx(e);return $(t,{code:E.invalid_type,expected:P.never,received:t.parsedType}),L}};Ge.create=r=>new Ge({typeName:U.ZodNever,...K(r)});var Qr=class extends H{_parse(e){if(this._getType(e)!==P.undefined){let n=this._getOrReturnCtx(e);return $(n,{code:E.invalid_type,expected:P.void,received:n.parsedType}),L}return we(e.data)}};Qr.create=r=>new Qr({typeName:U.ZodVoid,...K(r)});var ft=class r extends H{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==P.array)return $(t,{code:E.invalid_type,expected:P.array,received:t.parsedType}),L;if(s.exactLength!==null){let o=t.data.length>s.exactLength.value,a=t.data.length<s.exactLength.value;(o||a)&&($(t,{code:o?E.too_big:E.too_small,minimum:a?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&($(t,{code:E.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&($(t,{code:E.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>s.type._parseAsync(new Me(t,o,t.path,a)))).then(o=>ye.mergeArray(n,o));let i=[...t.data].map((o,a)=>s.type._parseSync(new Me(t,o,t.path,a)));return ye.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:O.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:O.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:O.toString(t)}})}nonempty(e){return this.min(1,e)}};ft.create=(r,e)=>new ft({type:r,minLength:null,maxLength:null,exactLength:null,typeName:U.ZodArray,...K(e)});function Yr(r){if(r instanceof Ce){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=Ne.create(Yr(n))}return new Ce({...r._def,shape:()=>e})}else return r instanceof ft?new ft({...r._def,type:Yr(r.element)}):r instanceof Ne?Ne.create(Yr(r.unwrap())):r instanceof et?et.create(Yr(r.unwrap())):r instanceof Qe?Qe.create(r.items.map(e=>Yr(e))):r}var Ce=class r extends H{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=X.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==P.object){let c=this._getOrReturnCtx(e);return $(c,{code:E.invalid_type,expected:P.object,received:c.parsedType}),L}let{status:n,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ge&&this._def.unknownKeys==="strip"))for(let c in s.data)o.includes(c)||a.push(c);let l=[];for(let c of o){let f=i[c],p=s.data[c];l.push({key:{status:"valid",value:c},value:f._parse(new Me(s,p,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof Ge){let c=this._def.unknownKeys;if(c==="passthrough")for(let f of a)l.push({key:{status:"valid",value:f},value:{status:"valid",value:s.data[f]}});else if(c==="strict")a.length>0&&($(s,{code:E.unrecognized_keys,keys:a}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let f of a){let p=s.data[f];l.push({key:{status:"valid",value:f},value:c._parse(new Me(s,p,s.path,f)),alwaysSet:f in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let c=[];for(let f of l){let p=await f.key,v=await f.value;c.push({key:p,value:v,alwaysSet:f.alwaysSet})}return c}).then(c=>ye.mergeObjectSync(n,c)):ye.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return O.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let s=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:O.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:U.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let n of X.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let n of X.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return Yr(this)}partial(e){let t={};for(let n of X.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let n of X.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof Ne;)i=i._def.innerType;t[n]=i}return new r({...this._def,shape:()=>t})}keyof(){return ou(X.objectKeys(this.shape))}};Ce.create=(r,e)=>new Ce({shape:()=>r,unknownKeys:"strip",catchall:Ge.create(),typeName:U.ZodObject,...K(e)});Ce.strictCreate=(r,e)=>new Ce({shape:()=>r,unknownKeys:"strict",catchall:Ge.create(),typeName:U.ZodObject,...K(e)});Ce.lazycreate=(r,e)=>new Ce({shape:r,unknownKeys:"strip",catchall:Ge.create(),typeName:U.ZodObject,...K(e)});var Xt=class extends H{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function s(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return t.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(a=>new xe(a.ctx.common.issues));return $(t,{code:E.invalid_union,unionErrors:o}),L}if(t.common.async)return Promise.all(n.map(async i=>{let o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let l of n){let c={...t,common:{...t.common,issues:[]},parent:null},f=l._parseSync({data:t.data,path:t.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 t.common.issues.push(...i.ctx.common.issues),i.result;let a=o.map(l=>new xe(l));return $(t,{code:E.invalid_union,unionErrors:a}),L}}get options(){return this._def.options}};Xt.create=(r,e)=>new Xt({options:r,typeName:U.ZodUnion,...K(e)});var dt=r=>r instanceof er?dt(r.schema):r instanceof ze?dt(r.innerType()):r instanceof tr?[r.value]:r instanceof rr?r.options:r instanceof nr?X.objectValues(r.enum):r instanceof sr?dt(r._def.innerType):r instanceof Jt?[void 0]:r instanceof Yt?[null]:r instanceof Ne?[void 0,...dt(r.unwrap())]:r instanceof et?[null,...dt(r.unwrap())]:r instanceof zn||r instanceof or?dt(r.unwrap()):r instanceof ir?dt(r._def.innerType):[],bs=class r extends H{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==P.object)return $(t,{code:E.invalid_type,expected:P.object,received:t.parsedType}),L;let n=this.discriminator,s=t.data[n],i=this.optionsMap.get(s);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):($(t,{code:E.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),L)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let s=new Map;for(let i of t){let o=dt(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of o){if(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,i)}}return new r({typeName:U.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...K(n)})}};function eo(r,e){let t=Xe(r),n=Xe(e);if(r===e)return{valid:!0,data:r};if(t===P.object&&n===P.object){let s=X.objectKeys(e),i=X.objectKeys(r).filter(a=>s.indexOf(a)!==-1),o={...r,...e};for(let a of i){let l=eo(r[a],e[a]);if(!l.valid)return{valid:!1};o[a]=l.data}return{valid:!0,data:o}}else if(t===P.array&&n===P.array){if(r.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<r.length;i++){let o=r[i],a=e[i],l=eo(o,a);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return t===P.date&&n===P.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var Qt=class extends H{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=(i,o)=>{if(ys(i)||ys(o))return L;let a=eo(i.value,o.value);return a.valid?((vs(i)||vs(o))&&t.dirty(),{status:t.value,value:a.data}):($(n,{code:E.invalid_intersection_types}),L)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Qt.create=(r,e,t)=>new Qt({left:r,right:e,typeName:U.ZodIntersection,...K(t)});var Qe=class r extends H{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==P.array)return $(n,{code:E.invalid_type,expected:P.array,received:n.parsedType}),L;if(n.data.length<this._def.items.length)return $(n,{code:E.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),L;!this._def.rest&&n.data.length>this._def.items.length&&($(n,{code:E.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...n.data].map((o,a)=>{let l=this._def.items[a]||this._def.rest;return l?l._parse(new Me(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(i).then(o=>ye.mergeArray(t,o)):ye.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};Qe.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Qe({items:r,typeName:U.ZodTuple,rest:null,...K(e)})};var ws=class r extends H{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==P.object)return $(n,{code:E.invalid_type,expected:P.object,received:n.parsedType}),L;let s=[],i=this._def.keyType,o=this._def.valueType;for(let a in n.data)s.push({key:i._parse(new Me(n,a,n.path,a)),value:o._parse(new Me(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?ye.mergeObjectAsync(t,s):ye.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof H?new r({keyType:e,valueType:t,typeName:U.ZodRecord,...K(n)}):new r({keyType:Rt.create(),valueType:e,typeName:U.ZodRecord,...K(t)})}},en=class extends H{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==P.map)return $(n,{code:E.invalid_type,expected:P.map,received:n.parsedType}),L;let s=this._def.keyType,i=this._def.valueType,o=[...n.data.entries()].map(([a,l],c)=>({key:s._parse(new Me(n,a,n.path,[c,"key"])),value:i._parse(new Me(n,l,n.path,[c,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let l of o){let c=await l.key,f=await l.value;if(c.status==="aborted"||f.status==="aborted")return L;(c.status==="dirty"||f.status==="dirty")&&t.dirty(),a.set(c.value,f.value)}return{status:t.value,value:a}})}else{let a=new Map;for(let l of o){let c=l.key,f=l.value;if(c.status==="aborted"||f.status==="aborted")return L;(c.status==="dirty"||f.status==="dirty")&&t.dirty(),a.set(c.value,f.value)}return{status:t.value,value:a}}}};en.create=(r,e,t)=>new en({valueType:e,keyType:r,typeName:U.ZodMap,...K(t)});var tn=class r extends H{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==P.set)return $(n,{code:E.invalid_type,expected:P.set,received:n.parsedType}),L;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&($(n,{code:E.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&($(n,{code:E.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let i=this._def.valueType;function o(l){let c=new Set;for(let f of l){if(f.status==="aborted")return L;f.status==="dirty"&&t.dirty(),c.add(f.value)}return{status:t.value,value:c}}let a=[...n.data.values()].map((l,c)=>i._parse(new Me(n,l,n.path,c)));return n.common.async?Promise.all(a).then(l=>o(l)):o(a)}min(e,t){return new r({...this._def,minSize:{value:e,message:O.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:O.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};tn.create=(r,e)=>new tn({valueType:r,minSize:null,maxSize:null,typeName:U.ZodSet,...K(e)});var _s=class r extends H{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==P.function)return $(t,{code:E.invalid_type,expected:P.function,received:t.parsedType}),L;function n(a,l){return Mn({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Wr(),ct].filter(c=>!!c),issueData:{code:E.invalid_arguments,argumentsError:l}})}function s(a,l){return Mn({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Wr(),ct].filter(c=>!!c),issueData:{code:E.invalid_return_type,returnTypeError:l}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof $t){let a=this;return we(async function(...l){let c=new xe([]),f=await a._def.args.parseAsync(l,i).catch(k=>{throw c.addIssue(n(l,k)),c}),p=await Reflect.apply(o,this,f);return await a._def.returns._def.type.parseAsync(p,i).catch(k=>{throw c.addIssue(s(p,k)),c})})}else{let a=this;return we(function(...l){let c=a._def.args.safeParse(l,i);if(!c.success)throw new xe([n(l,c.error)]);let f=Reflect.apply(o,this,c.data),p=a._def.returns.safeParse(f,i);if(!p.success)throw new xe([s(f,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:Qe.create(e).rest(ht.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||Qe.create([]).rest(ht.create()),returns:t||ht.create(),typeName:U.ZodFunction,...K(n)})}},er=class extends H{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};er.create=(r,e)=>new er({getter:r,typeName:U.ZodLazy,...K(e)});var tr=class extends H{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return $(t,{received:t.data,code:E.invalid_literal,expected:this._def.value}),L}return{status:"valid",value:e.data}}get value(){return this._def.value}};tr.create=(r,e)=>new tr({value:r,typeName:U.ZodLiteral,...K(e)});function ou(r,e){return new rr({values:r,typeName:U.ZodEnum,...K(e)})}var rr=class r extends H{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return $(t,{expected:X.joinValues(n),received:t.parsedType,code:E.invalid_type}),L}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return $(t,{received:t.data,code:E.invalid_enum_value,options:n}),L}return we(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};rr.create=ou;var nr=class extends H{_parse(e){let t=X.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==P.string&&n.parsedType!==P.number){let s=X.objectValues(t);return $(n,{expected:X.joinValues(s),received:n.parsedType,code:E.invalid_type}),L}if(this._cache||(this._cache=new Set(X.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=X.objectValues(t);return $(n,{received:n.data,code:E.invalid_enum_value,options:s}),L}return we(e.data)}get enum(){return this._def.values}};nr.create=(r,e)=>new nr({values:r,typeName:U.ZodNativeEnum,...K(e)});var $t=class extends H{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==P.promise&&t.common.async===!1)return $(t,{code:E.invalid_type,expected:P.promise,received:t.parsedType}),L;let n=t.parsedType===P.promise?t.data:Promise.resolve(t.data);return we(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};$t.create=(r,e)=>new $t({type:r,typeName:U.ZodPromise,...K(e)});var ze=class extends H{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===U.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{$(n,o),o.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(n.data,i);if(n.common.async)return Promise.resolve(o).then(async a=>{if(t.value==="aborted")return L;let l=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return l.status==="aborted"?L:l.status==="dirty"?Zt(l.value):t.value==="dirty"?Zt(l.value):l});{if(t.value==="aborted")return L;let a=this._def.schema._parseSync({data:o,path:n.path,parent:n});return a.status==="aborted"?L:a.status==="dirty"?Zt(a.value):t.value==="dirty"?Zt(a.value):a}}if(s.type==="refinement"){let o=a=>{let l=s.refinement(a,i);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?L:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?L:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.value,value:a.value}))))}if(s.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!It(o))return L;let a=s.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>It(o)?Promise.resolve(s.transform(o.value,i)).then(a=>({status:t.value,value:a})):L);X.assertNever(s)}};ze.create=(r,e,t)=>new ze({schema:r,typeName:U.ZodEffects,effect:e,...K(t)});ze.createWithPreprocess=(r,e,t)=>new ze({schema:e,effect:{type:"preprocess",transform:r},typeName:U.ZodEffects,...K(t)});var Ne=class extends H{_parse(e){return this._getType(e)===P.undefined?we(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ne.create=(r,e)=>new Ne({innerType:r,typeName:U.ZodOptional,...K(e)});var et=class extends H{_parse(e){return this._getType(e)===P.null?we(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};et.create=(r,e)=>new et({innerType:r,typeName:U.ZodNullable,...K(e)});var sr=class extends H{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===P.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};sr.create=(r,e)=>new sr({innerType:r,typeName:U.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...K(e)});var ir=class extends H{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Jr(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new xe(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new xe(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};ir.create=(r,e)=>new ir({innerType:r,typeName:U.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...K(e)});var rn=class extends H{_parse(e){if(this._getType(e)!==P.nan){let n=this._getOrReturnCtx(e);return $(n,{code:E.invalid_type,expected:P.nan,received:n.parsedType}),L}return{status:"valid",value:e.data}}};rn.create=r=>new rn({typeName:U.ZodNaN,...K(r)});var nf=Symbol("zod_brand"),zn=class extends H{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},Dn=class r extends H{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?L:i.status==="dirty"?(t.dirty(),Zt(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?L:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:U.ZodPipeline})}},or=class extends H{_parse(e){let t=this._def.innerType._parse(e),n=s=>(It(s)&&(s.value=Object.freeze(s.value)),s);return Jr(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}};or.create=(r,e)=>new or({innerType:r,typeName:U.ZodReadonly,...K(e)});function ru(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function au(r,e={},t){return r?At.create().superRefine((n,s)=>{let i=r(n);if(i instanceof Promise)return i.then(o=>{if(!o){let a=ru(e,n),l=a.fatal??t??!0;s.addIssue({code:"custom",...a,fatal:l})}});if(!i){let o=ru(e,n),a=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:a})}}):At.create()}var sf={object:Ce.lazycreate},U;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(U||(U={}));var of=(r,e={message:`Input not instance of ${r.name}`})=>au(t=>t instanceof r,e),uu=Rt.create,lu=Gt.create,af=rn.create,uf=Vt.create,cu=Ht.create,lf=Wt.create,cf=Xr.create,df=Jt.create,hf=Yt.create,ff=At.create,pf=ht.create,mf=Ge.create,gf=Qr.create,yf=ft.create,vf=Ce.create,bf=Ce.strictCreate,wf=Xt.create,_f=bs.create,kf=Qt.create,Sf=Qe.create,Tf=ws.create,xf=en.create,Cf=tn.create,Ef=_s.create,If=er.create,Rf=tr.create,Af=rr.create,$f=nr.create,Pf=$t.create,jf=ze.create,Of=Ne.create,Nf=et.create,Mf=ze.createWithPreprocess,zf=Dn.create,Df=()=>uu().optional(),Lf=()=>lu().optional(),Uf=()=>cu().optional(),qf={string:(r=>Rt.create({...r,coerce:!0})),number:(r=>Gt.create({...r,coerce:!0})),boolean:(r=>Ht.create({...r,coerce:!0})),bigint:(r=>Vt.create({...r,coerce:!0})),date:(r=>Wt.create({...r,coerce:!0}))};var Ff=L;var du=_.object({baseUrl:_.string().url(),email:_.string().email(),apiToken:_.string().min(1)}),to=_.object({controlPlaneUrl:_.string().url(),runnerId:_.string().optional(),runnerToken:_.string().optional(),runnerName:_.string().default(ks.default.hostname()),jira:du.optional(),repos:_.record(_.object({path:_.string(),jira:du.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 te(){let r=process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR;if(r)return r;let e=Ss.default.join(ks.default.homedir(),".config","allwright"),t=Ss.default.join(ks.default.homedir(),".config","ticketpilot");return!pt.default.existsSync(e)&&pt.default.existsSync(t)?t:e}function Pt(){return Ss.default.join(te(),"runner.json")}function pe(){let r=Pt();if(!pt.default.existsSync(r))return null;let e=JSON.parse(pt.default.readFileSync(r,"utf8"));return to.parse(e)}function he(r){let e=te();pt.default.mkdirSync(e,{recursive:!0,mode:448});let t=Pt(),n=t+".tmp";pt.default.writeFileSync(n,JSON.stringify(r,null,2)+`
|
|
259
|
-
`,{mode:384}),
|
|
260
|
-
`).filter(Boolean);for(let i of t)if(i.startsWith("/")||i.split("/").includes(".."))throw new Error(`refusing to import - unsafe path in archive: ${i}`);let n=te(),s;
|
|
260
|
+
`+t)}function Yr(r,e,t,n,s,i){if(r.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,Yr),r.emit("wsClientError",o,t,e)}else gs(t,n,s,i)}});var gh={};ks(gh,{buildSetupReport:()=>Cv,claudeLoggedIn:()=>mh,repoDefaultBranch:()=>ph});function ph(r){let e=(...s)=>{try{return(0,Ui.execFileSync)("git",["-C",r,...s],{encoding:"utf8",timeout:1e4}).trim()}catch{return null}},t=e("symbolic-ref","--short","refs/remotes/origin/HEAD");if(t?.startsWith("origin/"))return t.slice(7);let n=e("rev-parse","--abbrev-ref","HEAD");return n&&n!=="HEAD"?n:""}function mh(r=hh.default.homedir()){if(Gt.default.existsSync(Qr.default.join(r,".claude",".credentials.json")))return!0;try{return!!JSON.parse(Gt.default.readFileSync(Qr.default.join(r,".claude.json"),"utf8")).oauthAccount}catch{return!1}}async function Cv(r,e){let t=!1,n="";if(bs&&Date.now()-bs.at<6e4)t=bs.installed,n=bs.version;else{try{let{stdout:o}=await xv(r.claudeBin,["--version"],{timeout:1e4});t=!0,n=o.trim().slice(0,60)}catch{t=!1}bs={at:Date.now(),installed:t,version:n}}let s=e.map(o=>{let a=r.repos[o];if(!a)return{repoName:o,mapped:!1,pathExists:!1,isGit:!1,claudeMd:!1,deployMd:!1,testMd:!1,githubToken:!1,githubTokenOwn:!1,defaultBranch:""};let u=Gt.default.existsSync(a.path);return{repoName:o,mapped:!0,pathExists:u,isGit:u&&Gt.default.existsSync(Qr.default.join(a.path,".git")),claudeMd:u&&Gt.default.existsSync(Qr.default.join(a.path,"CLAUDE.md")),deployMd:u&&Gt.default.existsSync(Qr.default.join(a.path,"DEPLOY.md")),testMd:u&&Gt.default.existsSync(Qr.default.join(a.path,"TEST.md")),githubToken:!!Ae(r,o),githubTokenOwn:!!a.github?.token,defaultBranch:u?ph(a.path):""}}),i=Object.values(r.repos).find(o=>o.github?.token);return{jiraConfigured:!!r.jira,jiraEmail:r.jira?.email??"",claude:{installed:t,version:n,loggedIn:mh()},githubTokenSet:!!(r.github?.token||i),githubLogin:r.github?.login??i?.github?.login??"",deploysEnabled:r.deploy.enabled,jiraUserCount:Object.keys(r.jiraUsers).length,repos:s}}var Ui,Gt,hh,Qr,fh,xv,bs,yh=_s(()=>{"use strict";Ui=require("node:child_process"),Gt=E(require("node:fs"),1),hh=E(require("node:os"),1),Qr=E(require("node:path"),1),fh=require("node:util");Or();xv=(0,fh.promisify)(Ui.execFile);bs=null});var et=E(require("node:fs"),1),Fa=E(require("node:os"),1),Un=E(require("node:path"),1),Et=require("node:child_process"),qi=require("node:crypto"),en=E(require("node:readline/promises"),1);var al=E(ol(),1),{program:Mv,createCommand:zv,createArgument:Dv,createOption:Lv,CommanderError:Uv,InvalidArgumentError:qv,InvalidOptionArgumentError:Fv,Command:ll,Argument:Bv,Option:Kv,Help:Zv}=al.default;var yt=E(require("node:fs"),1),As=E(require("node:os"),1),$s=E(require("node:path"),1);var k={};ks(k,{BRAND:()=>ff,DIRTY:()=>Vt,EMPTY_PATH:()=>Kh,INVALID:()=>q,NEVER:()=>Yf,OK:()=>we,ParseStatus:()=>ve,Schema:()=>Y,ZodAny:()=>Pt,ZodArray:()=>gt,ZodBigInt:()=>Jt,ZodBoolean:()=>Yt,ZodBranded:()=>Zn,ZodCatch:()=>lr,ZodDate:()=>Xt,ZodDefault:()=>ar,ZodDiscriminatedUnion:()=>Is,ZodEffects:()=>Le,ZodEnum:()=>ir,ZodError:()=>xe,ZodFirstPartyTypeKind:()=>F,ZodFunction:()=>Es,ZodIntersection:()=>rr,ZodIssueCode:()=>I,ZodLazy:()=>nr,ZodLiteral:()=>sr,ZodMap:()=>an,ZodNaN:()=>un,ZodNativeEnum:()=>or,ZodNever:()=>Ge,ZodNull:()=>er,ZodNullable:()=>nt,ZodNumber:()=>Wt,ZodObject:()=>Ce,ZodOptional:()=>ze,ZodParsedType:()=>j,ZodPipeline:()=>Gn,ZodPromise:()=>jt,ZodReadonly:()=>ur,ZodRecord:()=>Rs,ZodSchema:()=>Y,ZodSet:()=>ln,ZodString:()=>$t,ZodSymbol:()=>sn,ZodTransformer:()=>Le,ZodTuple:()=>rt,ZodType:()=>Y,ZodUndefined:()=>Qt,ZodUnion:()=>tr,ZodUnknown:()=>mt,ZodVoid:()=>on,addIssueToContext:()=>$,any:()=>kf,array:()=>Cf,bigint:()=>yf,boolean:()=>bl,coerce:()=>Jf,custom:()=>gl,date:()=>vf,datetimeRegex:()=>pl,defaultErrorMap:()=>ft,discriminatedUnion:()=>Af,effect:()=>Ff,enum:()=>Lf,function:()=>Mf,getErrorMap:()=>tn,getParsedType:()=>tt,instanceof:()=>mf,intersection:()=>$f,isAborted:()=>xs,isAsync:()=>rn,isDirty:()=>Cs,isValid:()=>At,late:()=>pf,lazy:()=>zf,literal:()=>Df,makeIssue:()=>Kn,map:()=>Of,nan:()=>gf,nativeEnum:()=>Uf,never:()=>Tf,null:()=>_f,nullable:()=>Kf,number:()=>vl,object:()=>If,objectUtil:()=>so,oboolean:()=>Wf,onumber:()=>Vf,optional:()=>Bf,ostring:()=>Hf,pipeline:()=>Gf,preprocess:()=>Zf,promise:()=>qf,quotelessJson:()=>qh,record:()=>jf,set:()=>Nf,setErrorMap:()=>Bh,strictObject:()=>Rf,string:()=>yl,symbol:()=>bf,transformer:()=>Ff,tuple:()=>Pf,undefined:()=>wf,union:()=>Ef,unknown:()=>Sf,util:()=>X,void:()=>xf});var X;(function(r){r.assertEqual=s=>{};function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},r.getValidEnumValues=s=>{let i=r.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),o={};for(let a of i)o[a]=s[a];return r.objectValues(o)},r.objectValues=s=>r.objectKeys(s).map(function(i){return s[i]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},r.find=(s,i)=>{for(let o of s)if(i(o))return o},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}r.joinValues=n,r.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(X||(X={}));var so;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(so||(so={}));var j=X.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),tt=r=>{switch(typeof r){case"undefined":return j.undefined;case"string":return j.string;case"number":return Number.isNaN(r)?j.nan:j.number;case"boolean":return j.boolean;case"function":return j.function;case"bigint":return j.bigint;case"symbol":return j.symbol;case"object":return Array.isArray(r)?j.array:r===null?j.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?j.promise:typeof Map<"u"&&r instanceof Map?j.map:typeof Set<"u"&&r instanceof Set?j.set:typeof Date<"u"&&r instanceof Date?j.date:j.object;default:return j.unknown}};var I=X.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"]),qh=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),xe=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},n={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)n._errors.push(t(o));else{let a=n,u=0;for(;u<o.path.length;){let c=o.path[u];u===o.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(t(o))):a[c]=a[c]||{_errors:[]},a=a[c],u++}}};return s(this),n}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,X.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},n=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];t[i]=t[i]||[],t[i].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};xe.create=r=>new xe(r);var Fh=(r,e)=>{let t;switch(r.code){case I.invalid_type:r.received===j.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case I.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,X.jsonStringifyReplacer)}`;break;case I.unrecognized_keys:t=`Unrecognized key(s) in object: ${X.joinValues(r.keys,", ")}`;break;case I.invalid_union:t="Invalid input";break;case I.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${X.joinValues(r.options)}`;break;case I.invalid_enum_value:t=`Invalid enum value. Expected ${X.joinValues(r.options)}, received '${r.received}'`;break;case I.invalid_arguments:t="Invalid function arguments";break;case I.invalid_return_type:t="Invalid function return type";break;case I.invalid_date:t="Invalid date";break;case I.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:X.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case I.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case I.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case I.custom:t="Invalid input";break;case I.invalid_intersection_types:t="Intersection results could not be merged";break;case I.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case I.not_finite:t="Number must be finite";break;default:t=e.defaultError,X.assertNever(r)}return{message:t}},ft=Fh;var ul=ft;function Bh(r){ul=r}function tn(){return ul}var Kn=r=>{let{data:e,path:t,errorMaps:n,issueData:s}=r,i=[...t,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let a="",u=n.filter(c=>!!c).slice().reverse();for(let c of u)a=c(o,{data:e,defaultError:a}).message;return{...s,path:i,message:a}},Kh=[];function $(r,e){let t=tn(),n=Kn({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===ft?void 0:ft].filter(s=>!!s)});r.common.issues.push(n)}var ve=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let s of t){if(s.status==="aborted")return q;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let s of t){let i=await s.key,o=await s.value;n.push({key:i,value:o})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let s of t){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return q;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(n[i.value]=o.value)}return{status:e.value,value:n}}},q=Object.freeze({status:"aborted"}),Vt=r=>({status:"dirty",value:r}),we=r=>({status:"valid",value:r}),xs=r=>r.status==="aborted",Cs=r=>r.status==="dirty",At=r=>r.status==="valid",rn=r=>typeof Promise<"u"&&r instanceof Promise;var N;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(N||(N={}));var De=class{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},cl=(r,e)=>{if(At(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new xe(r.common.issues);return this._error=t,this._error}}};function Z(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,a)=>{let{message:u}=r;return o.code==="invalid_enum_value"?{message:u??a.defaultError}:typeof a.data>"u"?{message:u??n??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:u??t??a.defaultError}},description:s}}var Y=class{get description(){return this._def.description}_getType(e){return tt(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:tt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ve,ctx:{common:e.parent.common,data:e.data,parsedType:tt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(rn(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:tt(e)},s=this._parseSync({data:e,path:n.path,parent:n});return cl(n,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:tt(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return At(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>At(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:tt(e)},s=this._parse({data:e,path:n.path,parent:n}),i=await(rn(s)?s:Promise.resolve(s));return cl(n,i)}refine(e,t){let n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,i)=>{let o=e(s),a=()=>i.addIssue({code:I.custom,...n(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(u=>u?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new Le({schema:this,typeName:F.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return ze.create(this,this._def)}nullable(){return nt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return gt.create(this)}promise(){return jt.create(this,this._def)}or(e){return tr.create([this,e],this._def)}and(e){return rr.create(this,e,this._def)}transform(e){return new Le({...Z(this._def),schema:this,typeName:F.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new ar({...Z(this._def),innerType:this,defaultValue:t,typeName:F.ZodDefault})}brand(){return new Zn({typeName:F.ZodBranded,type:this,...Z(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new lr({...Z(this._def),innerType:this,catchValue:t,typeName:F.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Gn.create(this,e)}readonly(){return ur.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Zh=/^c[^\s-]{8,}$/i,Gh=/^[0-9a-z]+$/,Hh=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Vh=/^[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,Wh=/^[a-z0-9_-]{21}$/i,Jh=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Yh=/^[-+]?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)?)??$/,Xh=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Qh="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",io,ef=/^(?:(?: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])$/,tf=/^(?:(?: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])$/,rf=/^(([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]))$/,nf=/^(([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])$/,sf=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,of=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,hl="((\\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])))",af=new RegExp(`^${hl}$`);function fl(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function lf(r){return new RegExp(`^${fl(r)}$`)}function pl(r){let e=`${hl}T${fl(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function uf(r,e){return!!((e==="v4"||!e)&&ef.test(r)||(e==="v6"||!e)&&rf.test(r))}function cf(r,e){if(!Jh.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function df(r,e){return!!((e==="v4"||!e)&&tf.test(r)||(e==="v6"||!e)&&nf.test(r))}var $t=class r extends Y{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==j.string){let i=this._getOrReturnCtx(e);return $(i,{code:I.invalid_type,expected:j.string,received:i.parsedType}),q}let n=new ve,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),$(s,{code:I.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),$(s,{code:I.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(s=this._getOrReturnCtx(e,s),o?$(s,{code:I.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&$(s,{code:I.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")Xh.test(e.data)||(s=this._getOrReturnCtx(e,s),$(s,{validation:"email",code:I.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")io||(io=new RegExp(Qh,"u")),io.test(e.data)||(s=this._getOrReturnCtx(e,s),$(s,{validation:"emoji",code:I.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")Vh.test(e.data)||(s=this._getOrReturnCtx(e,s),$(s,{validation:"uuid",code:I.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")Wh.test(e.data)||(s=this._getOrReturnCtx(e,s),$(s,{validation:"nanoid",code:I.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")Zh.test(e.data)||(s=this._getOrReturnCtx(e,s),$(s,{validation:"cuid",code:I.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")Gh.test(e.data)||(s=this._getOrReturnCtx(e,s),$(s,{validation:"cuid2",code:I.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")Hh.test(e.data)||(s=this._getOrReturnCtx(e,s),$(s,{validation:"ulid",code:I.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),$(s,{validation:"url",code:I.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),$(s,{validation:"regex",code:I.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),$(s,{code:I.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),$(s,{code:I.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),$(s,{code:I.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?pl(i).test(e.data)||(s=this._getOrReturnCtx(e,s),$(s,{code:I.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?af.test(e.data)||(s=this._getOrReturnCtx(e,s),$(s,{code:I.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?lf(i).test(e.data)||(s=this._getOrReturnCtx(e,s),$(s,{code:I.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?Yh.test(e.data)||(s=this._getOrReturnCtx(e,s),$(s,{validation:"duration",code:I.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?uf(e.data,i.version)||(s=this._getOrReturnCtx(e,s),$(s,{validation:"ip",code:I.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?cf(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),$(s,{validation:"jwt",code:I.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?df(e.data,i.version)||(s=this._getOrReturnCtx(e,s),$(s,{validation:"cidr",code:I.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?sf.test(e.data)||(s=this._getOrReturnCtx(e,s),$(s,{validation:"base64",code:I.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?of.test(e.data)||(s=this._getOrReturnCtx(e,s),$(s,{validation:"base64url",code:I.invalid_string,message:i.message}),n.dirty()):X.assertNever(i);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:I.invalid_string,...N.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...N.errToObj(e)})}url(e){return this._addCheck({kind:"url",...N.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...N.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...N.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...N.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...N.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...N.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...N.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...N.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...N.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...N.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...N.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...N.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,...N.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,...N.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...N.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...N.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...N.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...N.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...N.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...N.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...N.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...N.errToObj(t)})}nonempty(e){return this.min(1,N.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};$t.create=r=>new $t({checks:[],typeName:F.ZodString,coerce:r?.coerce??!1,...Z(r)});function hf(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,i=Number.parseInt(r.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var Wt=class r extends Y{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)!==j.number){let i=this._getOrReturnCtx(e);return $(i,{code:I.invalid_type,expected:j.number,received:i.parsedType}),q}let n,s=new ve;for(let i of this._def.checks)i.kind==="int"?X.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),$(n,{code:I.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),$(n,{code:I.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),$(n,{code:I.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?hf(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),$(n,{code:I.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),$(n,{code:I.not_finite,message:i.message}),s.dirty()):X.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,N.toString(t))}gt(e,t){return this.setLimit("min",e,!1,N.toString(t))}lte(e,t){return this.setLimit("max",e,!0,N.toString(t))}lt(e,t){return this.setLimit("max",e,!1,N.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:N.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:N.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:N.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:N.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:N.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:N.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:N.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:N.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:N.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:N.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&X.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};Wt.create=r=>new Wt({checks:[],typeName:F.ZodNumber,coerce:r?.coerce||!1,...Z(r)});var Jt=class r extends Y{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)!==j.bigint)return this._getInvalidInput(e);let n,s=new ve;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),$(n,{code:I.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),$(n,{code:I.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),$(n,{code:I.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):X.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return $(t,{code:I.invalid_type,expected:j.bigint,received:t.parsedType}),q}gte(e,t){return this.setLimit("min",e,!0,N.toString(t))}gt(e,t){return this.setLimit("min",e,!1,N.toString(t))}lte(e,t){return this.setLimit("max",e,!0,N.toString(t))}lt(e,t){return this.setLimit("max",e,!1,N.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:N.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:N.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:N.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:N.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:N.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:N.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Jt.create=r=>new Jt({checks:[],typeName:F.ZodBigInt,coerce:r?.coerce??!1,...Z(r)});var Yt=class extends Y{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==j.boolean){let n=this._getOrReturnCtx(e);return $(n,{code:I.invalid_type,expected:j.boolean,received:n.parsedType}),q}return we(e.data)}};Yt.create=r=>new Yt({typeName:F.ZodBoolean,coerce:r?.coerce||!1,...Z(r)});var Xt=class r extends Y{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==j.date){let i=this._getOrReturnCtx(e);return $(i,{code:I.invalid_type,expected:j.date,received:i.parsedType}),q}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return $(i,{code:I.invalid_date}),q}let n=new ve,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),$(s,{code:I.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),$(s,{code:I.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):X.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:N.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:N.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};Xt.create=r=>new Xt({checks:[],coerce:r?.coerce||!1,typeName:F.ZodDate,...Z(r)});var sn=class extends Y{_parse(e){if(this._getType(e)!==j.symbol){let n=this._getOrReturnCtx(e);return $(n,{code:I.invalid_type,expected:j.symbol,received:n.parsedType}),q}return we(e.data)}};sn.create=r=>new sn({typeName:F.ZodSymbol,...Z(r)});var Qt=class extends Y{_parse(e){if(this._getType(e)!==j.undefined){let n=this._getOrReturnCtx(e);return $(n,{code:I.invalid_type,expected:j.undefined,received:n.parsedType}),q}return we(e.data)}};Qt.create=r=>new Qt({typeName:F.ZodUndefined,...Z(r)});var er=class extends Y{_parse(e){if(this._getType(e)!==j.null){let n=this._getOrReturnCtx(e);return $(n,{code:I.invalid_type,expected:j.null,received:n.parsedType}),q}return we(e.data)}};er.create=r=>new er({typeName:F.ZodNull,...Z(r)});var Pt=class extends Y{constructor(){super(...arguments),this._any=!0}_parse(e){return we(e.data)}};Pt.create=r=>new Pt({typeName:F.ZodAny,...Z(r)});var mt=class extends Y{constructor(){super(...arguments),this._unknown=!0}_parse(e){return we(e.data)}};mt.create=r=>new mt({typeName:F.ZodUnknown,...Z(r)});var Ge=class extends Y{_parse(e){let t=this._getOrReturnCtx(e);return $(t,{code:I.invalid_type,expected:j.never,received:t.parsedType}),q}};Ge.create=r=>new Ge({typeName:F.ZodNever,...Z(r)});var on=class extends Y{_parse(e){if(this._getType(e)!==j.undefined){let n=this._getOrReturnCtx(e);return $(n,{code:I.invalid_type,expected:j.void,received:n.parsedType}),q}return we(e.data)}};on.create=r=>new on({typeName:F.ZodVoid,...Z(r)});var gt=class r extends Y{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==j.array)return $(t,{code:I.invalid_type,expected:j.array,received:t.parsedType}),q;if(s.exactLength!==null){let o=t.data.length>s.exactLength.value,a=t.data.length<s.exactLength.value;(o||a)&&($(t,{code:o?I.too_big:I.too_small,minimum:a?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&($(t,{code:I.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&($(t,{code:I.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>s.type._parseAsync(new De(t,o,t.path,a)))).then(o=>ve.mergeArray(n,o));let i=[...t.data].map((o,a)=>s.type._parseSync(new De(t,o,t.path,a)));return ve.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:N.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:N.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:N.toString(t)}})}nonempty(e){return this.min(1,e)}};gt.create=(r,e)=>new gt({type:r,minLength:null,maxLength:null,exactLength:null,typeName:F.ZodArray,...Z(e)});function nn(r){if(r instanceof Ce){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=ze.create(nn(n))}return new Ce({...r._def,shape:()=>e})}else return r instanceof gt?new gt({...r._def,type:nn(r.element)}):r instanceof ze?ze.create(nn(r.unwrap())):r instanceof nt?nt.create(nn(r.unwrap())):r instanceof rt?rt.create(r.items.map(e=>nn(e))):r}var Ce=class r extends Y{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=X.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==j.object){let c=this._getOrReturnCtx(e);return $(c,{code:I.invalid_type,expected:j.object,received:c.parsedType}),q}let{status:n,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ge&&this._def.unknownKeys==="strip"))for(let c in s.data)o.includes(c)||a.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 De(s,p,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof Ge){let c=this._def.unknownKeys;if(c==="passthrough")for(let f of a)u.push({key:{status:"valid",value:f},value:{status:"valid",value:s.data[f]}});else if(c==="strict")a.length>0&&($(s,{code:I.unrecognized_keys,keys:a}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let f of a){let p=s.data[f];u.push({key:{status:"valid",value:f},value:c._parse(new De(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,v=await f.value;c.push({key:p,value:v,alwaysSet:f.alwaysSet})}return c}).then(c=>ve.mergeObjectSync(n,c)):ve.mergeObjectSync(n,u)}get shape(){return this._def.shape()}strict(e){return N.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let s=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:N.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:F.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let n of X.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let n of X.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return nn(this)}partial(e){let t={};for(let n of X.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let n of X.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof ze;)i=i._def.innerType;t[n]=i}return new r({...this._def,shape:()=>t})}keyof(){return ml(X.objectKeys(this.shape))}};Ce.create=(r,e)=>new Ce({shape:()=>r,unknownKeys:"strip",catchall:Ge.create(),typeName:F.ZodObject,...Z(e)});Ce.strictCreate=(r,e)=>new Ce({shape:()=>r,unknownKeys:"strict",catchall:Ge.create(),typeName:F.ZodObject,...Z(e)});Ce.lazycreate=(r,e)=>new Ce({shape:r,unknownKeys:"strip",catchall:Ge.create(),typeName:F.ZodObject,...Z(e)});var tr=class extends Y{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function s(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return t.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(a=>new xe(a.ctx.common.issues));return $(t,{code:I.invalid_union,unionErrors:o}),q}if(t.common.async)return Promise.all(n.map(async i=>{let o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let u of n){let c={...t,common:{...t.common,issues:[]},parent:null},f=u._parseSync({data:t.data,path:t.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 t.common.issues.push(...i.ctx.common.issues),i.result;let a=o.map(u=>new xe(u));return $(t,{code:I.invalid_union,unionErrors:a}),q}}get options(){return this._def.options}};tr.create=(r,e)=>new tr({options:r,typeName:F.ZodUnion,...Z(e)});var pt=r=>r instanceof nr?pt(r.schema):r instanceof Le?pt(r.innerType()):r instanceof sr?[r.value]:r instanceof ir?r.options:r instanceof or?X.objectValues(r.enum):r instanceof ar?pt(r._def.innerType):r instanceof Qt?[void 0]:r instanceof er?[null]:r instanceof ze?[void 0,...pt(r.unwrap())]:r instanceof nt?[null,...pt(r.unwrap())]:r instanceof Zn||r instanceof ur?pt(r.unwrap()):r instanceof lr?pt(r._def.innerType):[],Is=class r extends Y{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==j.object)return $(t,{code:I.invalid_type,expected:j.object,received:t.parsedType}),q;let n=this.discriminator,s=t.data[n],i=this.optionsMap.get(s);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):($(t,{code:I.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),q)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let s=new Map;for(let i of t){let o=pt(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of o){if(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,i)}}return new r({typeName:F.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...Z(n)})}};function oo(r,e){let t=tt(r),n=tt(e);if(r===e)return{valid:!0,data:r};if(t===j.object&&n===j.object){let s=X.objectKeys(e),i=X.objectKeys(r).filter(a=>s.indexOf(a)!==-1),o={...r,...e};for(let a of i){let u=oo(r[a],e[a]);if(!u.valid)return{valid:!1};o[a]=u.data}return{valid:!0,data:o}}else if(t===j.array&&n===j.array){if(r.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<r.length;i++){let o=r[i],a=e[i],u=oo(o,a);if(!u.valid)return{valid:!1};s.push(u.data)}return{valid:!0,data:s}}else return t===j.date&&n===j.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var rr=class extends Y{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=(i,o)=>{if(xs(i)||xs(o))return q;let a=oo(i.value,o.value);return a.valid?((Cs(i)||Cs(o))&&t.dirty(),{status:t.value,value:a.data}):($(n,{code:I.invalid_intersection_types}),q)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};rr.create=(r,e,t)=>new rr({left:r,right:e,typeName:F.ZodIntersection,...Z(t)});var rt=class r extends Y{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==j.array)return $(n,{code:I.invalid_type,expected:j.array,received:n.parsedType}),q;if(n.data.length<this._def.items.length)return $(n,{code:I.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),q;!this._def.rest&&n.data.length>this._def.items.length&&($(n,{code:I.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...n.data].map((o,a)=>{let u=this._def.items[a]||this._def.rest;return u?u._parse(new De(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(i).then(o=>ve.mergeArray(t,o)):ve.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};rt.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new rt({items:r,typeName:F.ZodTuple,rest:null,...Z(e)})};var Rs=class r extends Y{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==j.object)return $(n,{code:I.invalid_type,expected:j.object,received:n.parsedType}),q;let s=[],i=this._def.keyType,o=this._def.valueType;for(let a in n.data)s.push({key:i._parse(new De(n,a,n.path,a)),value:o._parse(new De(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?ve.mergeObjectAsync(t,s):ve.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof Y?new r({keyType:e,valueType:t,typeName:F.ZodRecord,...Z(n)}):new r({keyType:$t.create(),valueType:e,typeName:F.ZodRecord,...Z(t)})}},an=class extends Y{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==j.map)return $(n,{code:I.invalid_type,expected:j.map,received:n.parsedType}),q;let s=this._def.keyType,i=this._def.valueType,o=[...n.data.entries()].map(([a,u],c)=>({key:s._parse(new De(n,a,n.path,[c,"key"])),value:i._parse(new De(n,u,n.path,[c,"value"]))}));if(n.common.async){let a=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 q;(c.status==="dirty"||f.status==="dirty")&&t.dirty(),a.set(c.value,f.value)}return{status:t.value,value:a}})}else{let a=new Map;for(let u of o){let c=u.key,f=u.value;if(c.status==="aborted"||f.status==="aborted")return q;(c.status==="dirty"||f.status==="dirty")&&t.dirty(),a.set(c.value,f.value)}return{status:t.value,value:a}}}};an.create=(r,e,t)=>new an({valueType:e,keyType:r,typeName:F.ZodMap,...Z(t)});var ln=class r extends Y{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==j.set)return $(n,{code:I.invalid_type,expected:j.set,received:n.parsedType}),q;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&($(n,{code:I.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&($(n,{code:I.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let i=this._def.valueType;function o(u){let c=new Set;for(let f of u){if(f.status==="aborted")return q;f.status==="dirty"&&t.dirty(),c.add(f.value)}return{status:t.value,value:c}}let a=[...n.data.values()].map((u,c)=>i._parse(new De(n,u,n.path,c)));return n.common.async?Promise.all(a).then(u=>o(u)):o(a)}min(e,t){return new r({...this._def,minSize:{value:e,message:N.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:N.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};ln.create=(r,e)=>new ln({valueType:r,minSize:null,maxSize:null,typeName:F.ZodSet,...Z(e)});var Es=class r extends Y{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==j.function)return $(t,{code:I.invalid_type,expected:j.function,received:t.parsedType}),q;function n(a,u){return Kn({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,tn(),ft].filter(c=>!!c),issueData:{code:I.invalid_arguments,argumentsError:u}})}function s(a,u){return Kn({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,tn(),ft].filter(c=>!!c),issueData:{code:I.invalid_return_type,returnTypeError:u}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof jt){let a=this;return we(async function(...u){let c=new xe([]),f=await a._def.args.parseAsync(u,i).catch(S=>{throw c.addIssue(n(u,S)),c}),p=await Reflect.apply(o,this,f);return await a._def.returns._def.type.parseAsync(p,i).catch(S=>{throw c.addIssue(s(p,S)),c})})}else{let a=this;return we(function(...u){let c=a._def.args.safeParse(u,i);if(!c.success)throw new xe([n(u,c.error)]);let f=Reflect.apply(o,this,c.data),p=a._def.returns.safeParse(f,i);if(!p.success)throw new xe([s(f,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:rt.create(e).rest(mt.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||rt.create([]).rest(mt.create()),returns:t||mt.create(),typeName:F.ZodFunction,...Z(n)})}},nr=class extends Y{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};nr.create=(r,e)=>new nr({getter:r,typeName:F.ZodLazy,...Z(e)});var sr=class extends Y{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return $(t,{received:t.data,code:I.invalid_literal,expected:this._def.value}),q}return{status:"valid",value:e.data}}get value(){return this._def.value}};sr.create=(r,e)=>new sr({value:r,typeName:F.ZodLiteral,...Z(e)});function ml(r,e){return new ir({values:r,typeName:F.ZodEnum,...Z(e)})}var ir=class r extends Y{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return $(t,{expected:X.joinValues(n),received:t.parsedType,code:I.invalid_type}),q}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return $(t,{received:t.data,code:I.invalid_enum_value,options:n}),q}return we(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};ir.create=ml;var or=class extends Y{_parse(e){let t=X.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==j.string&&n.parsedType!==j.number){let s=X.objectValues(t);return $(n,{expected:X.joinValues(s),received:n.parsedType,code:I.invalid_type}),q}if(this._cache||(this._cache=new Set(X.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=X.objectValues(t);return $(n,{received:n.data,code:I.invalid_enum_value,options:s}),q}return we(e.data)}get enum(){return this._def.values}};or.create=(r,e)=>new or({values:r,typeName:F.ZodNativeEnum,...Z(e)});var jt=class extends Y{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==j.promise&&t.common.async===!1)return $(t,{code:I.invalid_type,expected:j.promise,received:t.parsedType}),q;let n=t.parsedType===j.promise?t.data:Promise.resolve(t.data);return we(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};jt.create=(r,e)=>new jt({type:r,typeName:F.ZodPromise,...Z(e)});var Le=class extends Y{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===F.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{$(n,o),o.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(n.data,i);if(n.common.async)return Promise.resolve(o).then(async a=>{if(t.value==="aborted")return q;let u=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return u.status==="aborted"?q:u.status==="dirty"?Vt(u.value):t.value==="dirty"?Vt(u.value):u});{if(t.value==="aborted")return q;let a=this._def.schema._parseSync({data:o,path:n.path,parent:n});return a.status==="aborted"?q:a.status==="dirty"?Vt(a.value):t.value==="dirty"?Vt(a.value):a}}if(s.type==="refinement"){let o=a=>{let u=s.refinement(a,i);if(n.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?q:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?q:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.value,value:a.value}))))}if(s.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!At(o))return q;let a=s.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>At(o)?Promise.resolve(s.transform(o.value,i)).then(a=>({status:t.value,value:a})):q);X.assertNever(s)}};Le.create=(r,e,t)=>new Le({schema:r,typeName:F.ZodEffects,effect:e,...Z(t)});Le.createWithPreprocess=(r,e,t)=>new Le({schema:e,effect:{type:"preprocess",transform:r},typeName:F.ZodEffects,...Z(t)});var ze=class extends Y{_parse(e){return this._getType(e)===j.undefined?we(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ze.create=(r,e)=>new ze({innerType:r,typeName:F.ZodOptional,...Z(e)});var nt=class extends Y{_parse(e){return this._getType(e)===j.null?we(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};nt.create=(r,e)=>new nt({innerType:r,typeName:F.ZodNullable,...Z(e)});var ar=class extends Y{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===j.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ar.create=(r,e)=>new ar({innerType:r,typeName:F.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Z(e)});var lr=class extends Y{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return rn(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new xe(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new xe(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};lr.create=(r,e)=>new lr({innerType:r,typeName:F.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Z(e)});var un=class extends Y{_parse(e){if(this._getType(e)!==j.nan){let n=this._getOrReturnCtx(e);return $(n,{code:I.invalid_type,expected:j.nan,received:n.parsedType}),q}return{status:"valid",value:e.data}}};un.create=r=>new un({typeName:F.ZodNaN,...Z(r)});var ff=Symbol("zod_brand"),Zn=class extends Y{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},Gn=class r extends Y{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?q:i.status==="dirty"?(t.dirty(),Vt(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?q:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:F.ZodPipeline})}},ur=class extends Y{_parse(e){let t=this._def.innerType._parse(e),n=s=>(At(s)&&(s.value=Object.freeze(s.value)),s);return rn(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}};ur.create=(r,e)=>new ur({innerType:r,typeName:F.ZodReadonly,...Z(e)});function dl(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function gl(r,e={},t){return r?Pt.create().superRefine((n,s)=>{let i=r(n);if(i instanceof Promise)return i.then(o=>{if(!o){let a=dl(e,n),u=a.fatal??t??!0;s.addIssue({code:"custom",...a,fatal:u})}});if(!i){let o=dl(e,n),a=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:a})}}):Pt.create()}var pf={object:Ce.lazycreate},F;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(F||(F={}));var mf=(r,e={message:`Input not instance of ${r.name}`})=>gl(t=>t instanceof r,e),yl=$t.create,vl=Wt.create,gf=un.create,yf=Jt.create,bl=Yt.create,vf=Xt.create,bf=sn.create,wf=Qt.create,_f=er.create,kf=Pt.create,Sf=mt.create,Tf=Ge.create,xf=on.create,Cf=gt.create,If=Ce.create,Rf=Ce.strictCreate,Ef=tr.create,Af=Is.create,$f=rr.create,Pf=rt.create,jf=Rs.create,Of=an.create,Nf=ln.create,Mf=Es.create,zf=nr.create,Df=sr.create,Lf=ir.create,Uf=or.create,qf=jt.create,Ff=Le.create,Bf=ze.create,Kf=nt.create,Zf=Le.createWithPreprocess,Gf=Gn.create,Hf=()=>yl().optional(),Vf=()=>vl().optional(),Wf=()=>bl().optional(),Jf={string:(r=>$t.create({...r,coerce:!0})),number:(r=>Wt.create({...r,coerce:!0})),boolean:(r=>Yt.create({...r,coerce:!0})),bigint:(r=>Jt.create({...r,coerce:!0})),date:(r=>Xt.create({...r,coerce:!0}))};var Yf=q;var wl=k.object({baseUrl:k.string().url(),email:k.string().email(),apiToken:k.string().min(1)}),ao=k.object({controlPlaneUrl:k.string().url(),runnerId:k.string().optional(),runnerToken:k.string().optional(),runnerName:k.string().default(As.default.hostname()),jira:wl.optional(),repos:k.record(k.object({path:k.string(),jira:wl.optional(),github:k.object({token:k.string().min(1),login:k.string().optional()}).optional()})).default({}),github:k.object({token:k.string().min(1),login:k.string().optional()}).optional(),githubUsers:k.record(k.object({token:k.string().min(1),login:k.string().optional()})).default({}),deploy:k.object({enabled:k.boolean().default(!1)}).default({enabled:!1}),environments:k.record(k.object({secrets:k.record(k.string()).default({})})).default({}),claudeProfiles:k.record(k.object({configDir:k.string()})).default({}),claudeBin:k.string().default("claude"),agents:k.record(k.object({bin:k.string()})).default({}),jiraUsers:k.record(k.object({email:k.string().email(),apiToken:k.string().min(1)})).default({}),auditSchedules:k.array(k.object({repoName:k.string(),role:k.enum(["security","testing"]),intervalHours:k.number().int().min(6).max(720)})).default([]),pollIntervalSeconds:k.number().int().min(10).max(600).default(30)});function te(){let r=process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR;if(r)return r;let e=$s.default.join(As.default.homedir(),".config","allwright"),t=$s.default.join(As.default.homedir(),".config","ticketpilot");return!yt.default.existsSync(e)&&yt.default.existsSync(t)?t:e}function Ot(){return $s.default.join(te(),"runner.json")}function pe(){let r=Ot();if(!yt.default.existsSync(r))return null;let e=JSON.parse(yt.default.readFileSync(r,"utf8"));return ao.parse(e)}function he(r){let e=te();yt.default.mkdirSync(e,{recursive:!0,mode:448});let t=Ot(),n=t+".tmp";yt.default.writeFileSync(n,JSON.stringify(r,null,2)+`
|
|
261
|
+
`,{mode:384}),yt.default.renameSync(n,t),yt.default.chmodSync(t,384)}function Ps(r,e){return`${r}:${e}`}function cr(r,e,t){return r.environments[Ps(e,t)]?.secrets??{}}function ne(){let r=pe();if(!r)throw new Error(`No runner config found at ${Ot()}. Run \`allwright init\` first.`);return r}var js=require("node:child_process"),Pe=E(require("node:fs"),1),Os=E(require("node:path"),1);var Xf=new Set(["runner.log","runner.pid"]);function Qf(r){return Pe.default.readdirSync(r).filter(e=>!Xf.has(e)&&!/\.bak-\d+$/.test(e)).sort()}function _l(r){let e=te();if(!Pe.default.existsSync(e))throw new Error(`nothing to export - ${e} does not exist`);let t=Qf(e);if(!t.length)throw new Error(`nothing to export - ${e} is empty`);let n=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),s=Os.default.resolve(r||`ticketpilot-backup-${n}.tgz`);return Pe.default.writeFileSync(s,"",{mode:384}),(0,js.execFileSync)("tar",["-czf",s,"-C",e,...t]),Pe.default.chmodSync(s,384),{file:s,entries:t}}function kl(r){let e=Os.default.resolve(r);if(!Pe.default.existsSync(e))throw new Error(`backup file not found: ${e}`);let t=(0,js.execFileSync)("tar",["-tzf",e],{encoding:"utf8"}).split(`
|
|
262
|
+
`).filter(Boolean);for(let i of t)if(i.startsWith("/")||i.split("/").includes(".."))throw new Error(`refusing to import - unsafe path in archive: ${i}`);let n=te(),s;Pe.default.existsSync(n)&&Pe.default.readdirSync(n).length&&(s=`${n}.bak-${Date.now()}`,Pe.default.renameSync(n,s)),Pe.default.mkdirSync(n,{recursive:!0,mode:448}),(0,js.execFileSync)("tar",["-xzf",e,"-C",n]);for(let i of Pe.default.readdirSync(n)){let o=Os.default.join(n,i);Pe.default.statSync(o).isFile()&&Pe.default.chmodSync(o,384)}return{restored:t.map(i=>i.replace(/\/$/,"")).sort(),previousDir:s}}var cn=E(require("node:fs"),1),Nt=E(require("node:path"),1),Ns=".ticketpilot-attachments",ep=15*1024*1024,tp=50*1024*1024,Sl=20;function Tl(r,e){let t=Nt.default.basename(r).replace(/[^\w.\- ()]/g,"_").replace(/^\.+/,"").slice(-100)||"file",n=t,s=1;for(;e.has(n);)n=`${s++}-${t}`;return e.add(n),n}async function dn(r,e,t,n){if(!e.length)return"";let s=Nt.default.join(t,Ns);cn.default.mkdirSync(s,{recursive:!0});let i=new Set,o=[],a=0;for(let u of e){if(o.length>=Sl){n("warn",`attachment cap reached (${Sl} files) - skipping the rest`);break}if(u.size>ep){n("warn",`skipping attachment "${u.filename}" - ${sp(u.size)} MB exceeds the 15 MB limit`);continue}if(a+u.size>tp){n("warn",`attachment size budget reached - skipping "${u.filename}" and the rest`);break}try{let c=await r.downloadAttachment(u.contentUrl),f=Tl(u.filename,i);cn.default.writeFileSync(Nt.default.join(s,f),c),a+=c.length,o.push(`- ${Ns}/${f} (${u.mimeType||"unknown type"}, ${lo(c.length)} KB)`),n("info",`Downloaded attachment "${u.filename}" (${lo(c.length)} KB)`)}catch(c){n("warn",`could not download attachment "${u.filename}": ${c instanceof Error?c.message:c}`)}}return o.length?`
|
|
261
263
|
|
|
262
264
|
Files attached to the Jira ticket, downloaded locally for this run. They are reference material and NOT part of the repository - never commit, copy, or edit them:
|
|
263
265
|
${o.join(`
|
|
264
266
|
`)}
|
|
265
|
-
Read them with the Read tool when relevant; images (screenshots) can be viewed directly.`:(
|
|
267
|
+
Read them with the Read tool when relevant; images (screenshots) can be viewed directly.`:(Mt(t),"")}function Mt(r){cn.default.rmSync(Nt.default.join(r,Ns),{recursive:!0,force:!0})}var rp=4*1024*1024,np=16*1024*1024;function xl(r,e,t){let n=Nt.default.join(r,Ns,`chat-${e.replace(/[^\w-]/g,"")}`);if(!t.length)return{section:"",dir:n};cn.default.mkdirSync(n,{recursive:!0});let s=new Set,i=[],o=0,a=Nt.default.relative(r,n);for(let c of t){let f=Buffer.from(c.contentBase64,"base64");if(f.length>rp||o+f.length>np){i.push(`- (skipped "${c.name}" - over the upload size budget)`);continue}let p=Tl(c.name,s);cn.default.writeFileSync(Nt.default.join(n,p),f),o+=f.length,i.push(`- ${a}/${p} (${lo(f.length)} KB)`)}return{section:`
|
|
266
268
|
|
|
267
269
|
The user attached file(s) with this message, staged locally for you. They are reference material and NOT part of the repository - never commit, copy, or edit them. If a ticket is created from this chat, these files are attached to it automatically, so reference them by filename instead of pasting their content:
|
|
268
270
|
${i.join(`
|
|
269
271
|
`)}
|
|
270
|
-
Read them with the Read tool; images can be viewed directly.`,dir:n}}var
|
|
272
|
+
Read them with the Read tool; images can be viewed directly.`,dir:n}}var lo=r=>Math.max(1,Math.round(r/1024)),sp=r=>Math.round(r/(1024*1024)*10)/10;var _e=E(require("node:fs"),1),zs=E(require("node:path"),1);function hn(){return zs.default.join(te(),"runner.pid")}function Ms(){return zs.default.join(te(),"runner.log")}function Cl(){_e.default.mkdirSync(te(),{recursive:!0,mode:448});let r=_e.default.openSync(Ms(),"a",384);try{_e.default.chmodSync(Ms(),384)}catch{}return r}function dr(){let r=hn();if(!_e.default.existsSync(r))return null;let e=Number(_e.default.readFileSync(r,"utf8").trim());return Number.isFinite(e)&&e>0?e:null}function hr(r){try{return process.kill(r,0),!0}catch{return!1}}function Il(r){_e.default.mkdirSync(te(),{recursive:!0,mode:448}),_e.default.writeFileSync(hn(),String(r),{mode:384})}function Rl(r){dr()===r&&_e.default.rmSync(hn(),{force:!0})}function uo(){return zs.default.join(te(),"runner.lock")}function Hn(){let r=uo();if(!_e.default.existsSync(r))return null;let e=Number(_e.default.readFileSync(r,"utf8").trim());return!Number.isFinite(e)||e<=0||e===process.pid?null:hr(e)?e:null}function El(){let r=Hn();return r?{ok:!1,pid:r}:(_e.default.mkdirSync(te(),{recursive:!0,mode:448}),_e.default.writeFileSync(uo(),String(process.pid),{mode:384}),{ok:!0})}function co(){try{let r=uo();_e.default.existsSync(r)&&Number(_e.default.readFileSync(r,"utf8").trim())===process.pid&&_e.default.rmSync(r,{force:!0})}catch{}}var Zs=E(require("node:fs"),1),Xn=E(require("node:path"),1),eu=E(be(),1);async function tu(r,e){let t=await fetch(new URL("/api/runners/enroll",r.controlPlaneUrl),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enrollToken:e,name:r.runnerName,platform:`${process.platform}/${process.arch}`,runnerVersion:Gs})});if(!t.ok){let i=await t.text().catch(()=>"");throw new Error(`enrollment failed (${t.status}): ${i.slice(0,300)}`)}let n=eu.EnrollResponse.parse(await t.json()),s={...r,runnerId:n.runnerId,runnerToken:n.runnerToken};return he(s),s}function Am(){try{let r=process.argv[1]?Zs.default.realpathSync(process.argv[1]):"";for(let e of[Xn.default.dirname(r),Xn.default.dirname(Xn.default.dirname(r))]){let t=Xn.default.join(e,"package.json");if(!Zs.default.existsSync(t))continue;let n=JSON.parse(Zs.default.readFileSync(t,"utf8")).version;if(typeof n=="string"&&n)return n}}catch{}return"0.0.0"}var Gs=Am();_t();var du="Posted automatically by Allwright",$m=["Posted automatically by TicketPilot"],ot=r=>r.includes(du)||$m.some(e=>r.includes(e));var Ee=class{constructor(e){this.auth=e}auth;headers(){return{Authorization:`Basic ${Buffer.from(`${this.auth.email}:${this.auth.apiToken}`).toString("base64")}`,Accept:"application/json","Content-Type":"application/json"}}async request(e,t,n){let s=new URL(t,this.auth.baseUrl).toString(),i=await fetch(s,{method:e,headers:this.headers(),body:n===void 0?void 0:JSON.stringify(n)});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`Jira ${e} ${t} -> ${i.status}: ${o.slice(0,500)}`)}if(i.status!==204)return await i.json()}async myself(){return this.request("GET","/rest/api/3/myself")}async searchUsers(e,t=20){let n=await this.userSearch(e,t);return n.length||!e.includes("@")?n:this.userSearch(e.slice(0,e.indexOf("@")),t)}async userSearch(e,t){return e.trim()?(await this.request("GET",`/rest/api/3/user/search?query=${encodeURIComponent(e)}&maxResults=${t}`)??[]).filter(s=>s.accountId&&(s.accountType??"atlassian")==="atlassian").map(s=>({accountId:s.accountId,displayName:s.displayName??"(no name)",email:s.emailAddress??"",active:s.active??!0})):[]}async search(e,t=20){return((await this.request("POST","/rest/api/3/search/jql",{jql:e,maxResults:t,fields:["summary","components"]})).issues??[]).map(s=>({key:s.key,summary:s.fields?.summary??"",components:(s.fields?.components??[]).map(i=>i.name??"").filter(Boolean)}))}async projectStatuses(e){let t=await this.request("GET",`/rest/api/3/project/${encodeURIComponent(e)}/statuses`),n=new Map;for(let i of t??[])for(let o of i.statuses??[])o.name&&!n.has(o.name)&&n.set(o.name,o.statusCategory?.key??"indeterminate");let s=i=>i==="new"?0:i==="done"?2:1;return[...n.entries()].sort((i,o)=>s(i[1])-s(o[1])).map(([i])=>i)}async searchEpics(e,t=20){return((await this.request("POST","/rest/api/3/search/jql",{jql:`project = "${e}" AND issuetype = Epic AND statusCategory != Done ORDER BY created DESC`,maxResults:t,fields:["summary","status"]})).issues??[]).map(s=>({key:s.key,summary:s.fields?.summary??"",status:s.fields?.status?.name??""}))}async epicChildren(e,t=50){return((await this.request("POST","/rest/api/3/search/jql",{jql:`parent = "${e}" ORDER BY created ASC`,maxResults:t,fields:["summary","status","labels"]})).issues??[]).map(s=>({key:s.key,summary:s.fields?.summary??"",status:s.fields?.status?.name??"",statusCategory:s.fields?.status?.statusCategory?.key??"indeterminate",labels:s.fields?.labels??[]}))}async searchBoard(e,t=100){return((await this.request("POST","/rest/api/3/search/jql",{jql:e,maxResults:t,fields:["summary","status","labels"]})).issues??[]).map(s=>({key:s.key,summary:s.fields?.summary??"",status:s.fields?.status?.name??"(no status)",statusId:s.fields?.status?.id??"",labels:s.fields?.labels??[]}))}async boardColumns(e){try{let n=(await this.request("GET",`/rest/agile/1.0/board?projectKeyOrId=${encodeURIComponent(e)}`)).values?.[0]?.id;if(!n)return null;let i=((await this.request("GET",`/rest/agile/1.0/board/${n}/configuration`)).columnConfig?.columns??[]).filter(o=>(o.statuses??[]).length>0&&o.name).map(o=>({name:o.name,statusIds:(o.statuses??[]).map(a=>a.id??"").filter(Boolean)}));return i.length?i:null}catch{return null}}async getIssue(e){let t=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}?fields=summary,description,labels,comment,status,attachment`),n;try{n=await this.listAllComments(e)}catch{n=t.fields.comment?.comments??[]}let s=n.map(o=>({id:o.id??"",author:o.author?.displayName??"unknown",authorAccountId:o.author?.accountId??null,created:o.created,body:cu(o.body)})),i=(t.fields.attachment??[]).filter(o=>o.id&&o.filename&&o.content).map(o=>({id:o.id,filename:o.filename,mimeType:o.mimeType??"",size:o.size??0,contentUrl:o.content}));return{key:t.key,summary:t.fields.summary??"",description:cu(t.fields.description),labels:t.fields.labels??[],status:t.fields.status?.name??"",comments:s,attachments:i}}async listAllComments(e){let t=await this.fetchCommentPage(e,0),n=t.total??t.comments.length;if(n<=t.comments.length)return t.comments;let s=Math.max(0,n-200),i=s===0?[...t.comments]:[];for(;i.length<Math.min(n,200);){let o=await this.fetchCommentPage(e,s+i.length);if(!o.comments.length)break;i.push(...o.comments)}return i.slice(-200)}async fetchCommentPage(e,t){let n=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}/comment?startAt=${t}&maxResults=100`);return{comments:n.comments??[],total:n.total}}async downloadAttachment(e){let t=await fetch(e,{headers:this.headers()});if(!t.ok)throw new Error(`attachment download failed: ${t.status}`);return Buffer.from(await t.arrayBuffer())}async lastEnteredStatus(e,t){let n=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}?expand=changelog&fields=status`),s=t.toLowerCase(),i=null;for(let o of n.changelog?.histories??[])(o.items??[]).some(u=>(u.field==="status"||u.fieldId==="status")&&(u.toString??"").toLowerCase()===s)&&(!i||new Date(o.created)>new Date(i.at))&&(i={at:o.created,author:o.author?.displayName??"unknown",authorAccountId:o.author?.accountId??null});return i}async createIssue(e,t,n,s="Task",i){return{key:(await this.request("POST","/rest/api/3/issue",{fields:{project:{key:e},issuetype:{name:s},summary:t.slice(0,250),description:No(n),...i?{parent:{key:i}}:{}}})).key}}async addAttachments(e,t){if(!t.length)return;let n=new FormData;for(let a of t)n.append("file",new Blob([new Uint8Array(a.content)]),a.name.slice(0,255));let s=new URL(`/rest/api/3/issue/${encodeURIComponent(e)}/attachments`,this.auth.baseUrl).toString(),i=Buffer.from(`${this.auth.email}:${this.auth.apiToken}`).toString("base64"),o=await fetch(s,{method:"POST",headers:{Authorization:`Basic ${i}`,Accept:"application/json","X-Atlassian-Token":"no-check"},body:n});if(!o.ok)throw new Error(`Jira attachment upload failed: HTTP ${o.status}`)}async addTriggerComment(e,t){await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/comment`,{body:No(t)})}async addComment(e,t){let n=`${t}
|
|
271
273
|
|
|
272
274
|
---
|
|
273
|
-
_${
|
|
275
|
+
_${du} - never treated as a trigger._`;await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/comment`,{body:No(n)})}async editLabels(e,t){let n=[...(t.add??[]).map(s=>({add:s})),...(t.remove??[]).map(s=>({remove:s}))];await this.request("PUT",`/rest/api/3/issue/${encodeURIComponent(e)}`,{update:{labels:n}})}async getTransitions(e){return((await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}/transitions`)).transitions??[]).map(n=>({id:n.id,name:n.name}))}async transition(e,t){await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/transitions`,{transition:{id:t}})}async transitionByName(e,t){let s=(await this.getTransitions(e)).find(i=>i.name.toLowerCase()===t.toLowerCase());return s?(await this.transition(e,s.id),!0):!1}};function cu(r){if(!r)return"";let e=[],t=n=>{n.text&&e.push(n.text),n.type==="hardBreak"&&e.push(`
|
|
274
276
|
`);for(let s of n.content??[])t(s);n.type&&["paragraph","heading","listItem","codeBlock","blockquote"].includes(n.type)&&e.push(`
|
|
275
277
|
`)};return t(r),e.join("").replace(/\n{3,}/g,`
|
|
276
278
|
|
|
277
|
-
`).trim()}function
|
|
279
|
+
`).trim()}function No(r){let e=r.replace(/\r\n/g,`
|
|
278
280
|
`).split(`
|
|
279
|
-
`),t=[],n=0,s=i=>{let o=[],a=/(\*\*[^*]+\*\*|`[^`]+`)/g,
|
|
280
|
-
`)||" "}]});continue}let a=i.match(/^(#{1,6})\s+(.*)$/);if(a){t.push({type:"heading",attrs:{level:a[1].length},content:s(a[2])}),n++;continue}if(i.match(/^\s*[-*]\s+(.*)$/)){let p=[];for(;n<e.length;){let v=e[n].match(/^\s*[-*]\s+(.*)$/);if(!v)break;p.push({type:"listItem",content:[{type:"paragraph",content:s(v[1])}]}),n++}t.push({type:"bulletList",content:p});continue}if(i.match(/^\s*\d+[.)]\s+(.*)$/)){let p=[];for(;n<e.length;){let v=e[n].match(/^\s*\d+[.)]\s+(.*)$/);if(!v)break;p.push({type:"listItem",content:[{type:"paragraph",content:s(v[1])}]}),n++}t.push({type:"orderedList",content:p});continue}let f=[i];for(n++;n<e.length&&e[n].trim()!==""&&!/^(#{1,6}\s|```|\s*[-*]\s|\s*\d+[.)]\s)/.test(e[n]);)f.push(e[n]),n++;t.push({type:"paragraph",content:s(f.join(" "))})}return{type:"doc",version:1,content:t}}function
|
|
281
|
+
`),t=[],n=0,s=i=>{let o=[],a=/(\*\*[^*]+\*\*|`[^`]+`)/g,u=0,c;for(;(c=a.exec(i))!==null;){c.index>u&&o.push({type:"text",text:i.slice(u,c.index)});let f=c[0];f.startsWith("**")?o.push({type:"text",text:f.slice(2,-2),marks:[{type:"strong"}]}):o.push({type:"text",text:f.slice(1,-1),marks:[{type:"code"}]}),u=c.index+f.length}return u<i.length&&o.push({type:"text",text:i.slice(u)}),o.length?o:[{type:"text",text:" "}]};for(;n<e.length;){let i=e[n];if(i.trim()===""){n++;continue}let o=i.match(/^```(\w*)\s*$/);if(o){let p=[];for(n++;n<e.length&&!/^```\s*$/.test(e[n]);)p.push(e[n]),n++;n++,t.push({type:"codeBlock",attrs:o[1]?{language:o[1]}:{},content:[{type:"text",text:p.join(`
|
|
282
|
+
`)||" "}]});continue}let a=i.match(/^(#{1,6})\s+(.*)$/);if(a){t.push({type:"heading",attrs:{level:a[1].length},content:s(a[2])}),n++;continue}if(i.match(/^\s*[-*]\s+(.*)$/)){let p=[];for(;n<e.length;){let v=e[n].match(/^\s*[-*]\s+(.*)$/);if(!v)break;p.push({type:"listItem",content:[{type:"paragraph",content:s(v[1])}]}),n++}t.push({type:"bulletList",content:p});continue}if(i.match(/^\s*\d+[.)]\s+(.*)$/)){let p=[];for(;n<e.length;){let v=e[n].match(/^\s*\d+[.)]\s+(.*)$/);if(!v)break;p.push({type:"listItem",content:[{type:"paragraph",content:s(v[1])}]}),n++}t.push({type:"orderedList",content:p});continue}let f=[i];for(n++;n<e.length&&e[n].trim()!==""&&!/^(#{1,6}\s|```|\s*[-*]\s|\s*\d+[.)]\s)/.test(e[n]);)f.push(e[n]),n++;t.push({type:"paragraph",content:s(f.join(" "))})}return{type:"doc",version:1,content:t}}function hu(r,e,t){let n=r.repos[e]?.jira??r.jira;if(!n)return{kind:"legacy"};let s=t.trim().toLowerCase();if(!s)return{kind:"legacy"};if(s===n.email.toLowerCase())return{kind:"self"};let i=r.jiraUsers[s];return i?{kind:"user",creds:{baseUrl:n.baseUrl,email:i.email,apiToken:i.apiToken}}:{kind:"missing",error:`Jira actions from Allwright post under YOUR OWN Atlassian identity, and no Jira credential is set up for ${s} on the runner yet. Ask your admin to run this on the runner machine:
|
|
281
283
|
|
|
282
284
|
allwright jira user-add ${s}
|
|
283
285
|
|
|
284
|
-
It prompts for your Atlassian email and an API token (create one at id.atlassian.com -> Security -> API tokens). Takes effect immediately - then just retry this action.`}}
|
|
286
|
+
It prompts for your Atlassian email and an API token (create one at id.atlassian.com -> Security -> API tokens). Takes effect immediately - then just retry this action.`}}Or();var Nr=require("node:child_process"),Tn=E(require("node:fs"),1),Mo=E(require("node:os"),1),Do=E(require("node:path"),1);var ts="allwright",pu=`/etc/systemd/system/${ts}.service`,zo="ticketpilot-runner";function Lo(){let r=process.env.SUDO_USER&&process.env.SUDO_USER!=="root"?process.env.SUDO_USER:"",e=r||Mo.default.userInfo().username,t=r?Do.default.join("/home",r):Mo.default.homedir();return{nodePath:process.execPath,scriptPath:Tn.default.realpathSync(process.argv[1]),user:e,home:t}}function Uo(r){let e=Do.default.dirname(r.nodePath);return`[Unit]
|
|
285
287
|
Description=Allwright runner
|
|
286
288
|
After=network-online.target
|
|
287
289
|
|
|
@@ -299,8 +301,8 @@ TimeoutStopSec=2h
|
|
|
299
301
|
|
|
300
302
|
[Install]
|
|
301
303
|
WantedBy=multi-user.target
|
|
302
|
-
`}function
|
|
303
|
-
`+t);return}try{(0,
|
|
304
|
+
`}function mu(){return process.platform==="linux"&&Tn.default.existsSync("/run/systemd/system")}function gu(r){if(!mu())throw new Error(process.platform==="win32"?"Windows service install isn't built in yet - use NSSM: nssm install allwright <node> <this script> start --foreground":"no systemd on this machine - run `allwright start` (background mode) instead");let e=Lo(),t=Uo(e);if(typeof process.getuid=="function"&&process.getuid()!==0){r.info("Root is needed to write the unit. Re-run as:"),r.info(' sudo env "PATH=$PATH" allwright service install'),r.info("(the env PATH part matters when node is installed via nvm - plain sudo can't find it)"),r.info(""),r.info(`This is exactly what it will write to ${pu}:`),r.info(`
|
|
305
|
+
`+t);return}try{(0,Nr.execFileSync)("systemctl",["disable","--now",zo]),r.info(`stopped the old ${zo} service - this one replaces it`)}catch{}let n=Hn();if(n)try{process.kill(n,"SIGTERM"),r.info(`stopped the running runner (pid ${n}) - the service takes over`)}catch{}Tn.default.writeFileSync(pu,t),(0,Nr.execFileSync)("systemctl",["daemon-reload"]),(0,Nr.execFileSync)("systemctl",["enable","--now",ts]),(0,Nr.execFileSync)("systemctl",["restart",ts]),r.info(`Installed and started (runs as ${e.user}, survives reboots).`),r.info(`Watch it: journalctl -u ${ts} -f`),r.info("Status: allwright service status")}function yu(r){if(!mu())throw new Error("no systemd on this machine");if(typeof process.getuid=="function"&&process.getuid()!==0)throw new Error("root is needed - run: sudo allwright service uninstall");for(let e of[ts,zo]){try{(0,Nr.execFileSync)("systemctl",["disable","--now",e])}catch{}let t=`/etc/systemd/system/${e}.service`;Tn.default.existsSync(t)&&Tn.default.rmSync(t)}(0,Nr.execFileSync)("systemctl",["daemon-reload"]),r.info("Service removed. The runner config and credentials were not touched.")}var vu=E(be(),1);function bu(r){return r.filter(e=>e.statusCategory!=="done"&&!e.labels.includes("agent-implemented")&&!e.labels.includes(vu.NEEDS_INPUT_LABEL))}function wu(r,e,t){let n=t.map(s=>{let i=(s.description??"").trim().slice(0,600);return`- ${s.key} [${s.status}] ${s.summary}${i?`
|
|
304
306
|
${i.replace(/\n+/g," ")}`:""}`}).join(`
|
|
305
307
|
`);return`You are looking at this repository to help sequence work on the Jira epic ${r} ("${e}"). These child tickets are still pending:
|
|
306
308
|
|
|
@@ -311,9 +313,9 @@ Pick the ONE ticket that should be implemented FIRST. Weigh, in this order: (1)
|
|
|
311
313
|
Answer with ONLY a fenced json block, nothing after it:
|
|
312
314
|
\`\`\`json
|
|
313
315
|
{"issueKey": "<one of the keys above>", "reason": "<2-3 sentences: why this one first, and what it unblocks>"}
|
|
314
|
-
\`\`\``}function
|
|
316
|
+
\`\`\``}function _u(r,e){let n=r.match(/```(?:json)?\s*(\{[\s\S]*?\})\s*```/)?.[1]??r.match(/\{[\s\S]*"issueKey"[\s\S]*?\}/)?.[0];if(!n)return{error:"the agent's answer contained no JSON recommendation"};try{let s=JSON.parse(n),i=typeof s.issueKey=="string"?s.issueKey.trim():"",o=typeof s.reason=="string"?s.reason.trim():"";return e.includes(i)?{issueKey:i,reason:o||"(no reasoning given)"}:{error:`the agent recommended "${i}", which is not a pending child of this epic`}}catch{return{error:"the agent's JSON recommendation did not parse"}}}var Vo=require("node:crypto"),Gu=E(require("node:fs"),1);var qo=E(require("node:fs"),1),ei=E(require("node:path"),1),ti=E(be(),1),Pm={security:"You are a security auditor. You can READ this repository; you can never run or change anything. Audit it against the knowledge packs below and report real, exploitable-here problems - not checklist theatre.",testing:"You are a test-coverage auditor. You can READ this repository (code and tests); you can never run anything. Find what is untested and fragile against the knowledge packs below - gaps that would actually bite this product, not generic coverage philosophy.",architecture:"You are a software architecture auditor. You can READ this repository; you can never run or change anything. Judge whether it is structurally HEALTHY for what it is trying to be, against the knowledge packs below - real structural pain for this team, not textbook purity."};function Su(r,e,t,n={}){let s=e.map(u=>`### Pack: ${u.name}
|
|
315
317
|
|
|
316
|
-
${
|
|
318
|
+
${u.content}`).join(`
|
|
317
319
|
|
|
318
320
|
`),i=t.trim()?`
|
|
319
321
|
|
|
@@ -331,7 +333,7 @@ Read whatever surrounding code you need for context, but every finding must be a
|
|
|
331
333
|
|
|
332
334
|
${n.testResults}
|
|
333
335
|
|
|
334
|
-
Fold what these results show - failures, flaky exits, suspiciously green suites - into your findings with the rest of the audit.`:"";return`${
|
|
336
|
+
Fold what these results show - failures, flaky exits, suspiciously green suites - into your findings with the rest of the audit.`:"";return`${Pm[r]}
|
|
335
337
|
|
|
336
338
|
Knowledge below is LAYERED: global (product) -> org (this company) -> project (this repo). More specific levels OVERRIDE general ones; entries referencing a rule id (SEC-001 style) modify or disable that rule.
|
|
337
339
|
|
|
@@ -345,8 +347,8 @@ Explore the repository first - entry points, routes, storage, tests - then audit
|
|
|
345
347
|
"evidence": [{"file": "<repo-relative path>", "line": <number, omit if n/a>, "note": "<what is there>"}],
|
|
346
348
|
"fix": "<2-4 sentences: concrete fix, specific to this code>"}]}
|
|
347
349
|
\`\`\`
|
|
348
|
-
Rules: every finding needs at least one evidence file you actually read - findings without real evidence will be DELETED from your report. Max 25 findings, worst first. An empty findings list with an honest summary is a valid, good answer.`}function
|
|
349
|
-
`).length:0}catch{return null}}function
|
|
350
|
+
Rules: every finding needs at least one evidence file you actually read - findings without real evidence will be DELETED from your report. Max 25 findings, worst first. An empty findings list with an honest summary is a valid, good answer.`}function Tu(r){let t=r.match(/```(?:json)?\s*(\{[\s\S]*\})\s*```(?![\s\S]*```)/)?.[1]??r.match(/\{[\s\S]*"findings"[\s\S]*\}/)?.[0];if(!t)return{error:"the agent's report contained no JSON block"};let n;try{n=JSON.parse(t)}catch{return{error:"the agent's JSON report did not parse"}}if(!Array.isArray(n.findings))return{error:"the report has no findings array"};let s=[],i=0,o=new Set;for(let a of n.findings.slice(0,25)){let u=jm(a),c=u?ti.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 n.summary=="string"?n.summary.trim().slice(0,2e3):"",findings:s,dropped:i}}function jm(r){if(typeof r!="object"||r===null)return null;let e=r,t=typeof e.severity=="string"?e.severity.toLowerCase():"",n=Array.isArray(e.evidence)?e.evidence.filter(i=>typeof i=="object"&&i!==null).map(i=>({file:typeof i.file=="string"?i.file:"",...ku(i.line)?{line:ku(i.line)}:{},note:typeof i.note=="string"?i.note:""})).filter(i=>i.file):[],s=typeof e.ruleId=="string"?e.ruleId.trim().toUpperCase():"";return{id:Om(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:ti.AuditSeverity.options.includes(t)?t:void 0,area:typeof e.area=="string"?e.area.slice(0,60):"",evidence:n,fix:typeof e.fix=="string"?e.fix.slice(0,2e3):""}}function ku(r){let e=typeof r=="number"?r:typeof r=="string"?parseInt(r,10):NaN;return Number.isInteger(e)&&e>0?e:void 0}function Om(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"finding"}function Nm(r){try{let e=qo.default.readFileSync(r,"utf8");return e?e.split(`
|
|
351
|
+
`).length:0}catch{return null}}function xu(r,e){let t=ei.default.resolve(r),n=[],s=[],i=0;for(let o of e){let a=[];for(let u of o.evidence){let c=u.file.trim().replace(/^\.\//,""),f=ei.default.resolve(t,c);if(f!==t&&!f.startsWith(t+ei.default.sep))continue;let p;try{p=qo.default.statSync(f)}catch{continue}if(p.isFile()){if(u.line!==void 0){let v=Nm(f);if(v!==null&&u.line>v){a.push({...u,line:void 0}),i++;continue}}a.push(u)}}if(!a.length){s.push({title:o.title,files:o.evidence.map(u=>u.file)});continue}n.push({...o,evidence:a})}return{findings:n,droppedFindings:s,correctedLines:i}}var rs=E(require("node:fs"),1),Fo=E(require("node:path"),1),Cu=E(be(),1);var Mm=20;function Iu(){return Fo.default.join(te(),"audits.json")}function xn(){try{return{byProject:JSON.parse(rs.default.readFileSync(Iu(),"utf8")).byProject??{}}}catch{return{byProject:{}}}}function Ru(r){let e=Iu();rs.default.mkdirSync(Fo.default.dirname(e),{recursive:!0,mode:448});let t=e+".tmp";rs.default.writeFileSync(t,JSON.stringify(r,null,2),{mode:384}),rs.default.renameSync(t,e)}function Eu(r,e){let t=xn(),n=t.byProject[r]??[];n.unshift(Cu.AuditRecord.parse(e)),t.byProject[r]=n.slice(0,Mm),Ru(t)}function Au(r){return(xn().byProject[r]??[]).map(e=>{let t={};for(let n of e.findings)t[n.severity]=(t[n.severity]??0)+1;return{id:e.id,role:e.role,createdAt:e.createdAt,findingCount:e.findings.length,bySeverity:t}})}function $u(r,e){let t=xn(),n=e?Date.parse(e):NaN,s={};for(let i of r){let o=(t.byProject[i]??[]).filter(u=>!Number.isFinite(n)||Date.parse(u.createdAt)>=n);if(!o.length)continue;let a={audits:o.length,findings:0,valid:0,falsePositive:0,wontFix:0,unreviewed:0};for(let u of o){a.findings+=u.findings.length;for(let c of u.findings){let f=u.verdicts[c.id]?.verdict;f==="valid"?a.valid++:f==="false-positive"?a.falsePositive++:f==="wont-fix"?a.wontFix++:a.unreviewed++}}s[i]=a}return s}function Bo(r,e,t){let n=xn(),i=(n.byProject[r]??[]).find(a=>a.id===e);if(!i)return null;i.ticketed??={},i.verdicts??={},i.lessonsWritten??=[];let o=new Set(i.findings.map(a=>a.id));t.selected&&(i.review={selected:t.selected.filter(a=>o.has(a)),updatedAt:new Date().toISOString()});for(let a of t.ticketed??[])o.has(a.findingId)&&(i.ticketed={...i.ticketed,[a.findingId]:a.issueKey});for(let a of t.verdicts??[])o.has(a.findingId)&&(i.verdicts={...i.verdicts,[a.findingId]:{verdict:a.verdict,note:a.note,by:t.verdictBy??"",at:new Date().toISOString()}});for(let a of t.markLessonsWritten??[])o.has(a)&&!i.lessonsWritten.includes(a)&&i.lessonsWritten.push(a);return Ru(n),i}function Pu(r,e){return(xn().byProject[r]??[]).find(s=>s.role===e&&(s.scope?.kind??"repo")==="repo")?.createdAt??null}function ju(r,e){return(xn().byProject[r]??[]).find(t=>t.id===e)??null}_t();var Se=E(require("node:fs"),1),at=E(require("node:path"),1),Nu=E(be(),1);var zm=`# Security baseline - what to check in any repo
|
|
350
352
|
|
|
351
353
|
Every rule has a stable id. Findings must cite the id they violate.
|
|
352
354
|
|
|
@@ -389,7 +391,7 @@ Every rule has a stable id. Findings must cite the id they violate.
|
|
|
389
391
|
- **SEC-042** TLS/redirect handling that downgrades to http.
|
|
390
392
|
|
|
391
393
|
Prioritize by real exploitability in THIS codebase, not by rule order.
|
|
392
|
-
`,
|
|
394
|
+
`,Dm=`# Test gaps - what to check in any repo
|
|
393
395
|
|
|
394
396
|
Every rule has a stable id. Findings must cite the id they violate.
|
|
395
397
|
|
|
@@ -419,7 +421,7 @@ Every rule has a stable id. Findings must cite the id they violate.
|
|
|
419
421
|
flaky suspects.
|
|
420
422
|
|
|
421
423
|
Report the GAP and why it is risky here, not generic coverage philosophy.
|
|
422
|
-
`,
|
|
424
|
+
`,Lm=`# GDPR readiness - data-protection audit for repos with EU exposure
|
|
423
425
|
|
|
424
426
|
FIRST decide exposure: if this product clearly has no EU users, no personal
|
|
425
427
|
data, or is a purely static/internal tool, say so in ONE summary sentence and
|
|
@@ -463,7 +465,7 @@ rules below. Cite the rule id AND map the area to the closest GDPR article
|
|
|
463
465
|
|
|
464
466
|
Severity: many users' data exposed or a missing legal-basis mechanism is
|
|
465
467
|
high/critical; hygiene and documentation gaps are medium/low.
|
|
466
|
-
|
|
468
|
+
`,Um=`# Architecture health - is this repository structurally sound?
|
|
467
469
|
|
|
468
470
|
Every rule has a stable id. Findings must cite the id they violate. Judge
|
|
469
471
|
against what THIS codebase is trying to be (a static site does not need
|
|
@@ -502,192 +504,192 @@ deviations.
|
|
|
502
504
|
|
|
503
505
|
Summarize with an overall verdict: is this repository HEALTHY for its
|
|
504
506
|
purpose, and what are the 2-3 structural moves with the best payoff?
|
|
505
|
-
`,
|
|
507
|
+
`,Ou={security:[{name:"baseline.md",content:zm},{name:"gdpr.md",content:Lm}],testing:[{name:"test-gaps.md",content:Dm}],architecture:[{name:"architecture-health.md",content:Um}]},qm=["You are auditing code you can READ but never run or change.","You are auditing test coverage by READING code and tests","\\`area\\`"];function Ko(r){return at.default.join(te(),"knowledge",r)}function Mu(r,e){return at.default.join(r,".ticketpilot","knowledge",`${e}.md`)}function Zo(r,e){return at.default.join(r,".ticketpilot","lessons",`${e}.md`)}function zu(r,e){let t=[],n=Ko(r),s=[];if(Se.default.existsSync(n)){for(let u of Se.default.readdirSync(n)){if(!u.endsWith(".md"))continue;let c=at.default.join(n,u),f=Se.default.readFileSync(c,"utf8");if(qm.some(p=>f.includes(p))&&Ou[r].map(v=>v.name).includes(u)&&!f.includes("SEC-0")&&!f.includes("TEST-0")&&!f.includes("GDPR-0")){Se.default.rmSync(c);continue}s.push(u)}s.sort()}let i=new Set(s);for(let u of Ou[r])i.has(u.name)||t.push({level:"global",source:"pack",name:u.name,content:u.content,editable:!1});for(let u of s)t.push({level:"org",source:"pack",name:u,content:Se.default.readFileSync(at.default.join(n,u),"utf8").slice(0,3e4),editable:!0});let o=Mu(e,r);Se.default.existsSync(o)&&t.push({level:"project",source:"pack",name:`${r}.md`,content:Se.default.readFileSync(o,"utf8").slice(0,3e4),editable:!0});let a=Zo(e,r);return Se.default.existsSync(a)&&t.push({level:"project",source:"lessons",name:`${r}.md`,content:Se.default.readFileSync(a,"utf8").slice(0,2e4),editable:!0}),t}function Du(r,e){let t=zu(r,e);return{packs:t.filter(n=>n.source==="pack").map(n=>({name:`${n.level}/${n.name}`,content:n.content})),lessons:t.find(n=>n.source==="lessons")?.content??"",layers:t}}function Go(r,e,t,n="project"){let s=n==="org"?at.default.join(Ko(e),"org-lessons.md"):Zo(r,e);Se.default.mkdirSync(at.default.dirname(s),{recursive:!0});let i=Se.default.existsSync(s)?"":`# ${e} lessons (${n} level)
|
|
506
508
|
|
|
507
509
|
Human-confirmed corrections and rules. Every ${e} audit reads this FIRST. Reference rule ids (SEC-001 style) when overriding a rule.
|
|
508
510
|
|
|
509
511
|
`;Se.default.appendFileSync(s,i+t.trimEnd()+`
|
|
510
512
|
|
|
511
|
-
`)}function
|
|
513
|
+
`)}function Lu(r,e,t,n){let s=new Date().toISOString().slice(0,10),i=r.evidence[0]?` (${r.evidence[0].file}${r.evidence[0].line?`:${r.evidence[0].line}`:""})`:"",o=r.ruleId?` \xB7 rule ${r.ruleId}`:"";return`## ${s} \xB7 ${e}${o} \xB7 ${r.title}${i}
|
|
512
514
|
Finding \`${r.id}\` [${r.severity}] was marked **${e}**`+(n?` by ${n}`:"")+`.${t?` Reason: ${t}`:""}
|
|
513
|
-
`+(e==="false-positive"?"Do not raise this class of finding here again unless the code meaningfully changes.":"Known and accepted - do not re-raise; mention only if its risk materially grows.")}function
|
|
514
|
-
${r.trim()}`}function
|
|
515
|
-
`)){let s=n.trim();!s||s.startsWith("#")||e.push(s)}return e.slice(0,10)}async function
|
|
516
|
-
[killed: timed out]`},s);c.on("close",
|
|
515
|
+
`+(e==="false-positive"?"Do not raise this class of finding here again unless the code meaningfully changes.":"Known and accepted - do not re-raise; mention only if its risk materially grows.")}function Uu(r,e){return`## ${new Date().toISOString().slice(0,10)} \xB7 taught${e?` by ${e}`:""}
|
|
516
|
+
${r.trim()}`}function qu(r){let e=[];for(let t of Nu.AuditRole.options)for(let n of zu(t,r))e.push({role:t,...n});return e}function Fu(r,e,t,n,s,i){if(!/^[a-zA-Z0-9._-]+\.md$/.test(s))throw new Error("file name must be a simple .md name");let o=t==="org"?at.default.join(Ko(e),s):n==="lessons"?Zo(r,e):Mu(r,e);Se.default.mkdirSync(at.default.dirname(o),{recursive:!0}),Se.default.writeFileSync(o,i,{mode:t==="org"?384:420})}var Ho=()=>new Date().toISOString(),g={info:r=>console.log(`${Ho()} [info] ${r}`),warn:r=>console.warn(`${Ho()} [warn] ${r}`),error:r=>console.error(`${Ho()} [error] ${r}`)};var Bu=require("node:child_process"),Ku=E(require("node:fs"),1),Zu=E(require("node:path"),1);function ri(r){for(let e of["TEST.md","TESTING.md","docs/TEST.md"]){let t=Zu.default.join(r,e);if(Ku.default.existsSync(t))return t}return null}function ni(r){let e=[];for(let t of r.matchAll(/```(?:bash|sh|shell)?\s*\n([\s\S]*?)```/g))for(let n of t[1].split(`
|
|
517
|
+
`)){let s=n.trim();!s||s.startsWith("#")||e.push(s)}return e.slice(0,10)}async function si(r,e,t={}){let n=[],s=t.perCommandTimeoutMs??6e5;for(let i of e){t.onProgress?.(`running: ${i}`);let o=Date.now(),a=await new Promise(u=>{let c=(0,Bu.spawn)("bash",["-lc",i],{cwd:r,env:{...process.env,CI:"1",FORCE_COLOR:"0"}}),f="",p=S=>{f+=S.toString(),f.length>2e5&&(f=f.slice(-1e5))};c.stdout.on("data",p),c.stderr.on("data",p);let v=setTimeout(()=>{c.kill("SIGKILL"),f+=`
|
|
518
|
+
[killed: timed out]`},s);c.on("close",S=>{clearTimeout(v),u({command:i,exitCode:S??-1,durationMs:Date.now()-o,tail:f.slice(-4e3)})}),c.on("error",S=>{clearTimeout(v),u({command:i,exitCode:-1,durationMs:Date.now()-o,tail:String(S)})})});t.onProgress?.(`exit ${a.exitCode} in ${Math.round(a.durationMs/1e3)}s: ${i}`),n.push(a)}return n}async function Cn(r){let{packs:e,lessons:t}=Du(r.role,r.repoPath);if(!e.length)return{ok:!1,error:`no knowledge packs found for the ${r.role} role - add markdown files under ~/.config/ticketpilot/knowledge/${r.role}/ on the runner`};let n="";if(r.scope.kind==="ticket"&&r.scope.ref){let p=r.scope.ref,v="";try{let T=await r.jira.getIssue(p);v=`Ticket ${p}: ${T.summary}
|
|
517
519
|
|
|
518
|
-
${T.description}`.slice(0,4e3)}catch{v=`Ticket ${p} (could not fetch its text from Jira).`}let
|
|
520
|
+
${T.description}`.slice(0,4e3)}catch{v=`Ticket ${p} (could not fetch its text from Jira).`}let S=await Co(r.repoPath,p).catch(()=>null);if(S){let{base:T,stat:x,diff:P}=await Xs(r.repoPath,S).catch(()=>({base:"",stat:"",diff:""}));n=`${v}
|
|
519
521
|
|
|
520
|
-
Its implementation branch \`${
|
|
522
|
+
Its implementation branch \`${S}\` vs \`${T}\`:
|
|
521
523
|
\`\`\`
|
|
522
524
|
${x}\`\`\`
|
|
523
525
|
\`\`\`diff
|
|
524
|
-
${
|
|
526
|
+
${P}
|
|
525
527
|
\`\`\``}else n=`${v}
|
|
526
528
|
|
|
527
|
-
No implementation branch found for ${p} - audit the parts of the codebase this ticket touches or would touch.`}else if(r.scope.kind==="branch"&&r.scope.ref){let{base:p,stat:v,diff:
|
|
529
|
+
No implementation branch found for ${p} - audit the parts of the codebase this ticket touches or would touch.`}else if(r.scope.kind==="branch"&&r.scope.ref){let{base:p,stat:v,diff:S}=await Xs(r.repoPath,r.scope.ref);n=`The diff of \`${r.scope.ref}\` vs \`${p}\`:
|
|
528
530
|
\`\`\`
|
|
529
531
|
${v}\`\`\`
|
|
530
532
|
\`\`\`diff
|
|
531
|
-
${
|
|
532
|
-
\`\`\``}let s,i;if(r.role==="testing"){let p=
|
|
533
|
-
(exit ${
|
|
534
|
-
${
|
|
533
|
+
${S}
|
|
534
|
+
\`\`\``}let s,i;if(r.role==="testing"){let p=ri(r.repoPath),v=p?ni(Gu.default.readFileSync(p,"utf8")):[];v.length&&(g.info(`Audit (testing): executing ${v.length} TEST.md command(s)`),i=await si(r.repoPath,v,{onProgress:S=>g.info(`[test-run] ${S}`)}),s=i.map(S=>`$ ${S.command}
|
|
535
|
+
(exit ${S.exitCode}, ${Math.round(S.durationMs/1e3)}s)
|
|
536
|
+
${S.tail.slice(-2e3)}`).join(`
|
|
535
537
|
|
|
536
538
|
---
|
|
537
539
|
|
|
538
|
-
`))}let o=r.model||r.agent.adapter.deepModel,a=await r.agent.adapter.run({repoPath:r.repoPath,prompt:gl(r.role,e,t,{scopeNote:n,testResults:s}),timeoutSeconds:480,bin:r.agent.bin,mode:"read_only",maxTurns:120,sessionId:(0,Uo.randomUUID)(),model:o,onLog:(p,v)=>{p==="agent"&&m.info(`[audit:${r.role}] ${v.slice(0,160)}`)}}),l=yl(a.resultText);if("error"in l)return{ok:!1,error:l.error};let c=vl(r.repoPath,l.findings);for(let p of c.droppedFindings)m.warn(`[audit:${r.role}] dropped "${p.title}" - cited files do not exist: `+p.files.join(", "));let f={id:(0,Uo.randomUUID)(),role:r.role,createdAt:new Date().toISOString(),model:a.model||o,summary:l.summary,packNames:e.map(p=>p.name),findings:c.findings,costUsd:a.costUsd??0,ticketed:{},verdicts:{},lessonsWritten:[],scope:r.scope,...i?{testRun:i}:{}};return kl(r.projectId,f),m.info(`Audit (${r.role}${r.scope.kind!=="repo"?` \xB7 ${r.scope.kind}:${r.scope.ref}`:""}) done: ${c.findings.length} finding(s)`+(l.dropped?`, ${l.dropped} malformed`:"")+(c.droppedFindings.length?`, ${c.droppedFindings.length} dropped for citing files that do not exist`:"")+(c.correctedLines?`, ${c.correctedLines} bad line number(s) stripped`:"")),{ok:!0,audit:f}}var Dr=R(ve(),1);var Qo=R(require("node:fs"),1),si=R(require("node:path"),1),ii=require("node:crypto"),Pe=R(ve(),1);var Ar=R(ve(),1);var qo=R(require("node:fs"),1),Ul=R(require("node:os"),1),Ys=R(require("node:path"),1),ql=require("node:child_process"),Fl=R(require("node:readline"),1),Bl=R(ve(),1),jm=4e3,Om={read_only:["Read(./**)","Glob(./**)","Grep(./**)"],edit_no_shell:["Read(./**)","Glob(./**)","Grep(./**)","Edit(./**)","Write(./**)"]};function Nm(r){if(process.env.ANTHROPIC_API_KEY)return"API key";let e=r??Ys.default.join(Ul.default.homedir(),".claude");try{if(qo.default.existsSync(Ys.default.join(e,".credentials.json"))||qo.default.existsSync(Ys.default.join(e,"credentials.json")))return"subscription"}catch{}return"unknown"}async function Mm(r){let e=["-p","--output-format","stream-json","--verbose","--allowedTools",Om[r.mode].join(","),"--max-turns",String(r.maxTurns??60),...r.model?["--model",r.model]:[],...r.resume?["--resume",r.sessionId]:["--session-id",r.sessionId]],t=Nm(r.configDir);return t!=="unknown"&&r.onLog("info",t==="subscription"?"Billing: Claude subscription - costs shown are notional list prices, not money charged":"Billing: Anthropic API key - costs shown are actual metered spend"),new Promise(n=>{let s=(0,ql.spawn)(r.bin,e,{cwd:r.repoPath,env:r.configDir?{...process.env,CLAUDE_CONFIG_DIR:r.configDir}:process.env,stdio:["pipe","pipe","pipe"]}),i={ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,billingMode:t==="subscription"?"subscription":t==="API key"?"api":"unknown"},o=0,a=0,l=0,c=0,f=0,p=()=>{if(!r.onUsage)return;let J=Date.now();J-f<jm||(f=J,r.onUsage({inputTokens:a,outputTokens:l,cacheReadTokens:c,turns:o}))},v=!1,k=()=>{v||(v=!0,clearTimeout(x),r.signal?.removeEventListener("abort",T),n(i))},T=()=>{i.cancelled=!0,i.error="stopped from the dashboard",r.onLog("error",i.error),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),3e3).unref()};r.signal?.addEventListener("abort",T,{once:!0});let x=setTimeout(()=>{i.timedOut=!0,i.error=`run exceeded ${r.timeoutSeconds}s wall-clock limit`,r.onLog("error",i.error),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),5e3).unref()},r.timeoutSeconds*1e3);s.stdin.write(r.prompt),s.stdin.end(),Fl.default.createInterface({input:s.stdout}).on("line",J=>{if(!J.trim())return;let M;try{M=JSON.parse(J)}catch{r.onLog("agent",J.slice(0,1e3));return}if(M.type==="system"&&M.subtype==="init")i.model=typeof M.model=="string"?M.model:void 0,r.onLog("info",`Claude Code session started (model: ${M.model??"default"})`);else if(M.type==="assistant"){o+=1;let z=M.message?.usage;z&&(a+=Number(z.input_tokens??0)+Number(z.cache_creation_input_tokens??0),l+=Number(z.output_tokens??0),c+=Number(z.cache_read_input_tokens??0),p());for(let Q of M.message?.content??[])if(Q.type==="text"&&Q.text?.trim())r.onLog("agent",Q.text.trim().slice(0,4e3));else if(Q.type==="tool_use"){let h=Q.input??{},g=["file_path","path","pattern","command","description","url"].map(C=>typeof h[C]=="string"?`${C}=${h[C]}`:null).filter(Boolean).join(" "),w=JSON.stringify(h).slice(0,400);r.onLog("info",`tool ${Q.name} ${g?`${g} `:""}${w}`)}}else M.type==="result"&&(i.costUsd=Number(M.total_cost_usd??0),i.inputTokens=Number(M.usage?.input_tokens??0)+Number(M.usage?.cache_creation_input_tokens??0),i.outputTokens=Number(M.usage?.output_tokens??0),a=Math.max(i.inputTokens,a),l=Math.max(i.outputTokens,l),i.inputTokens=a,i.outputTokens=l,c=Number(M.usage?.cache_read_input_tokens??c),i.cacheReadTokens=c,r.onUsage&&(r.onUsage({inputTokens:a,outputTokens:l,cacheReadTokens:c,costUsd:i.costUsd,turns:o}),f=Date.now()),M.subtype==="success"&&!M.is_error?(i.ok=!0,i.resultText=String(M.result??"")):M.subtype==="error_max_turns"?(i.turnLimitHit=!0,i.error=`hit the ${r.maxTurns??60}-turn limit before finishing`):(i.error=String(M.result??M.subtype??"unknown Claude Code error"),/rate.?limit|usage limit|limit (reached|exceeded)|overloaded/i.test(i.error)&&(i.error=`Claude usage limit hit for this account - the run will work again once the limit window resets. Original error: ${i.error.slice(0,400)}`)))});let S="";s.stderr.on("data",J=>{S=(S+J.toString()).slice(-2e3)}),s.on("error",J=>{i.error=`failed to start ${r.bin}: ${J.message}`,r.onLog("error",i.error),k()}),s.on("close",J=>{!i.ok&&!i.error&&(i.error=i.timedOut?i.error:`claude exited with code ${J}${S?`: ${S.slice(-500)}`:""}`),k()})})}var Xs={id:"claude-code",displayName:"Claude Code",fastModel:"claude-sonnet-5",deepModel:"claude-fable-5",capabilities:Bl.REGISTERED_AGENTS.find(r=>r.id==="claude-code").capabilities,run:Mm};var Kl=require("node:child_process"),Zl=R(require("node:readline"),1),Gl=R(ve(),1);async function zm(r){if(r.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(r.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",r.repoPath,...r.model?["--model",r.model]:[],"-"];return new Promise(t=>{let n=(0,Kl.spawn)(r.bin,e,{cwd:r.repoPath,env:process.env,stdio:["pipe","pipe","pipe"]}),s={ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,cacheReadTokens:0},i="",o=!1,a=()=>{o||(o=!0,clearTimeout(l),t(s))},l=setTimeout(()=>{s.timedOut=!0,s.error=`run exceeded ${r.timeoutSeconds}s wall-clock limit`,r.onLog("error",s.error),n.kill("SIGTERM"),setTimeout(()=>n.kill("SIGKILL"),5e3).unref()},r.timeoutSeconds*1e3);n.stdin.write(r.prompt),n.stdin.end(),Zl.default.createInterface({input:n.stdout}).on("line",p=>{if(!p.trim())return;let v;try{v=JSON.parse(p)}catch{r.onLog("agent",p.slice(0,1e3));return}let k=v.item??v.msg??v,T=k?.type??v.type,x=k?.text??k?.message??"";T==="agent_message"&&typeof x=="string"&&x.trim()?(i=x,r.onLog("agent",x.trim().slice(0,4e3))):T==="command_execution"||T==="exec_command_begin"?r.onLog("info",`tool ${String(k?.command??"").slice(0,300)}`):T==="error"&&typeof x=="string"&&x&&r.onLog("error",x.slice(0,1e3))});let f="";n.stderr.on("data",p=>{f=(f+p.toString()).slice(-2e3)}),n.on("error",p=>{s.error=`failed to start ${r.bin}: ${p.message} - is the Codex CLI installed and logged in?`,r.onLog("error",s.error),a()}),n.on("close",p=>{p===0&&i.trim()?(s.ok=!0,s.resultText=i):s.error||(s.error=`codex exited with code ${p}`+(i?"":" and produced no answer")+(f?`: ${f.slice(-500)}`:"")),a()})})}var Fo={id:"codex",fastModel:"",deepModel:"",displayName:"OpenAI Codex CLI (experimental)",capabilities:Gl.REGISTERED_AGENTS.find(r=>r.id==="codex").capabilities,run:zm};var Dm={[Xs.id]:Xs,[Fo.id]:Fo};function qt(r){return Dm[r||Ar.DEFAULT_AGENT_ID]??null}function vt(r,e){return!e||e===Xs.id?r.claudeBin:r.agents[e]?.bin??e}function Qs(r,e){let t=qt(r);if(!t)return`no agent adapter named "${r}" on this runner - update the runner, or set the rule's agent to "${Ar.DEFAULT_AGENT_ID}"`;let n=(0,Ar.missingAgentCapabilities)(t.id,e);return n&&n.length?`agent "${t.displayName}" cannot run ${e} rules: it cannot guarantee ${n.join(", ")}. Allwright refuses rather than weakening the isolation silently.`:null}function We(r,e,t){let n=e.defaultAgent||Ar.DEFAULT_AGENT_ID,s=qt(n);if(!s)return{error:`this project's default agent "${n}" is not on this runner - update the runner, or change the project's agent`};let i=(0,Ar.missingAgentCapabilities)(s.id,t);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:vt(r,s.id)}}function bt(r,e){return r.replace(/\{\{(\w+)\}\}/g,(t,n)=>n in e?e[n]:t)}var ec=R(ve(),1);it();Ir();Ut();var Te=R(require("node:fs"),1),wn=R(require("node:path"),1);var Um=_.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"),changesRequestedNotified:_.boolean().optional(),conflictNotified:_.boolean().optional()}),qm=_.record(Um),Fm=_.object({runId:_.string(),issueKey:_.string(),issueSummary:_.string().default(""),projectId:_.string(),repoName:_.string(),environmentName:_.string(),requestedBy:_.string().default(""),createdAt:_.string()}),Bm=_.record(Fm),Km=_.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"),issueSummary:_.string().default(""),claudeConfigDir:_.string().optional(),agent:_.string().optional(),model:_.string().optional(),actorEmail:_.string().optional()}),Zm=_.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"),doneLabel:_.string(),failedLabel:_.string(),jiraTransition:_.string().optional(),jiraTransitionOnMerge:_.string().optional(),actorEmail:_.string().optional(),resultSummary:_.string().default(""),costUsd:_.number().default(0),nextLogSeq:_.number().int().default(1e5),createdAt:_.string()}),Gm=_.record(Zm),Vm=_.object({runId:_.string(),issueKey:_.string(),repoName:_.string(),owner:_.string(),repo:_.string(),prNumber:_.number().int(),prUrl:_.string(),jiraTransitionOnMerge:_.string().default(""),createdAt:_.string()}),Hm=_.record(Vm),Wm=_.record(Km);function Vl(){return wn.default.join(te(),"pending-runs.json")}function Bo(){return wn.default.join(te(),"pending-deploys.json")}function Ko(){return wn.default.join(te(),"pending-inputs.json")}function Zo(){return wn.default.join(te(),"merge-watch.json")}function Go(){return wn.default.join(te(),"pending-pushes.json")}function Vo(){let r=Go();if(!Te.default.existsSync(r))return{};try{return Gm.parse(JSON.parse(Te.default.readFileSync(r,"utf8")))}catch{return{}}}function Ho(r){let e=Vo();e[r.runId]=r,wt(Go(),e)}function ei(r){return Vo()[r]??null}function Wo(r){let e=Vo();r in e&&(delete e[r],wt(Go(),e))}function ti(){let r=Zo();if(!Te.default.existsSync(r))return{};try{return Hm.parse(JSON.parse(Te.default.readFileSync(r,"utf8")))}catch{return{}}}function Hl(r){let e=ti();e[r.runId]=r,wt(Zo(),e)}function Wn(r){let e=ti();r in e&&(delete e[r],wt(Zo(),e))}function Jn(){let r=Vl();if(!Te.default.existsSync(r))return{};try{return qm.parse(JSON.parse(Te.default.readFileSync(r,"utf8")))}catch{return{}}}function wt(r,e){Te.default.mkdirSync(te(),{recursive:!0,mode:448});let t=r+".tmp";Te.default.writeFileSync(t,JSON.stringify(e,null,2)+`
|
|
539
|
-
`,{mode:384}),Te.default.renameSync(t,r),Te.default.chmodSync(r,384)}function
|
|
540
|
+
`))}let o=r.model||r.agent.adapter.deepModel,a=await r.agent.adapter.run({repoPath:r.repoPath,prompt:Su(r.role,e,t,{scopeNote:n,testResults:s}),timeoutSeconds:480,bin:r.agent.bin,mode:"read_only",maxTurns:120,sessionId:(0,Vo.randomUUID)(),model:o,onLog:(p,v)=>{p==="agent"&&g.info(`[audit:${r.role}] ${v.slice(0,160)}`)}}),u=Tu(a.resultText);if("error"in u)return{ok:!1,error:u.error};let c=xu(r.repoPath,u.findings);for(let p of c.droppedFindings)g.warn(`[audit:${r.role}] dropped "${p.title}" - cited files do not exist: `+p.files.join(", "));let f={id:(0,Vo.randomUUID)(),role:r.role,createdAt:new Date().toISOString(),model:a.model||o,summary:u.summary,packNames:e.map(p=>p.name),findings:c.findings,costUsd:a.costUsd??0,ticketed:{},verdicts:{},lessonsWritten:[],scope:r.scope,...i?{testRun:i}:{}};return Eu(r.projectId,f),g.info(`Audit (${r.role}${r.scope.kind!=="repo"?` \xB7 ${r.scope.kind}:${r.scope.ref}`:""}) done: ${c.findings.length} finding(s)`+(u.dropped?`, ${u.dropped} malformed`:"")+(c.droppedFindings.length?`, ${c.droppedFindings.length} dropped for citing files that do not exist`:"")+(c.correctedLines?`, ${c.correctedLines} bad line number(s) stripped`:"")),{ok:!0,audit:f}}var Kr=E(be(),1);var oa=E(require("node:fs"),1),di=E(require("node:path"),1),hi=require("node:crypto"),Oe=E(be(),1);var Mr=E(be(),1);var Wo=E(require("node:fs"),1),Hu=E(require("node:os"),1),ii=E(require("node:path"),1),Vu=require("node:child_process"),Wu=E(require("node:readline"),1),Ju=E(be(),1),Fm=4e3,Bm={read_only:["Read(./**)","Glob(./**)","Grep(./**)"],edit_no_shell:["Read(./**)","Glob(./**)","Grep(./**)","Edit(./**)","Write(./**)"]};function Km(r){if(process.env.ANTHROPIC_API_KEY)return"API key";let e=r??ii.default.join(Hu.default.homedir(),".claude");try{if(Wo.default.existsSync(ii.default.join(e,".credentials.json"))||Wo.default.existsSync(ii.default.join(e,"credentials.json")))return"subscription"}catch{}return"unknown"}async function Zm(r){let e=["-p","--output-format","stream-json","--verbose","--allowedTools",Bm[r.mode].join(","),"--max-turns",String(r.maxTurns??60),...r.model?["--model",r.model]:[],...r.resume?["--resume",r.sessionId]:["--session-id",r.sessionId]],t=Km(r.configDir);return t!=="unknown"&&r.onLog("info",t==="subscription"?"Billing: Claude subscription - costs shown are notional list prices, not money charged":"Billing: Anthropic API key - costs shown are actual metered spend"),new Promise(n=>{let s=(0,Vu.spawn)(r.bin,e,{cwd:r.repoPath,env:r.configDir?{...process.env,CLAUDE_CONFIG_DIR:r.configDir}:process.env,stdio:["pipe","pipe","pipe"]}),i={ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,billingMode:t==="subscription"?"subscription":t==="API key"?"api":"unknown"},o=0,a=0,u=0,c=0,f=0,p=()=>{if(!r.onUsage)return;let J=Date.now();J-f<Fm||(f=J,r.onUsage({inputTokens:a,outputTokens:u,cacheReadTokens:c,turns:o}))},v=!1,S=()=>{v||(v=!0,clearTimeout(x),r.signal?.removeEventListener("abort",T),n(i))},T=()=>{i.cancelled=!0,i.error="stopped from the dashboard",r.onLog("error",i.error),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),3e3).unref()};r.signal?.addEventListener("abort",T,{once:!0});let x=setTimeout(()=>{i.timedOut=!0,i.error=`run exceeded ${r.timeoutSeconds}s wall-clock limit`,r.onLog("error",i.error),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),5e3).unref()},r.timeoutSeconds*1e3);s.stdin.write(r.prompt),s.stdin.end(),Wu.default.createInterface({input:s.stdout}).on("line",J=>{if(!J.trim())return;let O;try{O=JSON.parse(J)}catch{r.onLog("agent",J.slice(0,1e3));return}if(O.type==="system"&&O.subtype==="init")i.model=typeof O.model=="string"?O.model:void 0,r.onLog("info",`Claude Code session started (model: ${O.model??"default"})`);else if(O.type==="assistant"){o+=1;let L=O.message?.usage;L&&(a+=Number(L.input_tokens??0)+Number(L.cache_creation_input_tokens??0),u+=Number(L.output_tokens??0),c+=Number(L.cache_read_input_tokens??0),p());for(let Q of O.message?.content??[])if(Q.type==="text"&&Q.text?.trim())r.onLog("agent",Q.text.trim().slice(0,4e3));else if(Q.type==="tool_use"){let h=Q.input??{},m=["file_path","path","pattern","command","description","url"].map(C=>typeof h[C]=="string"?`${C}=${h[C]}`:null).filter(Boolean).join(" "),y=JSON.stringify(h).slice(0,400);r.onLog("info",`tool ${Q.name} ${m?`${m} `:""}${y}`)}}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),a=Math.max(i.inputTokens,a),u=Math.max(i.outputTokens,u),i.inputTokens=a,i.outputTokens=u,c=Number(O.usage?.cache_read_input_tokens??c),i.cacheReadTokens=c,r.onUsage&&(r.onUsage({inputTokens:a,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 ${r.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 _="";s.stderr.on("data",J=>{_=(_+J.toString()).slice(-2e3)}),s.on("error",J=>{i.error=`failed to start ${r.bin}: ${J.message}`,r.onLog("error",i.error),S()}),s.on("close",J=>{!i.ok&&!i.error&&(i.error=i.timedOut?i.error:`claude exited with code ${J}${_?`: ${_.slice(-500)}`:""}`),S()})})}var oi={id:"claude-code",displayName:"Claude Code",fastModel:"claude-sonnet-5",deepModel:"claude-fable-5",capabilities:Ju.REGISTERED_AGENTS.find(r=>r.id==="claude-code").capabilities,run:Zm};var Yu=require("node:child_process"),Xu=E(require("node:readline"),1),Qu=E(be(),1);async function Gm(r){if(r.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(r.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",r.repoPath,...r.model?["--model",r.model]:[],"-"];return new Promise(t=>{let n=(0,Yu.spawn)(r.bin,e,{cwd:r.repoPath,env:process.env,stdio:["pipe","pipe","pipe"]}),s={ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,cacheReadTokens:0},i="",o=!1,a=()=>{o||(o=!0,clearTimeout(u),t(s))},u=setTimeout(()=>{s.timedOut=!0,s.error=`run exceeded ${r.timeoutSeconds}s wall-clock limit`,r.onLog("error",s.error),n.kill("SIGTERM"),setTimeout(()=>n.kill("SIGKILL"),5e3).unref()},r.timeoutSeconds*1e3);n.stdin.write(r.prompt),n.stdin.end(),Xu.default.createInterface({input:n.stdout}).on("line",p=>{if(!p.trim())return;let v;try{v=JSON.parse(p)}catch{r.onLog("agent",p.slice(0,1e3));return}let S=v.item??v.msg??v,T=S?.type??v.type,x=S?.text??S?.message??"";T==="agent_message"&&typeof x=="string"&&x.trim()?(i=x,r.onLog("agent",x.trim().slice(0,4e3))):T==="command_execution"||T==="exec_command_begin"?r.onLog("info",`tool ${String(S?.command??"").slice(0,300)}`):T==="error"&&typeof x=="string"&&x&&r.onLog("error",x.slice(0,1e3))});let f="";n.stderr.on("data",p=>{f=(f+p.toString()).slice(-2e3)}),n.on("error",p=>{s.error=`failed to start ${r.bin}: ${p.message} - is the Codex CLI installed and logged in?`,r.onLog("error",s.error),a()}),n.on("close",p=>{p===0&&i.trim()?(s.ok=!0,s.resultText=i):s.error||(s.error=`codex exited with code ${p}`+(i?"":" and produced no answer")+(f?`: ${f.slice(-500)}`:"")),a()})})}var Jo={id:"codex",fastModel:"",deepModel:"",displayName:"OpenAI Codex CLI (experimental)",capabilities:Qu.REGISTERED_AGENTS.find(r=>r.id==="codex").capabilities,run:Gm};var Hm={[oi.id]:oi,[Jo.id]:Jo};function lt(r){return Hm[r||Mr.DEFAULT_AGENT_ID]??null}function We(r,e){return!e||e===oi.id?r.claudeBin:r.agents[e]?.bin??e}function In(r,e){let t=lt(r);if(!t)return`no agent adapter named "${r}" on this runner - update the runner, or set the rule's agent to "${Mr.DEFAULT_AGENT_ID}"`;let n=(0,Mr.missingAgentCapabilities)(t.id,e);return n&&n.length?`agent "${t.displayName}" cannot run ${e} rules: it cannot guarantee ${n.join(", ")}. Allwright refuses rather than weakening the isolation silently.`:null}function Je(r,e,t){let n=e.defaultAgent||Mr.DEFAULT_AGENT_ID,s=lt(n);if(!s)return{error:`this project's default agent "${n}" is not on this runner - update the runner, or change the project's agent`};let i=(0,Mr.missingAgentCapabilities)(s.id,t);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:We(r,s.id)}}function kt(r,e){return r.replace(/\{\{(\w+)\}\}/g,(t,n)=>n in e?e[n]:t)}var ac=E(be(),1);Ye();Or();_t();var Te=E(require("node:fs"),1),Rn=E(require("node:path"),1);var Wm=k.object({runId:k.string(),issueKey:k.string(),repoName:k.string(),owner:k.string(),repo:k.string(),prNumber:k.number().int(),prUrl:k.string(),branch:k.string(),headSha:k.string(),doneLabel:k.string(),failedLabel:k.string(),jiraTransition:k.string().optional(),mergeOnApprove:k.boolean().default(!1),mergeMethod:k.enum(["squash","merge","rebase"]).default("squash"),changesRequestedNotified:k.boolean().optional(),conflictNotified:k.boolean().optional(),agentConfigDir:k.string().optional()}),Jm=k.record(Wm),Ym=k.object({runId:k.string(),issueKey:k.string(),issueSummary:k.string().default(""),projectId:k.string(),repoName:k.string(),environmentName:k.string(),requestedBy:k.string().default(""),createdAt:k.string()}),Xm=k.record(Ym),Qm=k.object({runId:k.string(),issueKey:k.string(),kind:k.enum(["plan","implement"]),repoPath:k.string(),sessionId:k.string(),doneLabel:k.string(),failedLabel:k.string(),timeoutSeconds:k.number(),createdAt:k.string(),questionsPostedAt:k.string(),rounds:k.number().int().default(1),nextLogSeq:k.number().int().nonnegative().default(0),baseRepoPath:k.string().optional(),repoName:k.string().optional(),branch:k.string().optional(),baseBranch:k.string().optional(),jiraTransition:k.string().optional(),jiraTransitionOnMerge:k.string().optional(),requireApproval:k.boolean().optional(),maxTurns:k.number().int().optional(),runTests:k.boolean().default(!0),mergeOnApprove:k.boolean().default(!1),mergeMethod:k.enum(["squash","merge","rebase"]).default("squash"),issueSummary:k.string().default(""),claudeConfigDir:k.string().optional(),agent:k.string().optional(),model:k.string().optional(),actorEmail:k.string().optional()}),eg=k.object({runId:k.string(),issueKey:k.string(),issueSummary:k.string().default(""),repoName:k.string(),baseRepoPath:k.string(),branch:k.string(),baseBranch:k.string(),headSha:k.string(),requireApproval:k.boolean(),mergeOnApprove:k.boolean().default(!1),mergeMethod:k.enum(["squash","merge","rebase"]).default("squash"),doneLabel:k.string(),failedLabel:k.string(),jiraTransition:k.string().optional(),jiraTransitionOnMerge:k.string().optional(),actorEmail:k.string().optional(),resultSummary:k.string().default(""),costUsd:k.number().default(0),nextLogSeq:k.number().int().default(1e5),createdAt:k.string()}),tg=k.record(eg),rg=k.object({runId:k.string(),issueKey:k.string(),repoName:k.string(),owner:k.string(),repo:k.string(),prNumber:k.number().int(),prUrl:k.string(),jiraTransitionOnMerge:k.string().default(""),createdAt:k.string()}),ng=k.record(rg),sg=k.record(Qm);function ec(){return Rn.default.join(te(),"pending-runs.json")}function Yo(){return Rn.default.join(te(),"pending-deploys.json")}function Xo(){return Rn.default.join(te(),"pending-inputs.json")}function Qo(){return Rn.default.join(te(),"merge-watch.json")}function ea(){return Rn.default.join(te(),"pending-pushes.json")}function ta(){let r=ea();if(!Te.default.existsSync(r))return{};try{return tg.parse(JSON.parse(Te.default.readFileSync(r,"utf8")))}catch{return{}}}function ra(r){let e=ta();e[r.runId]=r,St(ea(),e)}function ai(r){return ta()[r]??null}function na(r){let e=ta();r in e&&(delete e[r],St(ea(),e))}function li(){let r=Qo();if(!Te.default.existsSync(r))return{};try{return ng.parse(JSON.parse(Te.default.readFileSync(r,"utf8")))}catch{return{}}}function tc(r){let e=li();e[r.runId]=r,St(Qo(),e)}function ns(r){let e=li();r in e&&(delete e[r],St(Qo(),e))}function ss(){let r=ec();if(!Te.default.existsSync(r))return{};try{return Jm.parse(JSON.parse(Te.default.readFileSync(r,"utf8")))}catch{return{}}}function St(r,e){Te.default.mkdirSync(te(),{recursive:!0,mode:448});let t=r+".tmp";Te.default.writeFileSync(t,JSON.stringify(e,null,2)+`
|
|
541
|
+
`,{mode:384}),Te.default.renameSync(t,r),Te.default.chmodSync(r,384)}function rc(r){St(ec(),r)}function Bt(r){let e=ss();e[r.runId]=r,rc(e)}function is(r){return ss()[r]??null}function Dr(r){let e=ss();r in e&&(delete e[r],rc(e))}function sa(){let r=Yo();if(!Te.default.existsSync(r))return{};try{return Xm.parse(JSON.parse(Te.default.readFileSync(r,"utf8")))}catch{return{}}}function nc(r){let e=sa();e[r.runId]=r,St(Yo(),e)}function ui(r){return sa()[r]??null}function ci(r){let e=sa();r in e&&(delete e[r],St(Yo(),e))}function En(){let r=Xo();if(!Te.default.existsSync(r))return{};try{return sg.parse(JSON.parse(Te.default.readFileSync(r,"utf8")))}catch{return{}}}function sc(r){let e=En();e[r.runId]=r,St(Xo(),e)}function ut(r){let e=En();r in e&&(delete e[r],St(Xo(),e))}var ig=`
|
|
540
542
|
|
|
541
|
-
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.`;function
|
|
543
|
+
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.`;function aa(r){return oa.default.existsSync(di.default.join(r,"DESIGN.md"))?`
|
|
542
544
|
|
|
543
|
-
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
|
|
545
|
+
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 lc=5,ic=2,og=8,oc=2,ag="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 lg(r,e,t,n){let s=Date.now(),i="";n&&(i=await n().catch(()=>""));let o=await r.run(e),a=0,u="",c=n?og:ic;for(;!o.ok&&o.turnLimitHit&&!o.cancelled&&r.capabilities.sessionResume;){if(a>=c){u=`resume cap (${c}) reached`;break}if(n&&a>=ic){let p=await n().catch(()=>""),v=p!==""&&p!==i;if(i=p,!v){u="the last resume produced no new work";break}if(Date.now()-s>e.timeoutSeconds*oc*1e3){u=`wall-clock budget (${oc}x the rule's timeout) exhausted`;break}}a++,t("info",`Turn limit hit mid-work - auto-resuming the same session (resume ${a}, cap ${c})`);let f=await r.run({...e,prompt:ag,resume:!0});f.costUsd+=o.costUsd,f.inputTokens+=o.inputTokens,f.outputTokens+=o.outputTokens,o=f}return!o.ok&&o.turnLimitHit&&r.capabilities.sessionResume&&(o.error=`${o.error??"hit the turn limit"} - even after ${a} 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 ia=new Map;function uc(r){let e=ia.get(r);return e?(e.abort(),!0):!1}async function as(r,e,t,n,s){let i=new AbortController;ia.set(r,i);try{return await lg(e,{...t,signal:i.signal},n,s)}finally{ia.delete(r)}}function Lr(r,e,t=0){let n=t;return{emit:(a,u)=>{e.send({type:"run.log",runId:r,seq:n++,ts:new Date().toISOString(),level:a,message:u}),a!=="agent"&&g.info(`[run ${r}] ${u}`)},setStatus:(a,u={})=>{e.send({type:"run.status",runId:r,status:a,...u})},sendUsage:a=>{e.send({type:"run.usage",runId:r,inputTokens:Math.round(a.inputTokens),outputTokens:Math.round(a.outputTokens),cacheReadTokens:a.cacheReadTokens===void 0?void 0:Math.round(a.cacheReadTokens),costUsd:a.costUsd,turns:a.turns})},nextSeq:()=>n}}async function fi(r){return r.rule.action.type==="implement"?dg(r):r.rule.action.type==="respond"?cg(r):ug(r)}async function ug(r){let{emit:e,setStatus:t,sendUsage:n,nextSeq:s}=Lr(r.runId,r.transport),{trigger:i}=r.rule,o=r.rule.action;if(o.type!=="plan_only")return;let a=In(o.agent,o.type);if(a){e("error",a),await An(r,a),t("failed",{error:a});return}let u=(0,hi.randomUUID)();try{t("running"),e("info",`Run started for ${r.issueKey} (rule "${r.rule.name}", plan-only)`),e("info",`Fetching ${r.issueKey} from Jira`);let c=await r.jira.getIssue(r.issueKey),f=kt(o.promptTemplate,{issueKey:c.key,summary:c.summary,description:c.description||"(no description)",comments:us(c.comments)})+await dn(r.jira,c.attachments,r.repoPath,e)+aa(r.repoPath);e("info",`Starting Claude Code in ${r.repoPath} - read-only tools, path-jailed to the repo, timeout ${o.timeoutSeconds}s`);let p=await as(r.runId,lt(o.agent),{repoPath:r.repoPath,prompt:f,timeoutSeconds:o.timeoutSeconds,bin:We(r.cfg,o.agent),configDir:r.claudeConfigDir,mode:"read_only",model:o.model||void 0,sessionId:u,onLog:(T,x)=>e(T,x),onUsage:n},e),v={costUsd:p.costUsd,inputTokens:p.inputTokens,outputTokens:p.outputTokens,billingMode:p.billingMode,model:p.model};if(!p.ok||!p.resultText.trim()){let T=p.error??"Claude Code produced no output";e("error",`Run failed: ${T}`),await An(r,T),t(p.timedOut?"timed_out":"failed",{error:T,...p.cancelled?{errorKind:"guard"}:{},...v});return}let S=pi(p.resultText);if(S){await mi({kind:"plan",runId:r.runId,issueKey:r.issueKey,repoPath:r.repoPath,sessionId:u,doneLabel:i.doneLabel,failedLabel:i.failedLabel,timeoutSeconds:o.timeoutSeconds,jira:r.jira,nextLogSeq:s(),rounds:1,claudeConfigDir:r.claudeConfigDir,agent:o.agent,model:o.model},S,e,t,v);return}await dc({runId:r.runId,issueKey:r.issueKey,doneLabel:i.doneLabel,jira:r.jira,resultText:p.resultText,costFields:v,emit:e,setStatus:t})}catch(c){let f=c instanceof Error?c.message:String(c);e("error",`Run failed: ${f}`),await An(r,f),t("failed",{error:f})}finally{Mt(r.repoPath)}}async function cc(r,e,t,n){let{emit:s,setStatus:i,sendUsage:o,nextSeq:a}=Lr(r.runId,n.transport,r.nextLogSeq);try{i("running"),s("info",`Reply received on ${r.issueKey} - continuing run \`${r.runId}\``);let u=kc(e)+await dn(n.jiraFor(r.repoName??""),t,r.repoPath,s),c=await as(r.runId,lt(r.agent),{repoPath:r.repoPath,prompt:u,timeoutSeconds:r.timeoutSeconds,bin:We(n.cfg,r.agent??""),configDir:r.claudeConfigDir,mode:"read_only",model:r.model||void 0,sessionId:r.sessionId,resume:!0,onLog:(v,S)=>s(v,S),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 v=c.error??"Claude Code produced no output";s("error",`Run failed: ${v}`),await Tt(n.jiraFor(r.repoName??""),r.issueKey,r.runId,r.failedLabel,v),ut(r.runId),i(c.timedOut?"timed_out":"failed",{error:v,...c.cancelled?{errorKind:"guard"}:{},...f});return}let p=pi(c.resultText);if(p){if(r.rounds>=lc){await Sc(n.jiraFor(r.repoName??""),r,s,i,f);return}await mi({kind:"plan",runId:r.runId,issueKey:r.issueKey,repoPath:r.repoPath,sessionId:r.sessionId,doneLabel:r.doneLabel,failedLabel:r.failedLabel,timeoutSeconds:r.timeoutSeconds,jira:n.jiraFor(r.repoName??""),nextLogSeq:a(),rounds:r.rounds+1,createdAt:r.createdAt,claudeConfigDir:r.claudeConfigDir,actorEmail:r.actorEmail,agent:r.agent,model:r.model},p,s,i,f);return}await dc({runId:r.runId,issueKey:r.issueKey,doneLabel:r.doneLabel,jira:n.jiraFor(r.repoName??""),resultText:c.resultText,costFields:f,emit:s,setStatus:i}),ut(r.runId)}catch(u){let c=u instanceof Error?u.message:String(u);s("error",`Run failed: ${c}`),await Tt(n.jiraFor(r.repoName??""),r.issueKey,r.runId,r.failedLabel,c),ut(r.runId),i("failed",{error:c})}finally{Mt(r.repoPath)}}async function dc(r){let{runId:e,issueKey:t,doneLabel:n,jira:s,resultText:i,costFields:o,emit:a,setStatus:u}=r;u("posting",o),a("info",`Posting plan to ${t} (${i.length} chars)`);let c=`
|
|
544
546
|
|
|
545
547
|
---
|
|
546
|
-
_Allwright plan-only run \`${e}\` \xB7 cost $${o.costUsd.toFixed(4)} \xB7 no code was written._`;await s.addComment(t,i+c),await s.editLabels(t,{add:[n],remove:[
|
|
548
|
+
_Allwright plan-only run \`${e}\` \xB7 cost $${o.costUsd.toFixed(4)} \xB7 no code was written._`;await s.addComment(t,i+c),await s.editLabels(t,{add:[n],remove:[Oe.NEEDS_INPUT_LABEL]}),a("info",`Labeled ${t} with "${n}"`),u("succeeded",{...o,resultSummary:os(i)}),a("info",`Run succeeded \xB7 $${o.costUsd.toFixed(4)}`)}async function cg(r){let{emit:e,setStatus:t,sendUsage:n}=Lr(r.runId,r.transport),s=r.rule.action;if(s.type!=="respond")return;let i=In(s.agent,s.type);if(i){e("error",i),await r.jira.addComment(r.issueKey,`**Allwright could not answer this question.**
|
|
547
549
|
|
|
548
|
-
${i}`).catch(()=>{}),t("failed",{error:i});return}try{t("running"),e("info",`Run started for ${r.issueKey} (rule "${r.rule.name}", respond`+(r.question?`, question from ${r.question.author}`:"")+")"),e("info",`Fetching ${r.issueKey} from Jira`);let o=await r.jira.getIssue(r.issueKey),a=
|
|
550
|
+
${i}`).catch(()=>{}),t("failed",{error:i});return}try{t("running"),e("info",`Run started for ${r.issueKey} (rule "${r.rule.name}", respond`+(r.question?`, question from ${r.question.author}`:"")+")"),e("info",`Fetching ${r.issueKey} from Jira`);let o=await r.jira.getIssue(r.issueKey),a=kt(s.promptTemplate,{issueKey:o.key,summary:o.summary,description:o.description||"(no description)",comments:us(o.comments),question:r.question?.body??"(see the latest comment on the ticket)",questionAuthor:r.question?.author??"the commenter"})+await dn(r.jira,o.attachments,r.repoPath,e)+aa(r.repoPath);e("info",`Starting Claude Code in ${r.repoPath} - read-only tools, path-jailed, timeout ${s.timeoutSeconds}s`);let u=await as(r.runId,lt(s.agent),{repoPath:r.repoPath,prompt:a,timeoutSeconds:s.timeoutSeconds,bin:We(r.cfg,s.agent),configDir:r.claudeConfigDir,mode:"read_only",model:s.model||void 0,sessionId:(0,hi.randomUUID)(),onLog:(f,p)=>e(f,p),onUsage:n},e),c={costUsd:u.costUsd,inputTokens:u.inputTokens,outputTokens:u.outputTokens,billingMode:u.billingMode,model:u.model};if(!u.ok||!u.resultText.trim()){let f=u.error??"Claude Code produced no answer";e("error",`Run failed: ${f}`),await r.jira.addComment(r.issueKey,`**Allwright could not answer this question.**
|
|
549
551
|
|
|
550
552
|
Error: ${f.slice(0,800)}
|
|
551
553
|
|
|
552
|
-
Ask again in a new comment to retry. (run \`${r.runId}\`)`).catch(p=>
|
|
554
|
+
Ask again in a new comment to retry. (run \`${r.runId}\`)`).catch(p=>g.error(`could not post answer failure to ${r.issueKey}: ${p}`)),t(u.timedOut?"timed_out":"failed",{error:f,...u.cancelled?{errorKind:"guard"}:{},...c});return}t("posting",c),e("info",`Posting answer to ${r.issueKey} (${u.resultText.length} chars)`),await r.jira.addComment(r.issueKey,u.resultText),t("succeeded",{...c,resultSummary:os(u.resultText)}),e("info",`Run succeeded \xB7 $${u.costUsd.toFixed(4)}`)}catch(o){let a=o instanceof Error?o.message:String(o);e("error",`Run failed: ${a}`),t("failed",{error:a})}finally{Mt(r.repoPath)}}async function hc(r,e,t,n){let s=`${e}-wip`;try{return Mt(r),await Js(r,`WIP: turn limit exhausted (Allwright run ${t})`),await _o(r,s),n("info",`Partial work preserved on branch "${s}"`),s}catch(i){return n("warn",`could not preserve partial work: ${i instanceof Error?i.message:i}`),null}}function fc(r){return`
|
|
553
555
|
|
|
554
|
-
Partial work from this run is saved on branch \`${r}\` - it was NOT safety-checked or reviewed and never merges on its own; a future run or a developer can pick it up.`}async function
|
|
556
|
+
Partial work from this run is saved on branch \`${r}\` - it was NOT safety-checked or reviewed and never merges on its own; a future run or a developer can pick it up.`}async function dg(r){let{emit:e,setStatus:t,sendUsage:n,nextSeq:s}=Lr(r.runId,r.transport),{trigger:i}=r.rule,o=r.rule.action;if(o.type!=="implement")return;let a=In(o.agent,o.type);if(a){e("error",a),await An(r,a),t("failed",{error:a});return}let u=di.default.join(Ar(),r.runId),c=kt(o.branchTemplate,{issueKey:r.issueKey}),f=(0,hi.randomUUID)(),p=!1,v=!1;try{if(!Qs(pe()??r.cfg,r.project.repoName,r.actorEmail))throw new Error("no GitHub token applies to this repo - run `allwright github set-token` (runner-wide) or `github set <repoName>` (this repo only)");if(c===o.baseBranch&&!r.continueBranch)throw new Error(`rendered branch "${c}" equals the base branch - refusing (check the rule's branch template)`);if(t("running"),e("info",`Run started for ${r.issueKey} (rule "${r.rule.name}", implement)`),o.jiraTransitionOnStart)try{await r.jira.transitionByName(r.issueKey,o.jiraTransitionOnStart)?e("info",`Jira transition "${o.jiraTransitionOnStart}" applied at run start`):e("warn",`no transition named "${o.jiraTransitionOnStart}" is available from this ticket's current status - continuing anyway`)}catch(L){e("warn",`Jira start transition failed: ${L instanceof Error?L.message:L} - continuing anyway`)}let S=await jr(r.repoPath);if(e("info",`Repo origin: ${S}`),!Ve(S))throw new Error(`origin "${S}" is not a GitHub remote - implement mode supports GitHub only`);e("info",`Fetching ${r.issueKey} from Jira`);let T=await r.jira.getIssue(r.issueKey),x=r.continueBranch?c:o.baseBranch;e("info",r.continueBranch?`Continuing branch "${c}" from origin/${c} (autopilot batch)`:`Preparing worktree on branch "${c}" from origin/${o.baseBranch}`),await Sn(r.repoPath,x),await So(r.repoPath,c),await To(r.repoPath,u,c,x),p=!0;let P=kt(o.promptTemplate,{issueKey:T.key,summary:T.summary,description:T.description||"(no description)",comments:us(T.comments)})+await dn(r.jira,T.attachments,u,e)+aa(u)+ig+(o.writeTests?ac.WRITE_TESTS_PROMPT:"")+(o.updateMemory?Oe.MEMORY_UPDATE_PROMPT:"");e("info",`Starting Claude Code in the worktree - edit tools enabled, path-jailed, no shell, timeout ${o.timeoutSeconds}s`);let _=await as(r.runId,lt(o.agent),{repoPath:u,prompt:P,timeoutSeconds:o.timeoutSeconds,bin:We(r.cfg,o.agent),configDir:r.claudeConfigDir,mode:"edit_no_shell",model:o.model||void 0,maxTurns:o.maxTurns,sessionId:f,onLog:(L,Q)=>e(L,Q),onUsage:n},e,()=>Ws(u)),J={costUsd:_.costUsd,inputTokens:_.inputTokens,outputTokens:_.outputTokens,billingMode:_.billingMode,model:_.model};if(!_.ok){let L=_.error??"Claude Code failed";e("error",`Run failed: ${L}`);let Q=L;if(_.turnLimitHit){let h=await hc(u,c,r.runId,e);h&&(Q+=fc(h))}await An(r,Q),t(_.timedOut?"timed_out":"failed",{error:L,..._.cancelled?{errorKind:"guard"}:{},...J});return}let O=pi(_.resultText);if(O){v=!0,await mi({kind:"implement",runId:r.runId,issueKey:r.issueKey,repoPath:u,sessionId:f,doneLabel:i.doneLabel,failedLabel:i.failedLabel,timeoutSeconds:o.timeoutSeconds,jira:r.jira,nextLogSeq:s(),rounds:1,claudeConfigDir:r.claudeConfigDir,agent:o.agent,model:o.model,actorEmail:r.actorEmail,baseRepoPath:r.repoPath,repoName:r.project.repoName,branch:c,baseBranch:o.baseBranch,jiraTransition:o.jiraTransition,jiraTransitionOnMerge:o.jiraTransitionOnMerge,requireApproval:o.requireApproval,maxTurns:o.maxTurns,issueSummary:T.summary},O,e,t,J);return}Mt(u),await mc({runId:r.runId,issueKey:r.issueKey,issueSummary:T.summary,worktreePath:u,agentConfigDir:r.claudeConfigDir,baseRepoPath:r.repoPath,branch:c,baseBranch:o.baseBranch,jiraTransition:o.jiraTransition,jiraTransitionOnMerge:o.jiraTransitionOnMerge,requireApproval:o.requireApproval,doneLabel:i.doneLabel,failedLabel:i.failedLabel,repoName:r.project.repoName,jira:r.jira,cfg:r.cfg,actorEmail:r.actorEmail,resultText:_.resultText,costFields:J,runTests:o.runTests,mergeOnApprove:o.mergeOnApprove,mergeMethod:o.mergeMethod,emit:e,setStatus:t})}catch(S){let T=S instanceof Error?S.message:String(S);e("error",`Run failed: ${T}`),await An(r,T),t("failed",{error:T})}finally{p&&!v&&await Ft(r.repoPath,u).catch(()=>{})}}async function pc(r,e,t,n){let{emit:s,setStatus:i,sendUsage:o,nextSeq:a}=Lr(r.runId,n.transport,r.nextLogSeq),u=r.repoPath,c=!1;try{if(!Qs(pe()??n.cfg,r.repoName??"",r.actorEmail))throw new Error("no GitHub token applies to this repo - run `allwright github set-token` (runner-wide) or `github set <repoName>` (this repo only)");i("running"),s("info",`Reply received on ${r.issueKey} - continuing run \`${r.runId}\``);let f=kc(e)+await dn(n.jiraFor(r.repoName??""),t,u,s),p=await as(r.runId,lt(r.agent),{repoPath:u,prompt:f,timeoutSeconds:r.timeoutSeconds,bin:We(n.cfg,r.agent??""),configDir:r.claudeConfigDir,mode:"edit_no_shell",model:r.model||void 0,maxTurns:r.maxTurns??120,sessionId:r.sessionId,resume:!0,onLog:(T,x)=>s(T,x),onUsage:o},s,()=>Ws(u)),v={costUsd:p.costUsd,inputTokens:p.inputTokens,outputTokens:p.outputTokens,billingMode:p.billingMode,model:p.model};if(!p.ok){let T=p.error??"Claude Code failed";s("error",`Run failed: ${T}`);let x=T;if(p.turnLimitHit&&r.branch){let P=await hc(u,r.branch,r.runId,s);P&&(x+=fc(P))}await Tt(n.jiraFor(r.repoName??""),r.issueKey,r.runId,r.failedLabel,x),ut(r.runId),i(p.timedOut?"timed_out":"failed",{error:T,...p.cancelled?{errorKind:"guard"}:{},...v});return}let S=pi(p.resultText);if(S){if(r.rounds>=lc){await Sc(n.jiraFor(r.repoName??""),r,s,i,v);return}c=!0,await mi({kind:"implement",runId:r.runId,issueKey:r.issueKey,repoPath:u,sessionId:r.sessionId,doneLabel:r.doneLabel,failedLabel:r.failedLabel,timeoutSeconds:r.timeoutSeconds,jira:n.jiraFor(r.repoName??""),nextLogSeq:a(),rounds:r.rounds+1,createdAt:r.createdAt,claudeConfigDir:r.claudeConfigDir,actorEmail:r.actorEmail,agent:r.agent,model:r.model,baseRepoPath:r.baseRepoPath,repoName:r.repoName,branch:r.branch,baseBranch:r.baseBranch,jiraTransition:r.jiraTransition,jiraTransitionOnMerge:r.jiraTransitionOnMerge,requireApproval:r.requireApproval,maxTurns:r.maxTurns,issueSummary:r.issueSummary},S,s,i,v);return}Mt(u),await mc({runId:r.runId,issueKey:r.issueKey,issueSummary:r.issueSummary,worktreePath:u,agentConfigDir:r.claudeConfigDir,baseRepoPath:r.baseRepoPath??u,branch:r.branch,baseBranch:r.baseBranch,jiraTransition:r.jiraTransition,requireApproval:r.requireApproval??!0,doneLabel:r.doneLabel,failedLabel:r.failedLabel,repoName:r.repoName,jira:n.jiraFor(r.repoName??""),cfg:n.cfg,actorEmail:r.actorEmail,resultText:p.resultText,costFields:v,runTests:r.runTests,mergeOnApprove:r.mergeOnApprove,mergeMethod:r.mergeMethod,emit:s,setStatus:i}),ut(r.runId)}catch(f){let p=f instanceof Error?f.message:String(f);s("error",`Run failed: ${p}`),await Tt(n.jiraFor(r.repoName??""),r.issueKey,r.runId,r.failedLabel,p),ut(r.runId),i("failed",{error:p})}finally{c||await Ft(r.baseRepoPath??u,u).catch(()=>{})}}async function mc(r){let{runId:e,issueKey:t,issueSummary:n,worktreePath:s,baseRepoPath:i,branch:o,baseBranch:a,jiraTransition:u,jiraTransitionOnMerge:c,requireApproval:f,doneLabel:p,failedLabel:v,repoName:S,jira:T,cfg:x,actorEmail:P,runTests:_,mergeOnApprove:J,mergeMethod:O,resultText:L,costFields:Q,emit:h,setStatus:m}=r,y=await wo(s);y.deleted.length&&h("info",`Deleted ${y.deleted.length} file(s) listed in ${wn}: `+y.deleted.slice(0,10).join(", ")+(y.deleted.length>10?", \u2026":""));for(let M of y.refused)h("warn",`${wn} entry refused: ${M}`);h("info","Committing changes"),await Js(s,`${t}: ${n}
|
|
555
557
|
|
|
556
|
-
Allwright run ${e}`);let C=await
|
|
558
|
+
Allwright run ${e}`);let C=await Qn(s,a);if(!C.ok){let M=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 ${_n}/${kn})`;h("error",M),await Tt(T,t,e,v,M),m("failed",{error:M,errorKind:"guard",...Q});return}h("info",`Diff: ${C.files} file(s), +${C.insertions}/-${C.deletions}`);let D="";if(_){let M=ri(s);if(!M)h("info","No TEST.md in this repo - skipping the test run (nothing documented to run)");else{let re=ni(oa.default.readFileSync(M,"utf8"));if(!re.length)h("info",`${di.default.basename(M)} lists no commands - nothing to run`);else{h("info",`Running ${re.length} documented test command(s) - no tokens, plain shell`);let oe=await si(s,re,{perCommandTimeoutMs:15*6e4}),ce=oe.filter(fe=>fe.exitCode!==0);for(let fe of oe)h(fe.exitCode===0?"info":"warn",`${fe.exitCode===0?"PASS":"FAIL"} ${fe.command} (exit ${fe.exitCode})`+(fe.exitCode===0?"":`
|
|
557
559
|
${fe.tail.slice(-1500)}`));D=`
|
|
558
560
|
|
|
559
561
|
### Tests
|
|
560
|
-
`+
|
|
562
|
+
`+oe.map(fe=>`- ${fe.exitCode===0?"PASS":"FAIL"} \`${fe.command}\``).join(`
|
|
561
563
|
`)+(ce.length?`
|
|
562
564
|
|
|
563
|
-
**${ce.length} of ${
|
|
565
|
+
**${ce.length} of ${oe.length} failed.** Output is in the run log.`:`
|
|
564
566
|
|
|
565
|
-
All ${
|
|
567
|
+
All ${oe.length} passed.`),ce.length&&h("warn",`${ce.length} test command(s) failed - the PR will say so; review before merging`)}}}let V=await jr(s),K=Ve(V);if(!K){let M=`origin "${V}" is not a GitHub remote - implement mode supports GitHub only`;h("error",M),await Tt(T,t,e,v,M),m("failed",{error:M,...Q});return}let ie=await $r(s),W=hg(L);try{await gc({gitDir:s,ownerRepo:K,runId:e,issueKey:t,issueSummary:n,agentConfigDir:r.agentConfigDir,branch:o,baseBranch:a,jiraTransition:u,jiraTransitionOnMerge:c,requireApproval:f,doneLabel:p,failedLabel:v,repoName:S,jira:T,cfg:x,actorEmail:P,mergeOnApprove:J,mergeMethod:O,summary:W,cost:Q,testReport:D,emit:h,setStatus:m})}catch(M){let re=M instanceof Error?M.message:String(M);ra({runId:e,issueKey:t,issueSummary:n,mergeOnApprove:J,mergeMethod:O,repoName:S,baseRepoPath:i,branch:o,baseBranch:a,headSha:ie,requireApproval:f,doneLabel:p,failedLabel:v,jiraTransition:u,jiraTransitionOnMerge:c,actorEmail:P,resultSummary:W,costUsd:Q.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),h("error",`Run failed: ${re}`),h("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(T,t,e,v,`${re}
|
|
566
568
|
|
|
567
|
-
The agent's commit survived on the runner - "Retry push" on the dashboard's run page re-pushes it without a new agent run.`),
|
|
569
|
+
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:re,retryAvailable:!0,...Q})}}async function gc(r){let{gitDir:e,ownerRepo:t,runId:n,issueKey:s,issueSummary:i,mergeOnApprove:o,mergeMethod:a,branch:u,baseBranch:c,jiraTransition:f,jiraTransitionOnMerge:p,requireApproval:v,doneLabel:S,failedLabel:T,repoName:x,jira:P,cfg:_,actorEmail:J,summary:O,cost:L,testReport:Q,emit:h,setStatus:m}=r;h("info",`Pushing ${u} to origin`),await es(e,u);let y=await Ys(e,u),C=`${O}${Q??""}
|
|
568
570
|
|
|
569
571
|
---
|
|
570
|
-
Jira: ${new URL(`/browse/${s}`,
|
|
571
|
-
_Allwright implement run \`${n}\` \xB7 cost $${
|
|
572
|
+
Jira: ${new URL(`/browse/${s}`,_.jira?.baseUrl??"").toString()}
|
|
573
|
+
_Allwright implement run \`${n}\` \xB7 cost $${L.costUsd.toFixed(4)}. `+(Q?"Tests were run by the runner, not the agent._":"The agent has no shell and no tests were run here - review accordingly._");h("info","Opening pull request");let D=Qs(pe()??_,x,J);D.source==="user"&&h("info",`PR will be authored with ${J}'s own GitHub token`);let K=await new $e(D.token).createPullRequest(t.owner,t.repo,{title:`${s}: ${i}`.slice(0,250),head:u,base:c,body:C});h("info",`PR ready: ${K.url}`),tc({runId:n,issueKey:s,repoName:x,owner:t.owner,repo:t.repo,prNumber:K.number,prUrl:K.url,jiraTransitionOnMerge:p??"",createdAt:new Date().toISOString()}),m("posting",L);let ie={runId:n,issueKey:s,repoName:x,owner:t.owner,repo:t.repo,prNumber:K.number,prUrl:K.url,branch:u,headSha:y,doneLabel:S,failedLabel:T,jiraTransition:f,mergeOnApprove:o,mergeMethod:a,agentConfigDir:r.agentConfigDir};v?(Bt(ie),await P.addComment(s,`**Allwright opened a pull request for review.**
|
|
572
574
|
|
|
573
|
-
PR: ${
|
|
575
|
+
PR: ${K.url}
|
|
574
576
|
|
|
575
|
-
Approve the PR on GitHub OR on the Allwright dashboard - either completes the run. Rejecting on the dashboard closes the PR and deletes the branch. (run \`${n}\`)`),
|
|
577
|
+
Approve the PR on GitHub OR on the Allwright dashboard - either completes the run. Rejecting on the dashboard closes the PR and deletes the branch. (run \`${n}\`)`),m("awaiting_approval",{...L,prUrl:K.url,headSha:y,resultSummary:os(O),retryAvailable:!1}),h("info",`Awaiting approval on the dashboard \xB7 $${L.costUsd.toFixed(4)}`)):(await yc({jira:P,issueKey:s},ie,h),m("succeeded",{...L,prUrl:K.url,headSha:y,resultSummary:os(O),retryAvailable:!1}),h("info",`Run succeeded \xB7 ${K.url} \xB7 $${L.costUsd.toFixed(4)}`))}async function yc(r,e,t){let n=null;if(e.jiraTransition)try{await r.jira.transitionByName(e.issueKey,e.jiraTransition)?t("info",`Jira transition "${e.jiraTransition}" applied`):(n=`no transition named "${e.jiraTransition}" is available from this ticket's current status - the PR is fine, but move the ticket manually`,t("warn",n))}catch(s){n=`Jira transition failed: ${s instanceof Error?s.message:s}`,t("warn",n)}return await r.jira.addComment(e.issueKey,`**Allwright: implementation complete.**
|
|
576
578
|
|
|
577
579
|
PR: ${e.prUrl}`+(n?`
|
|
578
580
|
|
|
579
581
|
Note: ${n}`:"")+`
|
|
580
582
|
|
|
581
|
-
(run \`${e.runId}\`)`),await r.jira.editLabels(e.issueKey,{add:[e.doneLabel],remove:[
|
|
583
|
+
(run \`${e.runId}\`)`),await r.jira.editLabels(e.issueKey,{add:[e.doneLabel],remove:[Oe.NEEDS_INPUT_LABEL]}),n}async function ls(r,e,t){let n=is(e);if(!n){g.warn(`run.approved for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:s,setStatus:i}=wc(r,e);try{let o=Ae(pe()??r.cfg,n.repoName);if(!o)throw new Error("GitHub token missing on this runner");let a=new $e(o);s("info",`Approval received for ${n.issueKey} - verifying PR state`);let u=await a.getPullRequest(n.owner,n.repo,n.prNumber);if(!u)throw new Error(`PR #${n.prNumber} no longer exists on GitHub`);if(u.state==="closed"&&!u.merged)throw new Error(`PR #${n.prNumber} was closed on GitHub without merging`);let c=t??n.headSha;if(u.state==="open"&&u.headSha!==c){let f=`PR #${n.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 r.jiraFor(n.repoName??"").addComment(n.issueKey,`**Allwright:** ${f}`),i("awaiting_approval",{prUrl:n.prUrl,headSha:u.headSha,resultSummary:f});return}if(n.mergeOnApprove&&u.state==="open"&&!u.merged){s("info",`Merging PR #${n.prNumber} (${n.mergeMethod})`);let f=await a.mergePullRequest(n.owner,n.repo,n.prNumber,n.mergeMethod,{sha:c,title:`${n.issueKey} (#${n.prNumber})`});if(!f.merged){let p=`Approved, but the merge did not go through - ${f.reason}`;s("warn",p),await r.jiraFor(n.repoName??"").addComment(n.issueKey,`**Allwright:** ${p}
|
|
582
584
|
|
|
583
|
-
PR: ${n.prUrl}`),i("awaiting_approval",{prUrl:n.prUrl,headSha:
|
|
585
|
+
PR: ${n.prUrl}`),i("awaiting_approval",{prUrl:n.prUrl,headSha:u.headSha,resultSummary:p});return}s("info",`PR #${n.prNumber} merged`)}await yc({jira:r.jiraFor(n.repoName??""),issueKey:n.issueKey},n,s),i("succeeded",{prUrl:n.prUrl}),s("info","Run completed after approval"),Dr(e)}catch(o){let a=o instanceof Error?o.message:String(o);s("error",`Approval handling failed: ${a}`),await _c(r,n,a),i("failed",{error:a}),Dr(e)}}async function vc(r,e){let t=is(e);if(!t){g.warn(`run.rejected for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:n,setStatus:s}=wc(r,e);try{let i=Ae(pe()??r.cfg,t.repoName);if(!i)throw new Error("GitHub token missing on this runner");let o=new $e(i);n("info",`Rejection received for ${t.issueKey} - closing PR #${t.prNumber}`);let a=await o.getPullRequest(t.owner,t.repo,t.prNumber);a&&a.state==="open"&&await o.closePullRequest(t.owner,t.repo,t.prNumber),a?.merged||await o.deleteBranch(t.owner,t.repo,t.branch),await r.jiraFor(t.repoName??"").addComment(t.issueKey,`**Allwright: changes rejected.**
|
|
584
586
|
|
|
585
|
-
The pull request was closed and the branch deleted. This ticket is labeled \`${t.failedLabel}\`; remove the label to try again. (run \`${t.runId}\`)`),await r.jiraFor(t.repoName??"").editLabels(t.issueKey,{add:[t.failedLabel]}),s("failed",{error:"rejected by user"}),n("info","PR closed, branch deleted, ticket labeled"),
|
|
587
|
+
The pull request was closed and the branch deleted. This ticket is labeled \`${t.failedLabel}\`; remove the label to try again. (run \`${t.runId}\`)`),await r.jiraFor(t.repoName??"").editLabels(t.issueKey,{add:[t.failedLabel]}),s("failed",{error:"rejected by user"}),n("info","PR closed, branch deleted, ticket labeled"),Dr(e)}catch(i){let o=i instanceof Error?i.message:String(i);n("error",`Rejection handling failed: ${o}`),await _c(r,t,o),s("failed",{error:o}),Dr(e)}}async function bc(r,e){let t=ai(e);if(!t){g.warn(`run.retryPush for ${e}: no retry record (already pushed, or invalidated?)`);let{emit:a,setStatus:u,sendUsage:c}=Lr(e,r.transport,1e5);a("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:n,setStatus:s,sendUsage:i,nextSeq:o}=Lr(e,r.transport,t.nextLogSeq);try{let a=await Ys(t.baseRepoPath,t.branch);if(a!==t.headSha){n("error",`Retry push aborted: branch ${t.branch} no longer holds the commit this run produced (expected ${t.headSha.slice(0,7)}, ${a?`found ${a.slice(0,7)}`:"the branch is gone"}) - a newer run has likely reused the branch. Re-run the ticket instead.`),na(e),s("failed",{retryAvailable:!1});return}let u=await jr(t.baseRepoPath),c=Ve(u);if(!c)throw new Error(`origin "${u}" is not a GitHub remote`);n("info",`Retry push for ${t.issueKey}: branch ${t.branch} at ${t.headSha.slice(0,7)}`);let f=r.jiraFor(t.repoName);await gc({gitDir:t.baseRepoPath,ownerRepo:c,runId:t.runId,issueKey:t.issueKey,issueSummary:t.issueSummary,branch:t.branch,baseBranch:t.baseBranch,jiraTransition:t.jiraTransition,jiraTransitionOnMerge:t.jiraTransitionOnMerge,requireApproval:t.requireApproval,mergeOnApprove:t.mergeOnApprove??!1,mergeMethod:t.mergeMethod??"squash",doneLabel:t.doneLabel,failedLabel:t.failedLabel,repoName:t.repoName,jira:f,cfg:pe()??r.cfg,actorEmail:t.actorEmail,summary:t.resultSummary,cost:{costUsd:t.costUsd},emit:n,setStatus:s}),na(e),await f.editLabels(t.issueKey,{remove:[t.failedLabel]}).catch(()=>{})}catch(a){let u=a instanceof Error?a.message:String(a);n("error",`Retry push failed: ${u}`),ra({...t,nextLogSeq:o()}),s("failed",{error:u,retryAvailable:!0})}}function wc(r,e){let t=1e5;return{emit:(i,o)=>{r.transport.send({type:"run.log",runId:e,seq:t++,ts:new Date().toISOString(),level:i,message:o}),i!=="agent"&&g.info(`[run ${e}] ${o}`)},setStatus:(i,o={})=>{r.transport.send({type:"run.status",runId:e,status:i,...o})}}}async function _c(r,e,t){try{await r.jiraFor(e.repoName??"").addComment(e.issueKey,`**Allwright could not complete the approval decision.**
|
|
586
588
|
|
|
587
589
|
Error: ${t.slice(0,800)}
|
|
588
590
|
|
|
589
591
|
PR: ${e.prUrl}
|
|
590
|
-
(run \`${e.runId}\`)`),await r.jiraFor(e.repoName??"").editLabels(e.issueKey,{add:[e.failedLabel]})}catch(n){
|
|
592
|
+
(run \`${e.runId}\`)`),await r.jiraFor(e.repoName??"").editLabels(e.issueKey,{add:[e.failedLabel]})}catch(n){g.error(`could not post decision failure to ${e.issueKey}: ${n}`)}}function us(r){if(!r.length)return"(no comments)";let e=6e4,t=r.map(i=>`${i.author} (${i.created}):
|
|
591
593
|
${i.body}`),n=[],s=0;for(let i=t.length-1;i>=0;i--){if(s+=t[i].length+6,s>e){n.unshift(`(\u2026 ${i+1} earlier comment(s) omitted for length \u2026)`);break}n.unshift(t[i])}return n.join(`
|
|
592
594
|
---
|
|
593
|
-
`)}function
|
|
595
|
+
`)}function kc(r){return`The ticket author replied:
|
|
594
596
|
|
|
595
597
|
${r}
|
|
596
598
|
|
|
597
|
-
Continue from where you left off now that you have this information. If you are still missing what you need, ask again the same way as before (the ${
|
|
598
|
-
`,1)[0].trim(),n=o=>o.replace(/[^a-z]/gi,"").toUpperCase();if(n(t)!==n(
|
|
599
|
-
`);return s<0?null:e.slice(s+1).trim()||null}async function
|
|
599
|
+
Continue from where you left off now that you have this information. If you are still missing what you need, ask again the same way as before (the ${Oe.NEEDS_INPUT_MARKER} marker).`}function pi(r){let e=r.trim(),t=e.split(`
|
|
600
|
+
`,1)[0].trim(),n=o=>o.replace(/[^a-z]/gi,"").toUpperCase();if(n(t)!==n(Oe.NEEDS_INPUT_MARKER))return null;let s=e.indexOf(`
|
|
601
|
+
`);return s<0?null:e.slice(s+1).trim()||null}async function mi(r,e,t,n,s){t("info",`Claude needs more information - posting questions to ${r.issueKey}`),await r.jira.addComment(r.issueKey,`**${Oe.NEEDS_INPUT_COMMENT_MARKER} before it can continue.**
|
|
600
602
|
|
|
601
603
|
${e}
|
|
602
604
|
|
|
603
|
-
Reply with your answers in a comment on this ticket - this run will pick up right where it left off, automatically, once you do. (run \`${r.runId}\`)`);let i=new Date().toISOString();await r.jira.editLabels(r.issueKey,{add:[
|
|
605
|
+
Reply with your answers in a comment on this ticket - this run will pick up right where it left off, automatically, once you do. (run \`${r.runId}\`)`);let i=new Date().toISOString();await r.jira.editLabels(r.issueKey,{add:[Oe.NEEDS_INPUT_LABEL]}),sc({runId:r.runId,issueKey:r.issueKey,kind:r.kind,mergeOnApprove:r.mergeOnApprove??!1,mergeMethod:r.mergeMethod??"squash",repoPath:r.repoPath,sessionId:r.sessionId,doneLabel:r.doneLabel,failedLabel:r.failedLabel,timeoutSeconds:r.timeoutSeconds,createdAt:r.createdAt??i,questionsPostedAt:i,rounds:r.rounds,nextLogSeq:r.nextLogSeq,baseRepoPath:r.baseRepoPath,repoName:r.repoName,branch:r.branch,baseBranch:r.baseBranch,jiraTransition:r.jiraTransition,jiraTransitionOnMerge:r.jiraTransitionOnMerge,requireApproval:r.requireApproval,maxTurns:r.maxTurns,runTests:r.runTests??!0,issueSummary:r.issueSummary??"",claudeConfigDir:r.claudeConfigDir,agent:r.agent,model:r.model,actorEmail:r.actorEmail}),n("needs_input",{...s,resultSummary:os(e)}),t("info",`Waiting for a reply on ${r.issueKey} (label "${Oe.NEEDS_INPUT_LABEL}")`)}async function Sc(r,e,t,n,s){let i=`Claude asked for clarification ${e.rounds} times without reaching a result - giving up. Answer more completely and re-trigger manually if you want another attempt.`;t("error",i),await Tt(r,e.issueKey,e.runId,e.failedLabel,i),ut(e.runId),n("failed",{error:i,...s})}async function An(r,e){await Tt(r.jira,r.issueKey,r.runId,r.rule.trigger.failedLabel,e)}async function Tt(r,e,t,n,s){try{await r.addComment(e,`**Allwright run failed.**
|
|
604
606
|
|
|
605
607
|
Error: ${s.slice(0,800)}
|
|
606
608
|
|
|
607
|
-
This ticket has been labeled \`${n}\` and will not be retried automatically. To retry, fix the cause and remove the \`${n}\` label. (run \`${t}\`)`),await r.editLabels(e,{add:[n],remove:[
|
|
608
|
-
`)){let t=e.replace(/^#+\s*/,"").trim();if(t.length>10)return t.slice(0,200)}return r.slice(0,200)}var
|
|
609
|
+
This ticket has been labeled \`${n}\` and will not be retried automatically. To retry, fix the cause and remove the \`${n}\` label. (run \`${t}\`)`),await r.editLabels(e,{add:[n],remove:[Oe.NEEDS_INPUT_LABEL]})}catch(i){g.error(`could not post failure comment to ${e}: ${i}`)}}function hg(r){let e=/##\s*Summary of changes\s*\n([\s\S]*)$/i.exec(r);return(e?e[1]:r).trim().slice(0,8e3)||"(no summary provided)"}function os(r){for(let e of r.split(`
|
|
610
|
+
`)){let t=e.replace(/^#+\s*/,"").trim();if(t.length>10)return t.slice(0,200)}return r.slice(0,200)}var qr=E(require("node:fs"),1),Ur=E(require("node:path"),1),Fr=require("node:child_process"),ua=E(require("node:readline"),1),ca=require("node:crypto"),Br=E(be(),1);var Ec=E(be(),1);_t();Ye();Or();var Tc=4e3,fg=4e3;function da(r){let e=0;return{emit:(s,i)=>{r.transport.send({type:"run.log",runId:r.runId,seq:e++,ts:new Date().toISOString(),level:s,message:i.slice(0,fg)}),s!=="agent"&&g.info(`[deploy ${r.runId}] ${i}`)},setStatus:(s,i={})=>{r.transport.send({type:"run.status",runId:r.runId,status:s,...i})}}}async function gi(r){let{emit:e,setStatus:t}=da(r),n=r.environment;try{let s=pg(r);if(s){e("error",s),await Xe(r,`**Allwright could not deploy to \`${n.name}\`.**
|
|
609
611
|
|
|
610
|
-
${s}`),t("failed",{error:s});return}if(n.requireApproval){
|
|
612
|
+
${s}`),t("failed",{error:s});return}if(n.requireApproval){nc({runId:r.runId,issueKey:r.issueKey,issueSummary:r.issueSummary,projectId:r.project.id,repoName:r.project.repoName,environmentName:n.name,requestedBy:r.requestedBy,createdAt:new Date().toISOString()}),e("info",`Deploy to "${n.name}" is waiting for approval on the dashboard - no step has run yet`),await Xe(r,`**Allwright: deploy to \`${n.name}\` needs approval.**
|
|
611
613
|
|
|
612
|
-
${r.requestedBy?`Requested by ${r.requestedBy}. `:""}Nothing has been executed yet. Approve it on the Allwright dashboard to run the ${n.steps.length} deploy step(s), or reject to cancel. (run \`${r.runId}\`)`),t("awaiting_approval",{resultSummary:`Awaiting approval to deploy ${r.issueKey} to ${n.name}`});return}await
|
|
614
|
+
${r.requestedBy?`Requested by ${r.requestedBy}. `:""}Nothing has been executed yet. Approve it on the Allwright dashboard to run the ${n.steps.length} deploy step(s), or reject to cancel. (run \`${r.runId}\`)`),t("awaiting_approval",{resultSummary:`Awaiting approval to deploy ${r.issueKey} to ${n.name}`});return}await Ac(r,e,t)}catch(s){let i=s instanceof Error?s.message:String(s);e("error",`Deploy failed: ${i}`),await Xe(r,`**Allwright deploy to \`${n.name}\` failed.**
|
|
613
615
|
|
|
614
616
|
${i.slice(0,800)}
|
|
615
617
|
|
|
616
|
-
(run \`${r.runId}\`)`),t("failed",{error:i})}}function
|
|
618
|
+
(run \`${r.runId}\`)`),t("failed",{error:i})}}function pg(r){let e=r.environment;if(!r.cfg.deploy.enabled)return"deployments are turned off on this runner. Deploy steps are shell commands, so they stay disabled until someone with access to this machine runs `allwright deploy enable`.";if(!e.steps.length)return`environment "${e.name}" has no deploy steps configured - add them in the dashboard first`;if(e.promotionMode==="merge_and_deploy"&&!e.branch)return`environment "${e.name}" is set to merge-and-deploy but has no branch configured`;if(e.useDedicatedCheckout&&!e.branch)return`environment "${e.name}" wants a dedicated checkout but has no branch configured`;let t=cr(r.cfg,r.project.repoName,e.name),n=e.requiredSecrets.filter(s=>!t[s]&&!process.env[s]);return n.length?`missing deploy secret(s) on this runner: ${n.join(", ")}. Set them with: allwright env set "${r.project.repoName}" "${e.name}" ${n[0]}=...`:null}async function Ac(r,e,t){let n=r.environment,s=cr(r.cfg,r.project.repoName,n.name),i=bg(Object.values(s)),o=Date.now();if(t("running"),e("info",`Deploying ${r.issueKey} to "${n.name}"`+(r.requestedBy?` (requested by ${r.requestedBy})`:"")+` - ${n.steps.length} step(s), ${n.timeoutSeconds}s budget`),n.auditBeforeDeploy){e("info",`Pre-deploy ${n.auditBeforeDeploy} audit starting (advisory - will not block)`);try{let P=Je(r.cfg,r.project,"assist"),_="error"in P?{ok:!1,error:P.error}:await Cn({projectId:r.project.id,repoPath:r.repoPath,role:n.auditBeforeDeploy,scope:{kind:"repo",ref:""},model:"",agent:P,jira:r.jira});if(!_.ok)e("warn",`Pre-deploy audit could not run: ${_.error} - deploying anyway (advisory)`);else if(!_.audit.findings.length)e("info","Pre-deploy audit: no findings \u2713");else{let J={};for(let O of _.audit.findings)J[O.severity]=(J[O.severity]??0)+1;e("warn",`Pre-deploy audit: ${_.audit.findings.length} finding(s) (`+Object.entries(J).map(([O,L])=>`${L} ${O}`).join(", ")+") - full report on the Audits page. Deploying anyway (advisory).");for(let O of _.audit.findings.slice(0,5))e("warn",` [${O.severity}] ${O.title} - ${O.evidence[0]?.file??""}`)}}catch(P){e("warn",`Pre-deploy audit crashed: ${P instanceof Error?P.message:String(P)} - deploying anyway`)}}if(n.requireSyncCheck){if(!n.previousEnvBranch||!n.branch){let _=n.branch?`"${n.name}" requires a branch sync check, but no earlier stage in the pipeline has a branch to compare against. Check the pipeline order on the Environments page (was "${n.name}" moved to the top?), or turn the check off.`:`"${n.name}" requires a branch sync check but has no branch set - set it, or turn the check off`;e("error",_),await Xe(r,`**Allwright refused to deploy to \`${n.name}\`.**
|
|
617
619
|
|
|
618
|
-
${
|
|
620
|
+
${_}
|
|
619
621
|
|
|
620
|
-
(run \`${r.runId}\`)`),t("failed",{error:
|
|
622
|
+
(run \`${r.runId}\`)`),t("failed",{error:_,errorKind:"guard"});return}let P=await gg(r,e);if(P){await Xe(r,P.comment),t("failed",{error:P.error,...P.guard?{errorKind:"guard"}:{}});return}}let a=r.repoPath;if(n.useDedicatedCheckout||n.promotionMode==="merge_and_deploy"?(e("info",`Preparing ${n.name} checkout at origin/${n.branch}`),a=await Io({repoPath:r.repoPath,repoName:r.project.repoName,envName:n.name,branch:n.branch,attached:n.promotionMode==="merge_and_deploy"})):e("info",`No dedicated checkout for "${n.name}" - running the steps in the mapped checkout as it is`),n.promotionMode==="merge_and_deploy"){let P=kt(n.ticketBranchTemplate,{issueKey:r.issueKey});e("info",`Merging "${P}" into "${n.branch}"`);let _=await Ro(a,P,`Deploy ${r.issueKey} to ${n.name}
|
|
621
623
|
|
|
622
|
-
Allwright run ${r.runId}`);if(!
|
|
624
|
+
Allwright run ${r.runId}`);if(!_.ok){e("error",_.reason??"merge failed"),await Xe(r,`**Allwright deploy to \`${n.name}\` failed before running anything.**
|
|
623
625
|
|
|
624
|
-
${
|
|
626
|
+
${_.reason}`),t("failed",{error:_.reason});return}_.alreadyMerged?e("info",`"${P}" is already in "${n.branch}" - nothing to merge`):(e("info",`Pushing "${n.branch}" to origin`),await jo(a,n.branch))}let c=await $r(a).catch(()=>"");c&&e("info",`Deploying commit ${c.slice(0,10)}`);let f=yg(a,n.workdir),p={...process.env,...s,ALLWRIGHT_ENVIRONMENT:n.name,ALLWRIGHT_ISSUE_KEY:r.issueKey,ALLWRIGHT_RUN_ID:r.runId,ALLWRIGHT_DEPLOY_REF:c,ALLWRIGHT_BRANCH:n.branch,TICKETPILOT_ENVIRONMENT:n.name,TICKETPILOT_ISSUE_KEY:r.issueKey,TICKETPILOT_RUN_ID:r.runId,TICKETPILOT_DEPLOY_REF:c,TICKETPILOT_BRANCH:n.branch},v=0,S=n.timeoutSeconds*1e3;for(let[P,_]of n.steps.entries()){let J=S-(Date.now()-o);if(J<=0){let L=`deploy exceeded its ${n.timeoutSeconds}s budget before step ${P+1}`;e("error",L),await Xe(r,`**Allwright deploy to \`${n.name}\` timed out.**
|
|
625
627
|
|
|
626
|
-
${
|
|
628
|
+
${L}`),t("timed_out",{error:L,deployedRef:c});return}e("info",`\u25B6 step ${P+1}/${n.steps.length}: ${_.name}`);let O=await vg({command:_.run,cwd:f,env:p,timeoutMs:J,onLine:(L,Q)=>{v++,v===Tc&&e("warn","(output truncated - deploy log limit reached)"),!(v>=Tc)&&e(L,i(Q))}});if(O.timedOut){let L=`step "${_.name}" hit the ${n.timeoutSeconds}s deploy budget and was killed`;e("error",L),await Xe(r,`**Allwright deploy to \`${n.name}\` timed out.**
|
|
627
629
|
|
|
628
|
-
${
|
|
630
|
+
${L}`),t("timed_out",{error:L,deployedRef:c});return}if(O.code!==0){if(_.continueOnError){e("warn",`step "${_.name}" exited ${O.code} - continuing (marked continue-on-error)`);continue}let L="";try{L=i(await ko(a))}catch{}let Q=`step ${P+1} "${_.name}" failed with exit code ${O.code}`+(O.tail?`: ${i(O.tail)}`:"")+(L?`
|
|
629
631
|
|
|
630
632
|
Checkout at failure:
|
|
631
|
-
${
|
|
633
|
+
${L}`:"");e("error",Q),await Xe(r,`**Allwright deploy to \`${n.name}\` failed.**
|
|
632
634
|
|
|
633
|
-
Step ${
|
|
635
|
+
Step ${P+1} \`${_.name}\` exited ${O.code}.
|
|
634
636
|
|
|
635
|
-
`+(
|
|
636
|
-
${i(
|
|
637
|
+
`+(O.tail?`\`\`\`
|
|
638
|
+
${i(O.tail).slice(0,1200)}
|
|
637
639
|
\`\`\`
|
|
638
640
|
|
|
639
|
-
`:"")+(
|
|
641
|
+
`:"")+(L?`Checkout at failure:
|
|
640
642
|
\`\`\`
|
|
641
|
-
${
|
|
643
|
+
${L.slice(0,800)}
|
|
642
644
|
\`\`\`
|
|
643
645
|
|
|
644
|
-
`:"")+`Nothing after it ran. Full log is on the Allwright dashboard. (run \`${r.runId}\`)`),t("failed",{error:Q.slice(0,1600),deployedRef:c});return}e("info",`\u2713 step ${
|
|
646
|
+
`:"")+`Nothing after it ran. Full log is on the Allwright dashboard. (run \`${r.runId}\`)`),t("failed",{error:Q.slice(0,1600),deployedRef:c});return}e("info",`\u2713 step ${P+1}/${n.steps.length}: ${_.name}`)}t("posting");let T=Math.round((Date.now()-o)/1e3);r.issueKey!==Br.BRANCH_DEPLOY_ISSUE_KEY&&await Xe(r,`**Allwright deployed \`${r.issueKey}\` to \`${n.name}\`.**
|
|
645
647
|
|
|
646
648
|
`+(c?`Commit: \`${c.slice(0,10)}\`${n.branch?` on \`${n.branch}\``:""}
|
|
647
649
|
`:"")+`${n.steps.length} step(s) in ${T}s.`+(r.requestedBy?` Requested by ${r.requestedBy}.`:"")+`
|
|
648
650
|
|
|
649
|
-
(run \`${r.runId}\`)`);let x=await
|
|
651
|
+
(run \`${r.runId}\`)`);let x=await mg(r,e,c);t("succeeded",{resultSummary:`Deployed to ${n.name}${c?` at ${c.slice(0,10)}`:""} in ${T}s`+(x!==null?` \xB7 ${x} ticket(s) moved to "${n.deployToColumn}"`:""),deployedRef:c}),e("info",`Deploy to "${n.name}" succeeded in ${T}s`)}async function mg(r,e,t){let n=r.environment;if(!n.deployFromColumn||!n.deployToColumn)return null;let s=new Date().toISOString().slice(0,10),i;try{i=await r.jira.search(`project = "${r.project.jiraProjectKey}" AND status = "${n.deployFromColumn}" ORDER BY updated ASC`,50)}catch(a){return e("warn",`deploy succeeded, but listing tickets in "${n.deployFromColumn}" failed: ${a instanceof Error?a.message:a} - move them by hand`),null}if(!i.length)return e("info",`No tickets in "${n.deployFromColumn}" to move`),0;e("info",`Moving ${i.length} ticket(s) from "${n.deployFromColumn}" to "${n.deployToColumn}"`);let o=0;for(let a of i)try{if(await r.jira.addComment(a.key,`**Allwright: deployed to \`${n.name}\` on ${s}.**
|
|
650
652
|
|
|
651
653
|
`+(t?`Commit: \`${t.slice(0,10)}\`${n.branch?` on \`${n.branch}\``:""}
|
|
652
|
-
`:"")+(r.requestedBy?`Requested by ${r.requestedBy}. `:"")+`(run \`${r.runId}\`)`),!await r.jira.transitionByName(a.key,n.deployToColumn)){e("warn",`${a.key}: no workflow transition to "${n.deployToColumn}" from its current status - left in place`),await r.jira.addComment(a.key,`**Allwright could not move this ticket to \`${n.deployToColumn}\`** - no such transition from its current status. The deploy itself succeeded; move it by hand. (run \`${r.runId}\`)`).catch(()=>{});continue}o++,e("info",`\u2713 ${a.key} \u2192 "${n.deployToColumn}"`)}catch(
|
|
654
|
+
`:"")+(r.requestedBy?`Requested by ${r.requestedBy}. `:"")+`(run \`${r.runId}\`)`),!await r.jira.transitionByName(a.key,n.deployToColumn)){e("warn",`${a.key}: no workflow transition to "${n.deployToColumn}" from its current status - left in place`),await r.jira.addComment(a.key,`**Allwright could not move this ticket to \`${n.deployToColumn}\`** - no such transition from its current status. The deploy itself succeeded; move it by hand. (run \`${r.runId}\`)`).catch(()=>{});continue}o++,e("info",`\u2713 ${a.key} \u2192 "${n.deployToColumn}"`)}catch(u){e("warn",`${a.key}: sweep failed (${u instanceof Error?u.message:u}) - left in "${n.deployFromColumn}"`)}return e("info",`Moved ${o}/${i.length} ticket(s) to "${n.deployToColumn}"`),o}async function gg(r,e){let t=r.environment,n=t.previousEnvBranch,s=(a,u=!1)=>({error:a,guard:u,comment:`**Allwright could not deploy \`${r.issueKey}\` to \`${t.name}\`.**
|
|
653
655
|
|
|
654
656
|
${a}
|
|
655
657
|
|
|
656
|
-
(run \`${r.runId}\`)`});e("info",`Checking "${t.branch}" is in sync with "${n}" before deploying`);try{await
|
|
658
|
+
(run \`${r.runId}\`)`});e("info",`Checking "${t.branch}" is in sync with "${n}" before deploying`);try{await Sn(r.repoPath,n),await Sn(r.repoPath,t.branch)}catch(a){return s(`sync check could not fetch branches: ${a instanceof Error?a.message:String(a)}`)}let i;try{i=await Oo(r.repoPath,`origin/${n}`,`origin/${t.branch}`)}catch(a){return s(`sync check failed: ${a instanceof Error?a.message:String(a)}`)}if(!i)return e("info",`"${t.branch}" already matches "${n}" - continuing`),null;e("warn",`"${t.branch}" and "${n}" have diverged - opening a PR instead of deploying`);let o=Ae(pe()??r.cfg,r.project.repoName);if(!o)return s(`"${t.branch}" and "${n}" have diverged, and no GitHub token applies to this repo to open a PR. Run \`allwright github set-token\`, or merge them manually, then retry the deploy.`,!0);try{let a=await jr(r.repoPath),u=Ve(a);if(!u)throw new Error(`could not parse a GitHub owner/repo from origin "${a}"`);let f=await new $e(o).createPullRequest(u.owner,u.repo,{title:`Sync ${t.name} (${t.branch}) with ${n}`,head:n,base:t.branch,body:`Allwright opened this automatically while trying to deploy \`${r.issueKey}\` to \`${t.name}\`: \`${t.branch}\` doesn't have everything that's on \`${n}\` yet, so deploying now would ship different code than what was validated there. Merge this PR, then retry the deploy.
|
|
657
659
|
|
|
658
|
-
(run \`${r.runId}\`)`});return s(`"${t.branch}" is not in sync with "${n}" - opened ${f.url} to catch it up. Merge that, then retry the deploy.`,!0)}catch(a){return s(`could not open a sync PR: ${a instanceof Error?a.message:String(a)}`)}}function
|
|
659
|
-
`)}))},
|
|
660
|
+
(run \`${r.runId}\`)`});return s(`"${t.branch}" is not in sync with "${n}" - opened ${f.url} to catch it up. Merge that, then retry the deploy.`,!0)}catch(a){return s(`could not open a sync PR: ${a instanceof Error?a.message:String(a)}`)}}function yg(r,e){if(!e.trim())return r;let t=Ur.default.resolve(r,e),n=Ur.default.relative(r,t);if(n.startsWith("..")||Ur.default.isAbsolute(n))throw new Error(`working directory "${e}" is outside the repository checkout`);return t}function vg(r){return new Promise(e=>{let t=(0,Fr.spawn)("bash",["-lc",r.command],{cwd:r.cwd,env:r.env,detached:!0,stdio:["ignore","pipe","pipe"]}),n=[],s=c=>{n.push(c),n.length>20&&n.shift()},i=!1,o=!1,a=c=>{i||(i=!0,clearTimeout(u),e({code:c,timedOut:o,tail:n.join(`
|
|
661
|
+
`)}))},u=setTimeout(()=>{o=!0,xc(t.pid,"SIGTERM"),setTimeout(()=>xc(t.pid,"SIGKILL"),1e4).unref()},r.timeoutMs);ua.default.createInterface({input:t.stdout}).on("line",c=>{s(c),r.onLine("info",c)}),ua.default.createInterface({input:t.stderr}).on("line",c=>{s(c),r.onLine("warn",c)}),t.on("error",c=>{s(`failed to start: ${c.message}`),a(127)}),t.on("close",c=>a(c??1))})}function xc(r,e){if(r)try{process.kill(-r,e)}catch{try{process.kill(r,e)}catch{}}}function bg(r){let e=r.filter(t=>t&&t.length>=6).sort((t,n)=>n.length-t.length);return e.length?t=>{let n=t;for(let s of e)n=n.split(s).join("***");return n}:t=>t}async function Xe(r,e){if(r.issueKey!==Br.BRANCH_DEPLOY_ISSUE_KEY)try{await r.jira.addComment(r.issueKey,e)}catch(t){g.error(`could not post deploy comment to ${r.issueKey}: ${t}`)}}function ha(r){return ui(r)!==null}async function $c(r,e){let t=ui(e);if(!t)return;let{emit:n,setStatus:s}=da({runId:e,transport:r.transport}),i=r.lookup(t.projectId,t.environmentName);if(!i){let a=`approved, but environment "${t.environmentName}" is no longer in this runner's config (deleted or renamed?) - nothing was deployed`;n("error",a),s("failed",{error:a}),ci(e);return}ci(e);let o={runId:e,project:i.project,environment:i.environment,issueKey:t.issueKey,issueSummary:t.issueSummary,repoPath:i.repoPath,cfg:r.cfg,jira:r.jiraFor(i.project.repoName),transport:r.transport,requestedBy:t.requestedBy};n("info",`Approved - running the ${i.environment.steps.length} deploy step(s) now`);try{await Ac(o,n,s)}catch(a){let u=a instanceof Error?a.message:String(a);n("error",`Deploy failed: ${u}`),await Xe(o,`**Allwright deploy failed.**
|
|
660
662
|
|
|
661
|
-
${
|
|
663
|
+
${u.slice(0,800)}`),s("failed",{error:u})}}async function Pc(r,e){let t=ui(e);if(!t)return;let{emit:n,setStatus:s}=da({runId:e,transport:r.transport});ci(e),n("info",`Deploy to "${t.environmentName}" was rejected - nothing ran`);let i=r.lookup(t.projectId,t.environmentName);try{await r.jiraFor(i?.project.repoName??"").addComment(t.issueKey,`**Allwright: deploy to \`${t.environmentName}\` was rejected.**
|
|
662
664
|
|
|
663
|
-
No deploy step was executed. (run \`${e}\`)`)}catch(o){
|
|
665
|
+
No deploy step was executed. (run \`${e}\`)`)}catch(o){g.error(`could not post rejection comment to ${t.issueKey}: ${o}`)}s("failed",{error:"deploy rejected by a reviewer"})}var wg=k.object({steps:k.array(Br.DeployStep).max(50).default([]),requiredSecrets:k.array(k.string()).max(50).default([]),notes:k.string().default("")}),_g=[".ticketpilot/deploy.md","DEPLOY.md","DEPLOYMENT.md","docs/DEPLOY.md","docs/deploy.md","docs/deployment.md"],Cc=24e3;function yi(r){for(let e of _g){let t=Ur.default.join(r,e);try{if(!qr.default.existsSync(t))continue;let n=qr.default.readFileSync(t,"utf8");if(!n.trim())continue;return{path:e,content:n.length>Cc?n.slice(0,Cc)+`
|
|
664
666
|
|
|
665
|
-
[\u2026document truncated\u2026]`:n}}catch{continue}}return null}var
|
|
667
|
+
[\u2026document truncated\u2026]`:n}}catch{continue}}return null}var Ic=["docker","docker-compose","pm2","systemctl","node","pnpm","npm","yarn","make","python3","pip","rsync","ssh","caddy","nginx"];function jc(r){return Oc("bash",["-lc",`command -v ${JSON.stringify(r)}`]).trim().length>0}function Oc(r,e){try{let t=(0,Fr.spawnSync)(r,e,{encoding:"utf8",timeout:5e3});return t.status===0?t.stdout??"":""}catch{return""}}async function kg(r,e){let t;try{t=new URL(r)}catch{e.push({name:"public-url",ok:!1,detail:`not a valid URL: ${r}`});return}try{let{lookup:n}=await import("node:dns/promises"),s=await n(t.hostname);e.push({name:"public-url-dns",ok:!0,detail:`${t.hostname} \u2192 ${s.address}`})}catch{e.push({name:"public-url-dns",ok:!1,detail:`${t.hostname} does not resolve - add an A/CNAME record for it at your DNS provider (changes can take a few minutes to propagate)`});return}if(t.protocol==="https:"){let n=await import("node:tls");await new Promise(s=>{let i=n.connect({host:t.hostname,port:Number(t.port||443),servername:t.hostname,timeout:8e3},()=>{let o=i.getPeerCertificate(),a=o?.valid_to?Math.round((new Date(o.valid_to).getTime()-Date.now())/864e5):NaN;e.push(Number.isFinite(a)&&a>0?{name:"public-url-tls",ok:a>14,detail:`certificate valid, expires in ${a} day(s)${a<=14?" - renew soon":""}`}:{name:"public-url-tls",ok:!1,detail:"certificate expired or unreadable"}),i.end(),s()});i.on("error",o=>{e.push({name:"public-url-tls",ok:!1,detail:`TLS handshake failed: ${o.message} - is a certificate installed for this hostname?`}),s()}),i.on("timeout",()=>{e.push({name:"public-url-tls",ok:!1,detail:"TLS handshake timed out"}),i.destroy(),s()})})}try{let n=await fetch(t.toString(),{method:"GET",redirect:"manual",signal:AbortSignal.timeout(1e4)});e.push({name:"public-url-reachable",ok:n.status<500,detail:`HTTP ${n.status}${n.status>=300&&n.status<400?` \u2192 ${n.headers.get("location")??""}`:""}`})}catch(n){e.push({name:"public-url-reachable",ok:!1,detail:`not reachable from the runner: ${n instanceof Error?n.message:String(n)}`})}}function Sg(r){let e=r.match(/\/(?:var|home|opt|srv)\/[\w./-]+/g)??[],t=[...new Set(e.map(s=>s.replace(/[.,;:)\]'"`]+$/,"")))].slice(0,12);return t.length?`
|
|
666
668
|
- absolute paths the document mentions, checked on THIS machine:
|
|
667
|
-
${t.map(s=>` - ${s}: ${
|
|
668
|
-
`)}`:""}function
|
|
669
|
+
${t.map(s=>` - ${s}: ${qr.default.existsSync(s)?"EXISTS on this machine":"not found on this machine"}`).join(`
|
|
670
|
+
`)}`:""}function Tg(){let r=[],e=(t,n)=>{try{let s=(0,Fr.execFileSync)(n,["--version"],{encoding:"utf8",timeout:5e3}).trim();r.push(`- ${t}: ${s}`)}catch{}};for(let t of["node","npm","python3"]){let n="";try{n=(0,Fr.execFileSync)("which",[t],{encoding:"utf8",timeout:5e3}).trim()}catch{continue}e(`${t} in the RUNNER's PATH (${n}) - deploy steps run with THIS`,n);for(let s of[`/usr/bin/${t}`,`/usr/local/bin/${t}`])s!==n&&qr.default.existsSync(s)&&e(`${t} at ${s}`,s)}return r.length?`
|
|
669
671
|
- runtime versions (a MISMATCH between the runner's PATH and the system install is a common root cause):
|
|
670
672
|
${r.map(t=>` ${t}`).join(`
|
|
671
|
-
`)}`:""}function
|
|
673
|
+
`)}`:""}function Nc(r,e,t,n=""){let s=Ic.filter(a=>jc(a)),i=Ic.filter(a=>!s.includes(a)),o=Object.keys(cr(r,e,t));return`About the machine these steps will run on (gathered by the runner, trust it):
|
|
672
674
|
- available tools: ${s.join(", ")||"(none of the common ones)"}
|
|
673
675
|
- NOT installed: ${i.join(", ")||"(none missing)"}
|
|
674
|
-
- secrets already stored for this environment (names only): ${o.join(", ")||"(none yet)"}`+
|
|
676
|
+
- secrets already stored for this environment (names only): ${o.join(", ")||"(none yet)"}`+Tg()+Sg(n)}async function Mc(r){let e=[];if(r.publicUrl?.trim()&&await kg(r.publicUrl.trim(),e),e.push(qr.default.existsSync(r.repoPath)?{name:"repo-path",ok:!0,detail:r.repoPath}:{name:"repo-path",ok:!1,detail:`checkout missing: ${r.repoPath}`}),e.push({name:"deploys-enabled",ok:r.cfg.deploy.enabled,detail:r.cfg.deploy.enabled?"enabled on this runner":"disabled - run: allwright deploy enable (then restart the runner)"}),r.workdir){let a=Ur.default.isAbsolute(r.workdir)?r.workdir:Ur.default.join(r.repoPath,r.workdir);e.push(qr.default.existsSync(a)?{name:"workdir",ok:!0,detail:a}:{name:"workdir",ok:!1,detail:`does not exist: ${a}`})}if(r.branch){let a=Oc("git",["-C",r.repoPath,"ls-remote","--heads","origin",r.branch]);e.push(a.trim()?{name:"branch",ok:!0,detail:`origin/${r.branch} exists`}:{name:"branch",ok:!1,detail:`origin has no branch "${r.branch}" (or the remote is unreachable)`})}let t=cr(r.cfg,r.repoName,r.environmentName),n=new Set(r.requiredSecrets);for(let a of r.steps)for(let u of a.run.matchAll(/\$\{?([A-Z][A-Z0-9_]{2,})\}?/g))n.add(u[1]);let s=[...n].filter(a=>!t[a]&&!process.env[a]);e.push({name:"secrets",ok:s.length===0,detail:s.length?`missing: ${s.join(", ")} - set with: allwright env set "${r.repoName}" "${r.environmentName}" ${s[0]}=...`:`${n.size} present`});let i=new Set;for(let a of r.steps)for(let u of a.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(a=>!jc(a));return e.push({name:"binaries",ok:o.length===0,detail:o.length?`not found on this machine: ${o.join(", ")}`:`${i.size} found: ${[...i].slice(0,12).join(", ")}`}),{ok:e.every(a=>a.ok),checks:e}}async function zc(r){let e=Nc(r.cfg,r.repoName,r.environmentName),t=kt(Ec.DEPLOY_FIX_PROMPT_TEMPLATE,{envName:r.environmentName,steps:r.steps.map((c,f)=>`${f+1}. [${c.name}]${c.continueOnError?" (continues on error)":""}
|
|
675
677
|
${c.run}`).join(`
|
|
676
|
-
`),failedStep:r.failedStep||"(unknown)",errorText:r.errorText||"(no error text recorded)",machineContext:e}),n=await r.agent.adapter.run({repoPath:r.repoPath,prompt:t,timeoutSeconds:240,bin:r.agent.bin,mode:"read_only",maxTurns:40,sessionId:(0,
|
|
677
|
-
`+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
|
|
678
|
-
`)[0].trim()||`Step ${e+1}`).slice(0,120)}
|
|
678
|
+
`),failedStep:r.failedStep||"(unknown)",errorText:r.errorText||"(no error text recorded)",machineContext:e}),n=await r.agent.adapter.run({repoPath:r.repoPath,prompt:t,timeoutSeconds:240,bin:r.agent.bin,mode:"read_only",maxTurns:40,sessionId:(0,ca.randomUUID)(),onLog:()=>{}});if(!n.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:n.error??"the agent produced no output"};let s=Lc(n.resultText),i=n.resultText.split(/```/)[0]?.trim()??"",a=/```(?:markdown|md)\s*\n([\s\S]*?)```/i.exec(n.resultText)?.[1]?.trim()??"",u=a?yi(r.repoPath):null;return s?{ok:!0,...s,notes:i||s.notes,docPath:u?.path??(a?"DEPLOY.md":""),docContent:a}:{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: "${n.resultText.trim().slice(0,200).replace(/\s+/g," ")}\u2026"`}}async function Dc(r){let e=yi(r.repoPath);if(!e)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:'this repo has no deploy document. Create DEPLOY.md at the repo root (or .ticketpilot/deploy.md) describing how this project actually deploys - the same commands you run by hand. "Ask Claude for steps" translates that document; it does not guess.'};let t=Nc(r.cfg,r.repoName,r.environmentName,e.content),n=kt(Br.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE,{envName:r.environmentName,docPath:e.path,docContent:e.content,notes:r.notes.trim()||"(nothing specified)",machineContext:t}),s=await r.agent.adapter.run({repoPath:r.repoPath,prompt:n,timeoutSeconds:r.timeoutSeconds,bin:r.agent.bin,mode:"read_only",maxTurns:30,sessionId:(0,ca.randomUUID)(),onLog:()=>{}});if(!s.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:s.error??"Claude Code produced no output"};let i=Lc(s.resultText);return i?{ok:!0,...i}:(g.warn(`deploy step suggestion could not be parsed. Claude's raw answer follows:
|
|
679
|
+
`+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 Lc(r){for(let e of xg(r)){let t;try{t=JSON.parse(e)}catch{continue}let n=wg.safeParse(Cg(t));if(n.success&&n.data.steps.length||n.success&&n.data.notes.trim())return n.data}return null}function xg(r){let e=[];for(let s of r.matchAll(/```[a-zA-Z0-9_-]*[ \t]*\r?\n([\s\S]*?)```/g))s[1].trim()&&e.push(s[1]);let t=r.indexOf("{"),n=r.lastIndexOf("}");return t>=0&&n>t&&e.push(r.slice(t,n+1)),e}function Cg(r){if(!r||typeof r!="object")return r;let e=r,n=(Array.isArray(r)?r:Array.isArray(e.steps)?e.steps:Array.isArray(e.deploy_steps)?e.deploy_steps:Array.isArray(e.deploySteps)?e.deploySteps:[]).map((o,a)=>{if(typeof o=="string")return o.trim()?{name:Rc(o,a),run:o.trim()}:null;if(!o||typeof o!="object")return null;let u=o,c=la(u.run,u.command,u.cmd,u.script,u.shell);return c?{name:(la(u.name,u.title,u.description)??Rc(c,a)).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:n.slice(0,50),requiredSecrets:i.slice(0,50),notes:la(e.notes,e.note,e.explanation)??""}}function la(...r){for(let e of r)if(typeof e=="string"&&e.trim())return e.trim()}function Rc(r,e){return(r.split(`
|
|
680
|
+
`)[0].trim()||`Step ${e+1}`).slice(0,120)}_t();Ye();Or();function vi(r,e){if(!r.componentRoutes.length)return{project:r};let t=e.filter(Boolean);if(!t.length)return{error:`no Jira component set - project "${r.name}" routes by component (${r.componentRoutes.map(i=>i.component).join(", ")}); set one on the ticket`};let n=r.componentRoutes.filter(i=>t.includes(i.component));if(!n.length)return{error:`component(s) [${t.join(", ")}] not mapped - known: `+r.componentRoutes.map(i=>`${i.component}\u2192${i.repoName}`).join(", ")};let s=new Set(n.map(i=>i.repoName));return s.size>1?{error:`components map to DIFFERENT repos (${[...s].join(", ")}) - ambiguous, refusing`}:{project:{...r,repoName:n[0].repoName}}}var Uc=24*3600*1e3,bi=14,Ig=bi*24*3600*1e3,Rg=new Set(["to","on","this","the","a","an","env","environment","please","now","it"]),wi=class{constructor(e,t,n){this.cfg=e;this.jiraFor=t;this.transport=n}cfg;jiraFor;transport;projects=[];rules=[];environments=[];inFlight=new Set;autopilotPausedUntil=0;get busyCount(){return 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,t){this.routingWarned.has(e)||(this.routingWarned.add(e),g.warn(`Component routing refused - ${t}`))}resolveClaudeProfile(e,t){if(!t)return;let n=this.cfg.claudeProfiles[t]?.configDir;return!n&&e&&(this.transport.send({type:"run.log",runId:e,seq:99e3,ts:new Date().toISOString(),level:"warn",message:`Claude profile "${t}" is not set up on this runner (allwright claude login "${t}") - using the runner's own login instead.`}),g.warn(`run ${e}: claude profile "${t}" missing locally - using default login`)),n}setConfig(e,t,n=!1,s=[]){this.projects=e,this.rules=t,this.environments=s;let i=t.filter(o=>o.enabled).length;g.info(`config synced: ${e.length} project(s), ${t.length} rule(s) (${i} enabled), ${s.length} environment(s)`),n!==this.paused&&(g.info(n?"polling paused from the dashboard":"polling resumed from the dashboard"),this.paused=n)}start(){let e=this.cfg.pollIntervalSeconds*1e3;this.timer=setInterval(()=>{this.tick()},e),this.tick(),g.info(`polling Jira every ${this.cfg.pollIntervalSeconds}s`)}stop(){this.timer&&clearInterval(this.timer)}lastScheduleCheck=0;auditInFlight=!1;async runScheduledAudits(){if(!(!this.cfg.auditSchedules.length||this.auditInFlight)&&!(Date.now()-this.lastScheduleCheck<15*6e4)){this.lastScheduleCheck=Date.now();for(let e of this.cfg.auditSchedules){let t=this.projects.find(s=>s.repoName===e.repoName);if(!t)continue;let n=Pu(t.id,e.role);if(!(n&&Date.now()-new Date(n).getTime()<e.intervalHours*36e5)){this.auditInFlight=!0;try{g.info(`Scheduled ${e.role} audit of ${e.repoName} starting (every ${e.intervalHours}h)`);let s=Je(this.cfg,t,"assist");if("error"in s){g.warn(`Scheduled audit skipped: ${s.error}`);continue}let i=await Cn({projectId:t.id,repoPath:this.cfg.repos[e.repoName]?.path??"",role:e.role,scope:{kind:"repo",ref:""},model:"",agent:s,jira:this.jiraFor(e.repoName)});if(i.ok){let o=i.audit.findings.length;g.info(`Scheduled audit done: ${o} finding(s) - drift visible on the Audits page`)}else g.warn(`Scheduled audit failed: ${i.error}`)}catch(s){g.warn(`Scheduled audit crashed: ${s instanceof Error?s.message:String(s)}`)}finally{this.auditInFlight=!1}break}}}}async tick(){if(!(this.ticking||this.paused||!this.transport.connected)){this.ticking=!0;try{await this.runScheduledAudits(),await this.sweepMergedPRs(),await this.sweepGitHubApprovals();let e=new Set;for(let t of this.rules){if(!t.enabled)continue;let n=this.projects.find(i=>i.id===t.projectId);if(!n)continue;let s=this.cfg.repos[n.repoName];if(!s){g.warn(`rule "${t.name}": no local path for repo "${n.repoName}" - run: allwright repo add "${n.repoName}" /path/to/checkout`);continue}t.action.type==="deploy"?await this.pollDeployRule(t,n,s.path):t.action.type==="respond"?await this.pollRespondRule(t,n,s.path):(e.has(n.id)||(e.add(n.id),await this.sweepNeedsInput(n)),t.trigger.type==="comment_keyword"&&await this.sweepRevisions(t,n),await this.pollRule(t,n,s.path))}await this.pullAutopilotWork()}catch(e){g.warn(`poll tick failed: ${e instanceof Error?e.message:e}`)}finally{this.ticking=!1}}}async pullAutopilotWork(){if(this.inFlight.size>0||this.autopilotPausedUntil>Date.now())return;let e=await this.transport.requestAutopilotNext();if(!e?.ok)return;if(e.pausedUntil){let T=Date.parse(e.pausedUntil);Number.isFinite(T)&&(this.autopilotPausedUntil=T);return}let t=e.item;if(!t)return;let n=this.rules.find(T=>T.id===t.ruleId&&T.enabled),s=this.projects.find(T=>T.id===t.projectId);if(!n||!s){this.transport.sendAutopilotReport({itemId:t.id,outcome:"failed",error:"the rule or project this item was queued against no longer exists"});return}let i=vi(s,[]),o="project"in i?i.project:s,a=this.cfg.repos[o.repoName];if(!a){this.transport.sendAutopilotReport({itemId:t.id,outcome:"failed",error:`no local checkout mapped for "${o.repoName}" on this machine`});return}let u=t.baseOverride||t.branchOverride?{...n,action:n.action.type==="implement"?{...n.action,...t.baseOverride?{baseBranch:t.baseOverride}:{},...t.branchOverride?{branchTemplate:t.branchOverride}:{}}:n.action}:n;g.info(`autopilot: taking ${t.issueKey} (${n.name})`+(t.branchOverride?` -> shared branch ${t.branchOverride}`:"")+(t.baseOverride?` -> stacked on ${t.baseOverride}`:""));let c=this.jiraOf(o),f="";try{f=(await c.getIssue(t.issueKey))?.summary??""}catch(T){this.transport.sendAutopilotReport({itemId:t.id,outcome:"failed",error:`could not read ${t.issueKey} from Jira: ${T instanceof Error?T.message:String(T)}`});return}let p=await this.transport.claimRun({ruleId:n.id,issueKey:t.issueKey,issueSummary:f,triggerFingerprint:`autopilot:${t.id}`,dedupKey:`autopilot:${t.id}`});if(!p.accepted||!p.runId){this.transport.sendAutopilotReport({itemId:t.id,outcome:"failed",error:p.reason??"the control plane refused the run"});return}this.transport.sendAutopilotReport({itemId:t.id,outcome:"claimed",runId:p.runId});let v=`${n.id}:${t.issueKey}`;this.inFlight.add(v);let S=this.resolveClaudeProfile(p.runId,p.claudeProfile);this.enqueueForRepo(a.path,async()=>{try{await fi({runId:p.runId,rule:u,project:o,issueKey:t.issueKey,repoPath:a.path,cfg:this.cfg,jira:c,transport:this.transport,claudeConfigDir:S,actorEmail:p.actorEmail,continueBranch:t.continueBranch})}finally{this.inFlight.delete(v)}})}async sweepGitHubApprovals(){let e=Object.values(ss());if(!e.length)return;let t=pe()??this.cfg,n=new Map,s=i=>{let o=Ae(t,i);if(!o)return null;let a=n.get(o);return a||n.set(o,a=new $e(o)),a};for(let i of e.slice(0,10)){let o=s(i.repoName);if(!o)continue;let a=`gh-approve:${i.runId}`;if(this.inFlight.has(a))continue;let 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(S){g.warn(`review check failed for ${i.owner}/${i.repo}#${i.prNumber}: ${S instanceof Error?S.message:S}`);continue}if(!c)continue;let f={cfg:this.cfg,jiraFor:this.jiraFor,transport:this.transport};if(c.merged){g.info(`PR #${i.prNumber} for ${i.issueKey} was merged on GitHub - completing the run`),this.inFlight.add(a);try{await ls(f,i.runId,c.headSha)}finally{this.inFlight.delete(a)}continue}if(c.state==="closed"){g.info(`PR #${i.prNumber} for ${i.issueKey} was closed unmerged on GitHub - failing the run`);let S=this.jiraFor(i.repoName),T=`PR #${i.prNumber} was closed on GitHub without merging`;await S.addComment(i.issueKey,`**Allwright: the pull request for this ticket was closed on GitHub without merging.**
|
|
679
681
|
|
|
680
682
|
PR: ${i.prUrl}
|
|
681
683
|
|
|
682
|
-
The run is marked failed. Remove the \`${i.failedLabel}\` label (or hit Retry on the Allwright board) to implement again. (run \`${i.runId}\`)`).catch(()=>{}),await
|
|
684
|
+
The run is marked failed. Remove the \`${i.failedLabel}\` label (or hit Retry on the Allwright board) to implement again. (run \`${i.runId}\`)`).catch(()=>{}),await S.editLabels(i.issueKey,{add:[i.failedLabel]}).catch(()=>{}),this.transport.send({type:"run.status",runId:i.runId,status:"failed",error:T}),Dr(i.runId);continue}c.mergeableState==="dirty"?i.conflictNotified||(this.transport.send({type:"run.pr.conflict",runId:i.runId,conflicted:!0}),await this.jiraFor(i.repoName).addComment(i.issueKey,`**Allwright: the pull request for this ticket has merge conflicts.** The base branch moved after this change was built, so GitHub cannot merge it as-is.
|
|
683
685
|
|
|
684
686
|
PR: ${i.prUrl}
|
|
685
687
|
|
|
686
|
-
To fix: Reject this run on the Allwright dashboard (that closes the conflicted PR), then post the implement trigger comment again - a fresh run rebuilds the change on the current base. Or resolve the conflicts manually on branch \`${i.branch}\`; approval works normally once the PR is conflict-free. (run \`${i.runId}\`)`).catch(()=>{}),i.conflictNotified=!0,
|
|
688
|
+
To fix: Reject this run on the Allwright dashboard (that closes the conflicted PR), then post the implement trigger comment again - a fresh run rebuilds the change on the current base. Or resolve the conflicts manually on branch \`${i.branch}\`; approval works normally once the PR is conflict-free. (run \`${i.runId}\`)`).catch(()=>{}),i.conflictNotified=!0,Bt(i),g.info(`merge conflicts on PR #${i.prNumber} for ${i.issueKey} - ticket notified`)):i.conflictNotified&&c.mergeableState!==null&&c.mergeableState!=="unknown"&&(i.conflictNotified=!1,Bt(i),this.transport.send({type:"run.pr.conflict",runId:i.runId,conflicted:!1}));let p=u.filter(S=>S.state==="APPROVED"||S.state==="CHANGES_REQUESTED").sort((S,T)=>S.submittedAt.localeCompare(T.submittedAt)),v=p[p.length-1];if(v){if(v.state==="CHANGES_REQUESTED"){i.changesRequestedNotified||(await this.jiraFor(i.repoName).addComment(i.issueKey,`**Allwright: changes were requested on the pull request** (by ${v.user}).
|
|
687
689
|
|
|
688
690
|
PR: ${i.prUrl}
|
|
689
691
|
|
|
690
|
-
Reply to the review on GitHub, or reject the run on the Allwright dashboard and re-trigger with new instructions. (run \`${i.runId}\`)`).catch(()=>{}),
|
|
692
|
+
Reply to the review on GitHub, or reject the run on the Allwright dashboard and re-trigger with new instructions. (run \`${i.runId}\`)`).catch(()=>{}),Bt({...i,changesRequestedNotified:!0}),g.info(`changes requested on PR #${i.prNumber} for ${i.issueKey} - ticket notified`));continue}if(v.commitId===c.headSha){g.info(`PR #${i.prNumber} for ${i.issueKey} approved on GitHub by ${v.user} - completing the run`),this.inFlight.add(a);try{await ls(f,i.runId,v.commitId)}catch(S){g.warn(`github-approval completion failed for ${i.runId}: ${S instanceof Error?S.message:S}`)}finally{this.inFlight.delete(a)}}}}}async sweepMergedPRs(){let e=Object.values(li());if(!e.length)return;let t=pe()??this.cfg,n=new Map,s=a=>{let u=Ae(t,a);if(!u)return null;let c=n.get(u);return c||n.set(u,c=new $e(u)),c},i=20,o=720*3600*1e3;for(let a of e.slice(0,i)){let u=s(a.repoName);if(!u)continue;if(Date.now()-new Date(a.createdAt).getTime()>o){g.warn(`merge watch for ${a.issueKey} PR #${a.prNumber} is over 30 days old - dropping`),ns(a.runId);continue}let c;try{c=await u.getPullRequest(a.owner,a.repo,a.prNumber)}catch(v){g.warn(`merge check failed for ${a.owner}/${a.repo}#${a.prNumber}: ${v instanceof Error?v.message:v}`);continue}if(!c){ns(a.runId);continue}if(c.state==="open")continue;if(!c.merged){ns(a.runId);continue}let f=this.jiraFor(a.repoName),p="";if(a.jiraTransitionOnMerge)try{p=await f.transitionByName(a.issueKey,a.jiraTransitionOnMerge)?`
|
|
691
693
|
|
|
692
694
|
Ticket moved to **${a.jiraTransitionOnMerge}**.`:`
|
|
693
695
|
|
|
@@ -697,27 +699,39 @@ Note: the "${a.jiraTransitionOnMerge}" transition failed: ${v instanceof Error?v
|
|
|
697
699
|
|
|
698
700
|
PR: ${a.prUrl} (merged at \`${c.headSha.slice(0,10)}\`)${p}
|
|
699
701
|
|
|
700
|
-
(run \`${a.runId}\`)`)}catch(v){
|
|
702
|
+
(run \`${a.runId}\`)`)}catch(v){g.warn(`could not post merge comment to ${a.issueKey}: ${v instanceof Error?v.message:v}`);continue}g.info(`PR #${a.prNumber} for ${a.issueKey} merged - ticket updated`),ns(a.runId)}}async sweepNeedsInput(e){let t;try{t=await this.jiraOf(e).search(`project = "${e.jiraProjectKey}" AND labels = "${Kr.NEEDS_INPUT_LABEL}"`,10)}catch(s){g.warn(`needs-input sweep failed for ${e.jiraProjectKey}: ${s instanceof Error?s.message:s}`);return}if(!t.length)return;let n=En();for(let s of t){let i=Object.values(n).filter(a=>a.issueKey===s.key);if(!i.length){await this.jiraOf(e).editLabels(s.key,{remove:[Kr.NEEDS_INPUT_LABEL]}).catch(()=>{}),g.warn(`${s.key}: needs-input label with no local pending record - removed`);continue}let o=null;for(let a of i){let u=`resume:${a.runId}`;if(this.inFlight.has(u))continue;if(Date.now()-new Date(a.createdAt).getTime()>Ig){this.inFlight.add(u),this.abandonStaleInput(a,e).finally(()=>this.inFlight.delete(u));continue}try{o=o??await this.jiraOf(e).getIssue(s.key)}catch(T){g.warn(`needs-input check failed for ${s.key}: ${T instanceof Error?T.message:T}`);continue}let c=new Date(a.questionsPostedAt).getTime(),f=o.comments.filter(T=>!ot(T.body)&&new Date(T.created).getTime()>c);if(!f.length)continue;let p=us(f),v=o.attachments;this.inFlight.add(u),g.info(`reply received on ${s.key} - resuming run ${a.runId}`),await this.jiraOf(e).editLabels(s.key,{remove:[Kr.NEEDS_INPUT_LABEL]}).catch(T=>{g.warn(`could not remove needs-input label on ${s.key}: ${T}`)});let S={jiraFor:this.jiraFor,transport:this.transport,cfg:this.cfg};a.kind==="implement"?this.enqueueForRepo(a.baseRepoPath??a.repoPath,async()=>{try{await pc(a,p,v,S)}finally{this.inFlight.delete(u)}}):this.enqueueForRepo(a.repoPath,async()=>{try{await cc(a,p,v,S)}finally{this.inFlight.delete(u)}})}}}async abandonStaleInput(e,t){g.warn(`${e.issueKey}: needs-input unanswered for over ${bi}d - abandoning run ${e.runId}`);try{await this.jiraOf(t).addComment(e.issueKey,`**Allwright gave up waiting for an answer.**
|
|
701
703
|
|
|
702
|
-
No reply arrived within ${
|
|
704
|
+
No reply arrived within ${bi} days of the question above. This ticket has been labeled \`${e.failedLabel}\`; remove it and re-trigger to try again. (run \`${e.runId}\`)`),await this.jiraOf(t).editLabels(e.issueKey,{add:[e.failedLabel],remove:[Kr.NEEDS_INPUT_LABEL]})}catch(n){g.warn(`could not post staleness notice for ${e.issueKey}: ${n}`)}e.kind==="implement"&&await Ft(e.baseRepoPath??e.repoPath,e.repoPath).catch(()=>{}),ut(e.runId),this.transport.send({type:"run.status",runId:e.runId,status:"failed",error:`no reply within ${bi} days`})}async pollRule(e,t,n){let s=e.trigger.type==="label_added"?await this.matchLabelTrigger(e,t):await this.matchCommentTrigger(e,t);for(let i of s){let o=`${e.id}:${i.issueKey}`;if(this.inFlight.has(o))continue;let a=vi(t,i.components??[]);if("error"in a){this.warnRoutingOnce(`${e.id}:${i.issueKey}`,`${i.issueKey}: ${a.error}`);continue}let u=a.project,c=u.repoName===t.repoName?n: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"&&g.warn(`claim rejected for ${i.issueKey}: ${f.reason??"unknown"}`);continue}this.inFlight.add(o),g.info(`claimed run ${f.runId} for ${i.issueKey}`+(u.repoName!==t.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 fi({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,t,n){let s=e.trigger;if(s.type!=="comment_keyword"||e.action.type!=="respond")return;let i=await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=s.keyword.toLowerCase(),a=Date.now()-Uc;for(let u of i){let c=await this.jiraOf(t).getIssue(u.key);for(let f of c.comments){if(!f.body.toLowerCase().includes(o)||ot(f.body)||new Date(f.created).getTime()<a||!f.id)continue;let p=`respond:${f.id}`;if(this.inFlight.has(p))continue;let v=vi(t,u.components??[]);if("error"in v){this.warnRoutingOnce(`${e.id}:${u.key}`,`${u.key}: ${v.error}`);continue}let S=v.project,T=S.repoName===t.repoName?n:this.cfg.repos[S.repoName]?.path;if(!T){this.warnRoutingOnce(`${e.id}:${u.key}:path`,`${u.key}: routed to repo "${S.repoName}" but it has no local checkout - run: allwright repo add "${S.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"&&g.warn(`respond claim rejected for ${u.key}: ${x.reason??"unknown"}`);continue}this.inFlight.add(p),g.info(`claimed respond run ${x.runId}: ${u.key} (comment ${f.id})`+(S.repoName!==t.repoName?` (routed \u2192 ${S.repoName})`:"")+(x.claudeProfile?` (claude profile "${x.claudeProfile}")`:""));let P={author:f.author,body:f.body},_=this.resolveClaudeProfile(x.runId,x.claudeProfile);this.enqueueForRepo(T,async()=>{try{await fi({runId:x.runId,rule:e,project:S,issueKey:u.key,repoPath:T,cfg:this.cfg,jira:this.jiraOf(S),transport:this.transport,question:P,claudeConfigDir:_,actorEmail:x.actorEmail})}finally{this.inFlight.delete(p)}})}}}async sweepRevisions(e,t){let n=e.trigger;if(n.type!=="comment_keyword")return;let s;try{s=await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND labels = "${n.doneLabel}" AND updated >= "-2d"`,10)}catch(o){g.warn(`revision sweep failed for ${t.jiraProjectKey}: ${o instanceof Error?o.message:o}`);return}let i=n.keyword.toLowerCase();for(let o of s)try{let a=await this.jiraOf(t).getIssue(o.key),u=null;for(let f of a.comments)ot(f.body)&&(u=Math.max(u??0,new Date(f.created).getTime()));if(u===null||!a.comments.some(f=>!ot(f.body)&&f.body.toLowerCase().includes(i)&&new Date(f.created).getTime()>u))continue;await this.jiraOf(t).editLabels(o.key,{remove:[n.doneLabel]}),g.info(`revision requested on ${o.key} (new "${n.keyword}" after completion) - done label removed, rule will re-fire`)}catch(a){g.warn(`revision check failed for ${o.key}: ${a instanceof Error?a.message:a}`)}}async pollDeployRule(e,t,n){if(e.action.type!=="deploy")return;let s=e.trigger.type==="status_changed"?await this.matchStatusDeploys(e,t):await this.matchCommentDeploys(e,t);for(let i of s){let o=`deploy:${i.dedupKey}`;if(this.inFlight.has(o))continue;let a=await this.transport.claimDeploy({projectId:t.id,ruleId:e.id,issueKey:i.issueKey,issueSummary:i.summary,environmentName:i.environmentName,requestedByAccountId:i.requestedByAccountId,requestedByDisplayName:i.requestedByDisplayName,dedupKey:i.dedupKey,triggerFingerprint:i.fingerprint});if(!a.accepted||!a.runId||!a.environment){if(a.code==="duplicate")continue;a.reason&&a.runId?(await this.jiraOf(t).addComment(i.issueKey,`**Allwright did not deploy this ticket.**
|
|
703
705
|
|
|
704
706
|
${a.reason}`+(i.requestedByAccountId?`
|
|
705
707
|
|
|
706
708
|
Jira account id: \`${i.requestedByAccountId}\``:"")+`
|
|
707
709
|
|
|
708
|
-
(run \`${a.runId}\`)`).catch(c=>
|
|
709
|
-
`,{mode:384}),Lr.default.renameSync(t,e),Lr.default.chmodSync(e,384)}function zc(r,e,t,n){let s=oa(),o=s[e]??{sessionId:e,projectId:r,title:t.slice(0,80),updatedAt:new Date().toISOString(),messages:[]};o.messages.push({role:"user",text:t.slice(0,Oc)},{role:"agent",text:n.slice(0,Oc)}),o.messages=o.messages.slice(-xg),o.updatedAt=new Date().toISOString(),s[e]=o;let a=Object.values(s).filter(l=>l.projectId===o.projectId).sort((l,c)=>c.updatedAt.localeCompare(l.updatedAt));for(let l of a.slice(Tg))delete s[l.sessionId];Cg(s)}function Dc(r){return Object.values(oa()).filter(e=>e.projectId===r).sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt)).map(e=>({sessionId:e.sessionId,title:e.title,updatedAt:e.updatedAt,messageCount:e.messages.length}))}function aa(r){return oa()[r]??null}var Ur=R(require("node:fs"),1),Be=R(require("node:path"),1),ua=300,Eg=4,Lc=512*1024,Ig=new Set([".git","node_modules","dist","build","out",".next","vendor","coverage",".venv","venv","__pycache__",".turbo",".cache"]),Uc=/\.mdx?$/i;function qc(r){let e=Be.default.resolve(r),t=[],n=(s,i)=>{if(i>Eg||t.length>=ua)return;let o;try{o=Ur.default.readdirSync(s,{withFileTypes:!0})}catch{return}for(let a of o){if(t.length>=ua)return;if(!a.isFile()||!Uc.test(a.name))continue;let l=Be.default.join(s,a.name);try{let c=Ur.default.statSync(l);t.push({path:Be.default.relative(e,l).split(Be.default.sep).join("/"),sizeBytes:c.size,updatedAt:c.mtime.toISOString()})}catch{}}for(let a of o){if(t.length>=ua)return;!a.isDirectory()||a.isSymbolicLink()||Ig.has(a.name)||a.name.startsWith(".")||n(Be.default.join(s,a.name),i+1)}};return n(e,0),t}function Fc(r,e){let t=Be.default.resolve(r);if(!Uc.test(e))return{ok:!1,error:"only markdown files can be opened here"};let n=Be.default.resolve(t,e);if(n!==t&&!n.startsWith(t+Be.default.sep))return{ok:!1,error:"that path is outside the project checkout"};let s;try{s=Ur.default.realpathSync(n)}catch{return{ok:!1,error:"file not found in this checkout"}}let i=(()=>{try{return Ur.default.realpathSync(t)}catch{return t}})();if(s!==i&&!s.startsWith(i+Be.default.sep))return{ok:!1,error:"that path links outside the project checkout"};let o;try{o=Ur.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 a=Ur.default.readFileSync(s,"utf8"),l=Buffer.byteLength(a,"utf8")>Lc;return{ok:!0,path:Be.default.relative(i,s).split(Be.default.sep).join("/"),content:l?a.slice(0,Lc):a,truncated:l}}catch(a){return{ok:!1,error:a instanceof Error?a.message:"could not read the file"}}}var Ni=R(ve(),1);var pi=R(require("node:fs"),1),Bc=R(require("node:path"),1);var Rg=_.object({id:_.string(),name:_.string().default(""),jiraProjectKey:_.string().default(""),repoName:_.string().default(""),jiraSiteUrl:_.string().default("")}),Ag=_.array(Rg);function Kc(){return Bc.default.join(te(),"synced-projects.json")}function Zc(r){try{let e=r.map(t=>({id:t.id,name:t.name,jiraProjectKey:t.jiraProjectKey,repoName:t.repoName,jiraSiteUrl:t.jiraSiteUrl??""}));pi.default.mkdirSync(te(),{recursive:!0}),pi.default.writeFileSync(Kc(),JSON.stringify(e,null,2),{mode:384})}catch{}}function $g(){try{let r=Ag.safeParse(JSON.parse(pi.default.readFileSync(Kc(),"utf8")));return r.success?r.data:[]}catch{return[]}}function Gc(r){return $g().find(e=>e.repoName===r)??null}var Xy=R(qd(),1),Qy=R(Si(),1),ev=R(Cn(),1),tv=R(ba(),1),rv=R(ka(),1),nv=R(Ia(),1),Jd=R(Ei(),1),sv=R(Wd(),1);var Aa=Jd.default;var us=R(require("node:crypto"),1),ut=R(ve(),1);function iv(r){let e=r&&typeof r=="object"&&"name"in r?String(r.name):null;return e?`"${e}"`:"(unnamed)"}function $a(r,e,t,n){r.push(`dropped ${e} ${t} - this runner is out of date and does not understand it yet (${n}). Update the runner (npm install -g @ticketpilot/runner) to pick it up.`)}function ov(r){if(!r||typeof r!="object"||r.type!=="config")return null;let e=r,t=[],n=[];for(let a of Array.isArray(e.projects)?e.projects:[]){let l=ut.ProjectConfig.safeParse(a);l.success?n.push(l.data):$a(t,"project","",l.error.issues[0]?.message??"invalid shape")}let s=[];for(let a of Array.isArray(e.rules)?e.rules:[]){let l=ut.RuleConfig.safeParse(a);l.success?s.push(l.data):$a(t,"rule",iv(a),l.error.issues[0]?.message??"invalid shape")}let i=[];for(let a of Array.isArray(e.environments)?e.environments:[]){let l=ut.EnvironmentConfig.safeParse(a);l.success?i.push(l.data):$a(t,"environment","",l.error.issues[0]?.message??"invalid shape")}return{msg:{type:"config",projects:n,rules:s,environments:i,pollingPaused:typeof e.pollingPaused=="boolean"?e.pollingPaused:!1},warnings:t}}var av=2e4,uv=6e4,lv=5e3,Ri=class{constructor(e,t,n,s){this.wsUrl=e;this.runnerToken=t;this.meta=n;this.events=s}wsUrl;runnerToken;meta;events;ws=null;queue=[];pending=new Map;backoffMs=1e3;heartbeat=null;closed=!1;bootAnnounced=!1;start(){this.closed=!1,this.connect()}stop(){this.closed=!0,this.heartbeat&&clearInterval(this.heartbeat),this.ws?.close()}get connected(){return this.ws?.readyState===Aa.OPEN}connect(){if(this.closed)return;m.info(`connecting to control plane at ${this.wsUrl}`);let e=new Aa(this.wsUrl,{headers:{authorization:`Bearer ${this.runnerToken}`}});this.ws=e,e.on("open",()=>{this.backoffMs=1e3,this.sendNow({type:"hello",protocolVersion:ut.PROTOCOL_VERSION,runnerVersion:this.meta.runnerVersion,platform:`${process.platform}/${process.arch} node${process.versions.node}`,justBooted:!this.bootAnnounced});let t=this.queue.splice(0,this.queue.length);for(let n of t)this.sendNow(n);this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=setInterval(()=>{this.send({type:"heartbeat",ts:new Date().toISOString()})},av)}),e.on("message",t=>{let n;try{n=JSON.parse(t.toString())}catch(i){m.warn(`ignoring malformed server message (bad JSON): ${i}`);return}let s;try{s=(0,ut.parseServerMsg)(n)}catch(i){let o=ov(n);if(!o){m.warn(`ignoring malformed server message: ${i}`);return}for(let a of o.warnings)m.warn(a);m.warn(`config push had ${o.warnings.length} ${o.warnings.length===1?"entry":"entries"} this runner doesn't understand - applied everything else instead of dropping the whole config`),s=o.msg}this.handle(s)}),e.on("close",t=>{if(this.heartbeat&&clearInterval(this.heartbeat),t===4001)m.error("control plane rejected this runner version (protocol mismatch). Update with: npm install -g @ticketpilot/runner");else if(t===4003){m.error("this runner has been revoked from the control plane UI. Re-enroll with a fresh token if this was not intended."),this.closed=!0;return}if(this.closed)return;let n=Math.random()*.3+.85,s=Math.round(this.backoffMs*n);m.warn(`disconnected (code ${t}); reconnecting in ${Math.round(s/1e3)}s`),setTimeout(()=>this.connect(),s),this.backoffMs=Math.min(this.backoffMs*2,uv)}),e.on("error",t=>{m.warn(`websocket error: ${t.message}`)})}handle(e){if(e.type==="hello.ack"){this.bootAnnounced=!0,m.info(`connected as runner "${e.runnerName}" (${e.runnerId})`);return}if(e.type==="run.claim.result"||e.type==="deploy.claim.result"||e.type==="autopilot.next.result"){let t=this.pending.get(e.requestId);t&&(clearTimeout(t.timer),this.pending.delete(e.requestId),t.resolve(e));return}if(e.type==="config")return this.events.onConfig(e);if(e.type==="project.test")return this.events.onProjectTest(e);if(e.type==="rule.diagnose")return this.events.onRuleDiagnose(e);if(e.type==="run.cancel")return this.events.onCancel(e.runId);if(e.type==="run.approved")return this.events.onApproved(e.runId,e.headSha);if(e.type==="run.rejected")return this.events.onRejected(e.runId);if(e.type==="run.retryPush")return this.events.onRetryPush(e.runId);if(e.type==="deploy.start")return this.events.onDeployStart(e);if(e.type==="deploy.suggest")return this.events.onDeploySuggest(e);if(e.type==="deploy.fix")return this.events.onDeployFix(e);if(e.type==="env.preflight")return this.events.onEnvPreflight(e);if(e.type==="chat.turn")return this.events.onChatTurn(e);if(e.type==="chat.create.ticket")return this.events.onChatCreateTicket(e);if(e.type==="chat.list")return this.events.onChatList(e);if(e.type==="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==="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>=lv){let t=this.queue.findIndex(n=>n.type==="run.log");t>=0?this.queue.splice(t,1):this.queue.shift()}this.queue.push(e)}async claimRun(e){if(!this.connected)return{accepted:!1,reason:"control plane offline"};let t=us.default.randomUUID(),n=await new Promise(s=>{let i=setTimeout(()=>{this.pending.delete(t),s(null)},15e3);this.pending.set(t,{resolve:s,timer:i}),this.sendNow({type:"run.claim",requestId:t,...e})});return!n||n.type!=="run.claim.result"?{accepted:!1,reason:"claim timed out"}:{accepted:n.accepted,runId:n.runId,reason:n.reason,claudeProfile:n.claudeProfile,actorEmail:n.actorEmail}}async requestAutopilotNext(){if(!this.connected)return null;let e=us.default.randomUUID(),t=await new Promise(n=>{let s=setTimeout(()=>{this.pending.delete(e),n(null)},15e3);this.pending.set(e,{resolve:n,timer:s}),this.sendNow({type:"autopilot.next",requestId:e})});return!t||t.type!=="autopilot.next.result"?null:{ok:t.ok,item:t.item,pausedUntil:t.pausedUntil}}sendAutopilotReport(e){this.send({type:"autopilot.report",requestId:us.default.randomUUID(),itemId:e.itemId,outcome:e.outcome,runId:e.runId??"",error:e.error??""})}async claimDeploy(e){if(!this.connected)return{accepted:!1,reason:"control plane offline"};let t=us.default.randomUUID(),n=await new Promise(s=>{let i=setTimeout(()=>{this.pending.delete(t),s(null)},15e3);this.pending.set(t,{resolve:s,timer:i}),this.sendNow({type:"deploy.claim",requestId:t,...e})});return!n||n.type!=="deploy.claim.result"?{accepted:!1,reason:"deploy authorization timed out"}:{accepted:n.accepted,runId:n.runId,environment:n.environment,reason:n.reason,code:n.code}}sendDeploySuggestResult(e,t){this.send({type:"deploy.suggest.result",requestId:e,...t,docPath:t.docPath??"",docContent:t.docContent??""})}sendChatTurnResult(e,t){this.send({type:"chat.turn.result",requestId:e,...t,inputTokens:t.inputTokens??0,outputTokens:t.outputTokens??0,cacheReadTokens:t.cacheReadTokens??0,costUsd:t.costUsd??0,model:t.model??""})}sendChatCreateTicketResult(e,t){this.send({type:"chat.create.ticket.result",requestId:e,...t,childKeys:t.childKeys??[]})}sendChatListResult(e,t){this.send({type:"chat.list.result",requestId:e,sessions:t})}sendRepoDocsResult(e,t){this.send({type:"repo.docs.result",requestId:e,...t})}sendRepoDocReadResult(e,t){this.send({type:"repo.doc.read.result",requestId:e,...t})}sendChatLoadResult(e,t){this.send({type:"chat.load.result",requestId:e,...t})}sendBoardFetchResult(e,t){this.send({type:"board.fetch.result",requestId:e,...t,browseBaseUrl:t.browseBaseUrl??""})}sendAuditStartResult(e,t){this.send({type:"audit.start.result",requestId:e,...t})}sendAuditListResult(e,t){this.send({type:"audit.list.result",requestId:e,ok:t.ok,error:t.error,audits:t.audits??[]})}sendAuditGetResult(e,t){this.send({type:"audit.get.result",requestId:e,...t})}sendAuditReviewResult(e,t){this.send({type:"audit.review.result",requestId:e,...t})}sendKnowledgeListResult(e,t){this.send({type:"knowledge.list.result",requestId:e,ok:t.ok,error:t.error,files:t.files??[]})}sendKnowledgeSaveResult(e,t){this.send({type:"knowledge.save.result",requestId:e,...t})}sendEpicListResult(e,t){this.send({type:"epic.list.result",requestId:e,ok:t.ok,error:t.error,epics:t.epics??[],children:t.children??[]})}sendEpicSuggestResult(e,t){this.send({type:"epic.suggest.result",requestId:e,ok:t.ok,error:t.error,issueKey:t.issueKey??"",reason:t.reason??"",considered:t.considered??0})}sendTeamCredsResult(e,t){this.send({type:"team.creds.result",requestId:e,ok:t.ok,error:t.error,githubShared:t.githubShared??!1,sharedGithubLogin:t.sharedGithubLogin??"",entries:t.entries??[]})}sendBoardTriggerResult(e,t){this.send({type:"board.trigger.result",requestId:e,...t})}sendAuditStatsResult(e,t){this.send({type:"audit.stats.result",requestId:e,ok:t.ok,error:t.error,byProject:t.byProject??{}})}sendRunnerUpdateResult(e,t){this.send({type:"runner.update.result",requestId:e,ok:t.ok,error:t.error,note:t.note??"",scheduled:t.scheduled??!1})}sendSetupClaudeMdGenerateResult(e,t){this.send({type:"setup.claudemd.generate.result",requestId:e,ok:t.ok,error:t.error,content:t.content??""})}sendSetupClaudeMdSaveResult(e,t){this.send({type:"setup.claudemd.save.result",requestId:e,ok:t.ok,error:t.error,note:t.note??""})}sendRepoDocSaveResult(e,t){this.send({type:"repo.doc.save.result",requestId:e,ok:t.ok,error:t.error,note:t.note??""})}sendSetupStatusResult(e,t){this.send({type:"setup.status.result",requestId:e,ok:t.ok,error:t.error,jiraConfigured:t.jiraConfigured??!1,jiraEmail:t.jiraEmail??"",claude:t.claude,githubTokenSet:t.githubTokenSet??!1,githubLogin:t.githubLogin??"",deploysEnabled:t.deploysEnabled??!1,jiraUserCount:t.jiraUserCount??0,repos:t.repos??[]})}sendEnvPreflightResult(e,t){this.send({type:"env.preflight.result",requestId:e,...t,checks:this.withFixDefaults(t.checks)})}sendJiraUsersResult(e,t){this.send({type:"jira.users.result",requestId:e,...t})}withFixDefaults(e){return e.map(t=>({...t,kind:t.kind??"connection",fix:t.fix??[],fixNote:t.fixNote??""}))}sendProjectTestResult(e,t,n){this.send({type:"project.test.result",requestId:e,ok:t,checks:this.withFixDefaults(n)})}sendRuleDiagnoseResult(e,t){this.send({type:"rule.diagnose.result",requestId:e,...t,checks:this.withFixDefaults(t.checks)})}};var Ai=R(require("node:fs"),1),Pn=R(require("node:path"),1),Xd=require("node:child_process"),cv=/\.mdx?$/i,Yd=6,dv=/^[\w.\- ()]+$/;function hv(r,e){let t=e.trim().replace(/\\/g,"/").replace(/^\.\//,"");if(!t)return{ok:!1,error:"empty path"};if(Pn.default.isAbsolute(t))return{ok:!1,error:"path must be repo-relative"};if(!cv.test(t))return{ok:!1,error:"only markdown files (.md) can be saved"};let n=t.split("/");if(n.length>Yd)return{ok:!1,error:`path deeper than ${Yd} levels`};for(let o of n)if(o==="."||o===".."||!dv.test(o))return{ok:!1,error:`invalid path segment "${o}"`};if(n[0]===".git")return{ok:!1,error:"cannot write under .git"};let s=Pn.default.resolve(r),i=Pn.default.resolve(s,t);return i!==s&&!i.startsWith(s+Pn.default.sep)?{ok:!1,error:"path escapes the checkout"}:{ok:!0,abs:i,rel:t}}async function Pa(r){let e=hv(r.repoPath,r.relPath);if(!e.ok)return{ok:!1,error:e.error};if(Ai.default.existsSync(e.abs)&&!r.overwrite)return{ok:!1,error:`${e.rel} already exists in this checkout`};Ai.default.mkdirSync(Pn.default.dirname(e.abs),{recursive:!0}),Ai.default.writeFileSync(e.abs,r.content.endsWith(`
|
|
710
|
+
(run \`${a.runId}\`)`).catch(c=>g.warn(`could not post refusal to ${i.issueKey}: ${c}`)),g.warn(`deploy refused for ${i.issueKey}: ${a.reason}`)):a.reason&&g.warn(`deploy claim rejected for ${i.issueKey}: ${a.reason}`);continue}let u=a.environment;this.inFlight.add(o),g.info(`claimed deploy ${a.runId}: ${i.issueKey} \u2192 ${u.name}`),this.enqueue(this.envQueues,u.id,async()=>{try{await gi({runId:a.runId,project:t,environment:u,issueKey:i.issueKey,issueSummary:i.summary,repoPath:n,cfg:this.cfg,jira:this.jiraOf(t),transport:this.transport,requestedBy:i.requestedByDisplayName})}finally{this.inFlight.delete(o)}})}}async matchCommentDeploys(e,t){let n=e.trigger,s=e.action;if(n.type!=="comment_keyword"||s.type!=="deploy")return[];let i=await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=n.keyword.toLowerCase(),a=Date.now()-Uc,u=this.environments.filter(p=>p.projectId===t.id).map(p=>p.name),c=this.fixedEnvironmentName(s.environmentId),f=[];for(let p of i){let v=await this.jiraOf(t).getIssue(p.key);if(!(s.requireStatus&&v.status.toLowerCase()!==s.requireStatus.toLowerCase()))for(let S of v.comments){if(!S.body.toLowerCase().includes(o)||ot(S.body)||new Date(S.created).getTime()<a||!S.id)continue;let T=s.envSelection==="fixed"?c:Eg(S.body,n.keyword,u);f.push({issueKey:p.key,summary:p.summary,environmentName:T,requestedByAccountId:S.authorAccountId??void 0,requestedByDisplayName:S.author,dedupKey:`deploy:comment:${S.id}`,fingerprint:`comment "${n.keyword}" by ${S.author} at ${S.created}`+(T?` \u2192 ${T}`:"")})}}return f}async matchStatusDeploys(e,t){let n=e.trigger,s=e.action;if(n.type!=="status_changed"||s.type!=="deploy")return[];let i=await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND status = "${n.status}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=this.fixedEnvironmentName(s.environmentId),a=[];for(let u of i){let c=await this.jiraOf(t).lastEnteredStatus(u.key,n.status);c&&a.push({issueKey:u.key,summary:u.summary,environmentName:o,requestedByAccountId:c.authorAccountId??void 0,requestedByDisplayName:c.author,dedupKey:`deploy:status:${e.id}:${u.key}:${c.at}`,fingerprint:`moved to "${n.status}" by ${c.author} at ${c.at}`})}return a}fixedEnvironmentName(e){return e?this.environments.find(t=>t.id===e)?.name??"":""}async matchLabelTrigger(e,t){let n=e.trigger;if(n.type!=="label_added")return[];let s=`project = "${t.jiraProjectKey}" AND labels = "${n.label}" AND labels not in ("${n.doneLabel}", "${n.failedLabel}", "${Kr.NEEDS_INPUT_LABEL}") ORDER BY updated ASC`;return(await this.jiraOf(t).search(s,10)).map(o=>({issueKey:o.key,summary:o.summary,components:o.components,fingerprint:`label "${n.label}" matched at ${new Date().toISOString()}`}))}async matchCommentTrigger(e,t){let n=e.trigger;if(n.type!=="comment_keyword")return[];let s=`project = "${t.jiraProjectKey}" AND updated >= "-2d" AND (labels IS EMPTY OR labels not in ("${n.doneLabel}", "${n.failedLabel}", "${Kr.NEEDS_INPUT_LABEL}")) ORDER BY updated DESC`,i=await this.jiraOf(t).search(s,10),o=n.keyword.toLowerCase(),a=[];for(let u of i){let f=[...(await this.jiraOf(t).getIssue(u.key)).comments].reverse().find(p=>p.body.toLowerCase().includes(o)&&!ot(p.body));f&&a.push({issueKey:u.key,components:u.components,summary:u.summary,fingerprint:`comment keyword "${n.keyword}" by ${f.author} at ${f.created}`,triggeredByAccountId:f.authorAccountId??void 0})}return a}async diagnoseRule(e,t){let n=e.trigger;if(e.action.type==="deploy"){let u=n.type==="status_changed"?await this.matchStatusDeploys(e,t):await this.matchCommentDeploys(e,t),c=u.filter(f=>f.environmentName);return{matchedCount:c.length,excludedCount:u.length-c.length,excludedSample:u.filter(f=>!f.environmentName).slice(0,5).map(f=>f.issueKey)}}if(n.type==="status_changed")return{matchedCount:(await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND status = "${n.status}"`,50)).length,excludedCount:0,excludedSample:[]};if(n.type==="label_added"){let[u,c]=await Promise.all([this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND labels = "${n.label}" AND labels not in ("${n.doneLabel}", "${n.failedLabel}")`,50),this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND labels = "${n.label}" AND labels in ("${n.doneLabel}", "${n.failedLabel}")`,50)]);return{matchedCount:u.length,excludedCount:c.length,excludedSample:c.slice(0,5).map(f=>f.key)}}let s=n.keyword.toLowerCase(),[i,o]=await Promise.all([this.matchCommentTrigger(e,t),this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND updated >= "-2d" AND labels in ("${n.doneLabel}", "${n.failedLabel}")`,50)]),a=[];for(let u of o)(await this.jiraOf(t).getIssue(u.key)).comments.some(f=>f.body.toLowerCase().includes(s))&&a.push(u.key);return{matchedCount:i.length,excludedCount:a.length,excludedSample:a.slice(0,5)}}enqueueForRepo(e,t){this.enqueue(this.repoQueues,e,t)}runOnRepoQueue(e,t){this.enqueue(this.repoQueues,e,t)}runOnEnvironmentQueue(e,t){this.enqueue(this.envQueues,e,t)}enqueue(e,t,n){let i=(e.get(t)??Promise.resolve()).then(async()=>{this.activeWork++;try{await n()}finally{this.activeWork--}}).catch(o=>{g.error(`run crashed: ${o instanceof Error?o.stack:o}`)});e.set(t,i)}};function Eg(r,e,t){let n=r.toLowerCase().indexOf(e.toLowerCase());if(n<0)return"";let i=r.slice(n+e.length).split(/[^\w.-]+/).filter(Boolean);for(let o of i){let a=t.find(u=>u.toLowerCase()===o.toLowerCase());if(a)return a}for(let o of i)if(!Rg.has(o.toLowerCase()))return o;return""}var qc=E(require("node:fs"),1),Fc=E(require("node:path"),1),fa=require("node:crypto");_t();var Ag=`This repository is in the middle of a git merge: the base branch moved and some files conflict with the change on this branch. Your ONLY job is to resolve those conflicts.
|
|
711
|
+
|
|
712
|
+
Rules:
|
|
713
|
+
- Edit ONLY the conflicted files listed below. Do not touch anything else, do not refactor, do not "improve" surrounding code.
|
|
714
|
+
- In each file remove every conflict marker (<<<<<<<, =======, >>>>>>>) and leave code that keeps BOTH intentions: the change this branch was making, and whatever the base branch changed. If the two genuinely cannot coexist, prefer the base branch's version and say so in your summary.
|
|
715
|
+
- Do not delete the branch's feature work just to make the conflict go away.
|
|
716
|
+
- When you are done, every listed file must contain no conflict markers and must be syntactically valid.
|
|
717
|
+
|
|
718
|
+
Conflicted files:
|
|
719
|
+
`;async function Bc(r){let{cfg:e,repoPath:t,branch:n,baseBranch:s,issueKey:i,onLog:o}=r,a=Fc.default.join(Ar(),`conflict-${(0,fa.randomUUID)().slice(0,8)}`),u=!1;try{o("info",`Preparing a worktree for ${n} to merge ${s} into it`),await Po(t,a,n),u=!0;let c=await Eo(a,s);if(c.ok&&c.alreadyUpToDate)return o("info",`${n} 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 T=c.conflicts;o("info",`git merged everything except ${T.length} file(s): ${T.slice(0,20).join(", ")}`+(T.length>20?", \u2026":""));let x=lt(r.agentId);if(!x)return await Pr(a),{ok:!1,note:`no adapter for agent "${r.agentId}" on this runner`};let P=In(r.agentId,"edit_no_shell");if(P)return await Pr(a),{ok:!1,note:`${P} Resolve the conflicts yourself on branch ${n}, or use Rebuild on current base.`};o("info",`Asking ${x.displayName} to resolve only those files`);let _=await x.run({repoPath:a,prompt:Ag+T.map(O=>`- ${O}`).join(`
|
|
720
|
+
`),timeoutSeconds:r.timeoutSeconds,bin:We(e,r.agentId),configDir:r.configDir,mode:"edit_no_shell",sessionId:(0,fa.randomUUID)(),onLog:(O,L)=>o(O,L)});f={costUsd:_.costUsd,inputTokens:_.inputTokens,outputTokens:_.outputTokens},p=!0;let J=await $o(a);if(J.length)return await Pr(a),{ok:!1,...f,note:`The agent left conflict markers in ${J.slice(0,5).join(", ")}, so nothing was pushed and the merge was rolled back. Resolve it by hand on ${n}, or use Rebuild on current base to redo the ticket against today's base.`};await Ao(a,`${i}: merge ${s}, conflicts resolved by the agent
|
|
721
|
+
|
|
722
|
+
Resolved via Allwright`)}let v=await Qn(a,s);if(!v.ok){let T=v.forbidden.length?`the merged result touches protected paths (${v.forbidden.slice(0,5).join(", ")})`:`the merged result is too large (${v.files} files, ${v.insertions+v.deletions} lines; limits ${_n}/${kn})`;return await Pr(a),{ok:!1,...f,note:`Nothing was pushed: ${T}. The merge was rolled back.`}}await es(a,n);let S=await $r(a);return o("info",`Pushed the merge to ${n} (${S.slice(0,7)})`),{ok:!0,...f,freeOfCharge:!p,headSha:S,note:p?`Merged ${s} into ${n}; the agent resolved the overlapping files. The PR is the same one - review the merge commit, then approve.`:`Merged ${s} into ${n} cleanly - no agent was needed, so this cost nothing. The PR is the same one; review and approve.`}}catch(c){return await Pr(a).catch(()=>{}),{ok:!1,note:`Could not resolve the conflict: ${c instanceof Error?c.message.slice(0,300):String(c)}`}}finally{u&&(await Ft(t,a).catch(()=>{}),qc.default.rmSync(a,{recursive:!0,force:!0}))}}Ye();var Zr=E(require("node:fs"),1),Zc=E(require("node:path"),1);var $g=k.object({role:k.enum(["user","agent"]),text:k.string()}),Pg=k.object({sessionId:k.string(),projectId:k.string(),title:k.string().default(""),updatedAt:k.string(),messages:k.array($g).default([])}),jg=k.record(Pg),Og=10,Ng=200,Kc=2e4;function Gc(){return Zc.default.join(te(),"chat-sessions.json")}function pa(){let r=Gc();if(!Zr.default.existsSync(r))return{};try{return jg.parse(JSON.parse(Zr.default.readFileSync(r,"utf8")))}catch{return{}}}function Mg(r){Zr.default.mkdirSync(te(),{recursive:!0,mode:448});let e=Gc(),t=e+".tmp";Zr.default.writeFileSync(t,JSON.stringify(r,null,2)+`
|
|
723
|
+
`,{mode:384}),Zr.default.renameSync(t,e),Zr.default.chmodSync(e,384)}function Hc(r,e,t,n){let s=pa(),o=s[e]??{sessionId:e,projectId:r,title:t.slice(0,80),updatedAt:new Date().toISOString(),messages:[]};o.messages.push({role:"user",text:t.slice(0,Kc)},{role:"agent",text:n.slice(0,Kc)}),o.messages=o.messages.slice(-Ng),o.updatedAt=new Date().toISOString(),s[e]=o;let a=Object.values(s).filter(u=>u.projectId===o.projectId).sort((u,c)=>c.updatedAt.localeCompare(u.updatedAt));for(let u of a.slice(Og))delete s[u.sessionId];Mg(s)}function Vc(r){return Object.values(pa()).filter(e=>e.projectId===r).sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt)).map(e=>({sessionId:e.sessionId,title:e.title,updatedAt:e.updatedAt,messageCount:e.messages.length}))}function ma(r){return pa()[r]??null}var Gr=E(require("node:fs"),1),Be=E(require("node:path"),1),ga=300,zg=4,Wc=512*1024,Dg=new Set([".git","node_modules","dist","build","out",".next","vendor","coverage",".venv","venv","__pycache__",".turbo",".cache"]),Jc=/\.mdx?$/i;function Yc(r){let e=Be.default.resolve(r),t=[],n=(s,i)=>{if(i>zg||t.length>=ga)return;let o;try{o=Gr.default.readdirSync(s,{withFileTypes:!0})}catch{return}for(let a of o){if(t.length>=ga)return;if(!a.isFile()||!Jc.test(a.name))continue;let u=Be.default.join(s,a.name);try{let c=Gr.default.statSync(u);t.push({path:Be.default.relative(e,u).split(Be.default.sep).join("/"),sizeBytes:c.size,updatedAt:c.mtime.toISOString()})}catch{}}for(let a of o){if(t.length>=ga)return;!a.isDirectory()||a.isSymbolicLink()||Dg.has(a.name)||a.name.startsWith(".")||n(Be.default.join(s,a.name),i+1)}};return n(e,0),t}function Xc(r,e){let t=Be.default.resolve(r);if(!Jc.test(e))return{ok:!1,error:"only markdown files can be opened here"};let n=Be.default.resolve(t,e);if(n!==t&&!n.startsWith(t+Be.default.sep))return{ok:!1,error:"that path is outside the project checkout"};let s;try{s=Gr.default.realpathSync(n)}catch{return{ok:!1,error:"file not found in this checkout"}}let i=(()=>{try{return Gr.default.realpathSync(t)}catch{return t}})();if(s!==i&&!s.startsWith(i+Be.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 a=Gr.default.readFileSync(s,"utf8"),u=Buffer.byteLength(a,"utf8")>Wc;return{ok:!0,path:Be.default.relative(i,s).split(Be.default.sep).join("/"),content:u?a.slice(0,Wc):a,truncated:u}}catch(a){return{ok:!1,error:a instanceof Error?a.message:"could not read the file"}}}var Ht=E(be(),1);var _i=E(require("node:fs"),1),Qc=E(require("node:path"),1);var Lg=k.object({id:k.string(),name:k.string().default(""),jiraProjectKey:k.string().default(""),repoName:k.string().default(""),jiraSiteUrl:k.string().default("")}),Ug=k.array(Lg);function ed(){return Qc.default.join(te(),"synced-projects.json")}function td(r){try{let e=r.map(t=>({id:t.id,name:t.name,jiraProjectKey:t.jiraProjectKey,repoName:t.repoName,jiraSiteUrl:t.jiraSiteUrl??""}));_i.default.mkdirSync(te(),{recursive:!0}),_i.default.writeFileSync(ed(),JSON.stringify(e,null,2),{mode:384})}catch{}}function qg(){try{let r=Ug.safeParse(JSON.parse(_i.default.readFileSync(ed(),"utf8")));return r.success?r.data:[]}catch{return[]}}function rd(r){return qg().find(e=>e.repoName===r)??null}var lv=E(Yd(),1),uv=E(Ai(),1),cv=E(jn(),1),dv=E(Ia(),1),hv=E(Aa(),1),fv=E(Ma(),1),oh=E(Oi(),1),pv=E(ih(),1);var Da=oh.default;var ys=E(require("node:crypto"),1),dt=E(be(),1);function mv(r){let e=r&&typeof r=="object"&&"name"in r?String(r.name):null;return e?`"${e}"`:"(unnamed)"}function La(r,e,t,n){r.push(`dropped ${e} ${t} - this runner is out of date and does not understand it yet (${n}). Update the runner (npm install -g @ticketpilot/runner) to pick it up.`)}function gv(r){if(!r||typeof r!="object"||r.type!=="config")return null;let e=r,t=[],n=[];for(let a of Array.isArray(e.projects)?e.projects:[]){let u=dt.ProjectConfig.safeParse(a);u.success?n.push(u.data):La(t,"project","",u.error.issues[0]?.message??"invalid shape")}let s=[];for(let a of Array.isArray(e.rules)?e.rules:[]){let u=dt.RuleConfig.safeParse(a);u.success?s.push(u.data):La(t,"rule",mv(a),u.error.issues[0]?.message??"invalid shape")}let i=[];for(let a of Array.isArray(e.environments)?e.environments:[]){let u=dt.EnvironmentConfig.safeParse(a);u.success?i.push(u.data):La(t,"environment","",u.error.issues[0]?.message??"invalid shape")}return{msg:{type:"config",projects:n,rules:s,environments:i,pollingPaused:typeof e.pollingPaused=="boolean"?e.pollingPaused:!1},warnings:t}}var yv=2e4,vv=6e4,bv=5e3,Mi=class{constructor(e,t,n,s){this.wsUrl=e;this.runnerToken=t;this.meta=n;this.events=s}wsUrl;runnerToken;meta;events;ws=null;queue=[];pending=new Map;backoffMs=1e3;heartbeat=null;closed=!1;bootAnnounced=!1;start(){this.closed=!1,this.connect()}stop(){this.closed=!0,this.heartbeat&&clearInterval(this.heartbeat),this.ws?.close()}get connected(){return this.ws?.readyState===Da.OPEN}connect(){if(this.closed)return;g.info(`connecting to control plane at ${this.wsUrl}`);let e=new Da(this.wsUrl,{headers:{authorization:`Bearer ${this.runnerToken}`}});this.ws=e,e.on("open",()=>{this.backoffMs=1e3,this.sendNow({type:"hello",protocolVersion:dt.PROTOCOL_VERSION,runnerVersion:this.meta.runnerVersion,platform:`${process.platform}/${process.arch} node${process.versions.node}`,justBooted:!this.bootAnnounced});let t=this.queue.splice(0,this.queue.length);for(let n of t)this.sendNow(n);this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=setInterval(()=>{this.send({type:"heartbeat",ts:new Date().toISOString()})},yv)}),e.on("message",t=>{let n;try{n=JSON.parse(t.toString())}catch(i){g.warn(`ignoring malformed server message (bad JSON): ${i}`);return}let s;try{s=(0,dt.parseServerMsg)(n)}catch(i){let o=gv(n);if(!o){g.warn(`ignoring malformed server message: ${i}`);return}for(let a of o.warnings)g.warn(a);g.warn(`config push had ${o.warnings.length} ${o.warnings.length===1?"entry":"entries"} this runner doesn't understand - applied everything else instead of dropping the whole config`),s=o.msg}this.handle(s)}),e.on("close",t=>{if(this.heartbeat&&clearInterval(this.heartbeat),t===4001)g.error("control plane rejected this runner version (protocol mismatch). Update with: npm install -g @ticketpilot/runner");else if(t===4003){g.error("this runner has been revoked from the control plane UI. Re-enroll with a fresh token if this was not intended."),this.closed=!0;return}if(this.closed)return;let n=Math.random()*.3+.85,s=Math.round(this.backoffMs*n);g.warn(`disconnected (code ${t}); reconnecting in ${Math.round(s/1e3)}s`),setTimeout(()=>this.connect(),s),this.backoffMs=Math.min(this.backoffMs*2,vv)}),e.on("error",t=>{g.warn(`websocket error: ${t.message}`)})}handle(e){if(e.type==="hello.ack"){this.bootAnnounced=!0,g.info(`connected as runner "${e.runnerName}" (${e.runnerId})`);return}if(e.type==="run.claim.result"||e.type==="deploy.claim.result"||e.type==="autopilot.next.result"){let t=this.pending.get(e.requestId);t&&(clearTimeout(t.timer),this.pending.delete(e.requestId),t.resolve(e));return}if(e.type==="config")return this.events.onConfig(e);if(e.type==="project.test")return this.events.onProjectTest(e);if(e.type==="rule.diagnose")return this.events.onRuleDiagnose(e);if(e.type==="run.cancel")return this.events.onCancel(e.runId);if(e.type==="run.approved")return this.events.onApproved(e.runId,e.headSha);if(e.type==="run.rejected")return this.events.onRejected(e.runId);if(e.type==="run.retryPush")return this.events.onRetryPush(e.runId);if(e.type==="deploy.start")return this.events.onDeployStart(e);if(e.type==="deploy.suggest")return this.events.onDeploySuggest(e);if(e.type==="deploy.fix")return this.events.onDeployFix(e);if(e.type==="env.preflight")return this.events.onEnvPreflight(e);if(e.type==="chat.turn")return this.events.onChatTurn(e);if(e.type==="chat.create.ticket")return this.events.onChatCreateTicket(e);if(e.type==="chat.list")return this.events.onChatList(e);if(e.type==="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==="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>=bv){let t=this.queue.findIndex(n=>n.type==="run.log");t>=0?this.queue.splice(t,1):this.queue.shift()}this.queue.push(e)}async claimRun(e){if(!this.connected)return{accepted:!1,reason:"control plane offline"};let t=ys.default.randomUUID(),n=await new Promise(s=>{let i=setTimeout(()=>{this.pending.delete(t),s(null)},15e3);this.pending.set(t,{resolve:s,timer:i}),this.sendNow({type:"run.claim",requestId:t,...e})});return!n||n.type!=="run.claim.result"?{accepted:!1,reason:"claim timed out"}:{accepted:n.accepted,runId:n.runId,reason:n.reason,claudeProfile:n.claudeProfile,actorEmail:n.actorEmail}}async requestAutopilotNext(){if(!this.connected)return null;let e=ys.default.randomUUID(),t=await new Promise(n=>{let s=setTimeout(()=>{this.pending.delete(e),n(null)},15e3);this.pending.set(e,{resolve:n,timer:s}),this.sendNow({type:"autopilot.next",requestId:e})});return!t||t.type!=="autopilot.next.result"?null:{ok:t.ok,item:t.item,pausedUntil:t.pausedUntil}}sendAutopilotReport(e){this.send({type:"autopilot.report",requestId:ys.default.randomUUID(),itemId:e.itemId,outcome:e.outcome,runId:e.runId??"",error:e.error??""})}async claimDeploy(e){if(!this.connected)return{accepted:!1,reason:"control plane offline"};let t=ys.default.randomUUID(),n=await new Promise(s=>{let i=setTimeout(()=>{this.pending.delete(t),s(null)},15e3);this.pending.set(t,{resolve:s,timer:i}),this.sendNow({type:"deploy.claim",requestId:t,...e})});return!n||n.type!=="deploy.claim.result"?{accepted:!1,reason:"deploy authorization timed out"}:{accepted:n.accepted,runId:n.runId,environment:n.environment,reason:n.reason,code:n.code}}sendDeploySuggestResult(e,t){this.send({type:"deploy.suggest.result",requestId:e,...t,docPath:t.docPath??"",docContent:t.docContent??""})}sendChatTurnResult(e,t){this.send({type:"chat.turn.result",requestId:e,...t,inputTokens:t.inputTokens??0,outputTokens:t.outputTokens??0,cacheReadTokens:t.cacheReadTokens??0,costUsd:t.costUsd??0,model:t.model??""})}sendChatCreateTicketResult(e,t){this.send({type:"chat.create.ticket.result",requestId:e,...t,childKeys:t.childKeys??[]})}sendChatListResult(e,t){this.send({type:"chat.list.result",requestId:e,sessions:t})}sendRepoDocsResult(e,t){this.send({type:"repo.docs.result",requestId:e,...t})}sendRepoDocReadResult(e,t){this.send({type:"repo.doc.read.result",requestId:e,...t})}sendChatLoadResult(e,t){this.send({type:"chat.load.result",requestId:e,...t})}sendBoardFetchResult(e,t){this.send({type:"board.fetch.result",requestId:e,...t,browseBaseUrl:t.browseBaseUrl??""})}sendAuditStartResult(e,t){this.send({type:"audit.start.result",requestId:e,...t})}sendAuditListResult(e,t){this.send({type:"audit.list.result",requestId:e,ok:t.ok,error:t.error,audits:t.audits??[]})}sendAuditGetResult(e,t){this.send({type:"audit.get.result",requestId:e,...t})}sendAuditReviewResult(e,t){this.send({type:"audit.review.result",requestId:e,...t})}sendKnowledgeListResult(e,t){this.send({type:"knowledge.list.result",requestId:e,ok:t.ok,error:t.error,files:t.files??[]})}sendKnowledgeSaveResult(e,t){this.send({type:"knowledge.save.result",requestId:e,...t})}sendEpicListResult(e,t){this.send({type:"epic.list.result",requestId:e,ok:t.ok,error:t.error,epics:t.epics??[],children:t.children??[]})}sendEpicSuggestResult(e,t){this.send({type:"epic.suggest.result",requestId:e,ok:t.ok,error:t.error,issueKey:t.issueKey??"",reason:t.reason??"",considered:t.considered??0})}sendTeamCredsResult(e,t){this.send({type:"team.creds.result",requestId:e,ok:t.ok,error:t.error,githubShared:t.githubShared??!1,sharedGithubLogin:t.sharedGithubLogin??"",entries:t.entries??[]})}sendBoardTriggerResult(e,t){this.send({type:"board.trigger.result",requestId:e,...t})}sendAuditStatsResult(e,t){this.send({type:"audit.stats.result",requestId:e,ok:t.ok,error:t.error,byProject:t.byProject??{}})}sendRunnerUpdateResult(e,t){this.send({type:"runner.update.result",requestId:e,ok:t.ok,error:t.error,note:t.note??"",scheduled:t.scheduled??!1})}sendSetupClaudeMdGenerateResult(e,t){this.send({type:"setup.claudemd.generate.result",requestId:e,ok:t.ok,error:t.error,content:t.content??""})}sendSetupClaudeMdSaveResult(e,t){this.send({type:"setup.claudemd.save.result",requestId:e,ok:t.ok,error:t.error,note:t.note??""})}sendResolveConflictResult(e,t){this.send({type:"run.resolve.conflict.result",requestId:e,ok:t.ok,note:t.note??"",freeOfCharge:t.freeOfCharge??!1,headSha:t.headSha??"",costUsd:t.costUsd,inputTokens:t.inputTokens,outputTokens:t.outputTokens})}sendAgentProfilesResult(e,t){this.send({type:"agent.profiles.result",requestId:e,ok:t.ok,error:t.error,profiles:t.profiles??[],defaultLoggedIn:t.defaultLoggedIn??!1,agentsWithoutProfiles:t.agentsWithoutProfiles??[]})}sendRepoDocSaveResult(e,t){this.send({type:"repo.doc.save.result",requestId:e,ok:t.ok,error:t.error,note:t.note??""})}sendSetupStatusResult(e,t){this.send({type:"setup.status.result",requestId:e,ok:t.ok,error:t.error,jiraConfigured:t.jiraConfigured??!1,jiraEmail:t.jiraEmail??"",claude:t.claude,githubTokenSet:t.githubTokenSet??!1,githubLogin:t.githubLogin??"",deploysEnabled:t.deploysEnabled??!1,jiraUserCount:t.jiraUserCount??0,repos:t.repos??[]})}sendEnvPreflightResult(e,t){this.send({type:"env.preflight.result",requestId:e,...t,checks:this.withFixDefaults(t.checks)})}sendJiraUsersResult(e,t){this.send({type:"jira.users.result",requestId:e,...t})}withFixDefaults(e){return e.map(t=>({...t,kind:t.kind??"connection",fix:t.fix??[],fixNote:t.fixNote??""}))}sendProjectTestResult(e,t,n){this.send({type:"project.test.result",requestId:e,ok:t,checks:this.withFixDefaults(n)})}sendRuleDiagnoseResult(e,t){this.send({type:"rule.diagnose.result",requestId:e,...t,checks:this.withFixDefaults(t.checks)})}};var zi=E(require("node:fs"),1),Ln=E(require("node:path"),1),lh=require("node:child_process"),wv=/\.mdx?$/i,ah=6,_v=/^[\w.\- ()]+$/;function kv(r,e){let t=e.trim().replace(/\\/g,"/").replace(/^\.\//,"");if(!t)return{ok:!1,error:"empty path"};if(Ln.default.isAbsolute(t))return{ok:!1,error:"path must be repo-relative"};if(!wv.test(t))return{ok:!1,error:"only markdown files (.md) can be saved"};let n=t.split("/");if(n.length>ah)return{ok:!1,error:`path deeper than ${ah} levels`};for(let o of n)if(o==="."||o===".."||!_v.test(o))return{ok:!1,error:`invalid path segment "${o}"`};if(n[0]===".git")return{ok:!1,error:"cannot write under .git"};let s=Ln.default.resolve(r),i=Ln.default.resolve(s,t);return i!==s&&!i.startsWith(s+Ln.default.sep)?{ok:!1,error:"path escapes the checkout"}:{ok:!0,abs:i,rel:t}}async function Ua(r){let e=kv(r.repoPath,r.relPath);if(!e.ok)return{ok:!1,error:e.error};if(zi.default.existsSync(e.abs)&&!r.overwrite)return{ok:!1,error:`${e.rel} already exists in this checkout`};zi.default.mkdirSync(Ln.default.dirname(e.abs),{recursive:!0}),zi.default.writeFileSync(e.abs,r.content.endsWith(`
|
|
710
724
|
`)?r.content:r.content+`
|
|
711
|
-
`);let t=s=>new Promise((i,o)=>{(0,Xd.execFile)("git",["-C",r.repoPath,...s],{timeout:12e4},(a,l,c)=>a?o(new Error(c||a.message)):i())}),n="";try{await t(["add",e.rel]),await t(["-c","user.name=Allwright","-c","user.email=runner@allwright.local","commit","-m",r.commitMessage]);try{await t(["push"]),n="committed and pushed to the repo"}catch(s){n="committed locally, but push failed: "+(s instanceof Error?s.message.slice(0,200):"unknown")+" - push it from the server when convenient"}}catch(s){n="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:n}}var Gr=R(require("node:fs"),1),ja=R(require("node:path"),1),$i=require("node:child_process"),eh=require("node:util");Ir();Ut();var th=R(ve(),1),Qd=(0,eh.promisify)($i.execFile);function fv(r){try{return new URL(r).host}catch{return r}}function pv(r){try{return(0,$i.execFileSync)("git",["-C",r,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim()}catch{return null}}async function Pi(r,e,t=[],n){let s=[],i=r.repos[e.repoName]?.jira,o=i??r.jira,a=(e.jiraSiteUrl??"").trim().toLowerCase();if(!o)s.push({name:"jira-credentials",ok:!1,detail:"no Jira credentials configured on this runner"});else if(!a)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=fv(o.baseUrl),v=i?"this repo's own Jira credential":"the runner-wide Jira credential";if(p!==a)s.push({name:"jira-site",ok:!1,detail:`this project is on ${a}, but ${v} 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 ${a}: the base URL (https://${a}), 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 k=new Re(o);try{let T=await k.myself();s.push({name:"jira-auth",ok:!0,detail:`authenticated as ${T.displayName} on ${p} (${v})`});try{await k.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}: ${ls(x)}`})}}catch(T){s.push({name:"jira-auth",ok:!1,detail:`Jira auth failed on ${p}: ${ls(T)}`})}}}let l=r.repos[e.repoName];if(l&&Gr.default.existsSync(l.path)){let p=ja.default.join(l.path,"CLAUDE.md"),v=Gr.default.existsSync(p)&&Gr.default.readFileSync(p,"utf8").trim().length>0;s.push({name:"memory-file",kind:"content",ok:v,detail:v?"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.",...v?{}:{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 k=ci(l.path);s.push({name:"deploy-doc",kind:"content",ok:k!==null,detail:k?`${k.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.",...k?{}:{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(!l)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(!Gr.default.existsSync(l.path))s.push({name:"repo-path",ok:!1,detail:`path does not exist: ${l.path}`});else{let p=Gr.default.existsSync(ja.default.join(l.path,".git"));s.push({name:"repo-path",ok:!0,detail:`${l.path}${p?" (git checkout)":" (warning: not a git checkout)"}`})}let c=[...new Set([e.defaultAgent||"claude-code",...n??[]])];for(let p of c){let v=vt(r,p),k=p==="claude-code"?"claude-code":`agent:${p}`;try{let{stdout:T}=await Qd(v,["--version"],{timeout:15e3});s.push({name:k,ok:!0,detail:T.trim().slice(0,100)})}catch(T){s.push({name:k,ok:!1,detail:`cannot run "${v}" for agent "${p}": ${ls(T)}`,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 Qd("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: ${ls(p)}`})}let f=qe(r,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 ${th.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(()=>(it(),$r)),v=new p(f),k=await v.whoami(),T=l&&Gr.default.existsSync(l.path)?pv(l.path):null,x=T?He(T):null;if(!x)s.push({name:"github-token",ok:!0,detail:`authenticated as ${k} - repo access not checked (no local checkout yet)`});else{let j=await v.repoAccess(x.owner,x.repo);s.push({name:"github-token",ok:j.ok&&j.canPush,detail:j.ok?j.canPush?`${k} has push access to ${x.owner}/${x.repo}`:`${k} can read ${x.owner}/${x.repo} but NOT push to it - implement rules will fail at the push`:`${k} cannot see ${x.owner}/${x.repo}: ${j.error}`,...j.ok&&j.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:ls(p)})}if(t.length){r.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 t){let v=ar(r,e.repoName,p.name),k=p.requiredSecrets.filter(T=>!v[T]&&!process.env[T]);s.push({name:`env:${p.name}`,ok:k.length===0,detail:k.length?`missing secret(s): ${k.join(", ")} - allwright env set "${e.repoName}" "${p.name}" ${k[0]}=...`:`${p.steps.length} step(s), ${p.requiredSecrets.length} secret(s) present`+(p.branch?`, deploys origin/${p.branch}`:"")})}}return s}function ls(r){return(r instanceof Error?r.message:String(r)).slice(0,300)}var ge=new Qa;ge.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(Ds);function lh(r){m.info(`Create the token at ${Ni.GITHUB_TOKEN_PERMISSIONS.where}`);for(let e of Ni.GITHUB_TOKEN_PERMISSIONS.steps)m.info(` - ${e}`);m.info(Ni.GITHUB_TOKEN_PERMISSIONS.note),m.info(`Then paste it below for ${r}.`)}ge.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",uh.default.hostname()).option("--jira-url <url>","Jira base URL, e.g. https://yourorg.atlassian.net").option("--jira-email <email>","Jira account email").option("--jira-token <token>","Jira API token (stored locally only)").action(async r=>{let e=Hr.default.createInterface({input:process.stdin,output:process.stdout}),t=async(n,s,i=!1)=>{if(s)return s;let o=await e.question(`${n}: `);if(!o.trim())throw new Error(`${n} is required`);return o.trim()};try{let n=await t("Control plane URL",r.cpUrl),s=await t("Enrolment token (from the web UI)",r.enrollToken),i=await t("Jira base URL (https://yourorg.atlassian.net)",r.jiraUrl),o=await t("Jira account email",r.jiraEmail),a=await t("Jira API token (create at id.atlassian.com/manage-profile/security/api-tokens)",r.jiraToken,!0),l=to.parse({controlPlaneUrl:n,runnerName:r.name,jira:{baseUrl:i,email:o,apiToken:a}}),c=await new Re(l.jira).myself();m.info(`Jira credential OK - authenticated as ${c.displayName}`),l=await Gu(l,s),m.info(`Enrolled as runner "${l.runnerName}" (${l.runnerId})`),m.info(`Credentials saved to ${Pt()} (mode 600, this machine only)`),m.info("Next: map your repo with `allwright repo add <repoName> <localPath>`, then `allwright start`")}finally{e.close()}});var Oa=ge.command("repo").description("Map control-plane repo names to local checkouts");Oa.command("add <repoName> <localPath>").description("Map a repo name (as configured in the web UI) to a local checkout path").action(async(r,e)=>{let t=re();t.repos[r]={path:e},he(t),m.info(`mapped repo "${r}" -> ${e}`);try{let{originUrl:n}=await Promise.resolve().then(()=>(Ut(),rl));m.info(` origin remote: ${await n(e)} - make sure this is the repo you meant`)}catch{m.warn(` could not read an origin remote at ${e} - is it a git checkout?`)}});Oa.command("list").description("Show configured repo mappings").action(()=>{let r=re(),e=Object.entries(r.repos);if(!e.length)return m.info("no repos mapped yet");for(let[t,n]of e)m.info(`${t} -> ${n.path}`)});var ch=ge.command("claude").description("Per-user Claude login profiles - each teammate's runs bill their OWN Claude account");ch.command("login <profileName>").description("Create (or re-login) a named Claude profile. Opens Claude Code interactively with its own config directory - have the PERSON WHOSE ACCOUNT IT IS complete the /login flow with their credentials, then exit. Assign the profile to their user on the dashboard's Team page.").action(async r=>{if(!/^[a-zA-Z0-9._-]+$/.test(r))throw new Error("profile name: letters, digits, dots, dashes and underscores only");let e=re(),t=e.claudeProfiles[r]?.configDir??`${Pt().replace(/runner\.json$/,"")}claude-profiles/${r}`;Ct.default.mkdirSync(t,{recursive:!0,mode:448}),e.claudeProfiles[r]={configDir:t},he(e),m.info(`profile "${r}" -> ${t}`),m.info("Opening Claude Code with this profile. In it: run /login, complete the browser flow"),m.info("with the account this profile belongs to, then exit Claude (ctrl+c twice or /exit).");let n=(0,Et.spawn)(e.claudeBin,[],{env:{...process.env,CLAUDE_CONFIG_DIR:t},stdio:"inherit"});await new Promise(s=>n.on("exit",()=>s())),m.info(`Done. Assign it on the dashboard: Team -> the user -> Claude profile = "${r}".`),jn()});ch.command("list").description("Show configured Claude profiles and whether each looks logged in").action(()=>{let r=re(),e=Object.entries(r.claudeProfiles);if(m.info("default: this OS user's own Claude login (no profile)"),!e.length)return m.info("no named profiles yet - allwright claude login <name>");for(let[t,n]of e){let s=Ct.default.existsSync(n.configDir)&&Ct.default.readdirSync(n.configDir).length>0;m.info(`${t} -> ${n.configDir} ${s?"(logged in)":"(NOT logged in yet)"}`)}});Oa.command("remove <repoName>").description("Unmap a repo from this runner: removes the mapping plus its per-repo Jira/GitHub overrides and env secrets from the config. Does NOT touch the checkout on disk or anything in the control plane - delete the project on the dashboard separately.").action(r=>{let e=re();if(!e.repos[r]){let i=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${r}" - mapped repos: ${i}`)}let t=e.repos[r].path;delete e.repos[r];let n=Object.keys(e.environments).filter(i=>i.startsWith(`${r}:`));for(let i of n)delete e.environments[i];let s=e.auditSchedules.length;e.auditSchedules=e.auditSchedules.filter(i=>i.repoName!==r),he(e),m.info(`Removed "${r}" (was ${t})`),n.length&&m.info(`Also removed ${n.length} environment secret set(s): ${n.join(", ")}`),e.auditSchedules.length!==s&&m.info("Also removed its audit schedule(s)"),m.info("The checkout on disk was NOT touched - remove it yourself if you want it gone."),m.info("Restart the runner to apply. Dashboard project (if any) is deleted separately there.")});var Na=ge.command("service").description("Run the runner as a system service (starts on boot, restarts on crash)");Na.command("install").description("Install + start the systemd service - detects node, this script, your user and home; no hand-written unit files. Run with sudo. (--print shows the unit without installing.)").option("--print","print the generated unit file and exit").action(r=>{if(r.print){m.info(`
|
|
712
|
-
`+Po($o()));return}ll(m)});Na.command("uninstall").description("Stop and remove the systemd service (config/credentials untouched)").action(()=>cl(m));Na.command("status").description("systemctl status for the runner service").action(()=>{(0,Et.spawn)("systemctl",["status","allwright","--no-pager"],{stdio:"inherit"}).on("exit",e=>process.exit(e??0))});ge.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()=>{m.info("Updating: npm install -g allwright@latest");let r=(0,Et.spawn)("npm",["install","-g","allwright@latest"],{stdio:"inherit"});await new Promise((e,t)=>{r.on("exit",n=>n===0?e():t(new Error(`npm exited with code ${n}`))),r.on("error",t)}),m.info("Updated. Restart the runner service to load the new version (check active runs first).")});var hs=ge.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 r=>{let e=re();if(!e.repos[r]){let a=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${r}" - mapped repos: ${a}. Run \`allwright repo add\` first.`)}let t=Gc(r),n=(t?.jiraSiteUrl??"").trim(),s=n?`https://${n}`:"",i=e.jira?.email??"";if(s&&i&&e.jira?.apiToken){let a={baseUrl:s,email:i,apiToken:e.jira.apiToken};try{let l=await new Re(a).myself();if(e.repos[r].jira=a,he(e),m.info(`The token already on this server works on ${n} - authenticated as ${l.displayName}. Saved it for "${r}"; nothing to type.`),t?.jiraProjectKey)try{await new Re(a).search(`project = "${t.jiraProjectKey}"`,1),m.info(`Project ${t.jiraProjectKey} is readable with it.`)}catch{m.warn(`Authenticated, but project ${t.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.`)}jn();return}catch{m.info(`The token already on this server does not work on ${n} - asking for one that does.`)}}let o=Hr.default.createInterface({input:process.stdin,output:process.stdout});try{let l=(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(!l||!f||!p)throw new Error("all three values are required");let v={baseUrl:l,email:f,apiToken:p},k=await new Re(v).myself();m.info(`Jira credential OK - authenticated as ${k.displayName} on ${l}`),e.repos[r].jira=v,he(e),m.info(`Saved: repo "${r}" now polls ${l} (other repos keep the runner-wide credential)`),jn()}finally{o.close()}});hs.command("show").description("Show which Jira site each repo uses (never prints tokens)").action(()=>{let r=re();m.info(`runner-wide: ${r.jira?`${r.jira.baseUrl} (${r.jira.email})`:"(not configured)"}`);for(let[e,t]of Object.entries(r.repos))m.info(`${e} -> ${t.jira?`${t.jira.baseUrl} (${t.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 r=>{let e=re(),t=r.trim().toLowerCase();if(!t.includes("@"))throw new Error(`"${r}" doesn't look like an email`);let n=Hr.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await n.question(`Their ATLASSIAN account email [${t}]: `)).trim()||t,i=(await n.question("Their Jira API token (they create it at id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!i)throw new Error("API token is required");let o=[e.jira,...Object.values(e.repos).map(c=>c.jira)].filter(c=>!!c),a=new Set,l=!1;for(let c of o)if(!a.has(c.baseUrl)){a.add(c.baseUrl);try{let f=await new Re({baseUrl:c.baseUrl,email:s,apiToken:i}).myself();m.info(`${c.baseUrl}: OK - authenticated as ${f.displayName}`),l=!0}catch{m.warn(`${c.baseUrl}: this credential does NOT work there (fine if they don't use that site)`)}}if(!l)throw new Error("credential failed on every configured Jira site - nothing saved");e.jiraUsers[t]={email:s,apiToken:i},he(e),m.info(`Saved. Dashboard actions by ${t} now post to Jira as ${s}. No restart needed.`)}finally{n.close()}});hs.command("user-list").description("Show which Allwright users have their own Jira credential here (never prints tokens)").action(()=>{let r=re(),e=Object.entries(r.jiraUsers);if(!e.length)return m.info("none yet - everyone's dashboard clicks require one: allwright jira user-add <their-ticketpilot-email>");for(let[t,n]of e)m.info(`${t} -> posts to Jira as ${n.email}`)});hs.command("user-remove <ticketpilotEmail>").description("Delete a person's stored Jira credential").action(r=>{let e=re(),t=r.trim().toLowerCase();if(!e.jiraUsers[t])throw new Error(`no credential stored for ${t}`);delete e.jiraUsers[t],he(e),m.info(`Removed. Dashboard actions by ${t} will now be refused until a new credential is added.`)});var On=ge.command("github").description("GitHub credential for implement-mode rules");On.command("set-token").description("Store a GitHub token for opening pull requests (implement rules). Stored locally only, like your Jira token. Recommended: a fine-grained PAT scoped to the repo with contents:write + pull_requests:write.").option("--token <token>","GitHub token (omit to be prompted)").action(async r=>{let e=Hr.default.createInterface({input:process.stdin,output:process.stdout});try{let t=r.token??void lh("every repo on this server")??(await e.question("GitHub token: ")).trim();if(!t)throw new Error("token is required");let{GitHubClient:n}=await Promise.resolve().then(()=>(it(),$r)),s=await new n(t).whoami(),i=re();i.github={token:t,login:s},he(i),m.info(`GitHub token OK - authenticated as ${s}`),m.info(`Saved to ${Pt()} (mode 600, this machine only)`)}finally{e.close()}});On.command("set <repoName>").description("Store a GitHub token for ONE repo only - overrides the runner-wide token for that repo's PRs and PR-watching. Useful when projects need separately revocable access. Prompts on stdin; stored locally only.").action(async r=>{let e=re();if(!e.repos[r]){let i=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${r}" - mapped repos: ${i}. Run \`allwright repo add\` first.`)}let t=e.github?.token,n=e.repos[r]?.path;if(t&&n&&Ct.default.existsSync(n))try{let i=(0,Et.execFileSync)("git",["-C",n,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim(),o=He(i);if(o){let{GitHubClient:a}=await Promise.resolve().then(()=>(it(),$r)),l=new a(t),c=await l.repoAccess(o.owner,o.repo);if(c.ok&&c.canPush){let f=await l.whoami();m.info(`The shared token on this server already has push access to ${o.owner}/${o.repo} as ${f} - "${r}" needs nothing of its own. Storing a second token here would only give you two to rotate.`),m.info("Want a separately revocable one anyway? Paste it at the prompt below; press Enter to leave things as they are.")}}}catch{}let s=Hr.default.createInterface({input:process.stdin,output:process.stdout});try{lh(`"${r}"`);let i=(await s.question(`GitHub token for "${r}": `)).trim();if(!i&&t){m.info(`Nothing changed - "${r}" keeps using the shared token.`);return}if(!i)throw new Error("token is required");let{GitHubClient:o}=await Promise.resolve().then(()=>(it(),$r)),a=await new o(i).whoami();e.repos[r].github={token:i,login:a},he(e),m.info(`GitHub token OK - authenticated as ${a}`),m.info(`Saved: repo "${r}" now uses its own token (other repos keep the runner-wide one)`)}finally{s.close()}});On.command("user-add <ticketpilotEmail>").description("Store a PERSON's own GitHub token, so PRs from implement runs THEY trigger are authored by their GitHub account. Keyed by their Allwright login email. Optional - without it their runs fall back to the repo/runner-wide token. Needs contents:write + pull_requests:write on the repos they'll touch.").action(async r=>{let e=re(),t=r.trim().toLowerCase();if(!t.includes("@"))throw new Error(`"${r}" doesn't look like an email`);let n=Hr.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await n.question(`GitHub token for ${t}: `)).trim();if(!s)throw new Error("token is required");let{GitHubClient:i}=await Promise.resolve().then(()=>(it(),$r)),o=await new i(s).whoami();e.githubUsers[t]={token:s,login:o},he(e),m.info(`GitHub token OK - authenticated as ${o}`),m.info(`Saved. Implement runs triggered by ${t} now open PRs as ${o}. No restart needed.`)}finally{n.close()}});On.command("user-list").description("Show which Allwright users have their own GitHub token here (never prints tokens)").action(()=>{let r=re(),e=Object.entries(r.githubUsers);if(!e.length)return m.info("no per-user GitHub tokens - everyone's PRs use the repo/runner-wide token");for(let[t]of e)m.info(`${t} -> own GitHub token stored`)});On.command("user-remove <ticketpilotEmail>").description("Delete a person's stored GitHub token (their runs fall back to the shared token)").action(r=>{let e=re(),t=r.trim().toLowerCase();if(!e.githubUsers[t])throw new Error(`no GitHub token stored for ${t}`);delete e.githubUsers[t],he(e),m.info(`Removed. ${t}'s runs use the repo/runner-wide token again.`)});On.command("show").description("Show which GitHub token each repo and person would use (never prints tokens)").action(()=>{let r=re();m.info(`runner-wide: ${r.github?.token?"token set":"(not configured)"}`);for(let[t,n]of Object.entries(r.repos))m.info(`${t} -> ${n.github?.token?"own repo token":"runner-wide token"}`);let e=Object.keys(r.githubUsers);m.info(e.length?`per-user tokens: ${e.join(", ")}`:"per-user tokens: (none)")});var Ma=ge.command("audit").description("Recurring specialist audits on this runner");Ma.command("schedule <repoName> <role> <intervalHours>").description("Audit this repo's project on a cadence (role: security|testing; interval in hours, min 6). Runs on the runner's own clock; reports land in the Audits page history, where the diff-vs-previous view shows drift. Advisory only - nothing blocks.").action((r,e,t)=>{let n=re();if(!n.repos[r]){let i=Object.keys(n.repos).join(", ")||"(none)";throw new Error(`unknown repo "${r}" - mapped repos: ${i}`)}if(e!=="security"&&e!=="testing")throw new Error('role must be "security" or "testing"');let s=parseInt(t,10);if(!Number.isInteger(s)||s<6||s>720)throw new Error("intervalHours must be 6-720");n.auditSchedules=[...n.auditSchedules.filter(i=>!(i.repoName===r&&i.role===e)),{repoName:r,role:e,intervalHours:s}],he(n),m.info(`Scheduled: ${e} audit of "${r}" every ${s}h. Restart the runner to apply.`)});Ma.command("schedules").description("List scheduled audits").action(()=>{let r=re();if(!r.auditSchedules.length)return m.info("no scheduled audits - allwright audit schedule <repo> <role> <hours>");for(let e of r.auditSchedules)m.info(`${e.repoName} \xB7 ${e.role} \xB7 every ${e.intervalHours}h`)});Ma.command("unschedule <repoName> <role>").description("Remove a scheduled audit").action((r,e)=>{let t=re(),n=t.auditSchedules.length;if(t.auditSchedules=t.auditSchedules.filter(s=>!(s.repoName===r&&s.role===e)),t.auditSchedules.length===n)throw new Error("no such schedule");he(t),m.info("Removed. Restart the runner to apply.")});var za=ge.command("deploy").description("Deployment settings for this machine");za.command("enable").description("Allow this runner to execute the deploy steps saved in the dashboard. Those steps are shell commands that run here, as this user - so this switch lives on the machine, not in the web UI, and only someone with shell access can flip it.").action(()=>{let r=re();r.deploy={enabled:!0},he(r),m.info("deployments ENABLED on this runner"),m.info("This runner will now execute the deploy steps configured for your environments. Review them in the dashboard before shipping to production."),jn()});za.command("disable").description("Stop this runner from executing any deploy steps").action(()=>{let r=re();r.deploy={enabled:!1},he(r),m.info("deployments DISABLED on this runner"),jn()});za.command("status").description("Show whether deployments are enabled here, and which env secrets are stored").action(()=>{let r=re();m.info(`deployments: ${r.deploy.enabled?"enabled":"disabled"}`);let e=Object.entries(r.environments);if(!e.length)return m.info("no environment secrets stored");for(let[t,n]of e){let s=Object.keys(n.secrets);m.info(`${t}: ${s.length?s.join(", "):"(no secrets)"}`)}});var Da=ge.command("env").description("Per-environment deploy secrets. Values stay on this machine, like your Jira token.");Da.command("set <repoName> <envName> <assignments...>").description('Store secrets for one environment, e.g. env set acme/api production "SSH_HOST=1.2.3.4" "SSH_USER=deploy". Your deploy steps reference these as $SSH_HOST. The control plane only ever learns the NAMES.').action((r,e,t)=>{let n=re(),s=Ts(r,e),i=n.environments[s]??{secrets:{}},o=[];for(let a of t){let l=a.indexOf("=");if(l<=0)throw new Error(`expected KEY=VALUE, got "${a}"`);let c=a.slice(0,l).trim();i.secrets[c]=a.slice(l+1),o.push(c)}n.environments[s]=i,he(n),m.info(`stored ${o.length} secret(s) for ${s}: ${o.join(", ")}`),m.info(`Saved to ${Pt()} (mode 600, this machine only)`),jn()});Da.command("unset <repoName> <envName> <names...>").description("Remove stored secrets for an environment").action((r,e,t)=>{let n=re(),s=Ts(r,e),i=n.environments[s];if(!i)return m.info(`nothing stored for ${s}`);for(let o of t)delete i.secrets[o];n.environments[s]=i,he(n),m.info(`removed ${t.join(", ")} from ${s}`)});Da.command("list").description("Show which environments have secrets stored here (names only, never values)").action(()=>{let r=re(),e=Object.entries(r.environments);if(!e.length)return m.info("no environment secrets stored");for(let[t,n]of e)m.info(`${t}: ${Object.keys(n.secrets).join(", ")||"(none)"}`)});ge.command("export [file]").description("Back up ALL runner state (config+secrets, knowledge, audits, chats) to one tarball").action(r=>{try{let e=hu(r);m.info(`Backup written: ${e.file} (${e.entries.length} entries, mode 600)`),m.warn("This file CONTAINS YOUR SECRETS (Jira/GitHub tokens). Keep it private - anyone holding it can act as this runner."),m.info(`Restore on any machine with: allwright import ${ds.default.basename(e.file)}`)}catch(e){m.error(e instanceof Error?e.message:String(e)),process.exitCode=1}});ge.command("import <file>").description("Restore runner state from an `export` tarball (existing config is kept as a .bak dir)").action(r=>{let e=ur();if(e&&lr(e)){m.error("the runner is running - stop it first (systemctl stop allwright, or `allwright stop` for a pid-file daemon), then import."),process.exitCode=1;return}try{let t=fu(r);m.info(`Restored ${t.restored.length} entries into ${te()}`),t.previousDir&&m.info(`Previous config kept at ${t.previousDir}`),m.info("Start the runner and it will reconnect with the restored identity.")}catch(t){m.error(t instanceof Error?t.message:String(t)),process.exitCode=1}});ge.command("test").description("Check local setup: Jira auth, repo mappings, Claude Code binary").action(async()=>{let r=re(),e=Object.keys(r.repos);if(!r.jira){m.error("no Jira credentials configured - run `allwright init`"),process.exitCode=1;return}let t=e.length?e.map(s=>({jiraProjectKey:"*",repoName:s})):[{jiraProjectKey:"*",repoName:"(none mapped)"}],n=!0;for(let s of t){let i=await Pi(r,s);for(let o of i){if(s.jiraProjectKey==="*"&&o.name==="jira-project")continue;let a=o.ok?"PASS":"FAIL";(o.ok?m.info:m.error)(`[${a}] ${o.name}: ${o.detail}`),n&&=o.ok}}n||(process.exitCode=1)});function jn(){let r=ur();if(r&&lr(r)&&process.platform!=="win32")try{process.kill(r,"SIGHUP"),m.info("running runner reloaded its config live - no restart needed");return}catch{}m.info("No background runner found to reload. Under systemd: sudo systemctl kill -s HUP allwright - otherwise it applies on the next allwright start.")}function yv(r){if(!r.runnerToken)throw new Error("runner not enrolled - run `allwright init`");if(!r.jira)throw new Error("no Jira credentials - run `allwright init`");let e=wu();e.ok||(m.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",so);let t=new Re(r.jira),n=new Map,s=h=>{let g=r.repos[h]?.jira;if(!g)return t;let w=n.get(h);return w||(w=new Re(g),n.set(h,w)),w},i=new Map,o=(h,g)=>{let w=il(pe()??r,h,g);switch(w.kind){case"legacy":return{jira:s(h),authored:!1};case"self":return{jira:s(h),authored:!0};case"missing":return{error:w.error};case"user":{let C=`${w.creds.baseUrl}:${w.creds.email}:${w.creds.apiToken.slice(-6)}`,D=i.get(C);return D||(D=new Re(w.creds),i.set(C,D)),{jira:D,authored:!0}}}},a=new URL("/api/runner/ws",r.controlPlaneUrl);a.protocol=a.protocol==="https:"?"wss:":"ws:";let l=[],c=[],f=[],p,v=null,k={cfg:r,jiraFor:s,transport:null},T=new Set,x=h=>{let g=l.find(C=>C.id===h),w=g&&r.repos[g.repoName];return g&&w?{project:g,repoPath:w.path}:null},j={cfg:r,jiraFor:s,get transport(){return k.transport},lookup:(h,g)=>{let w=x(h),C=f.find(D=>D.projectId===h&&D.name===g);return w&&C?{...w,environment:C}:null}},S=new Ri(a.toString(),r.runnerToken,{runnerVersion:Ds},{onConfig:h=>{l=h.projects,Zc(h.projects),c=h.rules,f=h.environments,p.setConfig(h.projects,h.rules,h.pollingPaused,h.environments)},onDeployFix:async h=>{let g=x(h.projectId);if(!g){S.sendDeploySuggestResult(h.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:"this runner has no local checkout mapped for that project"});return}let w=We(r,g.project,"assist");if("error"in w){S.sendDeploySuggestResult(h.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:w.error});return}m.info(`investigating failed deploy of "${h.environmentName}" (step: ${h.failedStep||"?"})`);let C=await Ac({agent:w,repoPath:g.repoPath,repoName:g.project.repoName,environmentName:h.environmentName,steps:h.steps,failedStep:h.failedStep,errorText:h.errorText,cfg:r});S.sendDeploySuggestResult(h.requestId,C)},onProjectTest:async h=>{let g=l.find(C=>C.id===h.projectId);if(!g){S.sendProjectTestResult(h.requestId,!1,[{name:"config",ok:!1,detail:"project not in this runner's synced config yet"}]);return}m.info(`running connection test for project "${g.name}"`);let w=await Pi(pe()??r,g,f.filter(C=>C.projectId===g.id),c.filter(C=>C.projectId===g.id).map(C=>"agent"in C.action?C.action.agent:"").filter(Boolean));S.sendProjectTestResult(h.requestId,w.every(C=>C.ok),w)},onRuleDiagnose:async h=>{let g=c.find(W=>W.id===h.ruleId),w=g&&l.find(W=>W.id===g.projectId);if(!g||!w){S.sendRuleDiagnoseResult(h.requestId,{checks:[{name:"config",ok:!1,detail:"rule not in this runner's synced config yet"}],matchedCount:0,excludedCount:0,excludedSample:[]});return}m.info(`diagnosing rule "${g.name}"`);let C=await Pi(pe()??r,w,g.action.type==="deploy"?f.filter(W=>W.projectId===w.id):[]),D=g.action.type==="implement"?C:C.filter(W=>W.name!=="github-token"),{matchedCount:Y,excludedCount:B,excludedSample:se}=await p.diagnoseRule(g,w);S.sendRuleDiagnoseResult(h.requestId,{checks:D,matchedCount:Y,excludedCount:B,excludedSample:se})},onCancel:h=>{rc(h)?m.info(`run ${h} stopped from the dashboard`):m.warn(`cancel requested for run ${h}, but nothing is running under that id here - it likely finished already`)},onApproved:(h,g)=>{if(ia(h)){Tc(j,h).catch(w=>m.error(`deploy approval crashed for ${h}: ${w instanceof Error?w.stack:w}`));return}Qn(k,h,g).catch(w=>m.error(`approval handling crashed for ${h}: ${w instanceof Error?w.stack:w}`))},onRetryPush:h=>{let g=ei(h),w=()=>hc(k,h).catch(C=>m.error(`retry push crashed for ${h}: ${C instanceof Error?C.stack:C}`));g?p.runOnRepoQueue(g.baseRepoPath,w):w()},onRejected:h=>{if(ia(h)){xc(j,h).catch(g=>m.error(`deploy rejection crashed for ${h}: ${g instanceof Error?g.stack:g}`));return}dc(k,h).catch(g=>m.error(`rejection handling crashed for ${h}: ${g instanceof Error?g.stack:g}`))},onDeployStart:h=>{let g=`${h.runId}#${h.attempt}`;if(T.has(g))return;T.add(g);let w=x(h.projectId);if(!w){let C="this runner has no local checkout mapped for that project - run: allwright repo add <repoName> /path/to/checkout";m.error(`deploy ${h.runId}: ${C}`),S.send({type:"run.status",runId:h.runId,status:"failed",error:C});return}m.info(`deploy ${h.runId} requested from the dashboard: ${h.issueKey} \u2192 ${h.environment.name}`),p.runOnEnvironmentQueue(h.environment.id,()=>li({runId:h.runId,project:w.project,environment:h.environment,issueKey:h.issueKey,issueSummary:h.issueSummary,repoPath:w.repoPath,cfg:r,jira:s(w.project.repoName),transport:S,requestedBy:h.requestedBy}).catch(C=>m.error(`deploy crashed for ${h.runId}: ${C instanceof Error?C.stack:C}`)))},onDeploySuggest:async h=>{let g=x(h.projectId);if(!g){S.sendDeploySuggestResult(h.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:"this runner has no local checkout mapped for that project"});return}let w=We(r,g.project,"assist");if("error"in w){S.sendDeploySuggestResult(h.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:w.error});return}m.info(`asking ${w.adapter.displayName} for "${h.environmentName}" deploy steps in ${g.repoPath}`);let C=await $c({agent:w,repoPath:g.repoPath,repoName:g.project.repoName,environmentName:h.environmentName,notes:h.notes,timeoutSeconds:h.timeoutSeconds,cfg:r});S.sendDeploySuggestResult(h.requestId,C)},onEnvPreflight:async h=>{let g=x(h.projectId);if(!g){S.sendEnvPreflightResult(h.requestId,{ok:!1,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project"}]});return}let w=await Rc({repoPath:g.repoPath,repoName:g.project.repoName,environmentName:h.environmentName,steps:h.steps,requiredSecrets:h.requiredSecrets,workdir:h.workdir,branch:h.branch,publicUrl:h.publicUrl,cfg:r});S.sendEnvPreflightResult(h.requestId,w)},onChatTurn:async h=>{let g=x(h.projectId);if(!g){S.sendChatTurnResult(h.requestId,{ok:!1,sessionId:h.sessionId??"",reply:"",error:"this runner has no local checkout mapped for that project"});return}let w=h.sessionId||(0,Oi.randomUUID)(),C=!h.sessionId;if((C?0:aa(w)?.messages.length??0)>=44){S.sendChatTurnResult(h.requestId,{ok:!1,sessionId:w,reply:"",error:"this chat has hit its length limit - every turn re-reads the whole conversation, so long chats get slow and expensive. Start a new chat (it keeps the repo knowledge; only the conversation resets)."});return}let Y=h.files.length?gu(g.repoPath,h.requestId,h.files):null,B="```",se=C?`You are the project assistant for "${g.project.name}" - this working directory is its repository, and you have read-only access.
|
|
725
|
+
`);let t=s=>new Promise((i,o)=>{(0,lh.execFile)("git",["-C",r.repoPath,...s],{timeout:12e4},(a,u,c)=>a?o(new Error(c||a.message)):i())}),n="";try{await t(["add",e.rel]),await t(["-c","user.name=Allwright","-c","user.email=runner@allwright.local","commit","-m",r.commitMessage]);try{await t(["push"]),n="committed and pushed to the repo"}catch(s){n="committed locally, but push failed: "+(s instanceof Error?s.message.slice(0,200):"unknown")+" - push it from the server when convenient"}}catch(s){n="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:n}}var Xr=E(require("node:fs"),1),qa=E(require("node:path"),1),Di=require("node:child_process"),ch=require("node:util");Or();_t();var dh=E(be(),1),uh=(0,ch.promisify)(Di.execFile);function Sv(r){try{return new URL(r).host}catch{return r}}function Tv(r){try{return(0,Di.execFileSync)("git",["-C",r,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim()}catch{return null}}async function Li(r,e,t=[],n){let s=[],i=r.repos[e.repoName]?.jira,o=i??r.jira,a=(e.jiraSiteUrl??"").trim().toLowerCase();if(!o)s.push({name:"jira-credentials",ok:!1,detail:"no Jira credentials configured on this runner"});else if(!a)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=Sv(o.baseUrl),v=i?"this repo's own Jira credential":"the runner-wide Jira credential";if(p!==a)s.push({name:"jira-site",ok:!1,detail:`this project is on ${a}, but ${v} 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 ${a}: the base URL (https://${a}), 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 S=new Ee(o);try{let T=await S.myself();s.push({name:"jira-auth",ok:!0,detail:`authenticated as ${T.displayName} on ${p} (${v})`});try{await S.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}: ${vs(x)}`})}}catch(T){s.push({name:"jira-auth",ok:!1,detail:`Jira auth failed on ${p}: ${vs(T)}`})}}}let u=r.repos[e.repoName];if(u&&Xr.default.existsSync(u.path)){let p=qa.default.join(u.path,"CLAUDE.md"),v=Xr.default.existsSync(p)&&Xr.default.readFileSync(p,"utf8").trim().length>0;s.push({name:"memory-file",kind:"content",ok:v,detail:v?"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.",...v?{}:{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 S=yi(u.path);s.push({name:"deploy-doc",kind:"content",ok:S!==null,detail:S?`${S.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.",...S?{}:{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(!Xr.default.existsSync(u.path))s.push({name:"repo-path",ok:!1,detail:`path does not exist: ${u.path}`});else{let p=Xr.default.existsSync(qa.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",...n??[]])];for(let p of c){let v=We(r,p),S=p==="claude-code"?"claude-code":`agent:${p}`;try{let{stdout:T}=await uh(v,["--version"],{timeout:15e3});s.push({name:S,ok:!0,detail:T.trim().slice(0,100)})}catch(T){s.push({name:S,ok:!1,detail:`cannot run "${v}" for agent "${p}": ${vs(T)}`,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 uh("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: ${vs(p)}`})}let f=Ae(r,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 ${dh.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(()=>(Ye(),zr)),v=new p(f),S=await v.whoami(),T=u&&Xr.default.existsSync(u.path)?Tv(u.path):null,x=T?Ve(T):null;if(!x)s.push({name:"github-token",ok:!0,detail:`authenticated as ${S} - repo access not checked (no local checkout yet)`});else{let P=await v.repoAccess(x.owner,x.repo);s.push({name:"github-token",ok:P.ok&&P.canPush,detail:P.ok?P.canPush?`${S} has push access to ${x.owner}/${x.repo}`:`${S} can read ${x.owner}/${x.repo} but NOT push to it - implement rules will fail at the push`:`${S} cannot see ${x.owner}/${x.repo}: ${P.error}`,...P.ok&&P.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:vs(p)})}if(t.length){r.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 t){let v=cr(r,e.repoName,p.name),S=p.requiredSecrets.filter(T=>!v[T]&&!process.env[T]);s.push({name:`env:${p.name}`,ok:S.length===0,detail:S.length?`missing secret(s): ${S.join(", ")} - allwright env set "${e.repoName}" "${p.name}" ${S[0]}=...`:`${p.steps.length} step(s), ${p.requiredSecrets.length} secret(s) present`+(p.branch?`, deploys origin/${p.branch}`:"")})}}return s}function vs(r){return(r instanceof Error?r.message:String(r)).slice(0,300)}var ye=new ll;ye.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(Gs);function vh(r){g.info(`Create the token at ${Ht.GITHUB_TOKEN_PERMISSIONS.where}`);for(let e of Ht.GITHUB_TOKEN_PERMISSIONS.steps)g.info(` - ${e}`);g.info(Ht.GITHUB_TOKEN_PERMISSIONS.note),g.info(`Then paste it below for ${r}.`)}ye.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",Fa.default.hostname()).option("--jira-url <url>","Jira base URL, e.g. https://yourorg.atlassian.net").option("--jira-email <email>","Jira account email").option("--jira-token <token>","Jira API token (stored locally only)").action(async r=>{let e=en.default.createInterface({input:process.stdin,output:process.stdout}),t=async(n,s,i=!1)=>{if(s)return s;let o=await e.question(`${n}: `);if(!o.trim())throw new Error(`${n} is required`);return o.trim()};try{let n=await t("Control plane URL",r.cpUrl),s=await t("Enrolment token (from the web UI)",r.enrollToken),i=await t("Jira base URL (https://yourorg.atlassian.net)",r.jiraUrl),o=await t("Jira account email",r.jiraEmail),a=await t("Jira API token (create at id.atlassian.com/manage-profile/security/api-tokens)",r.jiraToken,!0),u=ao.parse({controlPlaneUrl:n,runnerName:r.name,jira:{baseUrl:i,email:o,apiToken:a}}),c=await new Ee(u.jira).myself();g.info(`Jira credential OK - authenticated as ${c.displayName}`),u=await tu(u,s),g.info(`Enrolled as runner "${u.runnerName}" (${u.runnerId})`),g.info(`Credentials saved to ${Ot()} (mode 600, this machine only)`),g.info("Next: map your repo with `allwright repo add <repoName> <localPath>`, then `allwright start`")}finally{e.close()}});var Ba=ye.command("repo").description("Map control-plane repo names to local checkouts");Ba.command("add <repoName> <localPath>").description("Map a repo name (as configured in the web UI) to a local checkout path").action(async(r,e)=>{let t=ne();t.repos[r]={path:e},he(t),g.info(`mapped repo "${r}" -> ${e}`);try{let{originUrl:n}=await Promise.resolve().then(()=>(_t(),uu));g.info(` origin remote: ${await n(e)} - make sure this is the repo you meant`)}catch{g.warn(` could not read an origin remote at ${e} - is it a git checkout?`)}});Ba.command("list").description("Show configured repo mappings").action(()=>{let r=ne(),e=Object.entries(r.repos);if(!e.length)return g.info("no repos mapped yet");for(let[t,n]of e)g.info(`${t} -> ${n.path}`)});var bh=ye.command("claude").description("Per-user Claude login profiles - each teammate's runs bill their OWN Claude account");bh.command("login <profileName>").description("Create (or re-login) a named Claude profile. Opens Claude Code interactively with its own config directory - have the PERSON WHOSE ACCOUNT IT IS complete the /login flow with their credentials, then exit. Assign the profile to their user on the dashboard's Team page.").action(async r=>{if(!/^[a-zA-Z0-9._-]+$/.test(r))throw new Error("profile name: letters, digits, dots, dashes and underscores only");let e=ne(),t=e.claudeProfiles[r]?.configDir??`${Ot().replace(/runner\.json$/,"")}claude-profiles/${r}`;et.default.mkdirSync(t,{recursive:!0,mode:448}),e.claudeProfiles[r]={configDir:t},he(e),g.info(`profile "${r}" -> ${t}`),g.info("Opening Claude Code with this profile. In it: run /login, complete the browser flow"),g.info("with the account this profile belongs to, then exit Claude (ctrl+c twice or /exit).");let n=(0,Et.spawn)(e.claudeBin,[],{env:{...process.env,CLAUDE_CONFIG_DIR:t},stdio:"inherit"});await new Promise(s=>n.on("exit",()=>s())),g.info(`Done. Assign it on the dashboard: Team -> the user -> Claude profile = "${r}".`),qn()});bh.command("list").description("Show configured Claude profiles and whether each looks logged in").action(()=>{let r=ne(),e=Object.entries(r.claudeProfiles);if(g.info("default: this OS user's own Claude login (no profile)"),!e.length)return g.info("no named profiles yet - allwright claude login <name>");for(let[t,n]of e){let s=et.default.existsSync(n.configDir)&&et.default.readdirSync(n.configDir).length>0;g.info(`${t} -> ${n.configDir} ${s?"(logged in)":"(NOT logged in yet)"}`)}});Ba.command("remove <repoName>").description("Unmap a repo from this runner: removes the mapping plus its per-repo Jira/GitHub overrides and env secrets from the config. Does NOT touch the checkout on disk or anything in the control plane - delete the project on the dashboard separately.").action(r=>{let e=ne();if(!e.repos[r]){let i=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${r}" - mapped repos: ${i}`)}let t=e.repos[r].path;delete e.repos[r];let n=Object.keys(e.environments).filter(i=>i.startsWith(`${r}:`));for(let i of n)delete e.environments[i];let s=e.auditSchedules.length;e.auditSchedules=e.auditSchedules.filter(i=>i.repoName!==r),he(e),g.info(`Removed "${r}" (was ${t})`),n.length&&g.info(`Also removed ${n.length} environment secret set(s): ${n.join(", ")}`),e.auditSchedules.length!==s&&g.info("Also removed its audit schedule(s)"),g.info("The checkout on disk was NOT touched - remove it yourself if you want it gone."),g.info("Restart the runner to apply. Dashboard project (if any) is deleted separately there.")});var Ka=ye.command("service").description("Run the runner as a system service (starts on boot, restarts on crash)");Ka.command("install").description("Install + start the systemd service - detects node, this script, your user and home; no hand-written unit files. Run with sudo. (--print shows the unit without installing.)").option("--print","print the generated unit file and exit").action(r=>{if(r.print){g.info(`
|
|
726
|
+
`+Uo(Lo()));return}gu(g)});Ka.command("uninstall").description("Stop and remove the systemd service (config/credentials untouched)").action(()=>yu(g));Ka.command("status").description("systemctl status for the runner service").action(()=>{(0,Et.spawn)("systemctl",["status","allwright","--no-pager"],{stdio:"inherit"}).on("exit",e=>process.exit(e??0))});ye.command("update").description("Update the runner to the latest published version (npm install -g allwright@latest). Restart the runner afterwards - and only when no runs are active.").action(async()=>{g.info("Updating: npm install -g allwright@latest");let r=(0,Et.spawn)("npm",["install","-g","allwright@latest"],{stdio:"inherit"});await new Promise((e,t)=>{r.on("exit",n=>n===0?e():t(new Error(`npm exited with code ${n}`))),r.on("error",t)}),g.info("Updated. Restart the runner service to load the new version (check active runs first).")});var ws=ye.command("jira").description("Per-repo Jira site overrides - for projects living on a different Atlassian site");ws.command("set <repoName>").description("Store Jira credentials for ONE repo's project (e.g. a project on a different *.atlassian.net site than the runner's main credential). Prompts on stdin; stored locally only, like every other credential.").action(async r=>{let e=ne();if(!e.repos[r]){let a=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${r}" - mapped repos: ${a}. Run \`allwright repo add\` first.`)}let t=rd(r),n=(t?.jiraSiteUrl??"").trim(),s=n?`https://${n}`:"",i=e.jira?.email??"";if(s&&i&&e.jira?.apiToken){let a={baseUrl:s,email:i,apiToken:e.jira.apiToken};try{let u=await new Ee(a).myself();if(e.repos[r].jira=a,he(e),g.info(`The token already on this server works on ${n} - authenticated as ${u.displayName}. Saved it for "${r}"; nothing to type.`),t?.jiraProjectKey)try{await new Ee(a).search(`project = "${t.jiraProjectKey}"`,1),g.info(`Project ${t.jiraProjectKey} is readable with it.`)}catch{g.warn(`Authenticated, but project ${t.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.`)}qn();return}catch{g.info(`The token already on this server does not work on ${n} - asking for one that does.`)}}let o=en.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 v={baseUrl:u,email:f,apiToken:p},S=await new Ee(v).myself();g.info(`Jira credential OK - authenticated as ${S.displayName} on ${u}`),e.repos[r].jira=v,he(e),g.info(`Saved: repo "${r}" now polls ${u} (other repos keep the runner-wide credential)`),qn()}finally{o.close()}});ws.command("show").description("Show which Jira site each repo uses (never prints tokens)").action(()=>{let r=ne();g.info(`runner-wide: ${r.jira?`${r.jira.baseUrl} (${r.jira.email})`:"(not configured)"}`);for(let[e,t]of Object.entries(r.repos))g.info(`${e} -> ${t.jira?`${t.jira.baseUrl} (${t.jira.email})`:"(runner-wide credential)"}`)});ws.command("user-add <ticketpilotEmail>").description("Store a PERSON's own Jira credential, so board buttons and Compose tickets they click post to Jira under THEIR Atlassian identity instead of the runner's account. Keyed by their Allwright login email. Prompts on stdin; stored locally only. Picked up on the next click - no restart needed.").action(async r=>{let e=ne(),t=r.trim().toLowerCase();if(!t.includes("@"))throw new Error(`"${r}" doesn't look like an email`);let n=en.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await n.question(`Their ATLASSIAN account email [${t}]: `)).trim()||t,i=(await n.question("Their Jira API token (they create it at id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!i)throw new Error("API token is required");let o=[e.jira,...Object.values(e.repos).map(c=>c.jira)].filter(c=>!!c),a=new Set,u=!1;for(let c of o)if(!a.has(c.baseUrl)){a.add(c.baseUrl);try{let f=await new Ee({baseUrl:c.baseUrl,email:s,apiToken:i}).myself();g.info(`${c.baseUrl}: OK - authenticated as ${f.displayName}`),u=!0}catch{g.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[t]={email:s,apiToken:i},he(e),g.info(`Saved. Dashboard actions by ${t} now post to Jira as ${s}. No restart needed.`)}finally{n.close()}});ws.command("user-list").description("Show which Allwright users have their own Jira credential here (never prints tokens)").action(()=>{let r=ne(),e=Object.entries(r.jiraUsers);if(!e.length)return g.info("none yet - everyone's dashboard clicks require one: allwright jira user-add <their-ticketpilot-email>");for(let[t,n]of e)g.info(`${t} -> posts to Jira as ${n.email}`)});ws.command("user-remove <ticketpilotEmail>").description("Delete a person's stored Jira credential").action(r=>{let e=ne(),t=r.trim().toLowerCase();if(!e.jiraUsers[t])throw new Error(`no credential stored for ${t}`);delete e.jiraUsers[t],he(e),g.info(`Removed. Dashboard actions by ${t} will now be refused until a new credential is added.`)});var Fn=ye.command("github").description("GitHub credential for implement-mode rules");Fn.command("set-token").description("Store a GitHub token for opening pull requests (implement rules). Stored locally only, like your Jira token. Recommended: a fine-grained PAT scoped to the repo with contents:write + pull_requests:write.").option("--token <token>","GitHub token (omit to be prompted)").action(async r=>{let e=en.default.createInterface({input:process.stdin,output:process.stdout});try{let t=r.token??void vh("every repo on this server")??(await e.question("GitHub token: ")).trim();if(!t)throw new Error("token is required");let{GitHubClient:n}=await Promise.resolve().then(()=>(Ye(),zr)),s=await new n(t).whoami(),i=ne();i.github={token:t,login:s},he(i),g.info(`GitHub token OK - authenticated as ${s}`),g.info(`Saved to ${Ot()} (mode 600, this machine only)`)}finally{e.close()}});Fn.command("set <repoName>").description("Store a GitHub token for ONE repo only - overrides the runner-wide token for that repo's PRs and PR-watching. Useful when projects need separately revocable access. Prompts on stdin; stored locally only.").action(async r=>{let e=ne();if(!e.repos[r]){let i=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${r}" - mapped repos: ${i}. Run \`allwright repo add\` first.`)}let t=e.github?.token,n=e.repos[r]?.path;if(t&&n&&et.default.existsSync(n))try{let i=(0,Et.execFileSync)("git",["-C",n,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim(),o=Ve(i);if(o){let{GitHubClient:a}=await Promise.resolve().then(()=>(Ye(),zr)),u=new a(t),c=await u.repoAccess(o.owner,o.repo);if(c.ok&&c.canPush){let f=await u.whoami();g.info(`The shared token on this server already has push access to ${o.owner}/${o.repo} as ${f} - "${r}" needs nothing of its own. Storing a second token here would only give you two to rotate.`),g.info("Want a separately revocable one anyway? Paste it at the prompt below; press Enter to leave things as they are.")}}}catch{}let s=en.default.createInterface({input:process.stdin,output:process.stdout});try{vh(`"${r}"`);let i=(await s.question(`GitHub token for "${r}": `)).trim();if(!i&&t){g.info(`Nothing changed - "${r}" keeps using the shared token.`);return}if(!i)throw new Error("token is required");let{GitHubClient:o}=await Promise.resolve().then(()=>(Ye(),zr)),a=await new o(i).whoami();e.repos[r].github={token:i,login:a},he(e),g.info(`GitHub token OK - authenticated as ${a}`),g.info(`Saved: repo "${r}" now uses its own token (other repos keep the runner-wide one)`)}finally{s.close()}});Fn.command("user-add <ticketpilotEmail>").description("Store a PERSON's own GitHub token, so PRs from implement runs THEY trigger are authored by their GitHub account. Keyed by their Allwright login email. Optional - without it their runs fall back to the repo/runner-wide token. Needs contents:write + pull_requests:write on the repos they'll touch.").action(async r=>{let e=ne(),t=r.trim().toLowerCase();if(!t.includes("@"))throw new Error(`"${r}" doesn't look like an email`);let n=en.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await n.question(`GitHub token for ${t}: `)).trim();if(!s)throw new Error("token is required");let{GitHubClient:i}=await Promise.resolve().then(()=>(Ye(),zr)),o=await new i(s).whoami();e.githubUsers[t]={token:s,login:o},he(e),g.info(`GitHub token OK - authenticated as ${o}`),g.info(`Saved. Implement runs triggered by ${t} now open PRs as ${o}. No restart needed.`)}finally{n.close()}});Fn.command("user-list").description("Show which Allwright users have their own GitHub token here (never prints tokens)").action(()=>{let r=ne(),e=Object.entries(r.githubUsers);if(!e.length)return g.info("no per-user GitHub tokens - everyone's PRs use the repo/runner-wide token");for(let[t]of e)g.info(`${t} -> own GitHub token stored`)});Fn.command("user-remove <ticketpilotEmail>").description("Delete a person's stored GitHub token (their runs fall back to the shared token)").action(r=>{let e=ne(),t=r.trim().toLowerCase();if(!e.githubUsers[t])throw new Error(`no GitHub token stored for ${t}`);delete e.githubUsers[t],he(e),g.info(`Removed. ${t}'s runs use the repo/runner-wide token again.`)});Fn.command("show").description("Show which GitHub token each repo and person would use (never prints tokens)").action(()=>{let r=ne();g.info(`runner-wide: ${r.github?.token?"token set":"(not configured)"}`);for(let[t,n]of Object.entries(r.repos))g.info(`${t} -> ${n.github?.token?"own repo token":"runner-wide token"}`);let e=Object.keys(r.githubUsers);g.info(e.length?`per-user tokens: ${e.join(", ")}`:"per-user tokens: (none)")});var Za=ye.command("audit").description("Recurring specialist audits on this runner");Za.command("schedule <repoName> <role> <intervalHours>").description("Audit this repo's project on a cadence (role: security|testing; interval in hours, min 6). Runs on the runner's own clock; reports land in the Audits page history, where the diff-vs-previous view shows drift. Advisory only - nothing blocks.").action((r,e,t)=>{let n=ne();if(!n.repos[r]){let i=Object.keys(n.repos).join(", ")||"(none)";throw new Error(`unknown repo "${r}" - mapped repos: ${i}`)}if(e!=="security"&&e!=="testing")throw new Error('role must be "security" or "testing"');let s=parseInt(t,10);if(!Number.isInteger(s)||s<6||s>720)throw new Error("intervalHours must be 6-720");n.auditSchedules=[...n.auditSchedules.filter(i=>!(i.repoName===r&&i.role===e)),{repoName:r,role:e,intervalHours:s}],he(n),g.info(`Scheduled: ${e} audit of "${r}" every ${s}h. Restart the runner to apply.`)});Za.command("schedules").description("List scheduled audits").action(()=>{let r=ne();if(!r.auditSchedules.length)return g.info("no scheduled audits - allwright audit schedule <repo> <role> <hours>");for(let e of r.auditSchedules)g.info(`${e.repoName} \xB7 ${e.role} \xB7 every ${e.intervalHours}h`)});Za.command("unschedule <repoName> <role>").description("Remove a scheduled audit").action((r,e)=>{let t=ne(),n=t.auditSchedules.length;if(t.auditSchedules=t.auditSchedules.filter(s=>!(s.repoName===r&&s.role===e)),t.auditSchedules.length===n)throw new Error("no such schedule");he(t),g.info("Removed. Restart the runner to apply.")});var Ga=ye.command("deploy").description("Deployment settings for this machine");Ga.command("enable").description("Allow this runner to execute the deploy steps saved in the dashboard. Those steps are shell commands that run here, as this user - so this switch lives on the machine, not in the web UI, and only someone with shell access can flip it.").action(()=>{let r=ne();r.deploy={enabled:!0},he(r),g.info("deployments ENABLED on this runner"),g.info("This runner will now execute the deploy steps configured for your environments. Review them in the dashboard before shipping to production."),qn()});Ga.command("disable").description("Stop this runner from executing any deploy steps").action(()=>{let r=ne();r.deploy={enabled:!1},he(r),g.info("deployments DISABLED on this runner"),qn()});Ga.command("status").description("Show whether deployments are enabled here, and which env secrets are stored").action(()=>{let r=ne();g.info(`deployments: ${r.deploy.enabled?"enabled":"disabled"}`);let e=Object.entries(r.environments);if(!e.length)return g.info("no environment secrets stored");for(let[t,n]of e){let s=Object.keys(n.secrets);g.info(`${t}: ${s.length?s.join(", "):"(no secrets)"}`)}});var Ha=ye.command("env").description("Per-environment deploy secrets. Values stay on this machine, like your Jira token.");Ha.command("set <repoName> <envName> <assignments...>").description('Store secrets for one environment, e.g. env set acme/api production "SSH_HOST=1.2.3.4" "SSH_USER=deploy". Your deploy steps reference these as $SSH_HOST. The control plane only ever learns the NAMES.').action((r,e,t)=>{let n=ne(),s=Ps(r,e),i=n.environments[s]??{secrets:{}},o=[];for(let a of t){let u=a.indexOf("=");if(u<=0)throw new Error(`expected KEY=VALUE, got "${a}"`);let c=a.slice(0,u).trim();i.secrets[c]=a.slice(u+1),o.push(c)}n.environments[s]=i,he(n),g.info(`stored ${o.length} secret(s) for ${s}: ${o.join(", ")}`),g.info(`Saved to ${Ot()} (mode 600, this machine only)`),qn()});Ha.command("unset <repoName> <envName> <names...>").description("Remove stored secrets for an environment").action((r,e,t)=>{let n=ne(),s=Ps(r,e),i=n.environments[s];if(!i)return g.info(`nothing stored for ${s}`);for(let o of t)delete i.secrets[o];n.environments[s]=i,he(n),g.info(`removed ${t.join(", ")} from ${s}`)});Ha.command("list").description("Show which environments have secrets stored here (names only, never values)").action(()=>{let r=ne(),e=Object.entries(r.environments);if(!e.length)return g.info("no environment secrets stored");for(let[t,n]of e)g.info(`${t}: ${Object.keys(n.secrets).join(", ")||"(none)"}`)});ye.command("export [file]").description("Back up ALL runner state (config+secrets, knowledge, audits, chats) to one tarball").action(r=>{try{let e=_l(r);g.info(`Backup written: ${e.file} (${e.entries.length} entries, mode 600)`),g.warn("This file CONTAINS YOUR SECRETS (Jira/GitHub tokens). Keep it private - anyone holding it can act as this runner."),g.info(`Restore on any machine with: allwright import ${Un.default.basename(e.file)}`)}catch(e){g.error(e instanceof Error?e.message:String(e)),process.exitCode=1}});ye.command("import <file>").description("Restore runner state from an `export` tarball (existing config is kept as a .bak dir)").action(r=>{let e=dr();if(e&&hr(e)){g.error("the runner is running - stop it first (systemctl stop allwright, or `allwright stop` for a pid-file daemon), then import."),process.exitCode=1;return}try{let t=kl(r);g.info(`Restored ${t.restored.length} entries into ${te()}`),t.previousDir&&g.info(`Previous config kept at ${t.previousDir}`),g.info("Start the runner and it will reconnect with the restored identity.")}catch(t){g.error(t instanceof Error?t.message:String(t)),process.exitCode=1}});ye.command("test").description("Check local setup: Jira auth, repo mappings, Claude Code binary").action(async()=>{let r=ne(),e=Object.keys(r.repos);if(!r.jira){g.error("no Jira credentials configured - run `allwright init`"),process.exitCode=1;return}let t=e.length?e.map(s=>({jiraProjectKey:"*",repoName:s})):[{jiraProjectKey:"*",repoName:"(none mapped)"}],n=!0;for(let s of t){let i=await Li(r,s);for(let o of i){if(s.jiraProjectKey==="*"&&o.name==="jira-project")continue;let a=o.ok?"PASS":"FAIL";(o.ok?g.info:g.error)(`[${a}] ${o.name}: ${o.detail}`),n&&=o.ok}}n||(process.exitCode=1)});function qn(){let r=dr();if(r&&hr(r)&&process.platform!=="win32")try{process.kill(r,"SIGHUP"),g.info("running runner reloaded its config live - no restart needed");return}catch{}g.info("No background runner found to reload. Under systemd: sudo systemctl kill -s HUP allwright - otherwise it applies on the next allwright start.")}function Iv(r){if(!r.runnerToken)throw new Error("runner not enrolled - run `allwright init`");if(!r.jira)throw new Error("no Jira credentials - run `allwright init`");let e=El();e.ok||(g.warn(`another runner is already running on this machine (pid ${e.pid}). Two runner processes with one identity kick each other off the control plane every second. Stop the other one first: \`allwright stop\` (background runner) or \`sudo systemctl stop allwright\` (service).`),process.exit(1)),process.on("exit",co);let t=new Ee(r.jira),n=new Map,s=h=>{let m=r.repos[h]?.jira;if(!m)return t;let y=n.get(h);return y||(y=new Ee(m),n.set(h,y)),y},i=new Map,o=(h,m)=>{let y=hu(pe()??r,h,m);switch(y.kind){case"legacy":return{jira:s(h),authored:!1};case"self":return{jira:s(h),authored:!0};case"missing":return{error:y.error};case"user":{let C=`${y.creds.baseUrl}:${y.creds.email}:${y.creds.apiToken.slice(-6)}`,D=i.get(C);return D||(D=new Ee(y.creds),i.set(C,D)),{jira:D,authored:!0}}}},a=new URL("/api/runner/ws",r.controlPlaneUrl);a.protocol=a.protocol==="https:"?"wss:":"ws:";let u=[],c=[],f=[],p,v=null,S={cfg:r,jiraFor:s,transport:null},T=new Set,x=h=>{let m=u.find(C=>C.id===h),y=m&&r.repos[m.repoName];return m&&y?{project:m,repoPath:y.path}:null},P={cfg:r,jiraFor:s,get transport(){return S.transport},lookup:(h,m)=>{let y=x(h),C=f.find(D=>D.projectId===h&&D.name===m);return y&&C?{...y,environment:C}:null}},_=new Mi(a.toString(),r.runnerToken,{runnerVersion:Gs},{onConfig:h=>{u=h.projects,td(h.projects),c=h.rules,f=h.environments,p.setConfig(h.projects,h.rules,h.pollingPaused,h.environments)},onDeployFix:async h=>{let m=x(h.projectId);if(!m){_.sendDeploySuggestResult(h.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:"this runner has no local checkout mapped for that project"});return}let y=Je(r,m.project,"assist");if("error"in y){_.sendDeploySuggestResult(h.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:y.error});return}g.info(`investigating failed deploy of "${h.environmentName}" (step: ${h.failedStep||"?"})`);let C=await zc({agent:y,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:h.environmentName,steps:h.steps,failedStep:h.failedStep,errorText:h.errorText,cfg:r});_.sendDeploySuggestResult(h.requestId,C)},onProjectTest:async h=>{let m=u.find(C=>C.id===h.projectId);if(!m){_.sendProjectTestResult(h.requestId,!1,[{name:"config",ok:!1,detail:"project not in this runner's synced config yet"}]);return}g.info(`running connection test for project "${m.name}"`);let y=await Li(pe()??r,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));_.sendProjectTestResult(h.requestId,y.every(C=>C.ok),y)},onRuleDiagnose:async h=>{let m=c.find(W=>W.id===h.ruleId),y=m&&u.find(W=>W.id===m.projectId);if(!m||!y){_.sendRuleDiagnoseResult(h.requestId,{checks:[{name:"config",ok:!1,detail:"rule not in this runner's synced config yet"}],matchedCount:0,excludedCount:0,excludedSample:[]});return}g.info(`diagnosing rule "${m.name}"`);let C=await Li(pe()??r,y,m.action.type==="deploy"?f.filter(W=>W.projectId===y.id):[]),D=m.action.type==="implement"?C:C.filter(W=>W.name!=="github-token"),{matchedCount:V,excludedCount:K,excludedSample:ie}=await p.diagnoseRule(m,y);_.sendRuleDiagnoseResult(h.requestId,{checks:D,matchedCount:V,excludedCount:K,excludedSample:ie})},onCancel:h=>{uc(h)?g.info(`run ${h} stopped from the dashboard`):g.warn(`cancel requested for run ${h}, but nothing is running under that id here - it likely finished already`)},onApproved:(h,m)=>{if(ha(h)){$c(P,h).catch(y=>g.error(`deploy approval crashed for ${h}: ${y instanceof Error?y.stack:y}`));return}ls(S,h,m).catch(y=>g.error(`approval handling crashed for ${h}: ${y instanceof Error?y.stack:y}`))},onRetryPush:h=>{let m=ai(h),y=()=>bc(S,h).catch(C=>g.error(`retry push crashed for ${h}: ${C instanceof Error?C.stack:C}`));m?p.runOnRepoQueue(m.baseRepoPath,y):y()},onRejected:h=>{if(ha(h)){Pc(P,h).catch(m=>g.error(`deploy rejection crashed for ${h}: ${m instanceof Error?m.stack:m}`));return}vc(S,h).catch(m=>g.error(`rejection handling crashed for ${h}: ${m instanceof Error?m.stack:m}`))},onDeployStart:h=>{let m=`${h.runId}#${h.attempt}`;if(T.has(m))return;T.add(m);let y=x(h.projectId);if(!y){let C="this runner has no local checkout mapped for that project - run: allwright repo add <repoName> /path/to/checkout";g.error(`deploy ${h.runId}: ${C}`),_.send({type:"run.status",runId:h.runId,status:"failed",error:C});return}g.info(`deploy ${h.runId} requested from the dashboard: ${h.issueKey} \u2192 ${h.environment.name}`),p.runOnEnvironmentQueue(h.environment.id,()=>gi({runId:h.runId,project:y.project,environment:h.environment,issueKey:h.issueKey,issueSummary:h.issueSummary,repoPath:y.repoPath,cfg:r,jira:s(y.project.repoName),transport:_,requestedBy:h.requestedBy}).catch(C=>g.error(`deploy crashed for ${h.runId}: ${C instanceof Error?C.stack:C}`)))},onDeploySuggest:async h=>{let m=x(h.projectId);if(!m){_.sendDeploySuggestResult(h.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:"this runner has no local checkout mapped for that project"});return}let y=Je(r,m.project,"assist");if("error"in y){_.sendDeploySuggestResult(h.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:y.error});return}g.info(`asking ${y.adapter.displayName} for "${h.environmentName}" deploy steps in ${m.repoPath}`);let C=await Dc({agent:y,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:h.environmentName,notes:h.notes,timeoutSeconds:h.timeoutSeconds,cfg:r});_.sendDeploySuggestResult(h.requestId,C)},onEnvPreflight:async h=>{let m=x(h.projectId);if(!m){_.sendEnvPreflightResult(h.requestId,{ok:!1,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project"}]});return}let y=await Mc({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:h.environmentName,steps:h.steps,requiredSecrets:h.requiredSecrets,workdir:h.workdir,branch:h.branch,publicUrl:h.publicUrl,cfg:r});_.sendEnvPreflightResult(h.requestId,y)},onChatTurn:async h=>{let m=x(h.projectId);if(!m){_.sendChatTurnResult(h.requestId,{ok:!1,sessionId:h.sessionId??"",reply:"",error:"this runner has no local checkout mapped for that project"});return}let y=h.sessionId||(0,qi.randomUUID)(),C=!h.sessionId;if((C?0:ma(y)?.messages.length??0)>=44){_.sendChatTurnResult(h.requestId,{ok:!1,sessionId:y,reply:"",error:"this chat has hit its length limit - every turn re-reads the whole conversation, so long chats get slow and expensive. Start a new chat (it keeps the repo knowledge; only the conversation resets)."});return}let V=h.files.length?xl(m.repoPath,h.requestId,h.files):null,K="```",ie=C?`You are the project assistant for "${m.project.name}" - this working directory is its repository, and you have read-only access.
|
|
713
727
|
|
|
714
728
|
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.
|
|
715
729
|
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.
|
|
716
730
|
|
|
717
731
|
ONLY when the user explicitly asks for a ticket, propose it by ending your reply with EXACTLY one fenced block in this shape:
|
|
718
|
-
${
|
|
732
|
+
${K}ticket
|
|
719
733
|
{"summary": "\u2026", "description": "\u2026"}
|
|
720
|
-
${
|
|
734
|
+
${K}
|
|
721
735
|
Before drafting, re-read this ENTIRE conversation from its first message and fold in every decision, constraint, and correction agreed along the way - the ticket reflects the final state of the whole discussion, not just the last message.
|
|
722
736
|
Write the description in plain human language, structured with these Markdown section headings in this order:
|
|
723
737
|
Story: - one or two sentences: who needs this and why.
|
|
@@ -726,16 +740,16 @@ Expected Flow: - the flow once this ticket is done, as numbered steps.
|
|
|
726
740
|
Current Flow: - how it behaves today; include ONLY when current behavior exists.
|
|
727
741
|
Acceptance Criteria: - testable bullet points a reviewer can check off one by one.
|
|
728
742
|
Include a section only when it carries real content, and add extra sections (Out of Scope, Notes, \u2026) when the work genuinely needs them. Use as many bullets as the work needs - no artificial length cap, but no padding either. It must stay concrete enough that a developer (or an agent) can implement it without asking questions. NEVER paste the conversation into the description; distill it. Refine the draft over further turns if the user asks.
|
|
729
|
-
EXCEPTION - verbatim payloads: when the user supplies literal content that must land in the ticket exactly (file contents, error logs, specs, commands), include it in the description IN FULL inside a fenced code block - the word budget applies to your own prose around it, never to the user's payload. Never summarize such content and never replace it with a placeholder like "[insert content here]": a placeholder makes the ticket unimplementable, because the implementing agent only ever sees the ticket. Inside the ${
|
|
743
|
+
EXCEPTION - verbatim payloads: when the user supplies literal content that must land in the ticket exactly (file contents, error logs, specs, commands), include it in the description IN FULL inside a fenced code block - the word budget applies to your own prose around it, never to the user's payload. Never summarize such content and never replace it with a placeholder like "[insert content here]": a placeholder makes the ticket unimplementable, because the implementing agent only ever sees the ticket. Inside the ${K}ticket JSON, fence such payloads with ~~~ (tildes), NEVER with triple backticks - a nested ${K} would end the outer block early and corrupt the draft.
|
|
730
744
|
EXCEPTION - big requirements: when the user asks for an epic with sub-tickets, or asks to ticket something clearly too large for one ticket, break it down instead and emit this shape in the \`\`\`ticket block:
|
|
731
745
|
{"epic": {"summary": "\u2026", "description": "\u2026"}, "tickets": [{"summary": "\u2026", "description": "\u2026"}, \u2026]}
|
|
732
746
|
3-8 tickets, each independently implementable and structured with the same section headings as above, ordered so foundations come first; the epic description is the overall goal in under 100 words.
|
|
733
747
|
|
|
734
|
-
${h.userName||"The user"} says: ${h.message}`+(
|
|
748
|
+
${h.userName||"The user"} says: ${h.message}`+(V?.section??""):`${h.userName||"The user"} says: ${h.message}`+(V?.section??""),W=0,M;try{let re=Je(r,m.project,"chat");if("error"in re){_.sendChatTurnResult(h.requestId,{ok:!1,sessionId:y,reply:"",error:re.error});return}M=await re.adapter.run({repoPath:m.repoPath,prompt:ie,timeoutSeconds:180,bin:re.bin,mode:"read_only",maxTurns:25,model:h.model||re.adapter.fastModel,sessionId:y,resume:!C,onLog:(oe,ce)=>{oe==="agent"&&_.send({type:"chat.stream",requestId:h.requestId,seq:W++,text:ce.slice(0,8e3)})},onUsage:oe=>{_.send({type:"chat.usage",requestId:h.requestId,inputTokens:Math.round(oe.inputTokens),outputTokens:Math.round(oe.outputTokens),cacheReadTokens:oe.cacheReadTokens===void 0?void 0:Math.round(oe.cacheReadTokens),turns:oe.turns})}})}finally{V&&et.default.rmSync(V.dir,{recursive:!0,force:!0})}M.ok&&Hc(h.projectId,y,h.message,M.resultText),_.sendChatTurnResult(h.requestId,{ok:M.ok,sessionId:y,reply:M.resultText,error:M.ok?void 0:M.error??"the agent produced no reply",inputTokens:M.inputTokens,outputTokens:M.outputTokens,cacheReadTokens:M.cacheReadTokens,costUsd:M.costUsd,model:M.model??""})},onChatList:h=>{_.sendChatListResult(h.requestId,Vc(h.projectId))},onRepoDocs:h=>{let m=x(h.projectId);if(!m){_.sendRepoDocsResult(h.requestId,{ok:!1,docs:[],error:"this runner has no local checkout mapped for that project"});return}_.sendRepoDocsResult(h.requestId,{ok:!0,docs:Yc(m.repoPath)})},onRepoDocRead:h=>{let m=x(h.projectId);if(!m){_.sendRepoDocReadResult(h.requestId,{ok:!1,path:h.path,content:"",truncated:!1,error:"this runner has no local checkout mapped for that project"});return}let y=Xc(m.repoPath,h.path);_.sendRepoDocReadResult(h.requestId,{ok:y.ok,path:y.ok?y.path:h.path,content:y.ok?y.content:"",truncated:y.ok?y.truncated:!1,error:y.ok?void 0:y.error})},onChatLoad:h=>{let m=ma(h.sessionId);_.sendChatLoadResult(h.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 h=>{let m=x(h.projectId);if(!m){_.sendBoardFetchResult(h.requestId,{ok:!1,columns:[],error:"this runner has no local checkout mapped for that project"});return}try{let y=s(m.project.repoName),C;try{C=await y.searchBoard(`project = "${m.project.jiraProjectKey}" ORDER BY Rank ASC`,100)}catch{C=await y.searchBoard(`project = "${m.project.jiraProjectKey}" ORDER BY updated DESC`,100)}let D=await y.boardColumns(m.project.jiraProjectKey),V;if(D){V=D.map(W=>({name:W.name,issues:[]}));let ie=new Map;for(let W of C){let M=D.findIndex(oe=>oe.statusIds.includes(W.statusId)),re={key:W.key,summary:W.summary,labels:W.labels};if(M>=0)V[M].issues.push(re);else{let oe=ie.get(W.status)??[];oe.push(re),ie.set(W.status,oe)}}for(let[W,M]of ie)V.push({name:W,issues:M})}else{let ie=ce=>ce.trim().toLowerCase(),W=new Map,M=new Map;for(let ce of C){let fe=ie(ce.status);W.has(fe)||W.set(fe,ce.status.trim());let Va=M.get(fe)??[];Va.push({key:ce.key,summary:ce.summary,labels:ce.labels}),M.set(fe,Va)}let re=[];try{re=await y.projectStatuses(m.project.jiraProjectKey)}catch{}let oe=[];for(let ce of re){let fe=ie(ce);!oe.includes(fe)&&M.has(fe)&&oe.push(fe)}for(let ce of M.keys())oe.includes(ce)||oe.push(ce);V=oe.map(ce=>({name:W.get(ce)??ce,issues:M.get(ce)??[]}))}let K=r.repos[m.project.repoName]?.jira??r.jira;_.sendBoardFetchResult(h.requestId,{ok:!0,browseBaseUrl:(K?.baseUrl??"").replace(/\/+$/,""),columns:V})}catch(y){_.sendBoardFetchResult(h.requestId,{ok:!1,columns:[],error:y instanceof Error?y.message:String(y)})}},onBoardTrigger:async h=>{let m=x(h.projectId);if(!m){_.sendBoardTriggerResult(h.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{let y=s(m.project.repoName),C=h.comment.trim()?o(m.project.repoName,h.requestedByEmail):{jira:y,authored:!1};if(C.error!==void 0){_.sendBoardTriggerResult(h.requestId,{ok:!1,error:C.error});return}if(h.reimplement){let D=await y.getIssue(h.issueKey),V=D.comments.filter(W=>ot(W.body)),K=V.length?Math.max(...V.map(W=>new Date(W.created).getTime())):0;if(!D.comments.some(W=>!ot(W.body)&&new Date(W.created).getTime()>K)){_.sendBoardTriggerResult(h.requestId,{ok:!1,error:`${h.issueKey} has nothing new since the last implementation - add a comment describing what should change, then hit Implement again. Re-running with the same ticket would just rebuild the same thing.`});return}await y.editLabels(h.issueKey,{remove:["agent-implemented"]})}h.removeLabel.trim()&&await y.editLabels(h.issueKey,{remove:[h.removeLabel.trim()]}),h.comment.trim()&&await C.jira.addTriggerComment(h.issueKey,`${h.comment.trim()}`+(!C.authored&&h.requestedBy?`
|
|
735
749
|
|
|
736
|
-
_(requested by ${h.requestedBy} via Allwright)_`:"")),
|
|
750
|
+
_(requested by ${h.requestedBy} via Allwright)_`:"")),g.info(`Board action on ${h.issueKey}`+(h.comment?` comment "${h.comment.trim()}"`:"")+(h.removeLabel?` -label ${h.removeLabel}`:"")+(h.requestedBy?` by ${h.requestedBy}`:"")),_.sendBoardTriggerResult(h.requestId,{ok:!0})}catch(y){_.sendBoardTriggerResult(h.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onChatCreateTicket:async h=>{let m=x(h.projectId);if(!m){_.sendChatCreateTicketResult(h.requestId,{ok:!1,issueKey:"",error:"this runner has no local checkout mapped for that project"});return}try{let y=o(m.project.repoName,h.requestedByEmail);if(y.error!==void 0){_.sendChatCreateTicketResult(h.requestId,{ok:!1,issueKey:"",error:y.error});return}let C=`
|
|
737
751
|
|
|
738
752
|
---
|
|
739
|
-
_Created via Allwright Compose`+(!
|
|
753
|
+
_Created via Allwright Compose`+(!y.authored&&h.requestedBy?` by ${h.requestedBy}`:"")+", drafted with the project agent._",{key:D}=await y.jira.createIssue(m.project.jiraProjectKey,h.summary,(h.description||"(no description)")+C,h.asEpic?"Epic":"Task");h.files.length&&await y.jira.addAttachments(D,h.files.map(K=>({name:K.name,content:Buffer.from(K.contentBase64,"base64")}))).then(()=>g.info(`Compose attached ${h.files.length} file(s) to ${D}`)).catch(K=>g.warn(`Compose could not attach files to ${D}: ${K instanceof Error?K.message:K}`));let V=[];if(h.asEpic){for(let K of h.children){let ie=await y.jira.createIssue(m.project.jiraProjectKey,K.summary,K.description||"(no description)","Task",D);V.push(ie.key)}g.info(`Compose created epic ${D} with ${V.length} child ticket(s)`),_.sendChatCreateTicketResult(h.requestId,{ok:!0,issueKey:D,childKeys:V});return}h.triggerComment.trim()&&await y.jira.addTriggerComment(D,`${h.triggerComment.trim()}`+(!y.authored&&h.requestedBy?`
|
|
740
754
|
|
|
741
|
-
_(requested by ${h.requestedBy} via Allwright)_`:"")),m.info(`Compose created ${D}`+(h.requestedBy?` for ${h.requestedBy}`:"")+(h.triggerComment?` with trigger "${h.triggerComment.trim()}"`:"")),S.sendChatCreateTicketResult(h.requestId,{ok:!0,issueKey:D})}catch(w){S.sendChatCreateTicketResult(h.requestId,{ok:!1,issueKey:"",error:w instanceof Error?w.message:String(w)})}},onAuditStart:async h=>{let g=x(h.projectId);if(!g){S.sendAuditStartResult(h.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{m.info(`Audit (${h.role}) starting on ${g.project.repoName}`+(h.scope.kind!=="repo"?` scoped to ${h.scope.kind}:${h.scope.ref}`:""));let w=We(r,g.project,"assist");if("error"in w){S.sendAuditStartResult(h.requestId,{ok:!1,error:w.error});return}let C=await bn({projectId:h.projectId,repoPath:g.repoPath,role:h.role,scope:h.scope,model:h.model,agent:w,jira:s(g.project.repoName)});if(!C.ok){S.sendAuditStartResult(h.requestId,{ok:!1,error:C.error});return}S.sendAuditStartResult(h.requestId,{ok:!0,audit:C.audit})}catch(w){S.sendAuditStartResult(h.requestId,{ok:!1,error:w instanceof Error?w.message:String(w)})}},onAuditList:async h=>{try{S.sendAuditListResult(h.requestId,{ok:!0,audits:Sl(h.projectId)})}catch(g){S.sendAuditListResult(h.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onAuditGet:async h=>{try{let g=Cl(h.projectId,h.auditId);if(!g){S.sendAuditGetResult(h.requestId,{ok:!1,error:"audit not found on this runner"});return}S.sendAuditGetResult(h.requestId,{ok:!0,audit:g})}catch(g){S.sendAuditGetResult(h.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onAuditReview:async h=>{try{let g=No(h.projectId,h.auditId,{selected:h.selected,ticketed:h.ticketed,verdicts:h.verdicts,verdictBy:h.verdictBy});if(!g){S.sendAuditReviewResult(h.requestId,{ok:!1,error:"audit not found on this runner"});return}let w=x(h.projectId);if(w&&h.verdicts.length){let C=[];for(let D of h.verdicts){if(D.verdict==="valid"||g.lessonsWritten.includes(D.findingId))continue;let Y=g.findings.find(B=>B.id===D.findingId);Y&&(Do(w.repoPath,g.role,Pl(Y,D.verdict,D.note,h.verdictBy)),C.push(D.findingId),m.info(`Lesson written (${g.role}): ${D.verdict} - ${Y.title.slice(0,60)}`))}C.length&&(g=No(h.projectId,h.auditId,{markLessonsWritten:C})??g)}S.sendAuditReviewResult(h.requestId,{ok:!0,audit:g})}catch(g){S.sendAuditReviewResult(h.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onKnowledgeList:async h=>{let g=x(h.projectId);if(!g){S.sendKnowledgeListResult(h.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{S.sendKnowledgeListResult(h.requestId,{ok:!0,files:Ol(g.repoPath)})}catch(w){S.sendKnowledgeListResult(h.requestId,{ok:!1,error:w instanceof Error?w.message:String(w)})}},onKnowledgeSave:async h=>{let g=x(h.projectId);if(!g){S.sendKnowledgeSaveResult(h.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{h.append?Do(g.repoPath,h.role,jl(h.content,h.by),h.level):Nl(g.repoPath,h.role,h.level,h.source,h.name,h.content),m.info(`Knowledge ${h.append?"taught":"saved"}: ${h.role}/${h.level}/${h.name}`),S.sendKnowledgeSaveResult(h.requestId,{ok:!0})}catch(w){S.sendKnowledgeSaveResult(h.requestId,{ok:!1,error:w instanceof Error?w.message:String(w)})}},onEpicList:async h=>{let g=x(h.projectId);if(!g){S.sendEpicListResult(h.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{let w=s(g.project.repoName);if(h.epicKey){let C=await w.epicChildren(h.epicKey);S.sendEpicListResult(h.requestId,{ok:!0,children:C})}else{let C=await w.searchEpics(g.project.jiraProjectKey);S.sendEpicListResult(h.requestId,{ok:!0,epics:C})}}catch(w){S.sendEpicListResult(h.requestId,{ok:!1,error:w instanceof Error?w.message:String(w)})}},onEpicSuggest:async h=>{let g=x(h.projectId);if(!g){S.sendEpicSuggestResult(h.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{let w=s(g.project.repoName),C=await w.epicChildren(h.epicKey),D=hl(C);if(!D.length){S.sendEpicSuggestResult(h.requestId,{ok:!1,error:`every child of ${h.epicKey} is already done or in an agent's hands - nothing to sequence`});return}if(D.length===1){S.sendEpicSuggestResult(h.requestId,{ok:!0,issueKey:D[0].key,reason:"It's the only pending ticket left in this epic.",considered:1});return}let Y=await Promise.all(D.slice(0,12).map(async ae=>{try{let ie=await w.getIssue(ae.key);return{...ae,description:ie.description}}catch{return{...ae,description:""}}})),B=(await w.getIssue(h.epicKey).catch(()=>null))?.summary??"";m.info(`Epic suggest: weighing ${Y.length} pending children of ${h.epicKey}`);let se=We(r,g.project,"assist");if("error"in se){S.sendEpicSuggestResult(h.requestId,{ok:!1,error:se.error});return}let W=await se.adapter.run({repoPath:g.repoPath,prompt:fl(h.epicKey,B,Y),timeoutSeconds:150,bin:se.bin,mode:"read_only",maxTurns:20,sessionId:(0,Oi.randomUUID)(),model:h.model||"claude-sonnet-5",onLog:()=>{}}),F=pl(W.resultText,Y.map(ae=>ae.key));if("error"in F){S.sendEpicSuggestResult(h.requestId,{ok:!1,error:F.error});return}m.info(`Epic suggest: ${h.epicKey} -> do ${F.issueKey} first`),S.sendEpicSuggestResult(h.requestId,{ok:!0,issueKey:F.issueKey,reason:F.reason,considered:Y.length})}catch(w){S.sendEpicSuggestResult(h.requestId,{ok:!1,error:w instanceof Error?w.message:String(w)})}},onTeamCreds:async h=>{try{let g=pe()??r;if(g.github?.token&&!g.github.login)try{let{GitHubClient:C}=await Promise.resolve().then(()=>(it(),$r));g.github.login=await new C(g.github.token).whoami(),he(g)}catch{}let w=ol(g,h.emails);S.sendTeamCredsResult(h.requestId,{ok:!0,...w})}catch(g){S.sendTeamCredsResult(h.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onSetupStatus:async h=>{try{let g=pe()??r,{buildSetupReport:w}=await Promise.resolve().then(()=>(ah(),oh)),C=await w(g,h.repoNames);S.sendSetupStatusResult(h.requestId,{ok:!0,...C})}catch(g){S.sendSetupStatusResult(h.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onSetupClaudeMdGenerate:async h=>{try{let g=x(h.projectId);if(!g){S.sendSetupClaudeMdGenerateResult(h.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let w=h.kind==="deploy"?"DEPLOY.md":h.kind==="design"?"DESIGN.md":"CLAUDE.md";m.info(`Setup: drafting ${w} for ${g.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.",D='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.',Y=`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.`,B=We(r,g.project,"assist");if("error"in B){S.sendSetupClaudeMdGenerateResult(h.requestId,{ok:!1,content:"",error:B.error});return}let W=(await B.adapter.run({repoPath:g.repoPath,prompt:h.kind==="deploy"?D:h.kind==="design"?Y:C,timeoutSeconds:240,bin:B.bin,mode:"read_only",maxTurns:40,sessionId:(0,Oi.randomUUID)(),onLog:()=>{}})).resultText.trim();if(!W){S.sendSetupClaudeMdGenerateResult(h.requestId,{ok:!1,error:"the agent returned no content - try again"});return}S.sendSetupClaudeMdGenerateResult(h.requestId,{ok:!0,content:W})}catch(g){S.sendSetupClaudeMdGenerateResult(h.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onSetupClaudeMdSave:async h=>{try{let g=x(h.projectId);if(!g){S.sendSetupClaudeMdSaveResult(h.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let w=h.kind==="deploy"?"DEPLOY.md":h.kind==="design"?"DESIGN.md":"CLAUDE.md",C=await Pa({repoPath:g.repoPath,relPath:w,content:h.content,overwrite:h.overwrite,commitMessage:`Add ${w} (agent-drafted, human-approved via Allwright)`});C.ok&&m.info(`Setup: wrote human-approved ${w} to ${g.repoPath}`),S.sendSetupClaudeMdSaveResult(h.requestId,C)}catch(g){S.sendSetupClaudeMdSaveResult(h.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onRepoDocSave:async h=>{try{let g=x(h.projectId);if(!g){S.sendRepoDocSaveResult(h.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let w=await Pa({repoPath:g.repoPath,relPath:h.relPath,content:h.content,overwrite:h.overwrite,commitMessage:`Add ${h.relPath.trim()} (written in Allwright Compose, human-approved)`});w.ok&&m.info(`Saved approved doc ${h.relPath} into ${g.repoPath}`),S.sendRepoDocSaveResult(h.requestId,w)}catch(g){S.sendRepoDocSaveResult(h.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onAuditStats:h=>{try{S.sendAuditStatsResult(h.requestId,{ok:!0,byProject:Tl(h.projectIds,h.since)})}catch(g){S.sendAuditStatsResult(h.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onRunnerUpdate:async h=>{if(!process.env.INVOCATION_ID){S.sendRunnerUpdateResult(h.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 g=()=>{m.info("Installing allwright@latest");let C=ds.default.dirname(process.execPath),D=Ct.default.existsSync(ds.default.join(C,"npm"))?ds.default.join(C,"npm"):"npm";(0,Et.execFile)(D,["install","-g","allwright@latest"],{timeout:18e4,env:{...process.env,PATH:`${C}:${process.env.PATH??""}`}},(Y,B,se)=>{if(Y){S.sendRunnerUpdateResult(h.requestId,{ok:!1,error:`npm install failed: ${(se||Y.message).slice(0,300)} - on the machine run: allwright update && sudo systemctl restart allwright`});return}S.sendRunnerUpdateResult(h.requestId,{ok:!0,note:"updated - restarting now, back in a few seconds"}),m.info("Update installed; exiting so systemd restarts on the new version"),setTimeout(()=>process.exit(0),1500)})};if(p.idle){g();return}if(v){S.sendRunnerUpdateResult(h.requestId,{ok:!0,scheduled:!0,note:"an update is already scheduled and will install once the current work finishes"});return}let w=p.busyCount;S.sendRunnerUpdateResult(h.requestId,{ok:!0,scheduled:!0,note:`scheduled - ${w} run(s)/deploy(s) active right now. Nothing is refused meanwhile; the install runs automatically as soon as this machine goes idle.`}),m.info(`Update scheduled: waiting for ${w} active run(s)/deploy(s) to finish`),v=setInterval(()=>{p.idle&&(clearInterval(v),v=null,g())},5e3)},onJiraUsers:async h=>{try{let g=await t.searchUsers(h.query);S.sendJiraUsersResult(h.requestId,{ok:!0,users:g})}catch(g){S.sendJiraUsersResult(h.requestId,{ok:!1,users:[],error:g instanceof Error?g.message:String(g)})}}});k.transport=S,p=new fi(r,s,S);let J=Object.values(kn()).filter(h=>h.kind==="implement").map(h=>h.repoPath);_o(Object.values(r.repos).map(h=>h.path),J).catch(()=>{}),S.start(),p.start();let M=()=>{m.info("shutting down"),v&&clearInterval(v),S.stop(),bu(process.pid),so(),process.exit(0)},z=!1,Q=()=>{if(z){m.warn("second stop signal - exiting NOW; the interrupted run will be marked failed"),M();return}if(z=!0,p.stop(),p.idle){M();return}m.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 h=setInterval(()=>{p.idle&&(clearInterval(h),M())},3e3)};process.on("SIGINT",Q),process.on("SIGTERM",Q),process.on("SIGHUP",()=>{try{let h=re();if(!h.jira)throw new Error("no Jira credentials in the reloaded config");for(let g of Object.keys(r))delete r[g];Object.assign(r,h),t=new Re(h.jira),n.clear(),m.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(h){m.error(`config reload failed - keeping the running config: ${h instanceof Error?h.message:String(h)}`)}})}ge.command("start").description("Start watching Jira. Runs in the background by default - close this terminal and it keeps going until you run `allwright stop`. Use --foreground to keep it attached (e.g. under systemd).").option("--foreground","run in this terminal instead of detaching to the background").action(async r=>{let e=re();if(r.foreground){yv(e);return}let t=ur();if(t&&lr(t)){m.info(`already running in the background (pid ${t}). Use \`allwright status\` or \`stop\`.`);return}let n=Ln();if(n){m.info(`a runner is already running on this machine (pid ${n}) - most likely the systemd service. One machine runs ONE runner; nothing to do. (Service controls: sudo systemctl status|stop|restart allwright)`);return}let s=yu(),i=(0,Et.spawn)(process.execPath,[process.argv[1],"start","--foreground"],{detached:!0,stdio:["ignore",s,s]});i.unref(),vu(i.pid),m.info(`Runner started in the background (pid ${i.pid}).`),m.info(`Logs: ${Is()}`),m.info("It will keep polling Jira until you run `allwright stop` - closing this terminal is fine.")});ge.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(r=>{let e=ur();if(!e||!lr(e)){m.info("no background runner is running"),e&&Ct.default.rmSync(on(),{force:!0});return}if(r.force){process.kill(e,"SIGKILL"),Ct.default.rmSync(on(),{force:!0}),m.info(`killed (pid ${e}) - any interrupted run will show as failed on the dashboard`);return}process.kill(e,"SIGTERM"),m.info(`stop signal sent (pid ${e}) - it stops polling now and exits once active work finishes (watch \`allwright status\`). Use --force to kill immediately.`)});ge.command("status").description("Check whether the background runner is running").action(()=>{let r=ur();r&&lr(r)?m.info(`running in the background (pid ${r})`):m.info("not running")});ge.parseAsync().catch(r=>{m.error(r instanceof Error?r.message:String(r)),process.exit(1)});
|
|
755
|
+
_(requested by ${h.requestedBy} via Allwright)_`:"")),g.info(`Compose created ${D}`+(h.requestedBy?` for ${h.requestedBy}`:"")+(h.triggerComment?` with trigger "${h.triggerComment.trim()}"`:"")),_.sendChatCreateTicketResult(h.requestId,{ok:!0,issueKey:D})}catch(y){_.sendChatCreateTicketResult(h.requestId,{ok:!1,issueKey:"",error:y instanceof Error?y.message:String(y)})}},onAuditStart:async h=>{let m=x(h.projectId);if(!m){_.sendAuditStartResult(h.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{g.info(`Audit (${h.role}) starting on ${m.project.repoName}`+(h.scope.kind!=="repo"?` scoped to ${h.scope.kind}:${h.scope.ref}`:""));let y=Je(r,m.project,"assist");if("error"in y){_.sendAuditStartResult(h.requestId,{ok:!1,error:y.error});return}let C=await Cn({projectId:h.projectId,repoPath:m.repoPath,role:h.role,scope:h.scope,model:h.model,agent:y,jira:s(m.project.repoName)});if(!C.ok){_.sendAuditStartResult(h.requestId,{ok:!1,error:C.error});return}_.sendAuditStartResult(h.requestId,{ok:!0,audit:C.audit})}catch(y){_.sendAuditStartResult(h.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onAuditList:async h=>{try{_.sendAuditListResult(h.requestId,{ok:!0,audits:Au(h.projectId)})}catch(m){_.sendAuditListResult(h.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditGet:async h=>{try{let m=ju(h.projectId,h.auditId);if(!m){_.sendAuditGetResult(h.requestId,{ok:!1,error:"audit not found on this runner"});return}_.sendAuditGetResult(h.requestId,{ok:!0,audit:m})}catch(m){_.sendAuditGetResult(h.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditReview:async h=>{try{let m=Bo(h.projectId,h.auditId,{selected:h.selected,ticketed:h.ticketed,verdicts:h.verdicts,verdictBy:h.verdictBy});if(!m){_.sendAuditReviewResult(h.requestId,{ok:!1,error:"audit not found on this runner"});return}let y=x(h.projectId);if(y&&h.verdicts.length){let C=[];for(let D of h.verdicts){if(D.verdict==="valid"||m.lessonsWritten.includes(D.findingId))continue;let V=m.findings.find(K=>K.id===D.findingId);V&&(Go(y.repoPath,m.role,Lu(V,D.verdict,D.note,h.verdictBy)),C.push(D.findingId),g.info(`Lesson written (${m.role}): ${D.verdict} - ${V.title.slice(0,60)}`))}C.length&&(m=Bo(h.projectId,h.auditId,{markLessonsWritten:C})??m)}_.sendAuditReviewResult(h.requestId,{ok:!0,audit:m})}catch(m){_.sendAuditReviewResult(h.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onKnowledgeList:async h=>{let m=x(h.projectId);if(!m){_.sendKnowledgeListResult(h.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{_.sendKnowledgeListResult(h.requestId,{ok:!0,files:qu(m.repoPath)})}catch(y){_.sendKnowledgeListResult(h.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onKnowledgeSave:async h=>{let m=x(h.projectId);if(!m){_.sendKnowledgeSaveResult(h.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{h.append?Go(m.repoPath,h.role,Uu(h.content,h.by),h.level):Fu(m.repoPath,h.role,h.level,h.source,h.name,h.content),g.info(`Knowledge ${h.append?"taught":"saved"}: ${h.role}/${h.level}/${h.name}`),_.sendKnowledgeSaveResult(h.requestId,{ok:!0})}catch(y){_.sendKnowledgeSaveResult(h.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onEpicList:async h=>{let m=x(h.projectId);if(!m){_.sendEpicListResult(h.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{let y=s(m.project.repoName);if(h.epicKey){let C=await y.epicChildren(h.epicKey);_.sendEpicListResult(h.requestId,{ok:!0,children:C})}else{let C=await y.searchEpics(m.project.jiraProjectKey);_.sendEpicListResult(h.requestId,{ok:!0,epics:C})}}catch(y){_.sendEpicListResult(h.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onEpicSuggest:async h=>{let m=x(h.projectId);if(!m){_.sendEpicSuggestResult(h.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{let y=s(m.project.repoName),C=await y.epicChildren(h.epicKey),D=bu(C);if(!D.length){_.sendEpicSuggestResult(h.requestId,{ok:!1,error:`every child of ${h.epicKey} is already done or in an agent's hands - nothing to sequence`});return}if(D.length===1){_.sendEpicSuggestResult(h.requestId,{ok:!0,issueKey:D[0].key,reason:"It's the only pending ticket left in this epic.",considered:1});return}let V=await Promise.all(D.slice(0,12).map(async re=>{try{let oe=await y.getIssue(re.key);return{...re,description:oe.description}}catch{return{...re,description:""}}})),K=(await y.getIssue(h.epicKey).catch(()=>null))?.summary??"";g.info(`Epic suggest: weighing ${V.length} pending children of ${h.epicKey}`);let ie=Je(r,m.project,"assist");if("error"in ie){_.sendEpicSuggestResult(h.requestId,{ok:!1,error:ie.error});return}let W=await ie.adapter.run({repoPath:m.repoPath,prompt:wu(h.epicKey,K,V),timeoutSeconds:150,bin:ie.bin,mode:"read_only",maxTurns:20,sessionId:(0,qi.randomUUID)(),model:h.model||"claude-sonnet-5",onLog:()=>{}}),M=_u(W.resultText,V.map(re=>re.key));if("error"in M){_.sendEpicSuggestResult(h.requestId,{ok:!1,error:M.error});return}g.info(`Epic suggest: ${h.epicKey} -> do ${M.issueKey} first`),_.sendEpicSuggestResult(h.requestId,{ok:!0,issueKey:M.issueKey,reason:M.reason,considered:V.length})}catch(y){_.sendEpicSuggestResult(h.requestId,{ok:!1,error:y instanceof Error?y.message:String(y)})}},onTeamCreds:async h=>{try{let m=pe()??r;if(m.github?.token&&!m.github.login)try{let{GitHubClient:C}=await Promise.resolve().then(()=>(Ye(),zr));m.github.login=await new C(m.github.token).whoami(),he(m)}catch{}let y=fu(m,h.emails);_.sendTeamCredsResult(h.requestId,{ok:!0,...y})}catch(m){_.sendTeamCredsResult(h.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupStatus:async h=>{try{let m=pe()??r,{buildSetupReport:y}=await Promise.resolve().then(()=>(yh(),gh)),C=await y(m,h.repoNames);_.sendSetupStatusResult(h.requestId,{ok:!0,...C})}catch(m){_.sendSetupStatusResult(h.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdGenerate:async h=>{try{let m=x(h.projectId);if(!m){_.sendSetupClaudeMdGenerateResult(h.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let y=h.kind==="deploy"?"DEPLOY.md":h.kind==="design"?"DESIGN.md":"CLAUDE.md";g.info(`Setup: drafting ${y} 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.",D='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.`,K=Je(r,m.project,"assist");if("error"in K){_.sendSetupClaudeMdGenerateResult(h.requestId,{ok:!1,content:"",error:K.error});return}let W=(await K.adapter.run({repoPath:m.repoPath,prompt:h.kind==="deploy"?D:h.kind==="design"?V:C,timeoutSeconds:240,bin:K.bin,mode:"read_only",maxTurns:40,sessionId:(0,qi.randomUUID)(),onLog:()=>{}})).resultText.trim();if(!W){_.sendSetupClaudeMdGenerateResult(h.requestId,{ok:!1,error:"the agent returned no content - try again"});return}_.sendSetupClaudeMdGenerateResult(h.requestId,{ok:!0,content:W})}catch(m){_.sendSetupClaudeMdGenerateResult(h.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdSave:async h=>{try{let m=x(h.projectId);if(!m){_.sendSetupClaudeMdSaveResult(h.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let y=h.kind==="deploy"?"DEPLOY.md":h.kind==="design"?"DESIGN.md":"CLAUDE.md",C=await Ua({repoPath:m.repoPath,relPath:y,content:h.content,overwrite:h.overwrite,commitMessage:`Add ${y} (agent-drafted, human-approved via Allwright)`});C.ok&&g.info(`Setup: wrote human-approved ${y} to ${m.repoPath}`),_.sendSetupClaudeMdSaveResult(h.requestId,C)}catch(m){_.sendSetupClaudeMdSaveResult(h.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRepoDocSave:async h=>{try{let m=x(h.projectId);if(!m){_.sendRepoDocSaveResult(h.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let y=await Ua({repoPath:m.repoPath,relPath:h.relPath,content:h.content,overwrite:h.overwrite,commitMessage:`Add ${h.relPath.trim()} (written in Allwright Compose, human-approved)`});y.ok&&g.info(`Saved approved doc ${h.relPath} into ${m.repoPath}`),_.sendRepoDocSaveResult(h.requestId,y)}catch(m){_.sendRepoDocSaveResult(h.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditStats:h=>{try{_.sendAuditStatsResult(h.requestId,{ok:!0,byProject:$u(h.projectIds,h.since)})}catch(m){_.sendAuditStatsResult(h.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRunnerUpdate:async h=>{if(!process.env.INVOCATION_ID){_.sendRunnerUpdateResult(h.requestId,{ok:!1,error:"this runner is not running as a systemd service, so it cannot restart itself after updating. On the machine run: allwright update && allwright stop && allwright start"});return}let m=()=>{g.info("Installing allwright@latest");let C=Un.default.dirname(process.execPath),D=et.default.existsSync(Un.default.join(C,"npm"))?Un.default.join(C,"npm"):"npm";(0,Et.execFile)(D,["install","-g","allwright@latest"],{timeout:18e4,env:{...process.env,PATH:`${C}:${process.env.PATH??""}`}},(V,K,ie)=>{if(V){_.sendRunnerUpdateResult(h.requestId,{ok:!1,error:`npm install failed: ${(ie||V.message).slice(0,300)} - on the machine run: allwright update && sudo systemctl restart allwright`});return}_.sendRunnerUpdateResult(h.requestId,{ok:!0,note:"updated - restarting now, back in a few seconds"}),g.info("Update installed; exiting so systemd restarts on the new version"),setTimeout(()=>process.exit(0),1500)})};if(p.idle){m();return}if(v){_.sendRunnerUpdateResult(h.requestId,{ok:!0,scheduled:!0,note:"an update is already scheduled and will install once the current work finishes"});return}let y=p.busyCount;_.sendRunnerUpdateResult(h.requestId,{ok:!0,scheduled:!0,note:`scheduled - ${y} run(s)/deploy(s) active right now. Nothing is refused meanwhile; the install runs automatically as soon as this machine goes idle.`}),g.info(`Update scheduled: waiting for ${y} active run(s)/deploy(s) to finish`),v=setInterval(()=>{p.idle&&(clearInterval(v),v=null,m())},5e3)},onResolveConflict:async h=>{let m=y=>_.sendResolveConflictResult(h.requestId,{ok:!1,note:y});try{let y=is(h.runId);if(!y){m("this runner no longer has that PR on file - it may have been decided already");return}let C=r.repos[y.repoName];if(!C){m(`no local checkout mapped for "${y.repoName}" on this machine`);return}let D=Ae(r,y.repoName);if(!D){m("no GitHub token on this runner for that repo");return}let V=await new $e(D).getPullRequest(y.owner,y.repo,y.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 K=u.find(re=>re.repoName===y.repoName),ie=0,W=(re,oe)=>_.send({type:"run.log",runId:h.runId,seq:Date.now()*10+ie++%10,ts:new Date().toISOString(),level:re,message:oe}),M=await Bc({cfg:r,repoPath:C.path,branch:y.branch,baseBranch:V.baseRef,issueKey:y.issueKey,agentId:K?.defaultAgent||Ht.DEFAULT_AGENT_ID,configDir:y.agentConfigDir,timeoutSeconds:900,onLog:W});M.ok&&M.headSha&&(y.headSha=M.headSha,y.conflictNotified=!1,Bt(y),_.send({type:"run.pr.conflict",runId:h.runId,conflicted:!1}),_.send({type:"run.status",runId:h.runId,status:"awaiting_approval",headSha:M.headSha,...M.costUsd!==void 0?{costUsd:M.costUsd}:{},...M.inputTokens!==void 0?{inputTokens:M.inputTokens}:{},...M.outputTokens!==void 0?{outputTokens:M.outputTokens}:{}})),_.sendResolveConflictResult(h.requestId,M)}catch(y){m(y instanceof Error?y.message.slice(0,300):String(y))}},onAgentProfiles:h=>{try{let m=C=>{try{return et.default.existsSync(C)&&et.default.readdirSync(C).length>0}catch{return!1}},y=Object.entries(r.claudeProfiles).map(([C,D])=>({agent:"claude-code",name:C,loggedIn:m(D.configDir)}));_.sendAgentProfilesResult(h.requestId,{ok:!0,profiles:y,defaultLoggedIn:m(Un.default.join(Fa.default.homedir(),".claude")),agentsWithoutProfiles:Ht.REGISTERED_AGENTS.filter(C=>!C.capabilities.loginProfiles).map(C=>C.id)})}catch(m){_.sendAgentProfilesResult(h.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onJiraUsers:async h=>{try{let m=await t.searchUsers(h.query);_.sendJiraUsersResult(h.requestId,{ok:!0,users:m})}catch(m){_.sendJiraUsersResult(h.requestId,{ok:!1,users:[],error:m instanceof Error?m.message:String(m)})}}});S.transport=_,p=new wi(r,s,_);let J=Object.values(En()).filter(h=>h.kind==="implement").map(h=>h.repoPath);xo(Object.values(r.repos).map(h=>h.path),J).catch(()=>{}),_.start(),p.start();let O=()=>{g.info("shutting down"),v&&clearInterval(v),_.stop(),Rl(process.pid),co(),process.exit(0)},L=!1,Q=()=>{if(L){g.warn("second stop signal - exiting NOW; the interrupted run will be marked failed"),O();return}if(L=!0,p.stop(),p.idle){O();return}g.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 h=setInterval(()=>{p.idle&&(clearInterval(h),O())},3e3)};process.on("SIGINT",Q),process.on("SIGTERM",Q),process.on("SIGHUP",()=>{try{let h=ne();if(!h.jira)throw new Error("no Jira credentials in the reloaded config");for(let m of Object.keys(r))delete r[m];Object.assign(r,h),t=new Ee(h.jira),n.clear(),g.info("config reloaded live - new Jira tokens/repos/rules apply from the next poll. (Poll interval and control-plane URL still need a restart.)")}catch(h){g.error(`config reload failed - keeping the running config: ${h instanceof Error?h.message:String(h)}`)}})}ye.command("start").description("Start watching Jira. Runs in the background by default - close this terminal and it keeps going until you run `allwright stop`. Use --foreground to keep it attached (e.g. under systemd).").option("--foreground","run in this terminal instead of detaching to the background").action(async r=>{let e=ne();if(r.foreground){Iv(e);return}let t=dr();if(t&&hr(t)){g.info(`already running in the background (pid ${t}). Use \`allwright status\` or \`stop\`.`);return}let n=Hn();if(n){g.info(`a runner is already running on this machine (pid ${n}) - most likely the systemd service. One machine runs ONE runner; nothing to do. (Service controls: sudo systemctl status|stop|restart allwright)`);return}let s=Cl(),i=(0,Et.spawn)(process.execPath,[process.argv[1],"start","--foreground"],{detached:!0,stdio:["ignore",s,s]});i.unref(),Il(i.pid),g.info(`Runner started in the background (pid ${i.pid}).`),g.info(`Logs: ${Ms()}`),g.info("It will keep polling Jira until you run `allwright stop` - closing this terminal is fine.")});ye.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(r=>{let e=dr();if(!e||!hr(e)){g.info("no background runner is running"),e&&et.default.rmSync(hn(),{force:!0});return}if(r.force){process.kill(e,"SIGKILL"),et.default.rmSync(hn(),{force:!0}),g.info(`killed (pid ${e}) - any interrupted run will show as failed on the dashboard`);return}process.kill(e,"SIGTERM"),g.info(`stop signal sent (pid ${e}) - it stops polling now and exits once active work finishes (watch \`allwright status\`). Use --force to kill immediately.`)});ye.command("status").description("Check whether the background runner is running").action(()=>{let r=dr();r&&hr(r)?g.info(`running in the background (pid ${r})`):g.info("not running")});ye.parseAsync().catch(r=>{g.error(r instanceof Error?r.message:String(r)),process.exit(1)});
|