allwright 1.24.0 → 1.24.2
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 +75 -71
- package/package.json +1 -1
package/bin/allwright.js
CHANGED
|
@@ -1,26 +1,26 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
"use strict";var Xh=Object.create;var uo=Object.defineProperty;var Qh=Object.getOwnPropertyDescriptor;var ef=Object.getOwnPropertyNames;var tf=Object.getPrototypeOf,nf=Object.prototype.hasOwnProperty;var Ks=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(r){throw t=[r],r}};var ne=(n,e)=>()=>{try{return e||n((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},Zs=(n,e)=>{for(var t in e)uo(n,t,{get:e[t],enumerable:!0})},rf=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ef(e))!nf.call(n,s)&&s!==t&&uo(n,s,{get:()=>e[s],enumerable:!(r=Qh(e,s))||r.enumerable});return n};var E=(n,e,t)=>(t=n!=null?Xh(tf(n)):{},rf(e||!n||!n.__esModule?uo(t,"default",{value:n,enumerable:!0}):t,n));var hs=ne(ho=>{var Hs=class extends Error{constructor(e,t,r){super(r),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},co=class extends Hs{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};ho.CommanderError=Hs;ho.InvalidArgumentError=co});var Gs=ne(po=>{var{InvalidArgumentError:sf}=hs(),fo=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,r)=>{if(!this.argChoices.includes(t))throw new sf(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,r):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function of(n){let e=n.name()+(n.variadic===!0?"...":"");return n.required?"<"+e+">":"["+e+"]"}po.Argument=fo;po.humanReadableArgName=of});var go=ne(gl=>{var{humanReadableArgName:af}=Gs(),mo=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),r=e._getHelpCommand();return r&&!r._hidden&&t.push(r),this.sortSubcommands&&t.sort((s,i)=>s.name().localeCompare(i.name())),t}compareOptions(e,t){let r=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return r(e).localeCompare(r(t))}visibleOptions(e){let t=e.options.filter(s=>!s.hidden),r=e._getHelpOption();if(r&&!r.hidden){let s=r.short&&e._findOption(r.short),i=r.long&&e._findOption(r.long);!s&&!i?t.push(r):r.long&&!i?t.push(e.createOption(r.long,r.description)):r.short&&!s&&t.push(e.createOption(r.short,r.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let r=e.parent;r;r=r.parent){let s=r.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(r=>af(r)).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((r,s)=>Math.max(r,t.subcommandTerm(s).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((r,s)=>Math.max(r,t.optionTerm(s).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((r,s)=>Math.max(r,t.optionTerm(s).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((r,s)=>Math.max(r,t.argumentTerm(s).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let r="";for(let s=e.parent;s;s=s.parent)r=s.name()+" "+r;return r+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(r=>JSON.stringify(r)).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(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let r=`(${t.join(", ")})`;return e.description?`${e.description} ${r}`:r}return e.description}formatHelp(e,t){let r=t.padWidth(e,t),s=t.helpWidth||80,i=2,o=2;function a(T,x){if(x){let P=`${T.padEnd(r+o)}${x}`;return t.wrap(P,s-i,r+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
|
|
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 b=t.visibleCommands(e).map(T=>a(t.subcommandTerm(T),t.subcommandDescription(T)));return b.length>0&&(c=c.concat(["Commands:",u(b),""])),c.join(`
|
|
4
4
|
`)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,r,s=40){let i=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",o=new RegExp(`[\\n][${i}]+`);if(e.match(o))return e;let a=t-r;if(a<s)return e;let u=e.slice(0,r),c=e.slice(r).replace(`\r
|
|
5
5
|
`,`
|
|
6
|
-
`),f=" ".repeat(r),
|
|
7
|
-
|.{1,${a-1}}([${
|
|
6
|
+
`),f=" ".repeat(r),v="\\s\u200B",b=new RegExp(`
|
|
7
|
+
|.{1,${a-1}}([${v}]|$)|[^${v}]+?([${v}]|$)`,"g"),T=c.match(b)||[];return u+T.map((x,P)=>x===`
|
|
8
8
|
`?"":(P>0?f:"")+x.trimEnd()).join(`
|
|
9
|
-
`)}};gl.Help=mo});var wo=ne(
|
|
9
|
+
`)}};gl.Help=mo});var wo=ne(bo=>{var{InvalidArgumentError:lf}=hs(),yo=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 r=cf(e);this.short=r.shortFlag,this.long=r.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,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,r)=>{if(!this.argChoices.includes(t))throw new lf(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,r):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return uf(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},vo=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,r)=>{this.positiveOptions.has(r)&&this.dualOptions.add(r)})}valueFromOption(e,t){let r=t.attributeName();if(!this.dualOptions.has(r))return!0;let s=this.negativeOptions.get(r).presetArg,i=s!==void 0?s:!1;return t.negate===(i===e)}};function uf(n){return n.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function cf(n){let e,t,r=n.split(/[ |,]+/);return r.length>1&&!/^[[<]/.test(r[1])&&(e=r.shift()),t=r.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}bo.Option=yo;bo.DualOptions=vo});var vl=ne(yl=>{function df(n,e){if(Math.abs(n.length-e.length)>3)return Math.max(n.length,e.length);let t=[];for(let r=0;r<=n.length;r++)t[r]=[r];for(let r=0;r<=e.length;r++)t[0][r]=r;for(let r=1;r<=e.length;r++)for(let s=1;s<=n.length;s++){let i=1;n[s-1]===e[r-1]?i=0:i=1,t[s][r]=Math.min(t[s-1][r]+1,t[s][r-1]+1,t[s-1][r-1]+i),s>1&&r>1&&n[s-1]===e[r-2]&&n[s-2]===e[r-1]&&(t[s][r]=Math.min(t[s][r],t[s-2][r-2]+1))}return t[n.length][e.length]}function hf(n,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=n.startsWith("--");t&&(n=n.slice(2),e=e.map(o=>o.slice(2)));let r=[],s=3,i=.4;return e.forEach(o=>{if(o.length<=1)return;let a=df(n,o),u=Math.max(n.length,o.length);(u-a)/u>i&&(a<s?(s=a,r=[o]):a===s&&r.push(o))}),r.sort((o,a)=>o.localeCompare(a)),t&&(r=r.map(o=>`--${o}`)),r.length>1?`
|
|
10
10
|
(Did you mean one of ${r.join(", ")}?)`:r.length===1?`
|
|
11
|
-
(Did you mean ${r[0]}?)`:""}yl.suggestSimilar=hf});var Sl=ne(kl=>{var ff=require("node:events").EventEmitter,_o=require("node:child_process"),xt=require("node:path"),ko=require("node:fs"),me=require("node:process"),{Argument:pf,humanReadableArgName:mf}=Gs(),{CommanderError:So}=hs(),{Help:gf}=go(),{Option:
|
|
11
|
+
(Did you mean ${r[0]}?)`:""}yl.suggestSimilar=hf});var Sl=ne(kl=>{var ff=require("node:events").EventEmitter,_o=require("node:child_process"),xt=require("node:path"),ko=require("node:fs"),me=require("node:process"),{Argument:pf,humanReadableArgName:mf}=Gs(),{CommanderError:So}=hs(),{Help:gf}=go(),{Option:bl,DualOptions:yf}=wo(),{suggestSimilar:wl}=vl(),To=class n extends ff{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=>me.stdout.write(t),writeErr:t=>me.stderr.write(t),getOutHelpWidth:()=>me.stdout.isTTY?me.stdout.columns:void 0,getErrHelpWidth:()=>me.stderr.isTTY?me.stderr.columns:void 0,outputError:(t,r)=>r(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,r){let s=t,i=r;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 n(e)}createHelp(){return Object.assign(new gf,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
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 pf(e,t)}argument(e,t,r,s){let i=this.createArgument(e,t);return typeof r=="function"?i.default(s).argParser(r):i.default(r),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[,r,s]=e.match(/([^ ]+) *(.*)/),i=t??"display help for command",o=this.createCommand(r);return o.helpOption(!1),s&&o.arguments(s),i&&o.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(e,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 r=["preSubcommand","preAction","postAction"];if(!r.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
13
|
-
Expecting one of '${r.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(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,r){this._exitCallback&&this._exitCallback(new So(e,t,r)),me.exit(e)}action(e){let t=r=>{let s=this.registeredArguments.length,i=r.slice(0,s);return this._storeOptionsAsProperties?i[s]=this:i[s]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=t,this}createOption(e,t){return new
|
|
14
|
-
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=s=>[s.name()].concat(s.aliases()),r=t(e).find(s=>this._findCommand(s));if(r){let s=t(this._findCommand(r)).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(),r=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(r,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(r,e.defaultValue,"default");let s=(i,o,a)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let u=this.getOptionValue(r);i!==null&&e.parseArg?i=this._callParseArg(e,i,u,o):i!==null&&e.variadic&&(i=e._concatValue(i,u)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(r,i,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,r,s,i){if(typeof t=="object"&&t instanceof
|
|
13
|
+
Expecting one of '${r.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,r){this._exitCallback&&this._exitCallback(new So(e,t,r)),me.exit(e)}action(e){let t=r=>{let s=this.registeredArguments.length,i=r.slice(0,s);return this._storeOptionsAsProperties?i[s]=this:i[s]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=t,this}createOption(e,t){return new bl(e,t)}_callParseArg(e,t,r,s){try{return e.parseArg(t,r)}catch(i){if(i.code==="commander.invalidArgument"){let o=`${s} ${i.message}`;this.error(o,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let r=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${r}'
|
|
14
|
+
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=s=>[s.name()].concat(s.aliases()),r=t(e).find(s=>this._findCommand(s));if(r){let s=t(this._findCommand(r)).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(),r=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(r,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(r,e.defaultValue,"default");let s=(i,o,a)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let u=this.getOptionValue(r);i!==null&&e.parseArg?i=this._callParseArg(e,i,u,o):i!==null&&e.variadic&&(i=e._concatValue(i,u)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(r,i,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,r,s,i){if(typeof t=="object"&&t instanceof bl)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(t,r);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,r,s){return this._optionEx({},e,t,r,s)}requiredOption(e,t,r,s){return this._optionEx({mandatory:!0},e,t,r,s)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,r){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=r,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(r=>{r.getOptionValueSource(e)!==void 0&&(t=r.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){me.versions?.electron&&(t.from="electron");let s=me.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(t.from="eval")}e===void 0&&(e=me.argv),this.rawArgs=e.slice();let r;switch(t.from){case void 0:case"node":this._scriptPath=e[1],r=e.slice(2);break;case"electron":me.defaultApp?(this._scriptPath=e[1],r=e.slice(2)):r=e.slice(1);break;case"user":r=e.slice(0);break;case"eval":r=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",r}parse(e,t){let r=this._prepareUserArgs(e,t);return this._parseCommand([],r),this}async parseAsync(e,t){let r=this._prepareUserArgs(e,t);return await this._parseCommand([],r),this}_executeSubCommand(e,t){t=t.slice();let r=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function i(f,p){let v=xt.resolve(f,p);if(ko.existsSync(v))return v;if(s.includes(xt.extname(p)))return;let b=s.find(T=>ko.existsSync(`${v}${T}`));if(b)return`${v}${b}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let f;try{f=ko.realpathSync(this._scriptPath)}catch{f=this._scriptPath}a=xt.resolve(xt.dirname(f),a)}if(a){let f=i(a,o);if(!f&&!e._executableFile&&this._scriptPath){let p=xt.basename(this._scriptPath,xt.extname(this._scriptPath));p!==this._name&&(f=i(a,`${p}-${e._name}`))}o=f||o}r=s.includes(xt.extname(o));let u;me.platform!=="win32"?r?(t.unshift(o),t=_l(me.execArgv).concat(t),u=_o.spawn(me.argv[0],t,{stdio:"inherit"})):u=_o.spawn(o,t,{stdio:"inherit"}):(t.unshift(o),t=_l(me.execArgv).concat(t),u=_o.spawn(me.execPath,t,{stdio:"inherit"})),u.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(p=>{me.on(p,()=>{u.killed===!1&&u.exitCode===null&&u.kill(p)})});let c=this._exitCallback;u.on("close",f=>{f=f??1,c?c(new So(f,"commander.executeSubCommandAsync","(close)")):me.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(
|
|
17
|
+
- ${p}`;throw new Error(v)}else if(f.code==="EACCES")throw new Error(`'${o}' not executable`);if(!c)me.exit(1);else{let p=new So(1,"commander.executeSubCommandAsync","(error)");p.nestedError=f,c(p)}}),this.runningCommand=u}_dispatchSubcommand(e,t,r){let s=this._findCommand(e);s||this.help({error:!0});let i;return i=this._chainOrCallSubCommandHook(i,s,"preSubcommand"),i=this._chainOrCall(i,()=>{if(s._executableHandler)this._executeSubCommand(s,t.concat(r));else return s._parseCommand(t,r)}),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=(r,s,i)=>{let o=s;if(s!==null&&r.parseArg){let a=`error: command-argument value '${s}' is invalid for argument '${r.name()}'.`;o=this._callParseArg(r,s,i,a)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((r,s)=>{let i=r.defaultValue;r.variadic?s<this.args.length?(i=this.args.slice(s),r.parseArg&&(i=i.reduce((o,a)=>e(r,a,o),r.defaultValue))):i===void 0&&(i=[]):s<this.args.length&&(i=this.args[s],r.parseArg&&(i=e(r,i,r.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 r=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=>{r=this._chainOrCall(r,()=>i.callback(i.hookedCommand,this))}),r}_chainOrCallSubCommandHook(e,t,r){let s=e;return this._lifeCycleHooks[r]!==void 0&&this._lifeCycleHooks[r].forEach(i=>{s=this._chainOrCall(s,()=>i(this,t))}),s}_parseCommand(e,t){let r=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(r.operands),t=r.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(r.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{r.unknown.length>0&&this.unknownOption(r.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){s(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(i,e,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(r=>{let s=r.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});e.filter(r=>r.conflictsWith.length>0).forEach(r=>{let s=e.find(i=>r.conflictsWith.includes(i.attributeName()));s&&this._conflictingOption(r,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],r=[],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===r&&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=r),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&r.length===0){if(this._findCommand(u)){t.push(u),i.length>0&&r.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){r.push(u),i.length>0&&r.push(...i);break}}if(this._passThroughOptions){s.push(u),i.length>0&&s.push(...i);break}s.push(u)}return{operands:t,unknown:r}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let r=0;r<t;r++){let s=this.options[r].attributeName();e[s]=s===this._versionOptionName?this._version:this[s]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,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
20
|
`),this.outputHelp({error:!0}));let r=t||{},s=r.exitCode||1,i=r.code||"commander.error";this._exit(s,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in me.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,me.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new yf(this.options),t=r=>this.getOptionValue(r)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(r));this.options.filter(r=>r.implied!==void 0&&t(r.attributeName())&&e.valueFromOption(this.getOptionValue(r.attributeName()),r)).forEach(r=>{Object.keys(r.implied).filter(s=>!t(s)).forEach(s=>{this.setOptionValueWithSource(s,r.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 r=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=r(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=wl(e,s)}let r=`error: unknown option '${e}'${t}`;this.error(r,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,r=t===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${r} 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=wl(e,s)}let r=`error: unknown command '${e}'${t}`;this.error(r,{code:"commander.unknownCommand"})}version(e,t,r){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",r=r||"output the version number";let s=this.createOption(t,r);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
21
21
|
`),this._exit(0,"commander.version",e)}),this}description(e,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 r=this.parent?._findCommand(e);if(r){let s=[r.name()].concat(r.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return 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(r=>mf(r));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=xt.basename(e,xt.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},r;return t.error?r=s=>this._outputConfiguration.writeErr(s):r=s=>this._outputConfiguration.writeOut(s),t.write=e.write||r,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let r=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",r)),this.emit("beforeHelp",r);let s=this.helpInformation(r);if(t&&(s=t(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");r.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",r),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",r))}helpOption(e,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=me.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let r=["beforeAll","before","after","afterAll"];if(!r.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
22
22
|
Expecting one of '${r.join("', '")}'`);let s=`${e}Help`;return this.on(s,i=>{let o;typeof 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 _l(n){return n.map(e=>{if(!e.startsWith("--inspect"))return e;let t,r="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]:r=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],r=i[3],s=i[4]),t&&s!=="0"?`${t}=${r}:${parseInt(s)+1}`:e})}kl.Command=To});var Il=ne(He=>{var{Argument:Tl}=Gs(),{Command:xo}=Sl(),{CommanderError:bf,InvalidArgumentError:xl}=hs(),{Help:vf}=go(),{Option:Cl}=wo();He.program=new xo;He.createCommand=n=>new xo(n);He.createOption=(n,e)=>new Cl(n,e);He.createArgument=(n,e)=>new Tl(n,e);He.Command=xo;He.Option=Cl;He.Argument=Tl;He.Help=vf;He.CommanderError=bf;He.InvalidArgumentError=xl;He.InvalidOptionArgumentError=xl});var ys=ne(ce=>{"use strict";Object.defineProperty(ce,"__esModule",{value:!0});ce.getParsedType=ce.ZodParsedType=ce.objectUtil=ce.util=void 0;var jo;(function(n){n.assertEqual=s=>{};function e(s){}n.assertIs=e;function t(s){throw new Error}n.assertNever=t,n.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},n.getValidEnumValues=s=>{let i=n.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),o={};for(let a of i)o[a]=s[a];return n.objectValues(o)},n.objectValues=s=>n.objectKeys(s).map(function(i){return s[i]}),n.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},n.find=(s,i)=>{for(let o of s)if(i(o))return o},n.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}n.joinValues=r,n.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(jo||(ce.util=jo={}));var Yl;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(Yl||(ce.objectUtil=Yl={}));ce.ZodParsedType=jo.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var zp=n=>{switch(typeof n){case"undefined":return ce.ZodParsedType.undefined;case"string":return ce.ZodParsedType.string;case"number":return Number.isNaN(n)?ce.ZodParsedType.nan:ce.ZodParsedType.number;case"boolean":return ce.ZodParsedType.boolean;case"function":return ce.ZodParsedType.function;case"bigint":return ce.ZodParsedType.bigint;case"symbol":return ce.ZodParsedType.symbol;case"object":return Array.isArray(n)?ce.ZodParsedType.array:n===null?ce.ZodParsedType.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?ce.ZodParsedType.promise:typeof Map<"u"&&n instanceof Map?ce.ZodParsedType.map:typeof Set<"u"&&n instanceof Set?ce.ZodParsedType.set:typeof Date<"u"&&n instanceof Date?ce.ZodParsedType.date:ce.ZodParsedType.object;default:return ce.ZodParsedType.unknown}};ce.getParsedType=zp});var ai=ne(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.ZodError=Xt.quotelessJson=Xt.ZodIssueCode=void 0;var Xl=ys();Xt.ZodIssueCode=Xl.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 Dp=n=>JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:");Xt.quotelessJson=Dp;var bs=class n extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let 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},r={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)r._errors.push(t(o));else{let a=r,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),r}static assert(e){if(!(e instanceof n))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Xl.util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},r=[];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 r.push(e(s));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}};Xt.ZodError=bs;bs.create=n=>new bs(n)});var No=ne(Oo=>{"use strict";Object.defineProperty(Oo,"__esModule",{value:!0});var Ce=ai(),On=ys(),Lp=(n,e)=>{let t;switch(n.code){case Ce.ZodIssueCode.invalid_type:n.received===On.ZodParsedType.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case Ce.ZodIssueCode.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,On.util.jsonStringifyReplacer)}`;break;case Ce.ZodIssueCode.unrecognized_keys:t=`Unrecognized key(s) in object: ${On.util.joinValues(n.keys,", ")}`;break;case Ce.ZodIssueCode.invalid_union:t="Invalid input";break;case Ce.ZodIssueCode.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${On.util.joinValues(n.options)}`;break;case Ce.ZodIssueCode.invalid_enum_value:t=`Invalid enum value. Expected ${On.util.joinValues(n.options)}, received '${n.received}'`;break;case Ce.ZodIssueCode.invalid_arguments:t="Invalid function arguments";break;case Ce.ZodIssueCode.invalid_return_type:t="Invalid function return type";break;case Ce.ZodIssueCode.invalid_date:t="Invalid date";break;case Ce.ZodIssueCode.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:On.util.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case Ce.ZodIssueCode.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case Ce.ZodIssueCode.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case Ce.ZodIssueCode.custom:t="Invalid input";break;case Ce.ZodIssueCode.invalid_intersection_types:t="Intersection results could not be merged";break;case Ce.ZodIssueCode.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case Ce.ZodIssueCode.not_finite:t="Number must be finite";break;default:t=e.defaultError,On.util.assertNever(n)}return{message:t}};Oo.default=Lp});var li=ne(Qt=>{"use strict";var Up=Qt&&Qt.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(Qt,"__esModule",{value:!0});Qt.defaultErrorMap=void 0;Qt.setErrorMap=qp;Qt.getErrorMap=Fp;var Ql=Up(No());Qt.defaultErrorMap=Ql.default;var eu=Ql.default;function qp(n){eu=n}function Fp(){return eu}});var zo=ne(ie=>{"use strict";var Bp=ie&&ie.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(ie,"__esModule",{value:!0});ie.isAsync=ie.isValid=ie.isDirty=ie.isAborted=ie.OK=ie.DIRTY=ie.INVALID=ie.ParseStatus=ie.EMPTY_PATH=ie.makeIssue=void 0;ie.addIssueToContext=Hp;var Kp=li(),tu=Bp(No()),Zp=n=>{let{data:e,path:t,errorMaps:r,issueData:s}=n,i=[...t,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let a="",u=r.filter(c=>!!c).slice().reverse();for(let c of u)a=c(o,{data:e,defaultError:a}).message;return{...s,path:i,message:a}};ie.makeIssue=Zp;ie.EMPTY_PATH=[];function Hp(n,e){let t=(0,Kp.getErrorMap)(),r=(0,ie.makeIssue)({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===tu.default?void 0:tu.default].filter(s=>!!s)});n.common.issues.push(r)}var Mo=class n{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let r=[];for(let s of t){if(s.status==="aborted")return ie.INVALID;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let s of t){let i=await s.key,o=await s.value;r.push({key:i,value:o})}return n.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let s of t){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return ie.INVALID;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(r[i.value]=o.value)}return{status:e.value,value:r}}};ie.ParseStatus=Mo;ie.INVALID=Object.freeze({status:"aborted"});var Gp=n=>({status:"dirty",value:n});ie.DIRTY=Gp;var Vp=n=>({status:"valid",value:n});ie.OK=Vp;var Wp=n=>n.status==="aborted";ie.isAborted=Wp;var Jp=n=>n.status==="dirty";ie.isDirty=Jp;var Yp=n=>n.status==="valid";ie.isValid=Yp;var Xp=n=>typeof Promise<"u"&&n instanceof Promise;ie.isAsync=Xp});var ru=ne(nu=>{"use strict";Object.defineProperty(nu,"__esModule",{value:!0})});var iu=ne(ui=>{"use strict";Object.defineProperty(ui,"__esModule",{value:!0});ui.errorUtil=void 0;var su;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e?.message})(su||(ui.errorUtil=su={}))});var yu=ne(k=>{"use strict";Object.defineProperty(k,"__esModule",{value:!0});k.discriminatedUnion=k.date=k.boolean=k.bigint=k.array=k.any=k.coerce=k.ZodFirstPartyTypeKind=k.late=k.ZodSchema=k.Schema=k.ZodReadonly=k.ZodPipeline=k.ZodBranded=k.BRAND=k.ZodNaN=k.ZodCatch=k.ZodDefault=k.ZodNullable=k.ZodOptional=k.ZodTransformer=k.ZodEffects=k.ZodPromise=k.ZodNativeEnum=k.ZodEnum=k.ZodLiteral=k.ZodLazy=k.ZodFunction=k.ZodSet=k.ZodMap=k.ZodRecord=k.ZodTuple=k.ZodIntersection=k.ZodDiscriminatedUnion=k.ZodUnion=k.ZodObject=k.ZodArray=k.ZodVoid=k.ZodNever=k.ZodUnknown=k.ZodAny=k.ZodNull=k.ZodUndefined=k.ZodSymbol=k.ZodDate=k.ZodBoolean=k.ZodBigInt=k.ZodNumber=k.ZodString=k.ZodType=void 0;k.NEVER=k.void=k.unknown=k.union=k.undefined=k.tuple=k.transformer=k.symbol=k.string=k.strictObject=k.set=k.record=k.promise=k.preprocess=k.pipeline=k.ostring=k.optional=k.onumber=k.oboolean=k.object=k.number=k.nullable=k.null=k.never=k.nativeEnum=k.nan=k.map=k.literal=k.lazy=k.intersection=k.instanceof=k.function=k.enum=k.effect=void 0;k.datetimeRegex=cu;k.custom=hu;var A=ai(),ci=li(),q=iu(),S=zo(),$=ys(),Ye=class{constructor(e,t,r,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},ou=(n,e)=>{if((0,S.isValid)(e))return{success:!0,data:e.value};if(!n.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 A.ZodError(n.common.issues);return this._error=t,this._error}}};function Y(n){if(!n)return{};let{errorMap:e,invalid_type_error:t,required_error:r,description:s}=n;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,a)=>{let{message:u}=n;return o.code==="invalid_enum_value"?{message:u??a.defaultError}:typeof a.data>"u"?{message:u??r??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:u??t??a.defaultError}},description:s}}var X=class{get description(){return this._def.description}_getType(e){return(0,$.getParsedType)(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:(0,$.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new S.ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:(0,$.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if((0,S.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 r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,$.getParsedType)(e)},s=this._parseSync({data:e,path:r.path,parent:r});return ou(r,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,$.getParsedType)(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return(0,S.isValid)(r)?{value:r.value}:{issues:t.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(r=>(0,S.isValid)(r)?{value:r.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,$.getParsedType)(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await((0,S.isAsync)(s)?s:Promise.resolve(s));return ou(r,i)}refine(e,t){let r=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:A.ZodIssueCode.custom,...r(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((r,s)=>e(r)?!0:(s.addIssue(typeof t=="function"?t(r,s):t),!1))}_refinement(e){return new Ue({schema:this,typeName:H.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 Je.create(this,this._def)}nullable(){return gt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ot.create(this)}promise(){return nn.create(this,this._def)}or(e){return qn.create([this,e],this._def)}and(e){return Fn.create(this,e,this._def)}transform(e){return new Ue({...Y(this._def),schema:this,typeName:H.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Gn({...Y(this._def),innerType:this,defaultValue:t,typeName:H.ZodDefault})}brand(){return new vs({typeName:H.ZodBranded,type:this,...Y(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Vn({...Y(this._def),innerType:this,catchValue:t,typeName:H.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ws.create(this,e)}readonly(){return Wn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};k.ZodType=X;k.Schema=X;k.ZodSchema=X;var Qp=/^c[^\s-]{8,}$/i,em=/^[0-9a-z]+$/,tm=/^[0-9A-HJKMNP-TV-Z]{26}$/i,nm=/^[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,rm=/^[a-z0-9_-]{21}$/i,sm=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,im=/^[-+]?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)?)??$/,om=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,am="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Do,lm=/^(?:(?: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])$/,um=/^(?:(?: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])$/,cm=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,dm=/^(([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])$/,hm=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,fm=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,lu="((\\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])))",pm=new RegExp(`^${lu}$`);function uu(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);let t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function mm(n){return new RegExp(`^${uu(n)}$`)}function cu(n){let e=`${lu}T${uu(n)}`,t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function gm(n,e){return!!((e==="v4"||!e)&&lm.test(n)||(e==="v6"||!e)&&cm.test(n))}function ym(n,e){if(!sm.test(n))return!1;try{let[t]=n.split(".");if(!t)return!1;let r=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function bm(n,e){return!!((e==="v4"||!e)&&um.test(n)||(e==="v6"||!e)&&dm.test(n))}var en=class n extends X{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==$.ZodParsedType.string){let i=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(i,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.string,received:i.parsedType}),S.INVALID}let r=new S.ParseStatus,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:A.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:A.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(s=this._getOrReturnCtx(e,s),o?(0,S.addIssueToContext)(s,{code:A.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&(0,S.addIssueToContext)(s,{code:A.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")om.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"email",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Do||(Do=new RegExp(am,"u")),Do.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"emoji",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")nm.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"uuid",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")rm.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"nanoid",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")Qp.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"cuid",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")em.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"cuid2",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")tm.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"ulid",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"url",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"regex",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:A.ZodIssueCode.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:A.ZodIssueCode.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:A.ZodIssueCode.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?cu(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:A.ZodIssueCode.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?pm.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:A.ZodIssueCode.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?mm(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:A.ZodIssueCode.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?im.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"duration",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?gm(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"ip",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?ym(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"jwt",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?bm(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"cidr",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?hm.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"base64",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?fm.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"base64url",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):$.util.assertNever(i);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(s=>e.test(s),{validation:t,code:A.ZodIssueCode.invalid_string,...q.errorUtil.errToObj(r)})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...q.errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...q.errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...q.errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...q.errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...q.errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...q.errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...q.errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...q.errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...q.errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...q.errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...q.errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...q.errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...q.errorUtil.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...q.errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...q.errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...q.errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...q.errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...q.errorUtil.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...q.errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...q.errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...q.errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...q.errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...q.errorUtil.errToObj(t)})}nonempty(e){return this.min(1,q.errorUtil.errToObj(e))}trim(){return new n({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new n({...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}};k.ZodString=en;en.create=n=>new en({checks:[],typeName:H.ZodString,coerce:n?.coerce??!1,...Y(n)});function vm(n,e){let t=(n.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=t>r?t:r,i=Number.parseInt(n.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var Nn=class n extends X{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==$.ZodParsedType.number){let i=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(i,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.number,received:i.parsedType}),S.INVALID}let r,s=new S.ParseStatus;for(let i of this._def.checks)i.kind==="int"?$.util.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?vm(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.not_finite,message:i.message}),s.dirty()):$.util.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,q.errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,q.errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,q.errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,q.errorUtil.toString(t))}setLimit(e,t,r,s){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:q.errorUtil.toString(s)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:q.errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:q.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:q.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:q.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:q.errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:q.errorUtil.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:q.errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:q.errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:q.errorUtil.toString(e)})}get minValue(){let e=null;for(let 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"&&$.util.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(t===null||r.value>t)&&(t=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}};k.ZodNumber=Nn;Nn.create=n=>new Nn({checks:[],typeName:H.ZodNumber,coerce:n?.coerce||!1,...Y(n)});var Mn=class n extends X{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==$.ZodParsedType.bigint)return this._getInvalidInput(e);let r,s=new S.ParseStatus;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):$.util.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(t,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.bigint,received:t.parsedType}),S.INVALID}gte(e,t){return this.setLimit("min",e,!0,q.errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,q.errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,q.errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,q.errorUtil.toString(t))}setLimit(e,t,r,s){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:q.errorUtil.toString(s)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:q.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:q.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:q.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:q.errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:q.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}};k.ZodBigInt=Mn;Mn.create=n=>new Mn({checks:[],typeName:H.ZodBigInt,coerce:n?.coerce??!1,...Y(n)});var zn=class extends X{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==$.ZodParsedType.boolean){let r=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.boolean,received:r.parsedType}),S.INVALID}return(0,S.OK)(e.data)}};k.ZodBoolean=zn;zn.create=n=>new zn({typeName:H.ZodBoolean,coerce:n?.coerce||!1,...Y(n)});var Dn=class n extends X{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==$.ZodParsedType.date){let i=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(i,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.date,received:i.parsedType}),S.INVALID}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(i,{code:A.ZodIssueCode.invalid_date}),S.INVALID}let r=new S.ParseStatus,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:A.ZodIssueCode.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:A.ZodIssueCode.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):$.util.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:q.errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:q.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}};k.ZodDate=Dn;Dn.create=n=>new Dn({checks:[],coerce:n?.coerce||!1,typeName:H.ZodDate,...Y(n)});var Mr=class extends X{_parse(e){if(this._getType(e)!==$.ZodParsedType.symbol){let r=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.symbol,received:r.parsedType}),S.INVALID}return(0,S.OK)(e.data)}};k.ZodSymbol=Mr;Mr.create=n=>new Mr({typeName:H.ZodSymbol,...Y(n)});var Ln=class extends X{_parse(e){if(this._getType(e)!==$.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.undefined,received:r.parsedType}),S.INVALID}return(0,S.OK)(e.data)}};k.ZodUndefined=Ln;Ln.create=n=>new Ln({typeName:H.ZodUndefined,...Y(n)});var Un=class extends X{_parse(e){if(this._getType(e)!==$.ZodParsedType.null){let r=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.null,received:r.parsedType}),S.INVALID}return(0,S.OK)(e.data)}};k.ZodNull=Un;Un.create=n=>new Un({typeName:H.ZodNull,...Y(n)});var tn=class extends X{constructor(){super(...arguments),this._any=!0}_parse(e){return(0,S.OK)(e.data)}};k.ZodAny=tn;tn.create=n=>new tn({typeName:H.ZodAny,...Y(n)});var jt=class extends X{constructor(){super(...arguments),this._unknown=!0}_parse(e){return(0,S.OK)(e.data)}};k.ZodUnknown=jt;jt.create=n=>new jt({typeName:H.ZodUnknown,...Y(n)});var st=class extends X{_parse(e){let t=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(t,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.never,received:t.parsedType}),S.INVALID}};k.ZodNever=st;st.create=n=>new st({typeName:H.ZodNever,...Y(n)});var zr=class extends X{_parse(e){if(this._getType(e)!==$.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.void,received:r.parsedType}),S.INVALID}return(0,S.OK)(e.data)}};k.ZodVoid=zr;zr.create=n=>new zr({typeName:H.ZodVoid,...Y(n)});var Ot=class n extends X{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==$.ZodParsedType.array)return(0,S.addIssueToContext)(t,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.array,received:t.parsedType}),S.INVALID;if(s.exactLength!==null){let o=t.data.length>s.exactLength.value,a=t.data.length<s.exactLength.value;(o||a)&&((0,S.addIssueToContext)(t,{code:o?A.ZodIssueCode.too_big:A.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}),r.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&((0,S.addIssueToContext)(t,{code:A.ZodIssueCode.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&((0,S.addIssueToContext)(t,{code:A.ZodIssueCode.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>s.type._parseAsync(new Ye(t,o,t.path,a)))).then(o=>S.ParseStatus.mergeArray(r,o));let i=[...t.data].map((o,a)=>s.type._parseSync(new Ye(t,o,t.path,a)));return S.ParseStatus.mergeArray(r,i)}get element(){return this._def.type}min(e,t){return new n({...this._def,minLength:{value:e,message:q.errorUtil.toString(t)}})}max(e,t){return new n({...this._def,maxLength:{value:e,message:q.errorUtil.toString(t)}})}length(e,t){return new n({...this._def,exactLength:{value:e,message:q.errorUtil.toString(t)}})}nonempty(e){return this.min(1,e)}};k.ZodArray=Ot;Ot.create=(n,e)=>new Ot({type:n,minLength:null,maxLength:null,exactLength:null,typeName:H.ZodArray,...Y(e)});function Nr(n){if(n instanceof Ne){let e={};for(let t in n.shape){let r=n.shape[t];e[t]=Je.create(Nr(r))}return new Ne({...n._def,shape:()=>e})}else return n instanceof Ot?new Ot({...n._def,type:Nr(n.element)}):n instanceof Je?Je.create(Nr(n.unwrap())):n instanceof gt?gt.create(Nr(n.unwrap())):n instanceof mt?mt.create(n.items.map(e=>Nr(e))):n}var Ne=class n extends X{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=$.util.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==$.ZodParsedType.object){let c=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(c,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.object,received:c.parsedType}),S.INVALID}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof st&&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 Ye(s,p,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof st){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,S.addIssueToContext)(s,{code:A.ZodIssueCode.unrecognized_keys,keys:a}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let f of a){let p=s.data[f];u.push({key:{status:"valid",value:f},value:c._parse(new Ye(s,p,s.path,f)),alwaysSet:f in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let c=[];for(let f of u){let p=await f.key,b=await f.value;c.push({key:p,value:b,alwaysSet:f.alwaysSet})}return c}).then(c=>S.ParseStatus.mergeObjectSync(r,c)):S.ParseStatus.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(e){return q.errorUtil.errToObj,new n({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{let s=this._def.errorMap?.(t,r).message??r.defaultError;return t.code==="unrecognized_keys"?{message:q.errorUtil.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new n({...this._def,unknownKeys:"strip"})}passthrough(){return new n({...this._def,unknownKeys:"passthrough"})}extend(e){return new n({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new n({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:H.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new n({...this._def,catchall:e})}pick(e){let t={};for(let r of $.util.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new n({...this._def,shape:()=>t})}omit(e){let t={};for(let r of $.util.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new n({...this._def,shape:()=>t})}deepPartial(){return Nr(this)}partial(e){let t={};for(let r of $.util.objectKeys(this.shape)){let s=this.shape[r];e&&!e[r]?t[r]=s:t[r]=s.optional()}return new n({...this._def,shape:()=>t})}required(e){let t={};for(let r of $.util.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Je;)i=i._def.innerType;t[r]=i}return new n({...this._def,shape:()=>t})}keyof(){return du($.util.objectKeys(this.shape))}};k.ZodObject=Ne;Ne.create=(n,e)=>new Ne({shape:()=>n,unknownKeys:"strip",catchall:st.create(),typeName:H.ZodObject,...Y(e)});Ne.strictCreate=(n,e)=>new Ne({shape:()=>n,unknownKeys:"strict",catchall:st.create(),typeName:H.ZodObject,...Y(e)});Ne.lazycreate=(n,e)=>new Ne({shape:n,unknownKeys:"strip",catchall:st.create(),typeName:H.ZodObject,...Y(e)});var qn=class extends X{_parse(e){let{ctx:t}=this._processInputParams(e),r=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 A.ZodError(a.ctx.common.issues));return(0,S.addIssueToContext)(t,{code:A.ZodIssueCode.invalid_union,unionErrors:o}),S.INVALID}if(t.common.async)return Promise.all(r.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 r){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 A.ZodError(u));return(0,S.addIssueToContext)(t,{code:A.ZodIssueCode.invalid_union,unionErrors:a}),S.INVALID}}get options(){return this._def.options}};k.ZodUnion=qn;qn.create=(n,e)=>new qn({options:n,typeName:H.ZodUnion,...Y(e)});var Pt=n=>n instanceof Bn?Pt(n.schema):n instanceof Ue?Pt(n.innerType()):n instanceof Kn?[n.value]:n instanceof Zn?n.options:n instanceof Hn?$.util.objectValues(n.enum):n instanceof Gn?Pt(n._def.innerType):n instanceof Ln?[void 0]:n instanceof Un?[null]:n instanceof Je?[void 0,...Pt(n.unwrap())]:n instanceof gt?[null,...Pt(n.unwrap())]:n instanceof vs||n instanceof Wn?Pt(n.unwrap()):n instanceof Vn?Pt(n._def.innerType):[],di=class n extends X{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==$.ZodParsedType.object)return(0,S.addIssueToContext)(t,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.object,received:t.parsedType}),S.INVALID;let r=this.discriminator,s=t.data[r],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,S.addIssueToContext)(t,{code:A.ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),S.INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){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 n({typeName:H.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...Y(r)})}};k.ZodDiscriminatedUnion=di;function Lo(n,e){let t=(0,$.getParsedType)(n),r=(0,$.getParsedType)(e);if(n===e)return{valid:!0,data:n};if(t===$.ZodParsedType.object&&r===$.ZodParsedType.object){let s=$.util.objectKeys(e),i=$.util.objectKeys(n).filter(a=>s.indexOf(a)!==-1),o={...n,...e};for(let a of i){let u=Lo(n[a],e[a]);if(!u.valid)return{valid:!1};o[a]=u.data}return{valid:!0,data:o}}else if(t===$.ZodParsedType.array&&r===$.ZodParsedType.array){if(n.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<n.length;i++){let o=n[i],a=e[i],u=Lo(o,a);if(!u.valid)return{valid:!1};s.push(u.data)}return{valid:!0,data:s}}else return t===$.ZodParsedType.date&&r===$.ZodParsedType.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}var Fn=class extends X{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),s=(i,o)=>{if((0,S.isAborted)(i)||(0,S.isAborted)(o))return S.INVALID;let a=Lo(i.value,o.value);return a.valid?(((0,S.isDirty)(i)||(0,S.isDirty)(o))&&t.dirty(),{status:t.value,value:a.data}):((0,S.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_intersection_types}),S.INVALID)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};k.ZodIntersection=Fn;Fn.create=(n,e,t)=>new Fn({left:n,right:e,typeName:H.ZodIntersection,...Y(t)});var mt=class n extends X{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==$.ZodParsedType.array)return(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.array,received:r.parsedType}),S.INVALID;if(r.data.length<this._def.items.length)return(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),S.INVALID;!this._def.rest&&r.data.length>this._def.items.length&&((0,S.addIssueToContext)(r,{code:A.ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...r.data].map((o,a)=>{let u=this._def.items[a]||this._def.rest;return u?u._parse(new Ye(r,o,r.path,a)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>S.ParseStatus.mergeArray(t,o)):S.ParseStatus.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new n({...this._def,rest:e})}};k.ZodTuple=mt;mt.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new mt({items:n,typeName:H.ZodTuple,rest:null,...Y(e)})};var hi=class n extends X{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==$.ZodParsedType.object)return(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.object,received:r.parsedType}),S.INVALID;let s=[],i=this._def.keyType,o=this._def.valueType;for(let a in r.data)s.push({key:i._parse(new Ye(r,a,r.path,a)),value:o._parse(new Ye(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?S.ParseStatus.mergeObjectAsync(t,s):S.ParseStatus.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,r){return t instanceof X?new n({keyType:e,valueType:t,typeName:H.ZodRecord,...Y(r)}):new n({keyType:en.create(),valueType:e,typeName:H.ZodRecord,...Y(t)})}};k.ZodRecord=hi;var Dr=class extends X{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==$.ZodParsedType.map)return(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.map,received:r.parsedType}),S.INVALID;let s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([a,u],c)=>({key:s._parse(new Ye(r,a,r.path,[c,"key"])),value:i._parse(new Ye(r,u,r.path,[c,"value"]))}));if(r.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 S.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 S.INVALID;(c.status==="dirty"||f.status==="dirty")&&t.dirty(),a.set(c.value,f.value)}return{status:t.value,value:a}}}};k.ZodMap=Dr;Dr.create=(n,e,t)=>new Dr({valueType:e,keyType:n,typeName:H.ZodMap,...Y(t)});var Lr=class n extends X{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==$.ZodParsedType.set)return(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.set,received:r.parsedType}),S.INVALID;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&((0,S.addIssueToContext)(r,{code:A.ZodIssueCode.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&((0,S.addIssueToContext)(r,{code:A.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 S.INVALID;f.status==="dirty"&&t.dirty(),c.add(f.value)}return{status:t.value,value:c}}let a=[...r.data.values()].map((u,c)=>i._parse(new Ye(r,u,r.path,c)));return r.common.async?Promise.all(a).then(u=>o(u)):o(a)}min(e,t){return new n({...this._def,minSize:{value:e,message:q.errorUtil.toString(t)}})}max(e,t){return new n({...this._def,maxSize:{value:e,message:q.errorUtil.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};k.ZodSet=Lr;Lr.create=(n,e)=>new Lr({valueType:n,minSize:null,maxSize:null,typeName:H.ZodSet,...Y(e)});var fi=class n extends X{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==$.ZodParsedType.function)return(0,S.addIssueToContext)(t,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.function,received:t.parsedType}),S.INVALID;function r(a,u){return(0,S.makeIssue)({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,(0,ci.getErrorMap)(),ci.defaultErrorMap].filter(c=>!!c),issueData:{code:A.ZodIssueCode.invalid_arguments,argumentsError:u}})}function s(a,u){return(0,S.makeIssue)({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,(0,ci.getErrorMap)(),ci.defaultErrorMap].filter(c=>!!c),issueData:{code:A.ZodIssueCode.invalid_return_type,returnTypeError:u}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof nn){let a=this;return(0,S.OK)(async function(...u){let c=new A.ZodError([]),f=await a._def.args.parseAsync(u,i).catch(v=>{throw c.addIssue(r(u,v)),c}),p=await Reflect.apply(o,this,f);return await a._def.returns._def.type.parseAsync(p,i).catch(v=>{throw c.addIssue(s(p,v)),c})})}else{let a=this;return(0,S.OK)(function(...u){let c=a._def.args.safeParse(u,i);if(!c.success)throw new A.ZodError([r(u,c.error)]);let f=Reflect.apply(o,this,c.data),p=a._def.returns.safeParse(f,i);if(!p.success)throw new A.ZodError([s(f,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new n({...this._def,args:mt.create(e).rest(jt.create())})}returns(e){return new n({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new n({args:e||mt.create([]).rest(jt.create()),returns:t||jt.create(),typeName:H.ZodFunction,...Y(r)})}};k.ZodFunction=fi;var Bn=class extends X{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})}};k.ZodLazy=Bn;Bn.create=(n,e)=>new Bn({getter:n,typeName:H.ZodLazy,...Y(e)});var Kn=class extends X{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(t,{received:t.data,code:A.ZodIssueCode.invalid_literal,expected:this._def.value}),S.INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}};k.ZodLiteral=Kn;Kn.create=(n,e)=>new Kn({value:n,typeName:H.ZodLiteral,...Y(e)});function du(n,e){return new Zn({values:n,typeName:H.ZodEnum,...Y(e)})}var Zn=class n extends X{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),r=this._def.values;return(0,S.addIssueToContext)(t,{expected:$.util.joinValues(r),received:t.parsedType,code:A.ZodIssueCode.invalid_type}),S.INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return(0,S.addIssueToContext)(t,{received:t.data,code:A.ZodIssueCode.invalid_enum_value,options:r}),S.INVALID}return(0,S.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 n.create(e,{...this._def,...t})}exclude(e,t=this._def){return n.create(this.options.filter(r=>!e.includes(r)),{...this._def,...t})}};k.ZodEnum=Zn;Zn.create=du;var Hn=class extends X{_parse(e){let t=$.util.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==$.ZodParsedType.string&&r.parsedType!==$.ZodParsedType.number){let s=$.util.objectValues(t);return(0,S.addIssueToContext)(r,{expected:$.util.joinValues(s),received:r.parsedType,code:A.ZodIssueCode.invalid_type}),S.INVALID}if(this._cache||(this._cache=new Set($.util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=$.util.objectValues(t);return(0,S.addIssueToContext)(r,{received:r.data,code:A.ZodIssueCode.invalid_enum_value,options:s}),S.INVALID}return(0,S.OK)(e.data)}get enum(){return this._def.values}};k.ZodNativeEnum=Hn;Hn.create=(n,e)=>new Hn({values:n,typeName:H.ZodNativeEnum,...Y(e)});var nn=class extends X{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==$.ZodParsedType.promise&&t.common.async===!1)return(0,S.addIssueToContext)(t,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.promise,received:t.parsedType}),S.INVALID;let r=t.parsedType===$.ZodParsedType.promise?t.data:Promise.resolve(t.data);return(0,S.OK)(r.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};k.ZodPromise=nn;nn.create=(n,e)=>new nn({type:n,typeName:H.ZodPromise,...Y(e)});var Ue=class extends X{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===H.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{(0,S.addIssueToContext)(r,o),o.fatal?t.abort():t.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(r.data,i);if(r.common.async)return Promise.resolve(o).then(async a=>{if(t.value==="aborted")return S.INVALID;let u=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return u.status==="aborted"?S.INVALID:u.status==="dirty"||t.value==="dirty"?(0,S.DIRTY)(u.value):u});{if(t.value==="aborted")return S.INVALID;let a=this._def.schema._parseSync({data:o,path:r.path,parent:r});return a.status==="aborted"?S.INVALID:a.status==="dirty"||t.value==="dirty"?(0,S.DIRTY)(a.value):a}}if(s.type==="refinement"){let o=a=>{let u=s.refinement(a,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?S.INVALID:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?S.INVALID:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.value,value:a.value}))))}if(s.type==="transform")if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!(0,S.isValid)(o))return S.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:r.data,path:r.path,parent:r}).then(o=>(0,S.isValid)(o)?Promise.resolve(s.transform(o.value,i)).then(a=>({status:t.value,value:a})):S.INVALID);$.util.assertNever(s)}};k.ZodEffects=Ue;k.ZodTransformer=Ue;Ue.create=(n,e,t)=>new Ue({schema:n,typeName:H.ZodEffects,effect:e,...Y(t)});Ue.createWithPreprocess=(n,e,t)=>new Ue({schema:e,effect:{type:"preprocess",transform:n},typeName:H.ZodEffects,...Y(t)});var Je=class extends X{_parse(e){return this._getType(e)===$.ZodParsedType.undefined?(0,S.OK)(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};k.ZodOptional=Je;Je.create=(n,e)=>new Je({innerType:n,typeName:H.ZodOptional,...Y(e)});var gt=class extends X{_parse(e){return this._getType(e)===$.ZodParsedType.null?(0,S.OK)(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};k.ZodNullable=gt;gt.create=(n,e)=>new gt({innerType:n,typeName:H.ZodNullable,...Y(e)});var Gn=class extends X{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return t.parsedType===$.ZodParsedType.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};k.ZodDefault=Gn;Gn.create=(n,e)=>new Gn({innerType:n,typeName:H.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Y(e)});var Vn=class extends X{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return(0,S.isAsync)(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new A.ZodError(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new A.ZodError(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};k.ZodCatch=Vn;Vn.create=(n,e)=>new Vn({innerType:n,typeName:H.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Y(e)});var Ur=class extends X{_parse(e){if(this._getType(e)!==$.ZodParsedType.nan){let r=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.nan,received:r.parsedType}),S.INVALID}return{status:"valid",value:e.data}}};k.ZodNaN=Ur;Ur.create=n=>new Ur({typeName:H.ZodNaN,...Y(n)});k.BRAND=Symbol("zod_brand");var vs=class extends X{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}};k.ZodBranded=vs;var ws=class n extends X{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?S.INVALID:i.status==="dirty"?(t.dirty(),(0,S.DIRTY)(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?S.INVALID:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,t){return new n({in:e,out:t,typeName:H.ZodPipeline})}};k.ZodPipeline=ws;var Wn=class extends X{_parse(e){let t=this._def.innerType._parse(e),r=s=>((0,S.isValid)(s)&&(s.value=Object.freeze(s.value)),s);return(0,S.isAsync)(t)?t.then(s=>r(s)):r(t)}unwrap(){return this._def.innerType}};k.ZodReadonly=Wn;Wn.create=(n,e)=>new Wn({innerType:n,typeName:H.ZodReadonly,...Y(e)});function au(n,e){let t=typeof n=="function"?n(e):typeof n=="string"?{message:n}:n;return typeof t=="string"?{message:t}:t}function hu(n,e={},t){return n?tn.create().superRefine((r,s)=>{let i=n(r);if(i instanceof Promise)return i.then(o=>{if(!o){let a=au(e,r),u=a.fatal??t??!0;s.addIssue({code:"custom",...a,fatal:u})}});if(!i){let o=au(e,r),a=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:a})}}):tn.create()}k.late={object:Ne.lazycreate};var H;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(H||(k.ZodFirstPartyTypeKind=H={}));var wm=(n,e={message:`Input not instance of ${n.name}`})=>hu(t=>t instanceof n,e);k.instanceof=wm;var fu=en.create;k.string=fu;var pu=Nn.create;k.number=pu;var _m=Ur.create;k.nan=_m;var km=Mn.create;k.bigint=km;var mu=zn.create;k.boolean=mu;var Sm=Dn.create;k.date=Sm;var Tm=Mr.create;k.symbol=Tm;var xm=Ln.create;k.undefined=xm;var Cm=Un.create;k.null=Cm;var Im=tn.create;k.any=Im;var Rm=jt.create;k.unknown=Rm;var Em=st.create;k.never=Em;var Am=zr.create;k.void=Am;var $m=Ot.create;k.array=$m;var Pm=Ne.create;k.object=Pm;var jm=Ne.strictCreate;k.strictObject=jm;var Om=qn.create;k.union=Om;var Nm=di.create;k.discriminatedUnion=Nm;var Mm=Fn.create;k.intersection=Mm;var zm=mt.create;k.tuple=zm;var Dm=hi.create;k.record=Dm;var Lm=Dr.create;k.map=Lm;var Um=Lr.create;k.set=Um;var qm=fi.create;k.function=qm;var Fm=Bn.create;k.lazy=Fm;var Bm=Kn.create;k.literal=Bm;var Km=Zn.create;k.enum=Km;var Zm=Hn.create;k.nativeEnum=Zm;var Hm=nn.create;k.promise=Hm;var gu=Ue.create;k.effect=gu;k.transformer=gu;var Gm=Je.create;k.optional=Gm;var Vm=gt.create;k.nullable=Vm;var Wm=Ue.createWithPreprocess;k.preprocess=Wm;var Jm=ws.create;k.pipeline=Jm;var Ym=()=>fu().optional();k.ostring=Ym;var Xm=()=>pu().optional();k.onumber=Xm;var Qm=()=>mu().optional();k.oboolean=Qm;k.coerce={string:(n=>en.create({...n,coerce:!0})),number:(n=>Nn.create({...n,coerce:!0})),boolean:(n=>zn.create({...n,coerce:!0})),bigint:(n=>Mn.create({...n,coerce:!0})),date:(n=>Dn.create({...n,coerce:!0}))};k.NEVER=S.INVALID});var Uo=ne(Xe=>{"use strict";var eg=Xe&&Xe.__createBinding||(Object.create?(function(n,e,t,r){r===void 0&&(r=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(n,r,s)}):(function(n,e,t,r){r===void 0&&(r=t),n[r]=e[t]})),qr=Xe&&Xe.__exportStar||function(n,e){for(var t in n)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&eg(e,n,t)};Object.defineProperty(Xe,"__esModule",{value:!0});qr(li(),Xe);qr(zo(),Xe);qr(ru(),Xe);qr(ys(),Xe);qr(yu(),Xe);qr(ai(),Xe)});var wu=ne(Me=>{"use strict";var bu=Me&&Me.__createBinding||(Object.create?(function(n,e,t,r){r===void 0&&(r=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(n,r,s)}):(function(n,e,t,r){r===void 0&&(r=t),n[r]=e[t]})),tg=Me&&Me.__setModuleDefault||(Object.create?(function(n,e){Object.defineProperty(n,"default",{enumerable:!0,value:e})}):function(n,e){n.default=e}),ng=Me&&Me.__importStar||function(n){if(n&&n.__esModule)return n;var e={};if(n!=null)for(var t in n)t!=="default"&&Object.prototype.hasOwnProperty.call(n,t)&&bu(e,n,t);return tg(e,n),e},rg=Me&&Me.__exportStar||function(n,e){for(var t in n)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&bu(e,n,t)};Object.defineProperty(Me,"__esModule",{value:!0});Me.z=void 0;var vu=ng(Uo());Me.z=vu;rg(Uo(),Me);Me.default=vu});var Se=ne(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.RepoDocReadMsg=h.RepoDocsResultMsg=h.RepoDocsMsg=h.ChatLoadResultMsg=h.ChatLoadMsg=h.ChatListResultMsg=h.ChatListMsg=h.ChatUsageMsg=h.ChatStreamMsg=h.JiraUsersResultMsg=h.DeployClaimResultMsg=h.DeployClaimMsg=h.RuleDiagnoseResultMsg=h.ProjectTestResultMsg=h.RunStatusMsg=h.FailedTest=h.RunUsageMsg=h.RunLogMsg=h.RunClaimMsg=h.HeartbeatMsg=h.HelloMsg=h.RuleConfig=h.ProjectConfig=h.ActionConfig=h.DeployAction=h.EnvironmentConfig=h.PromotionMode=h.DeployStep=h.RespondAction=h.ImplementAction=h.PlanOnlyAction=h.TriggerConfig=h.StatusChangedTrigger=h.CommentKeywordTrigger=h.LabelAddedTrigger=h.ActionType=h.TriggerType=h.ACTIVE_RUN_STATUSES=h.RunStatus=h.needsInputMarkerIn=h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=h.NEEDS_INPUT_COMMENT_MARKER=h.NEEDS_INPUT_LABEL=h.NEEDS_INPUT_MARKER=h.BRANCH_DEPLOY_ISSUE_KEY=h.REQUIRED_AGENT_CAPABILITIES=h.DEFAULT_AGENT_ID=h.REGISTERED_AGENTS=h.PROTOCOL_VERSION=h.GITHUB_TOKEN_PERMISSIONS=void 0;h.RunnerUpdateMsg=h.RepoDocSaveResultMsg=h.RepoDocSaveMsg=h.SetupClaudeMdSaveResultMsg=h.SetupClaudeMdSaveMsg=h.SetupClaudeMdGenerateResultMsg=h.SetupClaudeMdGenerateMsg=h.SetupStatusResultMsg=h.SetupStatusMsg=h.DeploySuggestResultMsg=h.EnvPreflightResultMsg=h.EnvPreflightMsg=h.ChatCreateTicketResultMsg=h.ChatCreateTicketMsg=h.ChatTurnResultMsg=h.ChatTurnMsg=h.ChatFile=h.TeamCredsResultMsg=h.TeamCredsMsg=h.KnowledgeSaveResultMsg=h.KnowledgeSaveMsg=h.KnowledgeListResultMsg=h.KnowledgeFile=h.KnowledgeListMsg=h.AuditReviewResultMsg=h.AuditReviewMsg=h.AuditGetResultMsg=h.AuditGetMsg=h.AuditListResultMsg=h.AuditStatsResultMsg=h.AuditStatsMsg=h.AuditListMsg=h.AuditStartResultMsg=h.AuditStartMsg=h.AuditRecord=h.AuditFinding=h.AuditScope=h.AuditSeverity=h.KnowledgeRole=h.AuditRole=h.EpicSuggestResultMsg=h.EpicSuggestMsg=h.EpicListResultMsg=h.EpicChild=h.EpicListMsg=h.BoardTriggerResultMsg=h.BoardTriggerMsg=h.BoardFetchResultMsg=h.BoardFetchMsg=h.RepoDocReadResultMsg=void 0;h.DEFAULT_DEPLOY_SUGGEST_PROMPT_TEMPLATE=h.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE=h.DEPLOY_FIX_PROMPT_TEMPLATE=h.PROMPT_PRESETS=h.DEFAULT_RESPOND_PROMPT_TEMPLATE=h.BUGFIX_IMPLEMENT_PROMPT_TEMPLATE=h.BUG_INVESTIGATION_PROMPT_TEMPLATE=h.TECHNICAL_PLAN_PROMPT_TEMPLATE=h.MEMORY_UPDATE_PROMPT=h.DEFAULT_IMPLEMENT_PROMPT_TEMPLATE=h.WRITE_TESTS_PROMPT=h.DEFAULT_PLAN_PROMPT_TEMPLATE=h.EnrollResponse=h.EnrollRequest=h.ServerToRunnerMsg=h.JiraUsersMsg=h.DeploySuggestMsg=h.DeployFixMsg=h.DeployStartMsg=h.RunRetryPushMsg=h.RunRejectedMsg=h.RunApprovedMsg=h.RunCancelMsg=h.RuleDiagnoseMsg=h.ProjectTestMsg=h.RunClaimResultMsg=h.ConfigMsg=h.HelloAckMsg=h.RunnerToServerMsg=h.AutopilotReportMsg=h.AutopilotNextResultMsg=h.AutopilotNextMsg=h.RunnerUpdateResultMsg=h.AgentProfilesResultMsg=h.AgentProfilesMsg=h.RunPrConflictMsg=h.RunResolveConflictResultMsg=h.RunTestFixResultMsg=h.RunTestFixMsg=h.RunResolveConflictMsg=void 0;h.missingAgentCapabilities=sg;h.parseRunnerMsg=og;h.parseServerMsg=ag;var l=wu();h.GITHUB_TOKEN_PERMISSIONS={where:"github.com/settings/personal-access-tokens/new (fine-grained token)",steps:["Resource owner: the org or user that OWNS the repo - not your personal account, unless the repo is under it","Repository access: Only select repositories -> pick this repo","Contents: Read and write - pushing the agent's branch","Pull requests: Read and write - opening the PR, and merging it when you approve","Metadata: Read-only - GitHub adds this itself and will not let you remove it","Workflows: Read and write - ONLY if changes may touch .github/workflows; without it GitHub rejects those pushes"],note:"A fine-grained token covers exactly ONE resource owner, so a repo in a different org always needs its own token. A classic token with the `repo` scope also works and is simpler, but it reaches every repository you can see - prefer fine-grained."};h.PROTOCOL_VERSION="1.46";h.REGISTERED_AGENTS=[{id:"claude-code",displayName:"Claude Code",capabilities:{readOnlyJail:!0,editNoShellJail:!0,sessionResume:!0,costReporting:!0,modelSelection:!0,loginProfiles:!0},suggestedModels:["claude-fable-5","claude-opus-5","claude-sonnet-5","claude-haiku-4-5-20251001"],experimental:!1},{id:"codex",displayName:"OpenAI Codex CLI (experimental)",capabilities:{readOnlyJail:!0,editNoShellJail:!1,sessionResume:!1,costReporting:!1,modelSelection:!0,loginProfiles:!1},suggestedModels:[],experimental:!0}];h.DEFAULT_AGENT_ID="claude-code";h.REQUIRED_AGENT_CAPABILITIES={plan_only:["readOnlyJail","sessionResume"],respond:["readOnlyJail"],implement:["editNoShellJail","sessionResume"],deploy:[],chat:["readOnlyJail","sessionResume"],assist:["readOnlyJail"]};function sg(n,e){let t=h.REGISTERED_AGENTS.find(r=>r.id===n);return t?(h.REQUIRED_AGENT_CAPABILITIES[e]??[]).filter(r=>!t.capabilities[r]):null}h.BRANCH_DEPLOY_ISSUE_KEY="(branch deploy)";h.NEEDS_INPUT_MARKER="NEEDS-INPUT";h.NEEDS_INPUT_LABEL="agent-needs-input";h.NEEDS_INPUT_COMMENT_MARKER="Allwright needs your input";h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=["TicketPilot needs your input"];var ig=n=>n.includes(h.NEEDS_INPUT_COMMENT_MARKER)||h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS.some(e=>n.includes(e));h.needsInputMarkerIn=ig;h.RunStatus=l.z.enum(["queued","running","posting","awaiting_approval","needs_input","succeeded","failed","timed_out"]);h.ACTIVE_RUN_STATUSES=["queued","running","posting","awaiting_approval"];h.TriggerType=l.z.enum(["label_added","comment_keyword","status_changed"]);h.ActionType=l.z.enum(["plan_only","implement","respond","deploy"]);h.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")});h.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")});h.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")});h.TriggerConfig=l.z.discriminatedUnion("type",[h.LabelAddedTrigger,h.CommentKeywordTrigger,h.StatusChangedTrigger]);h.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(h.DEFAULT_AGENT_ID),model:l.z.string().default("")});h.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(n=>n.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(h.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"),autoMerge:l.z.boolean().default(!0)});h.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(h.DEFAULT_AGENT_ID),model:l.z.string().default("")});h.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)});h.PromotionMode=l.z.enum(["deploy_only","merge_and_deploy"]);h.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:h.PromotionMode.default("deploy_only"),ticketBranchTemplate:l.z.string().default("agent/{{issueKey}}"),steps:l.z.array(h.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("")});h.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()});h.ActionConfig=l.z.discriminatedUnion("type",[h.PlanOnlyAction,h.ImplementAction,h.RespondAction,h.DeployAction]);h.ProjectConfig=l.z.object({id:l.z.string(),name:l.z.string(),jiraProjectKey:l.z.string(),goLiveIssueKey:l.z.string().default(""),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([])});h.RuleConfig=l.z.object({id:l.z.string(),projectId:l.z.string(),name:l.z.string(),enabled:l.z.boolean(),trigger:h.TriggerConfig,action:h.ActionConfig});h.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()});h.HeartbeatMsg=l.z.object({type:l.z.literal("heartbeat"),ts:l.z.string()});h.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()});h.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)});h.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()});h.FailedTest=l.z.object({command:l.z.string().max(500),exitCode:l.z.number().int(),tail:l.z.string().max(4e3)});h.RunStatusMsg=l.z.object({type:l.z.literal("run.status"),runId:l.z.string(),status:h.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(),failedTests:l.z.array(h.FailedTest).max(20).optional(),testsPassed:l.z.number().int().nonnegative().optional(),testsTotal:l.z.number().int().nonnegative().optional(),manualSteps:l.z.array(l.z.object({command:l.z.string().max(500),why:l.z.string().max(300).default("")})).max(20).optional(),goLiveDraft:l.z.string().max(4e3).optional()});h.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("")}))});h.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)});h.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()});h.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:h.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()});h.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()});h.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)});h.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()});h.ChatListMsg=l.z.object({type:l.z.literal("chat.list"),requestId:l.z.string(),projectId:l.z.string()});h.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([])});h.ChatLoadMsg=l.z.object({type:l.z.literal("chat.load"),requestId:l.z.string(),sessionId:l.z.string()});h.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(),steps:l.z.array(l.z.string()).default([])})).default([]),error:l.z.string().optional()});h.RepoDocsMsg=l.z.object({type:l.z.literal("repo.docs"),requestId:l.z.string(),projectId:l.z.string()});h.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()});h.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)});h.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()});h.BoardFetchMsg=l.z.object({type:l.z.literal("board.fetch"),requestId:l.z.string(),projectId:l.z.string()});h.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()});h.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)});h.BoardTriggerResultMsg=l.z.object({type:l.z.literal("board.trigger.result"),requestId:l.z.string(),ok:l.z.boolean(),error:l.z.string().optional()});h.EpicListMsg=l.z.object({type:l.z.literal("epic.list"),requestId:l.z.string(),projectId:l.z.string(),epicKey:l.z.string().default("")});h.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([])});h.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(h.EpicChild).default([])});h.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("")});h.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)});h.AuditRole=l.z.enum(["security","testing","architecture"]);h.KnowledgeRole=l.z.enum(["security","testing","architecture","implement"]);h.AuditSeverity=l.z.enum(["critical","high","medium","low","info"]);h.AuditScope=l.z.object({kind:l.z.enum(["repo","ticket","branch"]).default("repo"),ref:l.z.string().default("")});h.AuditFinding=l.z.object({id:l.z.string().min(1),title:l.z.string().min(1),ruleId:l.z.string().max(20).default(""),severity:h.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("")});h.AuditRecord=l.z.object({id:l.z.string(),role:h.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(h.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:h.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()});h.AuditStartMsg=l.z.object({type:l.z.literal("audit.start"),requestId:l.z.string(),projectId:l.z.string(),role:h.AuditRole,model:l.z.string().default(""),scope:h.AuditScope.default({kind:"repo",ref:""})});h.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:h.AuditRecord.optional()});h.AuditListMsg=l.z.object({type:l.z.literal("audit.list"),requestId:l.z.string(),projectId:l.z.string()});h.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("")});h.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({})});h.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:h.AuditRole,createdAt:l.z.string(),findingCount:l.z.number().int(),bySeverity:l.z.record(l.z.number().int()).default({})})).default([])});h.AuditGetMsg=l.z.object({type:l.z.literal("audit.get"),requestId:l.z.string(),projectId:l.z.string(),auditId:l.z.string()});h.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:h.AuditRecord.optional()});h.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("")});h.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:h.AuditRecord.optional()});h.KnowledgeListMsg=l.z.object({type:l.z.literal("knowledge.list"),requestId:l.z.string(),projectId:l.z.string()});h.KnowledgeFile=l.z.object({role:h.KnowledgeRole,level:l.z.enum(["global","org","project"]),source:l.z.enum(["pack","lessons","memory"]),name:l.z.string(),content:l.z.string(),editable:l.z.boolean().default(!1)});h.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(h.KnowledgeFile).default([])});h.KnowledgeSaveMsg=l.z.object({type:l.z.literal("knowledge.save"),requestId:l.z.string(),projectId:l.z.string(),role:h.KnowledgeRole,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("")});h.KnowledgeSaveResultMsg=l.z.object({type:l.z.literal("knowledge.save.result"),requestId:l.z.string(),ok:l.z.boolean(),error:l.z.string().optional()});h.TeamCredsMsg=l.z.object({type:l.z.literal("team.creds"),requestId:l.z.string(),emails:l.z.array(l.z.string()).max(200)});h.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([])});h.ChatFile=l.z.object({name:l.z.string().min(1).max(255),contentBase64:l.z.string().min(1).max(6e6)});h.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(h.ChatFile).max(8).default([])});h.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(""),contextTokens:l.z.number().int().nonnegative().default(0),contextLimit:l.z.number().int().nonnegative().default(0),compacted:l.z.boolean().default(!1),compactedMessages:l.z.number().int().nonnegative().default(0)});h.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([]),createAs:l.z.enum(["epic_with_children","separate_epics","separate_tasks"]).default("epic_with_children"),files:l.z.array(h.ChatFile).max(8).default([])});h.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([])});h.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(h.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("")});h.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([])});h.DeploySuggestResultMsg=l.z.object({type:l.z.literal("deploy.suggest.result"),requestId:l.z.string(),ok:l.z.boolean(),steps:l.z.array(h.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("")});h.SetupStatusMsg=l.z.object({type:l.z.literal("setup.status"),requestId:l.z.string(),repoNames:l.z.array(l.z.string()).max(100).default([])});h.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([])});h.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("")});h.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("")});h.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)});h.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("")});h.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)});h.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("")});h.RunnerUpdateMsg=l.z.object({type:l.z.literal("runner.update"),requestId:l.z.string()});h.RunResolveConflictMsg=l.z.object({type:l.z.literal("run.resolve.conflict"),requestId:l.z.string(),runId:l.z.string()});h.RunTestFixMsg=l.z.object({type:l.z.literal("run.testfix"),requestId:l.z.string(),runId:l.z.string(),failedTests:l.z.array(h.FailedTest).min(1).max(20)});h.RunTestFixResultMsg=l.z.object({type:l.z.literal("run.testfix.result"),requestId:l.z.string(),ok:l.z.boolean(),note:l.z.string().default(""),headSha:l.z.string().default(""),remaining:l.z.array(h.FailedTest).default([]),costUsd:l.z.number().nonnegative().optional(),inputTokens:l.z.number().int().nonnegative().optional(),outputTokens:l.z.number().int().nonnegative().optional()});h.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()});h.RunPrConflictMsg=l.z.object({type:l.z.literal("run.pr.conflict"),runId:l.z.string(),conflicted:l.z.boolean()});h.AgentProfilesMsg=l.z.object({type:l.z.literal("agent.profiles"),requestId:l.z.string()});h.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([])});h.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)});h.AutopilotNextMsg=l.z.object({type:l.z.literal("autopilot.next"),requestId:l.z.string()});h.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),autoMerge:l.z.boolean().default(!1)}).nullable().default(null),pausedUntil:l.z.string().default("")});h.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("")});h.RunnerToServerMsg=l.z.discriminatedUnion("type",[h.HelloMsg,h.HeartbeatMsg,h.RunClaimMsg,h.RunLogMsg,h.RunUsageMsg,h.RunStatusMsg,h.ProjectTestResultMsg,h.RuleDiagnoseResultMsg,h.DeployClaimMsg,h.DeploySuggestResultMsg,h.EnvPreflightResultMsg,h.ChatTurnResultMsg,h.ChatStreamMsg,h.ChatUsageMsg,h.ChatCreateTicketResultMsg,h.ChatListResultMsg,h.RepoDocsResultMsg,h.RepoDocReadResultMsg,h.ChatLoadResultMsg,h.BoardFetchResultMsg,h.BoardTriggerResultMsg,h.TeamCredsResultMsg,h.AuditStartResultMsg,h.AuditListResultMsg,h.AuditGetResultMsg,h.AuditReviewResultMsg,h.KnowledgeListResultMsg,h.KnowledgeSaveResultMsg,h.EpicListResultMsg,h.EpicSuggestResultMsg,h.JiraUsersResultMsg,h.SetupStatusResultMsg,h.SetupClaudeMdGenerateResultMsg,h.SetupClaudeMdSaveResultMsg,h.RepoDocSaveResultMsg,h.RunnerUpdateResultMsg,h.AgentProfilesResultMsg,h.RunPrConflictMsg,h.RunResolveConflictResultMsg,h.RunTestFixResultMsg,h.AuditStatsResultMsg,h.AutopilotNextMsg,h.AutopilotReportMsg]);h.HelloAckMsg=l.z.object({type:l.z.literal("hello.ack"),runnerId:l.z.string(),runnerName:l.z.string(),serverTime:l.z.string()});h.ConfigMsg=l.z.object({type:l.z.literal("config"),projects:l.z.array(h.ProjectConfig),rules:l.z.array(h.RuleConfig),environments:l.z.array(h.EnvironmentConfig).default([]),pollingPaused:l.z.boolean().default(!1)});h.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()});h.ProjectTestMsg=l.z.object({type:l.z.literal("project.test"),requestId:l.z.string(),projectId:l.z.string()});h.RuleDiagnoseMsg=l.z.object({type:l.z.literal("rule.diagnose"),requestId:l.z.string(),ruleId:l.z.string()});h.RunCancelMsg=l.z.object({type:l.z.literal("run.cancel"),runId:l.z.string()});h.RunApprovedMsg=l.z.object({type:l.z.literal("run.approved"),runId:l.z.string(),headSha:l.z.string().optional()});h.RunRejectedMsg=l.z.object({type:l.z.literal("run.rejected"),runId:l.z.string()});h.RunRetryPushMsg=l.z.object({type:l.z.literal("run.retryPush"),runId:l.z.string()});h.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:h.EnvironmentConfig,requestedBy:l.z.string().default(""),attempt:l.z.number().int().positive().default(1)});h.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("")});h.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)});h.JiraUsersMsg=l.z.object({type:l.z.literal("jira.users"),requestId:l.z.string(),query:l.z.string().default("")});h.ServerToRunnerMsg=l.z.discriminatedUnion("type",[h.HelloAckMsg,h.ConfigMsg,h.RunClaimResultMsg,h.ProjectTestMsg,h.RuleDiagnoseMsg,h.RunCancelMsg,h.RunApprovedMsg,h.RunRejectedMsg,h.RunRetryPushMsg,h.DeployClaimResultMsg,h.DeployStartMsg,h.DeploySuggestMsg,h.DeployFixMsg,h.EnvPreflightMsg,h.ChatTurnMsg,h.ChatCreateTicketMsg,h.ChatListMsg,h.RepoDocsMsg,h.RepoDocReadMsg,h.ChatLoadMsg,h.BoardFetchMsg,h.BoardTriggerMsg,h.TeamCredsMsg,h.AuditStartMsg,h.AuditListMsg,h.AuditGetMsg,h.AuditReviewMsg,h.KnowledgeListMsg,h.KnowledgeSaveMsg,h.EpicListMsg,h.EpicSuggestMsg,h.JiraUsersMsg,h.SetupStatusMsg,h.SetupClaudeMdGenerateMsg,h.SetupClaudeMdSaveMsg,h.RepoDocSaveMsg,h.RunnerUpdateMsg,h.AgentProfilesMsg,h.RunResolveConflictMsg,h.RunTestFixMsg,h.AuditStatsMsg,h.AutopilotNextResultMsg]);h.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()});h.EnrollResponse=l.z.object({runnerId:l.z.string(),runnerToken:l.z.string(),controlPlaneWsUrl:l.z.string()});function og(n){return h.RunnerToServerMsg.parse(n)}function ag(n){return h.ServerToRunnerMsg.parse(n)}h.DEFAULT_PLAN_PROMPT_TEMPLATE=`You are a senior engineer asked to assess a Jira ticket. You have read-only access to the repository - do not attempt to modify anything.
|
|
23
|
+
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(s=>t.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function _l(n){return n.map(e=>{if(!e.startsWith("--inspect"))return e;let t,r="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]:r=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],r=i[3],s=i[4]),t&&s!=="0"?`${t}=${r}:${parseInt(s)+1}`:e})}kl.Command=To});var Il=ne(He=>{var{Argument:Tl}=Gs(),{Command:xo}=Sl(),{CommanderError:vf,InvalidArgumentError:xl}=hs(),{Help:bf}=go(),{Option:Cl}=wo();He.program=new xo;He.createCommand=n=>new xo(n);He.createOption=(n,e)=>new Cl(n,e);He.createArgument=(n,e)=>new Tl(n,e);He.Command=xo;He.Option=Cl;He.Argument=Tl;He.Help=bf;He.CommanderError=vf;He.InvalidArgumentError=xl;He.InvalidOptionArgumentError=xl});var ys=ne(ce=>{"use strict";Object.defineProperty(ce,"__esModule",{value:!0});ce.getParsedType=ce.ZodParsedType=ce.objectUtil=ce.util=void 0;var jo;(function(n){n.assertEqual=s=>{};function e(s){}n.assertIs=e;function t(s){throw new Error}n.assertNever=t,n.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},n.getValidEnumValues=s=>{let i=n.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),o={};for(let a of i)o[a]=s[a];return n.objectValues(o)},n.objectValues=s=>n.objectKeys(s).map(function(i){return s[i]}),n.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},n.find=(s,i)=>{for(let o of s)if(i(o))return o},n.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}n.joinValues=r,n.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(jo||(ce.util=jo={}));var Yl;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(Yl||(ce.objectUtil=Yl={}));ce.ZodParsedType=jo.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var zp=n=>{switch(typeof n){case"undefined":return ce.ZodParsedType.undefined;case"string":return ce.ZodParsedType.string;case"number":return Number.isNaN(n)?ce.ZodParsedType.nan:ce.ZodParsedType.number;case"boolean":return ce.ZodParsedType.boolean;case"function":return ce.ZodParsedType.function;case"bigint":return ce.ZodParsedType.bigint;case"symbol":return ce.ZodParsedType.symbol;case"object":return Array.isArray(n)?ce.ZodParsedType.array:n===null?ce.ZodParsedType.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?ce.ZodParsedType.promise:typeof Map<"u"&&n instanceof Map?ce.ZodParsedType.map:typeof Set<"u"&&n instanceof Set?ce.ZodParsedType.set:typeof Date<"u"&&n instanceof Date?ce.ZodParsedType.date:ce.ZodParsedType.object;default:return ce.ZodParsedType.unknown}};ce.getParsedType=zp});var ai=ne(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.ZodError=Xt.quotelessJson=Xt.ZodIssueCode=void 0;var Xl=ys();Xt.ZodIssueCode=Xl.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 Dp=n=>JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:");Xt.quotelessJson=Dp;var vs=class n extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let 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},r={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)r._errors.push(t(o));else{let a=r,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),r}static assert(e){if(!(e instanceof n))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Xl.util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},r=[];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 r.push(e(s));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}};Xt.ZodError=vs;vs.create=n=>new vs(n)});var No=ne(Oo=>{"use strict";Object.defineProperty(Oo,"__esModule",{value:!0});var Ce=ai(),On=ys(),Lp=(n,e)=>{let t;switch(n.code){case Ce.ZodIssueCode.invalid_type:n.received===On.ZodParsedType.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case Ce.ZodIssueCode.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,On.util.jsonStringifyReplacer)}`;break;case Ce.ZodIssueCode.unrecognized_keys:t=`Unrecognized key(s) in object: ${On.util.joinValues(n.keys,", ")}`;break;case Ce.ZodIssueCode.invalid_union:t="Invalid input";break;case Ce.ZodIssueCode.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${On.util.joinValues(n.options)}`;break;case Ce.ZodIssueCode.invalid_enum_value:t=`Invalid enum value. Expected ${On.util.joinValues(n.options)}, received '${n.received}'`;break;case Ce.ZodIssueCode.invalid_arguments:t="Invalid function arguments";break;case Ce.ZodIssueCode.invalid_return_type:t="Invalid function return type";break;case Ce.ZodIssueCode.invalid_date:t="Invalid date";break;case Ce.ZodIssueCode.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:On.util.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case Ce.ZodIssueCode.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case Ce.ZodIssueCode.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case Ce.ZodIssueCode.custom:t="Invalid input";break;case Ce.ZodIssueCode.invalid_intersection_types:t="Intersection results could not be merged";break;case Ce.ZodIssueCode.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case Ce.ZodIssueCode.not_finite:t="Number must be finite";break;default:t=e.defaultError,On.util.assertNever(n)}return{message:t}};Oo.default=Lp});var li=ne(Qt=>{"use strict";var Up=Qt&&Qt.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(Qt,"__esModule",{value:!0});Qt.defaultErrorMap=void 0;Qt.setErrorMap=qp;Qt.getErrorMap=Fp;var Ql=Up(No());Qt.defaultErrorMap=Ql.default;var eu=Ql.default;function qp(n){eu=n}function Fp(){return eu}});var zo=ne(ie=>{"use strict";var Bp=ie&&ie.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(ie,"__esModule",{value:!0});ie.isAsync=ie.isValid=ie.isDirty=ie.isAborted=ie.OK=ie.DIRTY=ie.INVALID=ie.ParseStatus=ie.EMPTY_PATH=ie.makeIssue=void 0;ie.addIssueToContext=Hp;var Kp=li(),tu=Bp(No()),Zp=n=>{let{data:e,path:t,errorMaps:r,issueData:s}=n,i=[...t,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let a="",u=r.filter(c=>!!c).slice().reverse();for(let c of u)a=c(o,{data:e,defaultError:a}).message;return{...s,path:i,message:a}};ie.makeIssue=Zp;ie.EMPTY_PATH=[];function Hp(n,e){let t=(0,Kp.getErrorMap)(),r=(0,ie.makeIssue)({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===tu.default?void 0:tu.default].filter(s=>!!s)});n.common.issues.push(r)}var Mo=class n{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let r=[];for(let s of t){if(s.status==="aborted")return ie.INVALID;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let s of t){let i=await s.key,o=await s.value;r.push({key:i,value:o})}return n.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let s of t){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return ie.INVALID;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(r[i.value]=o.value)}return{status:e.value,value:r}}};ie.ParseStatus=Mo;ie.INVALID=Object.freeze({status:"aborted"});var Gp=n=>({status:"dirty",value:n});ie.DIRTY=Gp;var Vp=n=>({status:"valid",value:n});ie.OK=Vp;var Wp=n=>n.status==="aborted";ie.isAborted=Wp;var Jp=n=>n.status==="dirty";ie.isDirty=Jp;var Yp=n=>n.status==="valid";ie.isValid=Yp;var Xp=n=>typeof Promise<"u"&&n instanceof Promise;ie.isAsync=Xp});var ru=ne(nu=>{"use strict";Object.defineProperty(nu,"__esModule",{value:!0})});var iu=ne(ui=>{"use strict";Object.defineProperty(ui,"__esModule",{value:!0});ui.errorUtil=void 0;var su;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e?.message})(su||(ui.errorUtil=su={}))});var yu=ne(k=>{"use strict";Object.defineProperty(k,"__esModule",{value:!0});k.discriminatedUnion=k.date=k.boolean=k.bigint=k.array=k.any=k.coerce=k.ZodFirstPartyTypeKind=k.late=k.ZodSchema=k.Schema=k.ZodReadonly=k.ZodPipeline=k.ZodBranded=k.BRAND=k.ZodNaN=k.ZodCatch=k.ZodDefault=k.ZodNullable=k.ZodOptional=k.ZodTransformer=k.ZodEffects=k.ZodPromise=k.ZodNativeEnum=k.ZodEnum=k.ZodLiteral=k.ZodLazy=k.ZodFunction=k.ZodSet=k.ZodMap=k.ZodRecord=k.ZodTuple=k.ZodIntersection=k.ZodDiscriminatedUnion=k.ZodUnion=k.ZodObject=k.ZodArray=k.ZodVoid=k.ZodNever=k.ZodUnknown=k.ZodAny=k.ZodNull=k.ZodUndefined=k.ZodSymbol=k.ZodDate=k.ZodBoolean=k.ZodBigInt=k.ZodNumber=k.ZodString=k.ZodType=void 0;k.NEVER=k.void=k.unknown=k.union=k.undefined=k.tuple=k.transformer=k.symbol=k.string=k.strictObject=k.set=k.record=k.promise=k.preprocess=k.pipeline=k.ostring=k.optional=k.onumber=k.oboolean=k.object=k.number=k.nullable=k.null=k.never=k.nativeEnum=k.nan=k.map=k.literal=k.lazy=k.intersection=k.instanceof=k.function=k.enum=k.effect=void 0;k.datetimeRegex=cu;k.custom=hu;var A=ai(),ci=li(),q=iu(),S=zo(),$=ys(),Ye=class{constructor(e,t,r,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},ou=(n,e)=>{if((0,S.isValid)(e))return{success:!0,data:e.value};if(!n.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 A.ZodError(n.common.issues);return this._error=t,this._error}}};function Y(n){if(!n)return{};let{errorMap:e,invalid_type_error:t,required_error:r,description:s}=n;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,a)=>{let{message:u}=n;return o.code==="invalid_enum_value"?{message:u??a.defaultError}:typeof a.data>"u"?{message:u??r??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:u??t??a.defaultError}},description:s}}var X=class{get description(){return this._def.description}_getType(e){return(0,$.getParsedType)(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:(0,$.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new S.ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:(0,$.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if((0,S.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 r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,$.getParsedType)(e)},s=this._parseSync({data:e,path:r.path,parent:r});return ou(r,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,$.getParsedType)(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return(0,S.isValid)(r)?{value:r.value}:{issues:t.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(r=>(0,S.isValid)(r)?{value:r.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,$.getParsedType)(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await((0,S.isAsync)(s)?s:Promise.resolve(s));return ou(r,i)}refine(e,t){let r=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:A.ZodIssueCode.custom,...r(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((r,s)=>e(r)?!0:(s.addIssue(typeof t=="function"?t(r,s):t),!1))}_refinement(e){return new Ue({schema:this,typeName:H.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 Je.create(this,this._def)}nullable(){return gt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ot.create(this)}promise(){return nn.create(this,this._def)}or(e){return qn.create([this,e],this._def)}and(e){return Fn.create(this,e,this._def)}transform(e){return new Ue({...Y(this._def),schema:this,typeName:H.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Gn({...Y(this._def),innerType:this,defaultValue:t,typeName:H.ZodDefault})}brand(){return new bs({typeName:H.ZodBranded,type:this,...Y(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Vn({...Y(this._def),innerType:this,catchValue:t,typeName:H.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ws.create(this,e)}readonly(){return Wn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};k.ZodType=X;k.Schema=X;k.ZodSchema=X;var Qp=/^c[^\s-]{8,}$/i,em=/^[0-9a-z]+$/,tm=/^[0-9A-HJKMNP-TV-Z]{26}$/i,nm=/^[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,rm=/^[a-z0-9_-]{21}$/i,sm=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,im=/^[-+]?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)?)??$/,om=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,am="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Do,lm=/^(?:(?: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])$/,um=/^(?:(?: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])$/,cm=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,dm=/^(([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])$/,hm=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,fm=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,lu="((\\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])))",pm=new RegExp(`^${lu}$`);function uu(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);let t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function mm(n){return new RegExp(`^${uu(n)}$`)}function cu(n){let e=`${lu}T${uu(n)}`,t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function gm(n,e){return!!((e==="v4"||!e)&&lm.test(n)||(e==="v6"||!e)&&cm.test(n))}function ym(n,e){if(!sm.test(n))return!1;try{let[t]=n.split(".");if(!t)return!1;let r=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function vm(n,e){return!!((e==="v4"||!e)&&um.test(n)||(e==="v6"||!e)&&dm.test(n))}var en=class n extends X{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==$.ZodParsedType.string){let i=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(i,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.string,received:i.parsedType}),S.INVALID}let r=new S.ParseStatus,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:A.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:A.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(s=this._getOrReturnCtx(e,s),o?(0,S.addIssueToContext)(s,{code:A.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&(0,S.addIssueToContext)(s,{code:A.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")om.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"email",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Do||(Do=new RegExp(am,"u")),Do.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"emoji",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")nm.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"uuid",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")rm.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"nanoid",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")Qp.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"cuid",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")em.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"cuid2",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")tm.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"ulid",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"url",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"regex",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:A.ZodIssueCode.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:A.ZodIssueCode.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:A.ZodIssueCode.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?cu(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:A.ZodIssueCode.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?pm.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:A.ZodIssueCode.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?mm(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:A.ZodIssueCode.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?im.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"duration",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?gm(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"ip",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?ym(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"jwt",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?vm(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"cidr",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?hm.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"base64",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?fm.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"base64url",code:A.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):$.util.assertNever(i);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(s=>e.test(s),{validation:t,code:A.ZodIssueCode.invalid_string,...q.errorUtil.errToObj(r)})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...q.errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...q.errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...q.errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...q.errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...q.errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...q.errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...q.errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...q.errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...q.errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...q.errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...q.errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...q.errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...q.errorUtil.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...q.errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...q.errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...q.errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...q.errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...q.errorUtil.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...q.errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...q.errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...q.errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...q.errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...q.errorUtil.errToObj(t)})}nonempty(e){return this.min(1,q.errorUtil.errToObj(e))}trim(){return new n({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new n({...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}};k.ZodString=en;en.create=n=>new en({checks:[],typeName:H.ZodString,coerce:n?.coerce??!1,...Y(n)});function bm(n,e){let t=(n.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=t>r?t:r,i=Number.parseInt(n.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var Nn=class n extends X{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==$.ZodParsedType.number){let i=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(i,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.number,received:i.parsedType}),S.INVALID}let r,s=new S.ParseStatus;for(let i of this._def.checks)i.kind==="int"?$.util.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?bm(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.not_finite,message:i.message}),s.dirty()):$.util.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,q.errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,q.errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,q.errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,q.errorUtil.toString(t))}setLimit(e,t,r,s){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:q.errorUtil.toString(s)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:q.errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:q.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:q.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:q.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:q.errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:q.errorUtil.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:q.errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:q.errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:q.errorUtil.toString(e)})}get minValue(){let e=null;for(let 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"&&$.util.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(t===null||r.value>t)&&(t=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}};k.ZodNumber=Nn;Nn.create=n=>new Nn({checks:[],typeName:H.ZodNumber,coerce:n?.coerce||!1,...Y(n)});var Mn=class n extends X{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==$.ZodParsedType.bigint)return this._getInvalidInput(e);let r,s=new S.ParseStatus;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):$.util.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(t,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.bigint,received:t.parsedType}),S.INVALID}gte(e,t){return this.setLimit("min",e,!0,q.errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,q.errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,q.errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,q.errorUtil.toString(t))}setLimit(e,t,r,s){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:q.errorUtil.toString(s)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:q.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:q.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:q.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:q.errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:q.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}};k.ZodBigInt=Mn;Mn.create=n=>new Mn({checks:[],typeName:H.ZodBigInt,coerce:n?.coerce??!1,...Y(n)});var zn=class extends X{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==$.ZodParsedType.boolean){let r=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.boolean,received:r.parsedType}),S.INVALID}return(0,S.OK)(e.data)}};k.ZodBoolean=zn;zn.create=n=>new zn({typeName:H.ZodBoolean,coerce:n?.coerce||!1,...Y(n)});var Dn=class n extends X{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==$.ZodParsedType.date){let i=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(i,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.date,received:i.parsedType}),S.INVALID}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(i,{code:A.ZodIssueCode.invalid_date}),S.INVALID}let r=new S.ParseStatus,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:A.ZodIssueCode.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:A.ZodIssueCode.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):$.util.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:q.errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:q.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}};k.ZodDate=Dn;Dn.create=n=>new Dn({checks:[],coerce:n?.coerce||!1,typeName:H.ZodDate,...Y(n)});var Mr=class extends X{_parse(e){if(this._getType(e)!==$.ZodParsedType.symbol){let r=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.symbol,received:r.parsedType}),S.INVALID}return(0,S.OK)(e.data)}};k.ZodSymbol=Mr;Mr.create=n=>new Mr({typeName:H.ZodSymbol,...Y(n)});var Ln=class extends X{_parse(e){if(this._getType(e)!==$.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.undefined,received:r.parsedType}),S.INVALID}return(0,S.OK)(e.data)}};k.ZodUndefined=Ln;Ln.create=n=>new Ln({typeName:H.ZodUndefined,...Y(n)});var Un=class extends X{_parse(e){if(this._getType(e)!==$.ZodParsedType.null){let r=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.null,received:r.parsedType}),S.INVALID}return(0,S.OK)(e.data)}};k.ZodNull=Un;Un.create=n=>new Un({typeName:H.ZodNull,...Y(n)});var tn=class extends X{constructor(){super(...arguments),this._any=!0}_parse(e){return(0,S.OK)(e.data)}};k.ZodAny=tn;tn.create=n=>new tn({typeName:H.ZodAny,...Y(n)});var jt=class extends X{constructor(){super(...arguments),this._unknown=!0}_parse(e){return(0,S.OK)(e.data)}};k.ZodUnknown=jt;jt.create=n=>new jt({typeName:H.ZodUnknown,...Y(n)});var st=class extends X{_parse(e){let t=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(t,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.never,received:t.parsedType}),S.INVALID}};k.ZodNever=st;st.create=n=>new st({typeName:H.ZodNever,...Y(n)});var zr=class extends X{_parse(e){if(this._getType(e)!==$.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.void,received:r.parsedType}),S.INVALID}return(0,S.OK)(e.data)}};k.ZodVoid=zr;zr.create=n=>new zr({typeName:H.ZodVoid,...Y(n)});var Ot=class n extends X{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==$.ZodParsedType.array)return(0,S.addIssueToContext)(t,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.array,received:t.parsedType}),S.INVALID;if(s.exactLength!==null){let o=t.data.length>s.exactLength.value,a=t.data.length<s.exactLength.value;(o||a)&&((0,S.addIssueToContext)(t,{code:o?A.ZodIssueCode.too_big:A.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}),r.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&((0,S.addIssueToContext)(t,{code:A.ZodIssueCode.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&((0,S.addIssueToContext)(t,{code:A.ZodIssueCode.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>s.type._parseAsync(new Ye(t,o,t.path,a)))).then(o=>S.ParseStatus.mergeArray(r,o));let i=[...t.data].map((o,a)=>s.type._parseSync(new Ye(t,o,t.path,a)));return S.ParseStatus.mergeArray(r,i)}get element(){return this._def.type}min(e,t){return new n({...this._def,minLength:{value:e,message:q.errorUtil.toString(t)}})}max(e,t){return new n({...this._def,maxLength:{value:e,message:q.errorUtil.toString(t)}})}length(e,t){return new n({...this._def,exactLength:{value:e,message:q.errorUtil.toString(t)}})}nonempty(e){return this.min(1,e)}};k.ZodArray=Ot;Ot.create=(n,e)=>new Ot({type:n,minLength:null,maxLength:null,exactLength:null,typeName:H.ZodArray,...Y(e)});function Nr(n){if(n instanceof Ne){let e={};for(let t in n.shape){let r=n.shape[t];e[t]=Je.create(Nr(r))}return new Ne({...n._def,shape:()=>e})}else return n instanceof Ot?new Ot({...n._def,type:Nr(n.element)}):n instanceof Je?Je.create(Nr(n.unwrap())):n instanceof gt?gt.create(Nr(n.unwrap())):n instanceof mt?mt.create(n.items.map(e=>Nr(e))):n}var Ne=class n extends X{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=$.util.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==$.ZodParsedType.object){let c=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(c,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.object,received:c.parsedType}),S.INVALID}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof st&&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 Ye(s,p,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof st){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,S.addIssueToContext)(s,{code:A.ZodIssueCode.unrecognized_keys,keys:a}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let f of a){let p=s.data[f];u.push({key:{status:"valid",value:f},value:c._parse(new Ye(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=>S.ParseStatus.mergeObjectSync(r,c)):S.ParseStatus.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(e){return q.errorUtil.errToObj,new n({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{let s=this._def.errorMap?.(t,r).message??r.defaultError;return t.code==="unrecognized_keys"?{message:q.errorUtil.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new n({...this._def,unknownKeys:"strip"})}passthrough(){return new n({...this._def,unknownKeys:"passthrough"})}extend(e){return new n({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new n({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:H.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new n({...this._def,catchall:e})}pick(e){let t={};for(let r of $.util.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new n({...this._def,shape:()=>t})}omit(e){let t={};for(let r of $.util.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new n({...this._def,shape:()=>t})}deepPartial(){return Nr(this)}partial(e){let t={};for(let r of $.util.objectKeys(this.shape)){let s=this.shape[r];e&&!e[r]?t[r]=s:t[r]=s.optional()}return new n({...this._def,shape:()=>t})}required(e){let t={};for(let r of $.util.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Je;)i=i._def.innerType;t[r]=i}return new n({...this._def,shape:()=>t})}keyof(){return du($.util.objectKeys(this.shape))}};k.ZodObject=Ne;Ne.create=(n,e)=>new Ne({shape:()=>n,unknownKeys:"strip",catchall:st.create(),typeName:H.ZodObject,...Y(e)});Ne.strictCreate=(n,e)=>new Ne({shape:()=>n,unknownKeys:"strict",catchall:st.create(),typeName:H.ZodObject,...Y(e)});Ne.lazycreate=(n,e)=>new Ne({shape:n,unknownKeys:"strip",catchall:st.create(),typeName:H.ZodObject,...Y(e)});var qn=class extends X{_parse(e){let{ctx:t}=this._processInputParams(e),r=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 A.ZodError(a.ctx.common.issues));return(0,S.addIssueToContext)(t,{code:A.ZodIssueCode.invalid_union,unionErrors:o}),S.INVALID}if(t.common.async)return Promise.all(r.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 r){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 A.ZodError(u));return(0,S.addIssueToContext)(t,{code:A.ZodIssueCode.invalid_union,unionErrors:a}),S.INVALID}}get options(){return this._def.options}};k.ZodUnion=qn;qn.create=(n,e)=>new qn({options:n,typeName:H.ZodUnion,...Y(e)});var Pt=n=>n instanceof Bn?Pt(n.schema):n instanceof Ue?Pt(n.innerType()):n instanceof Kn?[n.value]:n instanceof Zn?n.options:n instanceof Hn?$.util.objectValues(n.enum):n instanceof Gn?Pt(n._def.innerType):n instanceof Ln?[void 0]:n instanceof Un?[null]:n instanceof Je?[void 0,...Pt(n.unwrap())]:n instanceof gt?[null,...Pt(n.unwrap())]:n instanceof bs||n instanceof Wn?Pt(n.unwrap()):n instanceof Vn?Pt(n._def.innerType):[],di=class n extends X{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==$.ZodParsedType.object)return(0,S.addIssueToContext)(t,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.object,received:t.parsedType}),S.INVALID;let r=this.discriminator,s=t.data[r],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,S.addIssueToContext)(t,{code:A.ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),S.INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){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 n({typeName:H.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...Y(r)})}};k.ZodDiscriminatedUnion=di;function Lo(n,e){let t=(0,$.getParsedType)(n),r=(0,$.getParsedType)(e);if(n===e)return{valid:!0,data:n};if(t===$.ZodParsedType.object&&r===$.ZodParsedType.object){let s=$.util.objectKeys(e),i=$.util.objectKeys(n).filter(a=>s.indexOf(a)!==-1),o={...n,...e};for(let a of i){let u=Lo(n[a],e[a]);if(!u.valid)return{valid:!1};o[a]=u.data}return{valid:!0,data:o}}else if(t===$.ZodParsedType.array&&r===$.ZodParsedType.array){if(n.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<n.length;i++){let o=n[i],a=e[i],u=Lo(o,a);if(!u.valid)return{valid:!1};s.push(u.data)}return{valid:!0,data:s}}else return t===$.ZodParsedType.date&&r===$.ZodParsedType.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}var Fn=class extends X{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),s=(i,o)=>{if((0,S.isAborted)(i)||(0,S.isAborted)(o))return S.INVALID;let a=Lo(i.value,o.value);return a.valid?(((0,S.isDirty)(i)||(0,S.isDirty)(o))&&t.dirty(),{status:t.value,value:a.data}):((0,S.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_intersection_types}),S.INVALID)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};k.ZodIntersection=Fn;Fn.create=(n,e,t)=>new Fn({left:n,right:e,typeName:H.ZodIntersection,...Y(t)});var mt=class n extends X{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==$.ZodParsedType.array)return(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.array,received:r.parsedType}),S.INVALID;if(r.data.length<this._def.items.length)return(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),S.INVALID;!this._def.rest&&r.data.length>this._def.items.length&&((0,S.addIssueToContext)(r,{code:A.ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...r.data].map((o,a)=>{let u=this._def.items[a]||this._def.rest;return u?u._parse(new Ye(r,o,r.path,a)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>S.ParseStatus.mergeArray(t,o)):S.ParseStatus.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new n({...this._def,rest:e})}};k.ZodTuple=mt;mt.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new mt({items:n,typeName:H.ZodTuple,rest:null,...Y(e)})};var hi=class n extends X{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==$.ZodParsedType.object)return(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.object,received:r.parsedType}),S.INVALID;let s=[],i=this._def.keyType,o=this._def.valueType;for(let a in r.data)s.push({key:i._parse(new Ye(r,a,r.path,a)),value:o._parse(new Ye(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?S.ParseStatus.mergeObjectAsync(t,s):S.ParseStatus.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,r){return t instanceof X?new n({keyType:e,valueType:t,typeName:H.ZodRecord,...Y(r)}):new n({keyType:en.create(),valueType:e,typeName:H.ZodRecord,...Y(t)})}};k.ZodRecord=hi;var Dr=class extends X{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==$.ZodParsedType.map)return(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.map,received:r.parsedType}),S.INVALID;let s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([a,u],c)=>({key:s._parse(new Ye(r,a,r.path,[c,"key"])),value:i._parse(new Ye(r,u,r.path,[c,"value"]))}));if(r.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 S.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 S.INVALID;(c.status==="dirty"||f.status==="dirty")&&t.dirty(),a.set(c.value,f.value)}return{status:t.value,value:a}}}};k.ZodMap=Dr;Dr.create=(n,e,t)=>new Dr({valueType:e,keyType:n,typeName:H.ZodMap,...Y(t)});var Lr=class n extends X{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==$.ZodParsedType.set)return(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.set,received:r.parsedType}),S.INVALID;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&((0,S.addIssueToContext)(r,{code:A.ZodIssueCode.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&((0,S.addIssueToContext)(r,{code:A.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 S.INVALID;f.status==="dirty"&&t.dirty(),c.add(f.value)}return{status:t.value,value:c}}let a=[...r.data.values()].map((u,c)=>i._parse(new Ye(r,u,r.path,c)));return r.common.async?Promise.all(a).then(u=>o(u)):o(a)}min(e,t){return new n({...this._def,minSize:{value:e,message:q.errorUtil.toString(t)}})}max(e,t){return new n({...this._def,maxSize:{value:e,message:q.errorUtil.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};k.ZodSet=Lr;Lr.create=(n,e)=>new Lr({valueType:n,minSize:null,maxSize:null,typeName:H.ZodSet,...Y(e)});var fi=class n extends X{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==$.ZodParsedType.function)return(0,S.addIssueToContext)(t,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.function,received:t.parsedType}),S.INVALID;function r(a,u){return(0,S.makeIssue)({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,(0,ci.getErrorMap)(),ci.defaultErrorMap].filter(c=>!!c),issueData:{code:A.ZodIssueCode.invalid_arguments,argumentsError:u}})}function s(a,u){return(0,S.makeIssue)({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,(0,ci.getErrorMap)(),ci.defaultErrorMap].filter(c=>!!c),issueData:{code:A.ZodIssueCode.invalid_return_type,returnTypeError:u}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof nn){let a=this;return(0,S.OK)(async function(...u){let c=new A.ZodError([]),f=await a._def.args.parseAsync(u,i).catch(b=>{throw c.addIssue(r(u,b)),c}),p=await Reflect.apply(o,this,f);return await a._def.returns._def.type.parseAsync(p,i).catch(b=>{throw c.addIssue(s(p,b)),c})})}else{let a=this;return(0,S.OK)(function(...u){let c=a._def.args.safeParse(u,i);if(!c.success)throw new A.ZodError([r(u,c.error)]);let f=Reflect.apply(o,this,c.data),p=a._def.returns.safeParse(f,i);if(!p.success)throw new A.ZodError([s(f,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new n({...this._def,args:mt.create(e).rest(jt.create())})}returns(e){return new n({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new n({args:e||mt.create([]).rest(jt.create()),returns:t||jt.create(),typeName:H.ZodFunction,...Y(r)})}};k.ZodFunction=fi;var Bn=class extends X{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})}};k.ZodLazy=Bn;Bn.create=(n,e)=>new Bn({getter:n,typeName:H.ZodLazy,...Y(e)});var Kn=class extends X{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(t,{received:t.data,code:A.ZodIssueCode.invalid_literal,expected:this._def.value}),S.INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}};k.ZodLiteral=Kn;Kn.create=(n,e)=>new Kn({value:n,typeName:H.ZodLiteral,...Y(e)});function du(n,e){return new Zn({values:n,typeName:H.ZodEnum,...Y(e)})}var Zn=class n extends X{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),r=this._def.values;return(0,S.addIssueToContext)(t,{expected:$.util.joinValues(r),received:t.parsedType,code:A.ZodIssueCode.invalid_type}),S.INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return(0,S.addIssueToContext)(t,{received:t.data,code:A.ZodIssueCode.invalid_enum_value,options:r}),S.INVALID}return(0,S.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 n.create(e,{...this._def,...t})}exclude(e,t=this._def){return n.create(this.options.filter(r=>!e.includes(r)),{...this._def,...t})}};k.ZodEnum=Zn;Zn.create=du;var Hn=class extends X{_parse(e){let t=$.util.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==$.ZodParsedType.string&&r.parsedType!==$.ZodParsedType.number){let s=$.util.objectValues(t);return(0,S.addIssueToContext)(r,{expected:$.util.joinValues(s),received:r.parsedType,code:A.ZodIssueCode.invalid_type}),S.INVALID}if(this._cache||(this._cache=new Set($.util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=$.util.objectValues(t);return(0,S.addIssueToContext)(r,{received:r.data,code:A.ZodIssueCode.invalid_enum_value,options:s}),S.INVALID}return(0,S.OK)(e.data)}get enum(){return this._def.values}};k.ZodNativeEnum=Hn;Hn.create=(n,e)=>new Hn({values:n,typeName:H.ZodNativeEnum,...Y(e)});var nn=class extends X{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==$.ZodParsedType.promise&&t.common.async===!1)return(0,S.addIssueToContext)(t,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.promise,received:t.parsedType}),S.INVALID;let r=t.parsedType===$.ZodParsedType.promise?t.data:Promise.resolve(t.data);return(0,S.OK)(r.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};k.ZodPromise=nn;nn.create=(n,e)=>new nn({type:n,typeName:H.ZodPromise,...Y(e)});var Ue=class extends X{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===H.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{(0,S.addIssueToContext)(r,o),o.fatal?t.abort():t.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(r.data,i);if(r.common.async)return Promise.resolve(o).then(async a=>{if(t.value==="aborted")return S.INVALID;let u=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return u.status==="aborted"?S.INVALID:u.status==="dirty"||t.value==="dirty"?(0,S.DIRTY)(u.value):u});{if(t.value==="aborted")return S.INVALID;let a=this._def.schema._parseSync({data:o,path:r.path,parent:r});return a.status==="aborted"?S.INVALID:a.status==="dirty"||t.value==="dirty"?(0,S.DIRTY)(a.value):a}}if(s.type==="refinement"){let o=a=>{let u=s.refinement(a,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?S.INVALID:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?S.INVALID:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.value,value:a.value}))))}if(s.type==="transform")if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!(0,S.isValid)(o))return S.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:r.data,path:r.path,parent:r}).then(o=>(0,S.isValid)(o)?Promise.resolve(s.transform(o.value,i)).then(a=>({status:t.value,value:a})):S.INVALID);$.util.assertNever(s)}};k.ZodEffects=Ue;k.ZodTransformer=Ue;Ue.create=(n,e,t)=>new Ue({schema:n,typeName:H.ZodEffects,effect:e,...Y(t)});Ue.createWithPreprocess=(n,e,t)=>new Ue({schema:e,effect:{type:"preprocess",transform:n},typeName:H.ZodEffects,...Y(t)});var Je=class extends X{_parse(e){return this._getType(e)===$.ZodParsedType.undefined?(0,S.OK)(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};k.ZodOptional=Je;Je.create=(n,e)=>new Je({innerType:n,typeName:H.ZodOptional,...Y(e)});var gt=class extends X{_parse(e){return this._getType(e)===$.ZodParsedType.null?(0,S.OK)(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};k.ZodNullable=gt;gt.create=(n,e)=>new gt({innerType:n,typeName:H.ZodNullable,...Y(e)});var Gn=class extends X{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return t.parsedType===$.ZodParsedType.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};k.ZodDefault=Gn;Gn.create=(n,e)=>new Gn({innerType:n,typeName:H.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Y(e)});var Vn=class extends X{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return(0,S.isAsync)(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new A.ZodError(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new A.ZodError(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};k.ZodCatch=Vn;Vn.create=(n,e)=>new Vn({innerType:n,typeName:H.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Y(e)});var Ur=class extends X{_parse(e){if(this._getType(e)!==$.ZodParsedType.nan){let r=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(r,{code:A.ZodIssueCode.invalid_type,expected:$.ZodParsedType.nan,received:r.parsedType}),S.INVALID}return{status:"valid",value:e.data}}};k.ZodNaN=Ur;Ur.create=n=>new Ur({typeName:H.ZodNaN,...Y(n)});k.BRAND=Symbol("zod_brand");var bs=class extends X{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}};k.ZodBranded=bs;var ws=class n extends X{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?S.INVALID:i.status==="dirty"?(t.dirty(),(0,S.DIRTY)(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?S.INVALID:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,t){return new n({in:e,out:t,typeName:H.ZodPipeline})}};k.ZodPipeline=ws;var Wn=class extends X{_parse(e){let t=this._def.innerType._parse(e),r=s=>((0,S.isValid)(s)&&(s.value=Object.freeze(s.value)),s);return(0,S.isAsync)(t)?t.then(s=>r(s)):r(t)}unwrap(){return this._def.innerType}};k.ZodReadonly=Wn;Wn.create=(n,e)=>new Wn({innerType:n,typeName:H.ZodReadonly,...Y(e)});function au(n,e){let t=typeof n=="function"?n(e):typeof n=="string"?{message:n}:n;return typeof t=="string"?{message:t}:t}function hu(n,e={},t){return n?tn.create().superRefine((r,s)=>{let i=n(r);if(i instanceof Promise)return i.then(o=>{if(!o){let a=au(e,r),u=a.fatal??t??!0;s.addIssue({code:"custom",...a,fatal:u})}});if(!i){let o=au(e,r),a=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:a})}}):tn.create()}k.late={object:Ne.lazycreate};var H;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(H||(k.ZodFirstPartyTypeKind=H={}));var wm=(n,e={message:`Input not instance of ${n.name}`})=>hu(t=>t instanceof n,e);k.instanceof=wm;var fu=en.create;k.string=fu;var pu=Nn.create;k.number=pu;var _m=Ur.create;k.nan=_m;var km=Mn.create;k.bigint=km;var mu=zn.create;k.boolean=mu;var Sm=Dn.create;k.date=Sm;var Tm=Mr.create;k.symbol=Tm;var xm=Ln.create;k.undefined=xm;var Cm=Un.create;k.null=Cm;var Im=tn.create;k.any=Im;var Rm=jt.create;k.unknown=Rm;var Em=st.create;k.never=Em;var Am=zr.create;k.void=Am;var $m=Ot.create;k.array=$m;var Pm=Ne.create;k.object=Pm;var jm=Ne.strictCreate;k.strictObject=jm;var Om=qn.create;k.union=Om;var Nm=di.create;k.discriminatedUnion=Nm;var Mm=Fn.create;k.intersection=Mm;var zm=mt.create;k.tuple=zm;var Dm=hi.create;k.record=Dm;var Lm=Dr.create;k.map=Lm;var Um=Lr.create;k.set=Um;var qm=fi.create;k.function=qm;var Fm=Bn.create;k.lazy=Fm;var Bm=Kn.create;k.literal=Bm;var Km=Zn.create;k.enum=Km;var Zm=Hn.create;k.nativeEnum=Zm;var Hm=nn.create;k.promise=Hm;var gu=Ue.create;k.effect=gu;k.transformer=gu;var Gm=Je.create;k.optional=Gm;var Vm=gt.create;k.nullable=Vm;var Wm=Ue.createWithPreprocess;k.preprocess=Wm;var Jm=ws.create;k.pipeline=Jm;var Ym=()=>fu().optional();k.ostring=Ym;var Xm=()=>pu().optional();k.onumber=Xm;var Qm=()=>mu().optional();k.oboolean=Qm;k.coerce={string:(n=>en.create({...n,coerce:!0})),number:(n=>Nn.create({...n,coerce:!0})),boolean:(n=>zn.create({...n,coerce:!0})),bigint:(n=>Mn.create({...n,coerce:!0})),date:(n=>Dn.create({...n,coerce:!0}))};k.NEVER=S.INVALID});var Uo=ne(Xe=>{"use strict";var eg=Xe&&Xe.__createBinding||(Object.create?(function(n,e,t,r){r===void 0&&(r=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(n,r,s)}):(function(n,e,t,r){r===void 0&&(r=t),n[r]=e[t]})),qr=Xe&&Xe.__exportStar||function(n,e){for(var t in n)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&eg(e,n,t)};Object.defineProperty(Xe,"__esModule",{value:!0});qr(li(),Xe);qr(zo(),Xe);qr(ru(),Xe);qr(ys(),Xe);qr(yu(),Xe);qr(ai(),Xe)});var wu=ne(Me=>{"use strict";var vu=Me&&Me.__createBinding||(Object.create?(function(n,e,t,r){r===void 0&&(r=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(n,r,s)}):(function(n,e,t,r){r===void 0&&(r=t),n[r]=e[t]})),tg=Me&&Me.__setModuleDefault||(Object.create?(function(n,e){Object.defineProperty(n,"default",{enumerable:!0,value:e})}):function(n,e){n.default=e}),ng=Me&&Me.__importStar||function(n){if(n&&n.__esModule)return n;var e={};if(n!=null)for(var t in n)t!=="default"&&Object.prototype.hasOwnProperty.call(n,t)&&vu(e,n,t);return tg(e,n),e},rg=Me&&Me.__exportStar||function(n,e){for(var t in n)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&vu(e,n,t)};Object.defineProperty(Me,"__esModule",{value:!0});Me.z=void 0;var bu=ng(Uo());Me.z=bu;rg(Uo(),Me);Me.default=bu});var Se=ne(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.RepoDocReadMsg=h.RepoDocsResultMsg=h.RepoDocsMsg=h.ChatLoadResultMsg=h.ChatLoadMsg=h.ChatListResultMsg=h.ChatListMsg=h.ChatUsageMsg=h.ChatStreamMsg=h.JiraUsersResultMsg=h.DeployClaimResultMsg=h.DeployClaimMsg=h.RuleDiagnoseResultMsg=h.ProjectTestResultMsg=h.RunStatusMsg=h.FailedTest=h.RunUsageMsg=h.RunLogMsg=h.RunClaimMsg=h.HeartbeatMsg=h.HelloMsg=h.RuleConfig=h.ProjectConfig=h.ActionConfig=h.DeployAction=h.EnvironmentConfig=h.PromotionMode=h.DeployStep=h.RespondAction=h.ImplementAction=h.PlanOnlyAction=h.TriggerConfig=h.StatusChangedTrigger=h.CommentKeywordTrigger=h.LabelAddedTrigger=h.ActionType=h.TriggerType=h.ACTIVE_RUN_STATUSES=h.RunStatus=h.needsInputMarkerIn=h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=h.NEEDS_INPUT_COMMENT_MARKER=h.NEEDS_INPUT_LABEL=h.NEEDS_INPUT_MARKER=h.BRANCH_DEPLOY_ISSUE_KEY=h.REQUIRED_AGENT_CAPABILITIES=h.DEFAULT_AGENT_ID=h.REGISTERED_AGENTS=h.PROTOCOL_VERSION=h.GITHUB_TOKEN_PERMISSIONS=void 0;h.RunnerUpdateMsg=h.RepoDocSaveResultMsg=h.RepoDocSaveMsg=h.SetupClaudeMdSaveResultMsg=h.SetupClaudeMdSaveMsg=h.SetupClaudeMdGenerateResultMsg=h.SetupClaudeMdGenerateMsg=h.SetupStatusResultMsg=h.SetupStatusMsg=h.DeploySuggestResultMsg=h.EnvPreflightResultMsg=h.EnvPreflightMsg=h.ChatCreateTicketResultMsg=h.ChatCreateTicketMsg=h.ChatTurnResultMsg=h.ChatTurnMsg=h.ChatFile=h.TeamCredsResultMsg=h.TeamCredsMsg=h.KnowledgeSaveResultMsg=h.KnowledgeSaveMsg=h.KnowledgeListResultMsg=h.KnowledgeFile=h.KnowledgeListMsg=h.AuditReviewResultMsg=h.AuditReviewMsg=h.AuditGetResultMsg=h.AuditGetMsg=h.AuditListResultMsg=h.AuditStatsResultMsg=h.AuditStatsMsg=h.AuditListMsg=h.AuditStartResultMsg=h.AuditStartMsg=h.AuditRecord=h.AuditFinding=h.AuditScope=h.AuditSeverity=h.KnowledgeRole=h.AuditRole=h.EpicSuggestResultMsg=h.EpicSuggestMsg=h.EpicListResultMsg=h.EpicChild=h.EpicListMsg=h.BoardTriggerResultMsg=h.BoardTriggerMsg=h.BoardFetchResultMsg=h.BoardFetchMsg=h.RepoDocReadResultMsg=void 0;h.DEFAULT_DEPLOY_SUGGEST_PROMPT_TEMPLATE=h.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE=h.DEPLOY_FIX_PROMPT_TEMPLATE=h.PROMPT_PRESETS=h.DEFAULT_RESPOND_PROMPT_TEMPLATE=h.BUGFIX_IMPLEMENT_PROMPT_TEMPLATE=h.BUG_INVESTIGATION_PROMPT_TEMPLATE=h.TECHNICAL_PLAN_PROMPT_TEMPLATE=h.MEMORY_UPDATE_PROMPT=h.DEFAULT_IMPLEMENT_PROMPT_TEMPLATE=h.WRITE_TESTS_PROMPT=h.DEFAULT_PLAN_PROMPT_TEMPLATE=h.EnrollResponse=h.EnrollRequest=h.ServerToRunnerMsg=h.JiraUsersMsg=h.DeploySuggestMsg=h.DeployFixMsg=h.DeployStartMsg=h.RunRetryPushMsg=h.RunRejectedMsg=h.RunApprovedMsg=h.RunCancelMsg=h.RuleDiagnoseMsg=h.ProjectTestMsg=h.RunClaimResultMsg=h.ConfigMsg=h.HelloAckMsg=h.RunnerToServerMsg=h.AutopilotReportMsg=h.AutopilotNextResultMsg=h.AutopilotNextMsg=h.RunnerUpdateResultMsg=h.AgentProfilesResultMsg=h.AgentProfilesMsg=h.RunPrConflictMsg=h.RunResolveConflictResultMsg=h.RunTestFixResultMsg=h.RunTestFixMsg=h.RunResolveConflictMsg=void 0;h.missingAgentCapabilities=sg;h.parseRunnerMsg=og;h.parseServerMsg=ag;var l=wu();h.GITHUB_TOKEN_PERMISSIONS={where:"github.com/settings/personal-access-tokens/new (fine-grained token)",steps:["Resource owner: the org or user that OWNS the repo - not your personal account, unless the repo is under it","Repository access: Only select repositories -> pick this repo","Contents: Read and write - pushing the agent's branch","Pull requests: Read and write - opening the PR, and merging it when you approve","Metadata: Read-only - GitHub adds this itself and will not let you remove it","Workflows: Read and write - ONLY if changes may touch .github/workflows; without it GitHub rejects those pushes"],note:"A fine-grained token covers exactly ONE resource owner, so a repo in a different org always needs its own token. A classic token with the `repo` scope also works and is simpler, but it reaches every repository you can see - prefer fine-grained."};h.PROTOCOL_VERSION="1.46";h.REGISTERED_AGENTS=[{id:"claude-code",displayName:"Claude Code",capabilities:{readOnlyJail:!0,editNoShellJail:!0,sessionResume:!0,costReporting:!0,modelSelection:!0,loginProfiles:!0},suggestedModels:["claude-fable-5","claude-opus-5","claude-sonnet-5","claude-haiku-4-5-20251001"],experimental:!1},{id:"codex",displayName:"OpenAI Codex CLI (experimental)",capabilities:{readOnlyJail:!0,editNoShellJail:!1,sessionResume:!1,costReporting:!1,modelSelection:!0,loginProfiles:!1},suggestedModels:[],experimental:!0}];h.DEFAULT_AGENT_ID="claude-code";h.REQUIRED_AGENT_CAPABILITIES={plan_only:["readOnlyJail","sessionResume"],respond:["readOnlyJail"],implement:["editNoShellJail","sessionResume"],deploy:[],chat:["readOnlyJail","sessionResume"],assist:["readOnlyJail"]};function sg(n,e){let t=h.REGISTERED_AGENTS.find(r=>r.id===n);return t?(h.REQUIRED_AGENT_CAPABILITIES[e]??[]).filter(r=>!t.capabilities[r]):null}h.BRANCH_DEPLOY_ISSUE_KEY="(branch deploy)";h.NEEDS_INPUT_MARKER="NEEDS-INPUT";h.NEEDS_INPUT_LABEL="agent-needs-input";h.NEEDS_INPUT_COMMENT_MARKER="Allwright needs your input";h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=["TicketPilot needs your input"];var ig=n=>n.includes(h.NEEDS_INPUT_COMMENT_MARKER)||h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS.some(e=>n.includes(e));h.needsInputMarkerIn=ig;h.RunStatus=l.z.enum(["queued","running","posting","awaiting_approval","needs_input","succeeded","failed","timed_out"]);h.ACTIVE_RUN_STATUSES=["queued","running","posting","awaiting_approval"];h.TriggerType=l.z.enum(["label_added","comment_keyword","status_changed"]);h.ActionType=l.z.enum(["plan_only","implement","respond","deploy"]);h.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")});h.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")});h.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")});h.TriggerConfig=l.z.discriminatedUnion("type",[h.LabelAddedTrigger,h.CommentKeywordTrigger,h.StatusChangedTrigger]);h.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(h.DEFAULT_AGENT_ID),model:l.z.string().default("")});h.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(n=>n.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(h.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"),autoMerge:l.z.boolean().default(!0)});h.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(h.DEFAULT_AGENT_ID),model:l.z.string().default("")});h.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)});h.PromotionMode=l.z.enum(["deploy_only","merge_and_deploy"]);h.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:h.PromotionMode.default("deploy_only"),ticketBranchTemplate:l.z.string().default("agent/{{issueKey}}"),steps:l.z.array(h.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("")});h.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()});h.ActionConfig=l.z.discriminatedUnion("type",[h.PlanOnlyAction,h.ImplementAction,h.RespondAction,h.DeployAction]);h.ProjectConfig=l.z.object({id:l.z.string(),name:l.z.string(),jiraProjectKey:l.z.string(),goLiveIssueKey:l.z.string().default(""),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([])});h.RuleConfig=l.z.object({id:l.z.string(),projectId:l.z.string(),name:l.z.string(),enabled:l.z.boolean(),trigger:h.TriggerConfig,action:h.ActionConfig});h.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()});h.HeartbeatMsg=l.z.object({type:l.z.literal("heartbeat"),ts:l.z.string()});h.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()});h.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)});h.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()});h.FailedTest=l.z.object({command:l.z.string().max(500),exitCode:l.z.number().int(),tail:l.z.string().max(4e3)});h.RunStatusMsg=l.z.object({type:l.z.literal("run.status"),runId:l.z.string(),status:h.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(),failedTests:l.z.array(h.FailedTest).max(20).optional(),testsPassed:l.z.number().int().nonnegative().optional(),testsTotal:l.z.number().int().nonnegative().optional(),manualSteps:l.z.array(l.z.object({command:l.z.string().max(500),why:l.z.string().max(300).default("")})).max(20).optional(),goLiveDraft:l.z.string().max(4e3).optional()});h.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("")}))});h.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)});h.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()});h.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:h.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()});h.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()});h.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)});h.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()});h.ChatListMsg=l.z.object({type:l.z.literal("chat.list"),requestId:l.z.string(),projectId:l.z.string()});h.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([])});h.ChatLoadMsg=l.z.object({type:l.z.literal("chat.load"),requestId:l.z.string(),sessionId:l.z.string()});h.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(),steps:l.z.array(l.z.string()).default([])})).default([]),error:l.z.string().optional()});h.RepoDocsMsg=l.z.object({type:l.z.literal("repo.docs"),requestId:l.z.string(),projectId:l.z.string()});h.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()});h.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)});h.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()});h.BoardFetchMsg=l.z.object({type:l.z.literal("board.fetch"),requestId:l.z.string(),projectId:l.z.string()});h.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()});h.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)});h.BoardTriggerResultMsg=l.z.object({type:l.z.literal("board.trigger.result"),requestId:l.z.string(),ok:l.z.boolean(),error:l.z.string().optional()});h.EpicListMsg=l.z.object({type:l.z.literal("epic.list"),requestId:l.z.string(),projectId:l.z.string(),epicKey:l.z.string().default("")});h.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([])});h.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(h.EpicChild).default([])});h.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("")});h.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)});h.AuditRole=l.z.enum(["security","testing","architecture"]);h.KnowledgeRole=l.z.enum(["security","testing","architecture","implement"]);h.AuditSeverity=l.z.enum(["critical","high","medium","low","info"]);h.AuditScope=l.z.object({kind:l.z.enum(["repo","ticket","branch"]).default("repo"),ref:l.z.string().default("")});h.AuditFinding=l.z.object({id:l.z.string().min(1),title:l.z.string().min(1),ruleId:l.z.string().max(20).default(""),severity:h.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("")});h.AuditRecord=l.z.object({id:l.z.string(),role:h.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(h.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:h.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()});h.AuditStartMsg=l.z.object({type:l.z.literal("audit.start"),requestId:l.z.string(),projectId:l.z.string(),role:h.AuditRole,model:l.z.string().default(""),scope:h.AuditScope.default({kind:"repo",ref:""})});h.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:h.AuditRecord.optional()});h.AuditListMsg=l.z.object({type:l.z.literal("audit.list"),requestId:l.z.string(),projectId:l.z.string()});h.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("")});h.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({})});h.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:h.AuditRole,createdAt:l.z.string(),findingCount:l.z.number().int(),bySeverity:l.z.record(l.z.number().int()).default({})})).default([])});h.AuditGetMsg=l.z.object({type:l.z.literal("audit.get"),requestId:l.z.string(),projectId:l.z.string(),auditId:l.z.string()});h.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:h.AuditRecord.optional()});h.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("")});h.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:h.AuditRecord.optional()});h.KnowledgeListMsg=l.z.object({type:l.z.literal("knowledge.list"),requestId:l.z.string(),projectId:l.z.string()});h.KnowledgeFile=l.z.object({role:h.KnowledgeRole,level:l.z.enum(["global","org","project"]),source:l.z.enum(["pack","lessons","memory"]),name:l.z.string(),content:l.z.string(),editable:l.z.boolean().default(!1)});h.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(h.KnowledgeFile).default([])});h.KnowledgeSaveMsg=l.z.object({type:l.z.literal("knowledge.save"),requestId:l.z.string(),projectId:l.z.string(),role:h.KnowledgeRole,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("")});h.KnowledgeSaveResultMsg=l.z.object({type:l.z.literal("knowledge.save.result"),requestId:l.z.string(),ok:l.z.boolean(),error:l.z.string().optional()});h.TeamCredsMsg=l.z.object({type:l.z.literal("team.creds"),requestId:l.z.string(),emails:l.z.array(l.z.string()).max(200)});h.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([])});h.ChatFile=l.z.object({name:l.z.string().min(1).max(255),contentBase64:l.z.string().min(1).max(6e6)});h.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(h.ChatFile).max(8).default([])});h.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(""),contextTokens:l.z.number().int().nonnegative().default(0),contextLimit:l.z.number().int().nonnegative().default(0),compacted:l.z.boolean().default(!1),compactedMessages:l.z.number().int().nonnegative().default(0)});h.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([]),createAs:l.z.enum(["epic_with_children","separate_epics","separate_tasks"]).default("epic_with_children"),files:l.z.array(h.ChatFile).max(8).default([])});h.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([])});h.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(h.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("")});h.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([])});h.DeploySuggestResultMsg=l.z.object({type:l.z.literal("deploy.suggest.result"),requestId:l.z.string(),ok:l.z.boolean(),steps:l.z.array(h.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("")});h.SetupStatusMsg=l.z.object({type:l.z.literal("setup.status"),requestId:l.z.string(),repoNames:l.z.array(l.z.string()).max(100).default([])});h.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([])});h.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("")});h.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("")});h.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)});h.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("")});h.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)});h.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("")});h.RunnerUpdateMsg=l.z.object({type:l.z.literal("runner.update"),requestId:l.z.string()});h.RunResolveConflictMsg=l.z.object({type:l.z.literal("run.resolve.conflict"),requestId:l.z.string(),runId:l.z.string()});h.RunTestFixMsg=l.z.object({type:l.z.literal("run.testfix"),requestId:l.z.string(),runId:l.z.string(),failedTests:l.z.array(h.FailedTest).min(1).max(20)});h.RunTestFixResultMsg=l.z.object({type:l.z.literal("run.testfix.result"),requestId:l.z.string(),ok:l.z.boolean(),note:l.z.string().default(""),headSha:l.z.string().default(""),remaining:l.z.array(h.FailedTest).default([]),costUsd:l.z.number().nonnegative().optional(),inputTokens:l.z.number().int().nonnegative().optional(),outputTokens:l.z.number().int().nonnegative().optional()});h.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()});h.RunPrConflictMsg=l.z.object({type:l.z.literal("run.pr.conflict"),runId:l.z.string(),conflicted:l.z.boolean()});h.AgentProfilesMsg=l.z.object({type:l.z.literal("agent.profiles"),requestId:l.z.string()});h.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([])});h.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)});h.AutopilotNextMsg=l.z.object({type:l.z.literal("autopilot.next"),requestId:l.z.string()});h.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),autoMerge:l.z.boolean().default(!1)}).nullable().default(null),pausedUntil:l.z.string().default("")});h.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("")});h.RunnerToServerMsg=l.z.discriminatedUnion("type",[h.HelloMsg,h.HeartbeatMsg,h.RunClaimMsg,h.RunLogMsg,h.RunUsageMsg,h.RunStatusMsg,h.ProjectTestResultMsg,h.RuleDiagnoseResultMsg,h.DeployClaimMsg,h.DeploySuggestResultMsg,h.EnvPreflightResultMsg,h.ChatTurnResultMsg,h.ChatStreamMsg,h.ChatUsageMsg,h.ChatCreateTicketResultMsg,h.ChatListResultMsg,h.RepoDocsResultMsg,h.RepoDocReadResultMsg,h.ChatLoadResultMsg,h.BoardFetchResultMsg,h.BoardTriggerResultMsg,h.TeamCredsResultMsg,h.AuditStartResultMsg,h.AuditListResultMsg,h.AuditGetResultMsg,h.AuditReviewResultMsg,h.KnowledgeListResultMsg,h.KnowledgeSaveResultMsg,h.EpicListResultMsg,h.EpicSuggestResultMsg,h.JiraUsersResultMsg,h.SetupStatusResultMsg,h.SetupClaudeMdGenerateResultMsg,h.SetupClaudeMdSaveResultMsg,h.RepoDocSaveResultMsg,h.RunnerUpdateResultMsg,h.AgentProfilesResultMsg,h.RunPrConflictMsg,h.RunResolveConflictResultMsg,h.RunTestFixResultMsg,h.AuditStatsResultMsg,h.AutopilotNextMsg,h.AutopilotReportMsg]);h.HelloAckMsg=l.z.object({type:l.z.literal("hello.ack"),runnerId:l.z.string(),runnerName:l.z.string(),serverTime:l.z.string()});h.ConfigMsg=l.z.object({type:l.z.literal("config"),projects:l.z.array(h.ProjectConfig),rules:l.z.array(h.RuleConfig),environments:l.z.array(h.EnvironmentConfig).default([]),pollingPaused:l.z.boolean().default(!1)});h.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()});h.ProjectTestMsg=l.z.object({type:l.z.literal("project.test"),requestId:l.z.string(),projectId:l.z.string()});h.RuleDiagnoseMsg=l.z.object({type:l.z.literal("rule.diagnose"),requestId:l.z.string(),ruleId:l.z.string()});h.RunCancelMsg=l.z.object({type:l.z.literal("run.cancel"),runId:l.z.string()});h.RunApprovedMsg=l.z.object({type:l.z.literal("run.approved"),runId:l.z.string(),headSha:l.z.string().optional()});h.RunRejectedMsg=l.z.object({type:l.z.literal("run.rejected"),runId:l.z.string()});h.RunRetryPushMsg=l.z.object({type:l.z.literal("run.retryPush"),runId:l.z.string()});h.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:h.EnvironmentConfig,requestedBy:l.z.string().default(""),attempt:l.z.number().int().positive().default(1)});h.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("")});h.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)});h.JiraUsersMsg=l.z.object({type:l.z.literal("jira.users"),requestId:l.z.string(),query:l.z.string().default("")});h.ServerToRunnerMsg=l.z.discriminatedUnion("type",[h.HelloAckMsg,h.ConfigMsg,h.RunClaimResultMsg,h.ProjectTestMsg,h.RuleDiagnoseMsg,h.RunCancelMsg,h.RunApprovedMsg,h.RunRejectedMsg,h.RunRetryPushMsg,h.DeployClaimResultMsg,h.DeployStartMsg,h.DeploySuggestMsg,h.DeployFixMsg,h.EnvPreflightMsg,h.ChatTurnMsg,h.ChatCreateTicketMsg,h.ChatListMsg,h.RepoDocsMsg,h.RepoDocReadMsg,h.ChatLoadMsg,h.BoardFetchMsg,h.BoardTriggerMsg,h.TeamCredsMsg,h.AuditStartMsg,h.AuditListMsg,h.AuditGetMsg,h.AuditReviewMsg,h.KnowledgeListMsg,h.KnowledgeSaveMsg,h.EpicListMsg,h.EpicSuggestMsg,h.JiraUsersMsg,h.SetupStatusMsg,h.SetupClaudeMdGenerateMsg,h.SetupClaudeMdSaveMsg,h.RepoDocSaveMsg,h.RunnerUpdateMsg,h.AgentProfilesMsg,h.RunResolveConflictMsg,h.RunTestFixMsg,h.AuditStatsMsg,h.AutopilotNextResultMsg]);h.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()});h.EnrollResponse=l.z.object({runnerId:l.z.string(),runnerToken:l.z.string(),controlPlaneWsUrl:l.z.string()});function og(n){return h.RunnerToServerMsg.parse(n)}function ag(n){return h.ServerToRunnerMsg.parse(n)}h.DEFAULT_PLAN_PROMPT_TEMPLATE=`You are a senior engineer asked to assess a Jira ticket. You have read-only access to the repository - do not attempt to modify anything.
|
|
24
24
|
|
|
25
25
|
Ticket {{issueKey}}: {{summary}}
|
|
26
26
|
|
|
@@ -234,9 +234,9 @@ 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 Au={};Zs(Au,{DELETE_MANIFEST_FILE:()=>Nt,MAX_CHANGED_FILES:()=>rn,MAX_CHANGED_LINES:()=>sn,abortMerge:()=>ln,applyDeleteManifest:()=>Fr,branchForIssue:()=>Ho,branchSha:()=>
|
|
238
|
-
`).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#"));for(let i of s.slice(0,200)){if(he.default.isAbsolute(i)){e.refused.push(`${i} - absolute paths are not allowed`);continue}let o=he.default.resolve(r,i);if(o!==r&&!o.startsWith(r+he.default.sep)){e.refused.push(`${i} - escapes the worktree`);continue}let a=he.default.relative(r,o).split(he.default.sep).join("/");if(a===Nt)continue;if(Iu.some(c=>c.test(a))){e.refused.push(`${i} - protected path (CI/hook files are never touched)`);continue}let u;try{u=
|
|
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 Au={};Zs(Au,{DELETE_MANIFEST_FILE:()=>Nt,MAX_CHANGED_FILES:()=>rn,MAX_CHANGED_LINES:()=>sn,abortMerge:()=>ln,applyDeleteManifest:()=>Fr,branchForIssue:()=>Ho,branchSha:()=>bi,branchesDiffer:()=>Qo,checkDiffSafety:()=>an,commitAll:()=>Yn,commitMergeResolution:()=>Jo,deleteStaleBranch:()=>Bo,diffAgainstDefault:()=>wi,envCheckoutPath:()=>Eu,envCheckoutsRoot:()=>Ru,fetchBase:()=>on,findConflictMarkers:()=>_i,headSha:()=>Qe,mergeBaseIntoWorktree:()=>Wo,mergeTicketBranch:()=>Vo,originUrl:()=>Qn,parseOwnerRepo:()=>it,prepareEnvCheckout:()=>Go,pruneWorktrees:()=>Zo,pushBranch:()=>Xn,pushEnvBranch:()=>Xo,pushWipBranch:()=>qo,removeWorktree:()=>yt,resetHard:()=>Br,statusSnapshot:()=>Fo,unresolvedAmong:()=>Yo,worktreeAdd:()=>Ko,worktreeAddExisting:()=>ks,worktreeFingerprint:()=>vi,worktreesRoot:()=>Mt});async function F(n,e,t={}){try{let{stdout:r}=await Cu("git",["-C",n,...e],{timeout:t.timeoutMs??12e4,maxBuffer:16777216,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});return r}catch(r){let s=r;throw new Error(`git ${e[0]} failed: ${(s.stderr||s.message||"").trim().slice(0,500)}`)}}async function Fr(n){let e={deleted:[],refused:[]},t=he.default.join(n,Nt);if(!be.default.existsSync(t))return e;let r=he.default.resolve(n),s=be.default.readFileSync(t,"utf8").split(`
|
|
238
|
+
`).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#"));for(let i of s.slice(0,200)){if(he.default.isAbsolute(i)){e.refused.push(`${i} - absolute paths are not allowed`);continue}let o=he.default.resolve(r,i);if(o!==r&&!o.startsWith(r+he.default.sep)){e.refused.push(`${i} - escapes the worktree`);continue}let a=he.default.relative(r,o).split(he.default.sep).join("/");if(a===Nt)continue;if(Iu.some(c=>c.test(a))){e.refused.push(`${i} - protected path (CI/hook files are never touched)`);continue}let u;try{u=be.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{be.default.rmSync(o),e.deleted.push(a)}catch(c){e.refused.push(`${i} - ${c instanceof Error?c.message:"delete failed"}`)}}return be.default.rmSync(t,{force:!0}),e}async function qo(n,e){await F(n,["push","--force","origin",`HEAD:refs/heads/${e}`],{timeoutMs:3e5})}async function vi(n){let e=await F(n,["status","--porcelain"]),t=await F(n,["diff","--numstat"]),r=e.split(`
|
|
239
|
+
`).filter(s=>s.startsWith("??")).map(s=>s.slice(3).trim()).slice(0,500).map(s=>{try{let i=be.default.statSync(he.default.join(n,s));return`${s}:${i.size}:${i.mtimeMs}`}catch{return s}}).join(`
|
|
240
240
|
`);return`${e}
|
|
241
241
|
--
|
|
242
242
|
${t}
|
|
@@ -246,19 +246,19 @@ ${r}`}async function Fo(n){let e=(await F(n,["rev-parse","--abbrev-ref","HEAD"])
|
|
|
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 Mt(){let n=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(
|
|
250
|
-
`))i.startsWith("worktree ")&&(s=i.slice(9).trim()),i===`branch refs/heads/${e}`&&s&&s.startsWith(r)&&await F(n,["worktree","remove","--force",s]);await F(n,["worktree","prune"])}catch{}try{await F(n,["branch","-D",e])}catch{}}async function Ko(n,e,t,r){
|
|
251
|
-
`).filter(Boolean),s=r.filter(c=>Iu.some(f=>f.test(c))),i=await F(n,["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&&r.length<=rn&&o+a<=sn,files:r.length,insertions:o,deletions:a,forbidden:s}}async function Xn(n,e){await F(n,["fetch","--prune","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],{timeoutMs:12e4}).catch(()=>F(n,["update-ref","-d",`refs/remotes/origin/${e}`]).catch(()=>{})),await F(n,["push","--force-with-lease","-u","origin",e],{timeoutMs:3e5})}async function Qe(n){return(await F(n,["rev-parse","HEAD"])).trim()}async function
|
|
252
|
-
`).map(s=>s.trim()).filter(s=>s&&!s.includes("->"))[0]??null}async function wi(n,e,t=6e4){let s=(await F(n,["symbolic-ref","refs/remotes/origin/HEAD"]).catch(()=>"")).trim().replace("refs/remotes/","")||"origin/main",i=await F(n,["diff","--stat",`${s}...${e}`]),o=await F(n,["diff",`${s}...${e}`]);return{base:s,stat:i.slice(0,4e3),diff:o.slice(0,t)}}function Ru(){let n=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(
|
|
249
|
+
${i}${o}`:"clean"}`}function Mt(){let n=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(be.default.existsSync(he.default.join(Jn.default.homedir(),".cache","ticketpilot"))?he.default.join(Jn.default.homedir(),".cache","ticketpilot"):he.default.join(Jn.default.homedir(),".cache","allwright"));return he.default.join(n,"worktrees")}async function on(n,e){try{await F(n,["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 Bo(n,e){try{let t=await F(n,["worktree","list","--porcelain"]),r=Mt(),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(r)&&await F(n,["worktree","remove","--force",s]);await F(n,["worktree","prune"])}catch{}try{await F(n,["branch","-D",e])}catch{}}async function Ko(n,e,t,r){be.default.mkdirSync(he.default.dirname(e),{recursive:!0,mode:448}),await F(n,["worktree","add","-b",t,e,`origin/${r}`])}async function Yn(n,e){if(await F(n,["add","-A"]),!(await F(n,["status","--porcelain"])).trim())throw new Error("Claude wrote no changes - nothing to commit");await F(n,["-c",`user.name=${gi}`,"-c",`user.email=${yi}`,"commit","-m",e])}async function an(n,e){let r=(await F(n,["diff","--name-only",`origin/${e}...HEAD`])).split(`
|
|
251
|
+
`).filter(Boolean),s=r.filter(c=>Iu.some(f=>f.test(c))),i=await F(n,["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&&r.length<=rn&&o+a<=sn,files:r.length,insertions:o,deletions:a,forbidden:s}}async function Xn(n,e){await F(n,["fetch","--prune","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],{timeoutMs:12e4}).catch(()=>F(n,["update-ref","-d",`refs/remotes/origin/${e}`]).catch(()=>{})),await F(n,["push","--force-with-lease","-u","origin",e],{timeoutMs:3e5})}async function Qe(n){return(await F(n,["rev-parse","HEAD"])).trim()}async function bi(n,e){try{return(await F(n,["rev-parse","--verify",`refs/heads/${e}`])).trim()}catch{return null}}async function Br(n,e){await F(n,["reset","--hard",e])}async function yt(n,e){try{await F(n,["worktree","remove","--force",e])}catch{be.default.rmSync(e,{recursive:!0,force:!0})}}async function Zo(n,e=[]){let t=new Set(e.map(s=>he.default.basename(he.default.resolve(s))).filter(s=>s.length>0)),r=Mt();if(be.default.existsSync(r))for(let s of be.default.readdirSync(r))t.has(s)||be.default.rmSync(he.default.join(r,s),{recursive:!0,force:!0});for(let s of n)try{await F(s,["worktree","prune"])}catch{}}async function Ho(n,e){return await F(n,["fetch","origin","--prune"]).catch(()=>{}),(await F(n,["branch","-r","--list",`*${e}*`])).split(`
|
|
252
|
+
`).map(s=>s.trim()).filter(s=>s&&!s.includes("->"))[0]??null}async function wi(n,e,t=6e4){let s=(await F(n,["symbolic-ref","refs/remotes/origin/HEAD"]).catch(()=>"")).trim().replace("refs/remotes/","")||"origin/main",i=await F(n,["diff","--stat",`${s}...${e}`]),o=await F(n,["diff",`${s}...${e}`]);return{base:s,stat:i.slice(0,4e3),diff:o.slice(0,t)}}function Ru(){let n=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(be.default.existsSync(he.default.join(Jn.default.homedir(),".cache","ticketpilot"))?he.default.join(Jn.default.homedir(),".cache","ticketpilot"):he.default.join(Jn.default.homedir(),".cache","allwright"));return he.default.join(n,"env-checkouts")}function Su(n){return n.replace(/[^\w.-]+/g,"_")}function Eu(n,e){return he.default.join(Ru(),Su(n),Su(e))}async function Go(n){let e=Eu(n.repoName,n.envName);return await F(n.repoPath,["fetch","origin",n.branch],{timeoutMs:3e5}),be.default.existsSync(he.default.join(e,".git"))?await F(e,["fetch","origin",n.branch],{timeoutMs:3e5}):(be.default.rmSync(e,{recursive:!0,force:!0}),be.default.mkdirSync(he.default.dirname(e),{recursive:!0,mode:448}),await F(n.repoPath,["worktree","prune"]).catch(()=>{}),await F(n.repoPath,["worktree","add","--detach",e,`origin/${n.branch}`])),n.attached?await F(e,["checkout","-B",n.branch,`origin/${n.branch}`]):await F(e,["checkout","--force","--detach",`origin/${n.branch}`]),e}async function Vo(n,e,t){try{await F(n,["fetch","origin",e],{timeoutMs:3e5})}catch{return{ok:!1,reason:`branch "${e}" does not exist on origin - nothing to promote. Check the environment's ticket branch template against the branch your implement rule creates.`}}try{return await F(n,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyMerged:!0}}catch{}try{return await F(n,["-c",`user.name=${gi}`,"-c",`user.email=${yi}`,"merge","--no-ff","-m",t,`origin/${e}`]),{ok:!0}}catch(r){return await F(n,["merge","--abort"]).catch(()=>{}),{ok:!1,reason:`could not merge "${e}" into the environment branch - ${r instanceof Error?r.message:r}. Resolve it manually and deploy again.`}}}async function Wo(n,e){await F(n,["fetch","origin",e],{timeoutMs:3e5});try{return await F(n,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyUpToDate:!0}}catch{}try{return await F(n,["-c",`user.name=${gi}`,"-c",`user.email=${yi}`,"merge","--no-edit",`origin/${e}`]),{ok:!0,alreadyUpToDate:!1}}catch(t){let s=(await F(n,["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
|
|
253
253
|
`).filter(Boolean);return s.length?{ok:!1,conflicts:s}:(await F(n,["merge","--abort"]).catch(()=>{}),{ok:!1,conflicts:null,reason:t instanceof Error?t.message.slice(0,300):String(t)})}}async function ln(n){await F(n,["merge","--abort"]).catch(()=>{})}async function Jo(n,e){await F(n,["add","-A"]),await F(n,["-c",`user.name=${gi}`,"-c",`user.email=${yi}`,"commit","--no-edit","-m",e])}async function Yo(n,e){let t=new Set(await _i(n));return e.filter(r=>t.has(r))}async function _i(n){let e=new Set;try{let r=await F(n,["grep","-l","-I","-E","^(<{7}|>{7})( |$)"]);for(let s of r.split(`
|
|
254
254
|
`).filter(Boolean))e.add(s)}catch{}let t=[];try{t=(await F(n,["grep","-l","-I","-E","^={7}$"])).split(`
|
|
255
|
-
`).filter(Boolean).filter(s=>!e.has(s))}catch{}for(let r of t)try{let s=await F(n,["show",`HEAD:${r}`]);/^={7}$/m.test(s)||e.add(r)}catch{e.add(r)}return[...e]}async function ks(n,e,t){ve.default.mkdirSync(he.default.dirname(e),{recursive:!0,mode:448}),await F(n,["fetch","origin",t],{timeoutMs:3e5}),await F(n,["worktree","add","--detach",e,`origin/${t}`]),await F(e,["checkout","-B",t,`origin/${t}`])}async function Xo(n,e){try{await F(n,["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 Qo(n,e,t){try{return await Cu("git",["-C",n,"diff","--quiet",e,t,"--"],{timeout:12e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),!1}catch(r){let s=r;if(s.code===1)return!0;throw new Error(`git diff failed comparing ${e}..${t}: ${(s.stderr||s.message||"").trim().slice(0,500)}`)}}async function Qn(n){return(await F(n,["config","--get","remote.origin.url"])).trim()}function it(n){let e=/^git@github\.com(?:-[\w.-]+)?:([^/]+)\/(.+?)(\.git)?$/.exec(n)??/^https:\/\/github\.com\/([^/]+)\/(.+?)(\.git)?\/?$/.exec(n)??/^ssh:\/\/git@github\.com(?:-[\w.-]+)?\/([^/]+)\/(.+?)(\.git)?$/.exec(n);return e?{owner:e[1],repo:e[2]}:null}var ve,Jn,he,Tu,xu,Cu,gi,yi,rn,sn,Iu,Nt,bt=Ks(()=>{"use strict";ve=E(require("node:fs"),1),Jn=E(require("node:os"),1),he=E(require("node:path"),1),Tu=require("node:child_process"),xu=require("node:util"),Cu=(0,xu.promisify)(Tu.execFile),gi="Allwright Agent",yi="agent@ticketpilot.local",rn=200,sn=2e4,Iu=[/^\.github\/workflows\//,/^\.git\b/,/(^|\/)\.githooks\//];Nt=".ticketpilot-delete"});function ki(n,e,t){let r=(t??"").trim().toLowerCase(),s=r?n.githubUsers[r]?.token:void 0;if(s)return{token:s,source:"user"};let i=n.repos[e]?.github?.token;return i?{token:i,source:"repo"}:n.github?.token?{token:n.github.token,source:"global"}:null}function Ie(n,e){return n.repos[e]?.github?.token??n.github?.token??null}function Ou(n,e){let t=[n.jira,...Object.values(n.repos).map(a=>a.jira)].filter(a=>!!a),r=new Set(t.map(a=>a.email.toLowerCase())),s=!!n.github?.token||Object.values(n.repos).some(a=>a.github?.token),i=n.github?.login??Object.values(n.repos).find(a=>a.github?.login)?.github?.login??"",o=e.map(a=>{let u=a.trim().toLowerCase(),c=n.jiraUsers[u]?"own":r.has(u)?"runner-account":"missing",f=c==="own"?n.jiraUsers[u].email:c==="runner-account"?u:"",p=n.githubUsers[u]?"own":s?"shared":"missing",b=p==="own"?n.githubUsers[u].login??"":p==="shared"?i:"";return{email:u,jira:c,jiraAs:f,github:p,githubAs:b}});return{githubShared:s,sharedGithubLogin:i,entries:o}}var er=Ks(()=>{"use strict"});var sr={};Zs(sr,{GitHubClient:()=>Re});var Eg,Re,at=Ks(()=>{"use strict";Eg=process.env.TICKETPILOT_GITHUB_API??"https://api.github.com",Re=class{constructor(e){this.token=e}token;async request(e,t,r){let s=await fetch(`${Eg}${t}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"allwright",...r!==void 0?{"Content-Type":"application/json"}:{}},body:r===void 0?void 0:JSON.stringify(r)}),i=await s.text(),o=null;try{o=i?JSON.parse(i):null}catch{}if(s.status===401)throw new Error("GitHub rejected the token (401) - expired or revoked? Run `allwright github set-token`");if(!s.ok&&s.status!==422){let 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,r){let{status:s,data:i}=await this.request("POST",`/repos/${e}/${t}/pulls`,r);if(s===422){let{data:o}=await this.request("GET",`/repos/${e}/${t}/pulls?head=${encodeURIComponent(`${e}:${r.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:r.base}}async getReviews(e,t,r){let{data:s}=await this.request("GET",`/repos/${e}/${t}/pulls/${r}/reviews?per_page=100`);return(s??[]).map(i=>({state:i.state??"",commitId:i.commit_id??"",user:i.user?.login??"",submittedAt:i.submitted_at??""}))}async getPullRequest(e,t,r){try{let{data:s}=await this.request("GET",`/repos/${e}/${t}/pulls/${r}`);return{number:s.number,url:s.html_url,state:s.state,merged:s.merged,headSha:s.head.sha,mergeableState:s.mergeable_state??null,baseRef:s.base?.ref??""}}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return null;throw s}}async mergePullRequest(e,t,r,s,i={}){try{return await this.request("PUT",`/repos/${e}/${t}/pulls/${r}/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:r}=await this.request("GET",`/repos/${e}/${t}`);return{ok:!0,canPush:!!(r.permissions?.push||r.permissions?.admin)}}catch(r){let s=r instanceof Error?r.message:String(r);return{ok:!1,canPush:!1,error:s.includes("-> 404")?"not found (private repo this token cannot see, or the name is wrong)":s.slice(0,200)}}}async closePullRequest(e,t,r){await this.request("PATCH",`/repos/${e}/${t}/pulls/${r}`,{state:"closed"})}async deleteBranch(e,t,r){try{await this.request("DELETE",`/repos/${e}/${t}/git/refs/heads/${encodeURIComponent(r)}`)}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return;throw s}}}});var Ut=ne((bk,zd)=>{"use strict";var Nd=["nodebuffer","arraybuffer","fragments"],Md=typeof Blob<"u";Md&&Nd.push("blob");zd.exports={BINARY_TYPES:Nd,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Md,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var js=ne((vk,Bi)=>{"use strict";var{EMPTY_BUFFER:jy}=Ut(),La=Buffer[Symbol.species];function Oy(n,e){if(n.length===0)return jy;if(n.length===1)return n[0];let t=Buffer.allocUnsafe(e),r=0;for(let s=0;s<n.length;s++){let i=n[s];t.set(i,r),r+=i.length}return r<e?new La(t.buffer,t.byteOffset,r):t}function Dd(n,e,t,r,s){for(let i=0;i<s;i++)t[r+i]=n[i]^e[i&3]}function Ld(n,e){for(let t=0;t<n.length;t++)n[t]^=e[t&3]}function Ny(n){return n.length===n.buffer.byteLength?n.buffer:n.buffer.slice(n.byteOffset,n.byteOffset+n.length)}function Ua(n){if(Ua.readOnly=!0,Buffer.isBuffer(n))return n;let e;return n instanceof ArrayBuffer?e=new La(n):ArrayBuffer.isView(n)?e=new La(n.buffer,n.byteOffset,n.byteLength):(e=Buffer.from(n),Ua.readOnly=!1),e}Bi.exports={concat:Oy,mask:Dd,toArrayBuffer:Ny,toBuffer:Ua,unmask:Ld};if(!process.env.WS_NO_BUFFER_UTIL)try{let n=require("bufferutil");Bi.exports.mask=function(e,t,r,s,i){i<48?Dd(e,t,r,s,i):n.mask(e,t,r,s,i)},Bi.exports.unmask=function(e,t){e.length<32?Ld(e,t):n.unmask(e,t)}}catch{}});var Fd=ne((wk,qd)=>{"use strict";var Ud=Symbol("kDone"),qa=Symbol("kRun"),Fa=class{constructor(e){this[Ud]=()=>{this.pending--,this[qa]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[qa]()}[qa](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Ud])}}};qd.exports=Fa});var ns=ne((_k,Hd)=>{"use strict";var Os=require("zlib"),Bd=js(),My=Fd(),{kStatusCode:Kd}=Ut(),zy=Buffer[Symbol.species],Dy=Buffer.from([0,0,255,255]),Zi=Symbol("permessage-deflate"),qt=Symbol("total-length"),es=Symbol("callback"),cn=Symbol("buffers"),ts=Symbol("error"),Ki,Ba=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,!Ki){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ki=new My(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[es];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,r=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(!r)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(r.server_no_context_takeover=!0),t.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(r.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?r.client_max_window_bits=t.clientMaxWindowBits:(r.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}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(r=>{let s=t[r];if(s.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(s=s[0],r==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else if(r==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else throw new Error(`Unknown parameter "${r}"`);t[r]=s})}),e}decompress(e,t,r){Ki.add(s=>{this._decompress(e,t,(i,o)=>{s(),r(i,o)})})}compress(e,t,r){Ki.add(s=>{this._compress(e,t,(i,o)=>{s(),r(i,o)})})}_decompress(e,t,r){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Os.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Os.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Zi]=this,this._inflate[qt]=0,this._inflate[cn]=[],this._inflate.on("error",Uy),this._inflate.on("data",Zd)}this._inflate[es]=r,this._inflate.write(e),t&&this._inflate.write(Dy),this._inflate.flush(()=>{let i=this._inflate[ts];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=Bd.concat(this._inflate[cn],this._inflate[qt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[qt]=0,this._inflate[cn]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,t,r){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Os.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Os.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[qt]=0,this._deflate[cn]=[],this._deflate.on("data",Ly)}this._deflate[es]=r,this._deflate.write(e),this._deflate.flush(Os.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Bd.concat(this._deflate[cn],this._deflate[qt]);t&&(i=new zy(i.buffer,i.byteOffset,i.length-4)),this._deflate[es]=null,this._deflate[qt]=0,this._deflate[cn]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};Hd.exports=Ba;function Ly(n){this[cn].push(n),this[qt]+=n.length}function Zd(n){if(this[qt]+=n.length,this[Zi]._maxPayload<1||this[qt]<=this[Zi]._maxPayload){this[cn].push(n);return}this[ts]=new RangeError("Max payload size exceeded"),this[ts].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ts][Kd]=1009,this.removeListener("data",Zd),this.reset()}function Uy(n){if(this[Zi]._inflate=null,this[ts]){this[es](this[ts]);return}n[Kd]=1007,this[es](n)}});var rs=ne((kk,Hi)=>{"use strict";var{isUtf8:Gd}=require("buffer"),{hasBlob:qy}=Ut(),Fy=[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 By(n){return n>=1e3&&n<=1014&&n!==1004&&n!==1005&&n!==1006||n>=3e3&&n<=4999}function Ka(n){let e=n.length,t=0;for(;t<e;)if((n[t]&128)===0)t++;else if((n[t]&224)===192){if(t+1===e||(n[t+1]&192)!==128||(n[t]&254)===192)return!1;t+=2}else if((n[t]&240)===224){if(t+2>=e||(n[t+1]&192)!==128||(n[t+2]&192)!==128||n[t]===224&&(n[t+1]&224)===128||n[t]===237&&(n[t+1]&224)===160)return!1;t+=3}else if((n[t]&248)===240){if(t+3>=e||(n[t+1]&192)!==128||(n[t+2]&192)!==128||(n[t+3]&192)!==128||n[t]===240&&(n[t+1]&240)===128||n[t]===244&&n[t+1]>143||n[t]>244)return!1;t+=4}else return!1;return!0}function Ky(n){return qy&&typeof n=="object"&&typeof n.arrayBuffer=="function"&&typeof n.type=="string"&&typeof n.stream=="function"&&(n[Symbol.toStringTag]==="Blob"||n[Symbol.toStringTag]==="File")}Hi.exports={isBlob:Ky,isValidStatusCode:By,isValidUTF8:Ka,tokenChars:Fy};if(Gd)Hi.exports.isValidUTF8=function(n){return n.length<24?Ka(n):Gd(n)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let n=require("utf-8-validate");Hi.exports.isValidUTF8=function(e){return e.length<32?Ka(e):n(e)}}catch{}});var Wa=ne((Sk,eh)=>{"use strict";var{Writable:Zy}=require("stream"),Vd=ns(),{BINARY_TYPES:Hy,EMPTY_BUFFER:Wd,kStatusCode:Gy,kWebSocket:Vy}=Ut(),{concat:Za,toArrayBuffer:Wy,unmask:Jy}=js(),{isValidStatusCode:Yy,isValidUTF8:Jd}=rs(),Gi=Buffer[Symbol.species],tt=0,Yd=1,Xd=2,Qd=3,Ha=4,Ga=5,Vi=6,Va=class extends Zy{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Hy[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[Vy]=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=tt}_write(e,t,r){if(this._opcode===8&&this._state==tt)return r();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){r(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new Gi(r.buffer,r.byteOffset+e,r.length-e),new Gi(r.buffer,r.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let r=this._buffers[0],s=t.length-e;e>=r.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new Gi(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case tt:this.getInfo(e);break;case Yd:this.getPayloadLength16(e);break;case Xd:this.getPayloadLength64(e);break;case Qd:this.getMask();break;case Ha:this.getData(e);break;case Ga:case Vi: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 r=(t[0]&64)===64;if(r&&!this._extensions[Vd.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(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(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=Yd:this._payloadLength===127?this._state=Xd: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),r=t.readUInt32BE(0);if(r>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=r*Math.pow(2,32)+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=Qd:this._state=Ha}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Ha}getData(e){let t=Wd;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&&Jy(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let r=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(r);return}if(this._compressed){this._state=Ga,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Vd.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===tt&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=tt;return}let t=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=Za(r,t):this._binaryType==="arraybuffer"?s=Wy(Za(r,t)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=tt):(this._state=Vi,setImmediate(()=>{this.emit("message",s,!0),this._state=tt,this.startLoop(e)}))}else{let s=Za(r,t);if(!this._skipUTF8Validation&&!Jd(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Ga||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=tt):(this._state=Vi,setImmediate(()=>{this.emit("message",s,!1),this._state=tt,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Wd),this.end();else{let r=e.readUInt16BE(0);if(!Yy(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new Gi(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Jd(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",r,s),this.end()}this._state=tt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=tt):(this._state=Vi,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=tt,this.startLoop(t)}))}createError(e,t,r,s,i){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[Gy]=s,o}};eh.exports=Va});var Xa=ne((xk,rh)=>{"use strict";var{Duplex:Tk}=require("stream"),{randomFillSync:Xy}=require("crypto"),{types:{isUint8Array:Qy}}=require("util"),th=ns(),{EMPTY_BUFFER:eb,kWebSocket:tb,NOOP:nb}=Ut(),{isBlob:ss,isValidStatusCode:rb}=rs(),{mask:nh,toBuffer:mr}=js(),nt=Symbol("kByteLength"),sb=Buffer.alloc(4),Wi=8*1024,gr,is=Wi,ct=0,ib=1,ob=2,Ja=class n{constructor(e,t,r){this._extensions=t||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=ct,this.onerror=nb,this[tb]=void 0}static frame(e,t){let r,s=!1,i=2,o=!1;t.mask&&(r=t.maskBuffer||sb,t.generateMask?t.generateMask(r):(is===Wi&&(gr===void 0&&(gr=Buffer.alloc(Wi)),Xy(gr,0,Wi),is=0),r[0]=gr[is++],r[1]=gr[is++],r[2]=gr[is++],r[3]=gr[is++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!t.mask||o)&&t[nt]!==void 0?a=t[nt]:(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]=r[0],c[i-3]=r[1],c[i-2]=r[2],c[i-1]=r[3],o?[c,e]:s?(nh(e,r,c,i,a),[c]):(nh(e,r,e,0,a),[c,e])):[c,e]}close(e,t,r,s){let i;if(e===void 0)i=eb;else{if(typeof e!="number"||!rb(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(Qy(t))i.set(t,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[nt]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ct?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(n.frame(i,o),s)}ping(e,t,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):ss(e)?(s=e.size,i=!1):(e=mr(e),s=e.length,i=mr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[nt]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};ss(e)?this._state!==ct?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==ct?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(n.frame(e,o),r)}pong(e,t,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):ss(e)?(s=e.size,i=!1):(e=mr(e),s=e.length,i=mr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[nt]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};ss(e)?this._state!==ct?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==ct?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(n.frame(e,o),r)}send(e,t,r){let s=this._extensions[th.extensionName],i=t.binary?2:1,o=t.compress,a,u;typeof e=="string"?(a=Buffer.byteLength(e),u=!1):ss(e)?(a=e.size,u=!1):(e=mr(e),a=e.length,u=mr.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={[nt]:a,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:u,rsv1:o};ss(e)?this._state!==ct?this.enqueue([this.getBlobData,e,this._compress,c,r]):this.getBlobData(e,this._compress,c,r):this._state!==ct?this.enqueue([this.dispatch,e,this._compress,c,r]):this.dispatch(e,this._compress,c,r)}getBlobData(e,t,r,s){this._bufferedBytes+=r[nt],this._state=ob,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Ya,this,a,s);return}this._bufferedBytes-=r[nt];let o=mr(i);t?this.dispatch(o,t,r,s):(this._state=ct,this.sendFrame(n.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(ab,this,i,s)})}dispatch(e,t,r,s){if(!t){this.sendFrame(n.frame(e,r),s);return}let i=this._extensions[th.extensionName];this._bufferedBytes+=r[nt],this._state=ib,i.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");Ya(this,u,s);return}this._bufferedBytes-=r[nt],this._state=ct,r.readOnly=!1,this.sendFrame(n.frame(a,r),s),this.dequeue()})}dequeue(){for(;this._state===ct&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][nt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][nt],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)}};rh.exports=Ja;function Ya(n,e,t){typeof t=="function"&&t(e);for(let r=0;r<n._queue.length;r++){let s=n._queue[r],i=s[s.length-1];typeof i=="function"&&i(e)}}function ab(n,e,t){Ya(n,e,t),n.onerror(e)}});var hh=ne((Ck,dh)=>{"use strict";var{kForOnEventAttribute:Ns,kListener:Qa}=Ut(),sh=Symbol("kCode"),ih=Symbol("kData"),oh=Symbol("kError"),ah=Symbol("kMessage"),lh=Symbol("kReason"),os=Symbol("kTarget"),uh=Symbol("kType"),ch=Symbol("kWasClean"),Ft=class{constructor(e){this[os]=null,this[uh]=e}get target(){return this[os]}get type(){return this[uh]}};Object.defineProperty(Ft.prototype,"target",{enumerable:!0});Object.defineProperty(Ft.prototype,"type",{enumerable:!0});var yr=class extends Ft{constructor(e,t={}){super(e),this[sh]=t.code===void 0?0:t.code,this[lh]=t.reason===void 0?"":t.reason,this[ch]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[sh]}get reason(){return this[lh]}get wasClean(){return this[ch]}};Object.defineProperty(yr.prototype,"code",{enumerable:!0});Object.defineProperty(yr.prototype,"reason",{enumerable:!0});Object.defineProperty(yr.prototype,"wasClean",{enumerable:!0});var as=class extends Ft{constructor(e,t={}){super(e),this[oh]=t.error===void 0?null:t.error,this[ah]=t.message===void 0?"":t.message}get error(){return this[oh]}get message(){return this[ah]}};Object.defineProperty(as.prototype,"error",{enumerable:!0});Object.defineProperty(as.prototype,"message",{enumerable:!0});var Ms=class extends Ft{constructor(e,t={}){super(e),this[ih]=t.data===void 0?null:t.data}get data(){return this[ih]}};Object.defineProperty(Ms.prototype,"data",{enumerable:!0});var lb={addEventListener(n,e,t={}){for(let s of this.listeners(n))if(!t[Ns]&&s[Qa]===e&&!s[Ns])return;let r;if(n==="message")r=function(i,o){let a=new Ms("message",{data:o?i:i.toString()});a[os]=this,Ji(e,this,a)};else if(n==="close")r=function(i,o){let a=new yr("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[os]=this,Ji(e,this,a)};else if(n==="error")r=function(i){let o=new as("error",{error:i,message:i.message});o[os]=this,Ji(e,this,o)};else if(n==="open")r=function(){let i=new Ft("open");i[os]=this,Ji(e,this,i)};else return;r[Ns]=!!t[Ns],r[Qa]=e,t.once?this.once(n,r):this.on(n,r)},removeEventListener(n,e){for(let t of this.listeners(n))if(t[Qa]===e&&!t[Ns]){this.removeListener(n,t);break}}};dh.exports={CloseEvent:yr,ErrorEvent:as,Event:Ft,EventTarget:lb,MessageEvent:Ms};function Ji(n,e,t){typeof n=="object"&&n.handleEvent?n.handleEvent.call(n,t):n.call(e,t)}});var Yi=ne((Ik,fh)=>{"use strict";var{tokenChars:zs}=rs();function St(n,e,t){n[e]===void 0?n[e]=[t]:n[e].push(t)}function ub(n){let e=Object.create(null),t=Object.create(null),r=!1,s=!1,i=!1,o,a,u=-1,c=-1,f=-1,p=0;for(;p<n.length;p++)if(c=n.charCodeAt(p),o===void 0)if(f===-1&&zs[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 v=n.slice(u,f);c===44?(St(e,v,t),t=Object.create(null)):o=v,u=f=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(a===void 0)if(f===-1&&zs[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),St(t,n.slice(u,f),!0),c===44&&(St(e,o,t),t=Object.create(null),o=void 0),u=f=-1}else if(c===61&&u!==-1&&f===-1)a=n.slice(u,p),u=f=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(s){if(zs[c]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:r||(r=!0),s=!1}else if(i)if(zs[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&&n.charCodeAt(p-1)===61)i=!0;else if(f===-1&&zs[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 v=n.slice(u,f);r&&(v=v.replace(/\\/g,""),r=!1),St(t,a,v),c===44&&(St(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 b=n.slice(u,f);return o===void 0?St(e,b,t):(a===void 0?St(t,b,!0):r?St(t,a,b.replace(/\\/g,"")):St(t,a,b),St(e,o,t)),e}function cb(n){return Object.keys(n).map(e=>{let t=n[e];return Array.isArray(t)||(t=[t]),t.map(r=>[e].concat(Object.keys(r).map(s=>{let i=r[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}fh.exports={format:cb,parse:ub}});var to=ne((Ak,xh)=>{"use strict";var db=require("events"),hb=require("https"),fb=require("http"),gh=require("net"),pb=require("tls"),{randomBytes:mb,createHash:gb}=require("crypto"),{Duplex:Rk,Readable:Ek}=require("stream"),{URL:el}=require("url"),dn=ns(),yb=Wa(),bb=Xa(),{isBlob:vb}=rs(),{BINARY_TYPES:ph,CLOSE_TIMEOUT:wb,EMPTY_BUFFER:Xi,GUID:_b,kForOnEventAttribute:tl,kListener:kb,kStatusCode:Sb,kWebSocket:we,NOOP:yh}=Ut(),{EventTarget:{addEventListener:Tb,removeEventListener:xb}}=hh(),{format:Cb,parse:Ib}=Yi(),{toBuffer:Rb}=js(),bh=Symbol("kAborted"),nl=[8,13],Bt=["CONNECTING","OPEN","CLOSING","CLOSED"],Eb=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,pe=class n extends db{constructor(e,t,r){super(),this._binaryType=ph[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Xi,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=n.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?(r=t,t=[]):t=[t]),vh(this,e,t,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){ph.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,r){let s=new yb({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new bb(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[we]=this,i[we]=this,e[we]=this,s.on("conclude",Pb),s.on("drain",jb),s.on("error",Ob),s.on("message",Nb),s.on("ping",Mb),s.on("pong",zb),i.onerror=Db,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",kh),e.on("data",eo),e.on("end",Sh),e.on("error",Th),this._readyState=n.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[dn.extensionName]&&this._extensions[dn.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){Ke(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===n.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=n.CLOSING,this._sender.close(e,t,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),_h(this)}}pause(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,r){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=t=void 0):typeof t=="function"&&(r=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){rl(this,e,r);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Xi,t,r)}pong(e,t,r){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=t=void 0):typeof t=="function"&&(r=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){rl(this,e,r);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Xi,t,r)}resume(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,r){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(r=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){rl(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[dn.extensionName]||(s.compress=!1),this._sender.send(e||Xi,s,r)}terminate(){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){Ke(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=n.CLOSING,this._socket.destroy())}}};Object.defineProperty(pe,"CONNECTING",{enumerable:!0,value:Bt.indexOf("CONNECTING")});Object.defineProperty(pe.prototype,"CONNECTING",{enumerable:!0,value:Bt.indexOf("CONNECTING")});Object.defineProperty(pe,"OPEN",{enumerable:!0,value:Bt.indexOf("OPEN")});Object.defineProperty(pe.prototype,"OPEN",{enumerable:!0,value:Bt.indexOf("OPEN")});Object.defineProperty(pe,"CLOSING",{enumerable:!0,value:Bt.indexOf("CLOSING")});Object.defineProperty(pe.prototype,"CLOSING",{enumerable:!0,value:Bt.indexOf("CLOSING")});Object.defineProperty(pe,"CLOSED",{enumerable:!0,value:Bt.indexOf("CLOSED")});Object.defineProperty(pe.prototype,"CLOSED",{enumerable:!0,value:Bt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(n=>{Object.defineProperty(pe.prototype,n,{enumerable:!0})});["open","error","close","message"].forEach(n=>{Object.defineProperty(pe.prototype,`on${n}`,{enumerable:!0,get(){for(let e of this.listeners(n))if(e[tl])return e[kb];return null},set(e){for(let t of this.listeners(n))if(t[tl]){this.removeListener(n,t);break}typeof e=="function"&&this.addEventListener(n,e,{[tl]:!0})}})});pe.prototype.addEventListener=Tb;pe.prototype.removeEventListener=xb;xh.exports=pe;function vh(n,e,t,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:wb,protocolVersion:nl[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(n._autoPong=s.autoPong,n._closeTimeout=s.closeTimeout,!nl.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${nl.join(", ")})`);let i;if(e instanceof el)i=e;else try{i=new el(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),n._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(n._redirects===0)throw x;Qi(n,x);return}let c=o?443:80,f=mb(16).toString("base64"),p=o?hb.request:fb.request,b=new Set,v;if(s.createConnection=s.createConnection||(o?$b:Ab),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&&(v=new dn({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=Cb({[dn.extensionName]:v.offer()})),t.length){for(let x of t){if(typeof x!="string"||!Eb.test(x)||b.has(x))throw new SyntaxError("An invalid or duplicated subprotocol was specified");b.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(n._redirects===0){n._originalIpc=a,n._originalSecure=o,n._originalHostOrSocketPath=a?s.socketPath:i.host;let x=r&&r.headers;if(r={...r,headers:{}},x)for(let[P,I]of Object.entries(x))r.headers[P.toLowerCase()]=I}else if(n.listenerCount("redirect")===0){let x=a?n._originalIpc?s.socketPath===n._originalHostOrSocketPath:!1:n._originalIpc?!1:i.host===n._originalHostOrSocketPath;(!x||n._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,x||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),T=n._req=p(s),n._redirects&&n.emit("redirect",n.url,T)}else T=n._req=p(s);s.timeout&&T.on("timeout",()=>{Ke(n,T,"Opening handshake has timed out")}),T.on("error",x=>{T===null||T[bh]||(T=n._req=null,Qi(n,x))}),T.on("response",x=>{let P=x.headers.location,I=x.statusCode;if(P&&s.followRedirects&&I>=300&&I<400){if(++n._redirects>s.maxRedirects){Ke(n,T,"Maximum redirects exceeded");return}T.abort();let w;try{w=new el(P,e)}catch{let M=new SyntaxError(`Invalid URL: ${P}`);Qi(n,M);return}vh(n,w,t,r)}else n.emit("unexpected-response",T,x)||Ke(n,T,`Unexpected server response: ${x.statusCode}`)}),T.on("upgrade",(x,P,I)=>{if(n.emit("upgrade",x),n.readyState!==pe.CONNECTING)return;T=n._req=null;let w=x.headers.upgrade;if(w===void 0||w.toLowerCase()!=="websocket"){Ke(n,P,"Invalid Upgrade header");return}let B=gb("sha1").update(f+_b).digest("base64");if(x.headers["sec-websocket-accept"]!==B){Ke(n,P,"Invalid Sec-WebSocket-Accept header");return}let M=x.headers["sec-websocket-protocol"],D;if(M!==void 0?b.size?b.has(M)||(D="Server sent an invalid subprotocol"):D="Server sent a subprotocol but none was requested":b.size&&(D="Server sent no subprotocol"),D){Ke(n,P,D);return}M&&(n._protocol=M);let W=x.headers["sec-websocket-extensions"];if(W!==void 0){if(!v){Ke(n,P,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let d;try{d=Ib(W)}catch{Ke(n,P,"Invalid Sec-WebSocket-Extensions header");return}let m=Object.keys(d);if(m.length!==1||m[0]!==dn.extensionName){Ke(n,P,"Server indicated an extension that was not requested");return}try{v.accept(d[dn.extensionName])}catch{Ke(n,P,"Invalid Sec-WebSocket-Extensions header");return}n._extensions[dn.extensionName]=v}n.setSocket(P,I,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(T,n):T.end()}function Qi(n,e){n._readyState=pe.CLOSING,n._errorEmitted=!0,n.emit("error",e),n.emitClose()}function Ab(n){return n.path=n.socketPath,gh.connect(n)}function $b(n){return n.path=void 0,!n.servername&&n.servername!==""&&(n.servername=gh.isIP(n.host)?"":n.host),pb.connect(n)}function Ke(n,e,t){n._readyState=pe.CLOSING;let r=new Error(t);Error.captureStackTrace(r,Ke),e.setHeader?(e[bh]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Qi,n,r)):(e.destroy(r),e.once("error",n.emit.bind(n,"error")),e.once("close",n.emitClose.bind(n)))}function rl(n,e,t){if(e){let r=vb(e)?e.size:Rb(e).length;n._socket?n._sender._bufferedBytes+=r:n._bufferedAmount+=r}if(t){let r=new Error(`WebSocket is not open: readyState ${n.readyState} (${Bt[n.readyState]})`);process.nextTick(t,r)}}function Pb(n,e){let t=this[we];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=n,t._socket[we]!==void 0&&(t._socket.removeListener("data",eo),process.nextTick(wh,t._socket),n===1005?t.close():t.close(n,e))}function jb(){let n=this[we];n.isPaused||n._socket.resume()}function Ob(n){let e=this[we];e._socket[we]!==void 0&&(e._socket.removeListener("data",eo),process.nextTick(wh,e._socket),e.close(n[Sb])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n))}function mh(){this[we].emitClose()}function Nb(n,e){this[we].emit("message",n,e)}function Mb(n){let e=this[we];e._autoPong&&e.pong(n,!this._isServer,yh),e.emit("ping",n)}function zb(n){this[we].emit("pong",n)}function wh(n){n.resume()}function Db(n){let e=this[we];e.readyState!==pe.CLOSED&&(e.readyState===pe.OPEN&&(e._readyState=pe.CLOSING,_h(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n)))}function _h(n){n._closeTimer=setTimeout(n._socket.destroy.bind(n._socket),n._closeTimeout)}function kh(){let n=this[we];if(this.removeListener("close",kh),this.removeListener("data",eo),this.removeListener("end",Sh),n._readyState=pe.CLOSING,!this._readableState.endEmitted&&!n._closeFrameReceived&&!n._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);n._receiver.write(e)}n._receiver.end(),this[we]=void 0,clearTimeout(n._closeTimer),n._receiver._writableState.finished||n._receiver._writableState.errorEmitted?n.emitClose():(n._receiver.on("error",mh),n._receiver.on("finish",mh))}function eo(n){this[we]._receiver.write(n)||this.pause()}function Sh(){let n=this[we];n._readyState=pe.CLOSING,n._receiver.end(),this.end()}function Th(){let n=this[we];this.removeListener("error",Th),this.on("error",yh),n&&(n._readyState=pe.CLOSING,this.destroy())}});var Eh=ne((Pk,Rh)=>{"use strict";var $k=to(),{Duplex:Lb}=require("stream");function Ch(n){n.emit("close")}function Ub(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Ih(n){this.removeListener("error",Ih),this.destroy(),this.listenerCount("error")===0&&this.emit("error",n)}function qb(n,e){let t=!0,r=new Lb({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return n.on("message",function(i,o){let a=!o&&r._readableState.objectMode?i.toString():i;r.push(a)||n.pause()}),n.once("error",function(i){r.destroyed||(t=!1,r.destroy(i))}),n.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(s,i){if(n.readyState===n.CLOSED){i(s),process.nextTick(Ch,r);return}let o=!1;n.once("error",function(u){o=!0,i(u)}),n.once("close",function(){o||i(s),process.nextTick(Ch,r)}),t&&n.terminate()},r._final=function(s){if(n.readyState===n.CONNECTING){n.once("open",function(){r._final(s)});return}n._socket!==null&&(n._socket._writableState.finished?(s(),r._readableState.endEmitted&&r.destroy()):(n._socket.once("finish",function(){s()}),n.close()))},r._read=function(){n.isPaused&&n.resume()},r._write=function(s,i,o){if(n.readyState===n.CONNECTING){n.once("open",function(){r._write(s,i,o)});return}n.send(s,o)},r.on("end",Ub),r.on("error",Ih),r}Rh.exports=qb});var sl=ne((jk,Ah)=>{"use strict";var{tokenChars:Fb}=rs();function Bb(n){let e=new Set,t=-1,r=-1,s=0;for(s;s<n.length;s++){let o=n.charCodeAt(s);if(r===-1&&Fb[o]===1)t===-1&&(t=s);else if(s!==0&&(o===32||o===9))r===-1&&t!==-1&&(r=s);else if(o===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${s}`);r===-1&&(r=s);let a=n.slice(t,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),t=r=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(t===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let i=n.slice(t,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}Ah.exports={parse:Bb}});var zh=ne((Nk,Mh)=>{"use strict";var Kb=require("events"),no=require("http"),{Duplex:Ok}=require("stream"),{createHash:Zb}=require("crypto"),$h=Yi(),br=ns(),Hb=sl(),Gb=to(),{CLOSE_TIMEOUT:Vb,GUID:Wb,kWebSocket:Jb}=Ut(),Yb=/^[+/0-9A-Za-z]{22}==$/,Ph=0,jh=1,Nh=2,il=class extends Kb{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:Vb,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Gb,...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=no.createServer((r,s)=>{let i=no.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 r=this.emit.bind(this,"connection");this._removeListeners=Xb(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Ph}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(Ds,this);return}if(e&&this.once("close",e),this._state!==jh)if(this._state=jh,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(Ds,this):process.nextTick(Ds,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{Ds(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,r,s){t.on("error",Oh);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){vr(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){vr(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!Yb.test(i)){vr(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){vr(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Ls(t,400);return}let u=e.headers["sec-websocket-protocol"],c=new Set;if(u!==void 0)try{c=Hb.parse(u)}catch{vr(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 b=new br({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let v=$h.parse(f);v[br.extensionName]&&(b.accept(v[br.extensionName]),p[br.extensionName]=b)}catch{vr(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let b={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(b,(v,T,x,P)=>{if(!v)return Ls(t,T||401,x,P);this.completeUpgrade(p,i,c,e,t,r,s)});return}if(!this.options.verifyClient(b))return Ls(t,401)}this.completeUpgrade(p,i,c,e,t,r,s)}completeUpgrade(e,t,r,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[Jb])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Ph)return Ls(i,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Zb("sha1").update(t+Wb).digest("base64")}`],f=new this.options.WebSocket(null,void 0,this.options);if(r.size){let p=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;p&&(c.push(`Sec-WebSocket-Protocol: ${p}`),f._protocol=p)}if(e[br.extensionName]){let p=e[br.extensionName].params,b=$h.format({[br.extensionName]:[p]});c.push(`Sec-WebSocket-Extensions: ${b}`),f._extensions=e}this.emit("headers",c,s),i.write(c.concat(`\r
|
|
255
|
+
`).filter(Boolean).filter(s=>!e.has(s))}catch{}for(let r of t)try{let s=await F(n,["show",`HEAD:${r}`]);/^={7}$/m.test(s)||e.add(r)}catch{e.add(r)}return[...e]}async function ks(n,e,t){be.default.mkdirSync(he.default.dirname(e),{recursive:!0,mode:448}),await F(n,["fetch","origin",t],{timeoutMs:3e5}),await F(n,["worktree","add","--detach",e,`origin/${t}`]),await F(e,["checkout","-B",t,`origin/${t}`])}async function Xo(n,e){try{await F(n,["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 Qo(n,e,t){try{return await Cu("git",["-C",n,"diff","--quiet",e,t,"--"],{timeout:12e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),!1}catch(r){let s=r;if(s.code===1)return!0;throw new Error(`git diff failed comparing ${e}..${t}: ${(s.stderr||s.message||"").trim().slice(0,500)}`)}}async function Qn(n){return(await F(n,["config","--get","remote.origin.url"])).trim()}function it(n){let e=/^git@github\.com(?:-[\w.-]+)?:([^/]+)\/(.+?)(\.git)?$/.exec(n)??/^https:\/\/github\.com\/([^/]+)\/(.+?)(\.git)?\/?$/.exec(n)??/^ssh:\/\/git@github\.com(?:-[\w.-]+)?\/([^/]+)\/(.+?)(\.git)?$/.exec(n);return e?{owner:e[1],repo:e[2]}:null}var be,Jn,he,Tu,xu,Cu,gi,yi,rn,sn,Iu,Nt,vt=Ks(()=>{"use strict";be=E(require("node:fs"),1),Jn=E(require("node:os"),1),he=E(require("node:path"),1),Tu=require("node:child_process"),xu=require("node:util"),Cu=(0,xu.promisify)(Tu.execFile),gi="Allwright Agent",yi="agent@ticketpilot.local",rn=200,sn=2e4,Iu=[/^\.github\/workflows\//,/^\.git\b/,/(^|\/)\.githooks\//];Nt=".ticketpilot-delete"});function ki(n,e,t){let r=(t??"").trim().toLowerCase(),s=r?n.githubUsers[r]?.token:void 0;if(s)return{token:s,source:"user"};let i=n.repos[e]?.github?.token;return i?{token:i,source:"repo"}:n.github?.token?{token:n.github.token,source:"global"}:null}function Ie(n,e){return n.repos[e]?.github?.token??n.github?.token??null}function Ou(n,e){let t=[n.jira,...Object.values(n.repos).map(a=>a.jira)].filter(a=>!!a),r=new Set(t.map(a=>a.email.toLowerCase())),s=!!n.github?.token||Object.values(n.repos).some(a=>a.github?.token),i=n.github?.login??Object.values(n.repos).find(a=>a.github?.login)?.github?.login??"",o=e.map(a=>{let u=a.trim().toLowerCase(),c=n.jiraUsers[u]?"own":r.has(u)?"runner-account":"missing",f=c==="own"?n.jiraUsers[u].email:c==="runner-account"?u:"",p=n.githubUsers[u]?"own":s?"shared":"missing",v=p==="own"?n.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 er=Ks(()=>{"use strict"});var sr={};Zs(sr,{GitHubClient:()=>Re});var Eg,Re,at=Ks(()=>{"use strict";Eg=process.env.TICKETPILOT_GITHUB_API??"https://api.github.com",Re=class{constructor(e){this.token=e}token;async request(e,t,r){let s=await fetch(`${Eg}${t}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"allwright",...r!==void 0?{"Content-Type":"application/json"}:{}},body:r===void 0?void 0:JSON.stringify(r)}),i=await s.text(),o=null;try{o=i?JSON.parse(i):null}catch{}if(s.status===401)throw new Error("GitHub rejected the token (401) - expired or revoked? Run `allwright github set-token`");if(!s.ok&&s.status!==422){let 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,r){let{status:s,data:i}=await this.request("POST",`/repos/${e}/${t}/pulls`,r);if(s===422){let{data:o}=await this.request("GET",`/repos/${e}/${t}/pulls?head=${encodeURIComponent(`${e}:${r.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:r.base}}async getReviews(e,t,r){let{data:s}=await this.request("GET",`/repos/${e}/${t}/pulls/${r}/reviews?per_page=100`);return(s??[]).map(i=>({state:i.state??"",commitId:i.commit_id??"",user:i.user?.login??"",submittedAt:i.submitted_at??""}))}async getPullRequest(e,t,r){try{let{data:s}=await this.request("GET",`/repos/${e}/${t}/pulls/${r}`);return{number:s.number,url:s.html_url,state:s.state,merged:s.merged,headSha:s.head.sha,mergeableState:s.mergeable_state??null,baseRef:s.base?.ref??""}}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return null;throw s}}async mergePullRequest(e,t,r,s,i={}){try{return await this.request("PUT",`/repos/${e}/${t}/pulls/${r}/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:r}=await this.request("GET",`/repos/${e}/${t}`);return{ok:!0,canPush:!!(r.permissions?.push||r.permissions?.admin)}}catch(r){let s=r instanceof Error?r.message:String(r);return{ok:!1,canPush:!1,error:s.includes("-> 404")?"not found (private repo this token cannot see, or the name is wrong)":s.slice(0,200)}}}async closePullRequest(e,t,r){await this.request("PATCH",`/repos/${e}/${t}/pulls/${r}`,{state:"closed"})}async deleteBranch(e,t,r){try{await this.request("DELETE",`/repos/${e}/${t}/git/refs/heads/${encodeURIComponent(r)}`)}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return;throw s}}}});var Ut=ne((vk,zd)=>{"use strict";var Nd=["nodebuffer","arraybuffer","fragments"],Md=typeof Blob<"u";Md&&Nd.push("blob");zd.exports={BINARY_TYPES:Nd,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Md,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var js=ne((bk,Bi)=>{"use strict";var{EMPTY_BUFFER:jy}=Ut(),La=Buffer[Symbol.species];function Oy(n,e){if(n.length===0)return jy;if(n.length===1)return n[0];let t=Buffer.allocUnsafe(e),r=0;for(let s=0;s<n.length;s++){let i=n[s];t.set(i,r),r+=i.length}return r<e?new La(t.buffer,t.byteOffset,r):t}function Dd(n,e,t,r,s){for(let i=0;i<s;i++)t[r+i]=n[i]^e[i&3]}function Ld(n,e){for(let t=0;t<n.length;t++)n[t]^=e[t&3]}function Ny(n){return n.length===n.buffer.byteLength?n.buffer:n.buffer.slice(n.byteOffset,n.byteOffset+n.length)}function Ua(n){if(Ua.readOnly=!0,Buffer.isBuffer(n))return n;let e;return n instanceof ArrayBuffer?e=new La(n):ArrayBuffer.isView(n)?e=new La(n.buffer,n.byteOffset,n.byteLength):(e=Buffer.from(n),Ua.readOnly=!1),e}Bi.exports={concat:Oy,mask:Dd,toArrayBuffer:Ny,toBuffer:Ua,unmask:Ld};if(!process.env.WS_NO_BUFFER_UTIL)try{let n=require("bufferutil");Bi.exports.mask=function(e,t,r,s,i){i<48?Dd(e,t,r,s,i):n.mask(e,t,r,s,i)},Bi.exports.unmask=function(e,t){e.length<32?Ld(e,t):n.unmask(e,t)}}catch{}});var Fd=ne((wk,qd)=>{"use strict";var Ud=Symbol("kDone"),qa=Symbol("kRun"),Fa=class{constructor(e){this[Ud]=()=>{this.pending--,this[qa]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[qa]()}[qa](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Ud])}}};qd.exports=Fa});var ns=ne((_k,Hd)=>{"use strict";var Os=require("zlib"),Bd=js(),My=Fd(),{kStatusCode:Kd}=Ut(),zy=Buffer[Symbol.species],Dy=Buffer.from([0,0,255,255]),Zi=Symbol("permessage-deflate"),qt=Symbol("total-length"),es=Symbol("callback"),cn=Symbol("buffers"),ts=Symbol("error"),Ki,Ba=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,!Ki){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ki=new My(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[es];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,r=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(!r)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(r.server_no_context_takeover=!0),t.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(r.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?r.client_max_window_bits=t.clientMaxWindowBits:(r.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}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(r=>{let s=t[r];if(s.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(s=s[0],r==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else if(r==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else throw new Error(`Unknown parameter "${r}"`);t[r]=s})}),e}decompress(e,t,r){Ki.add(s=>{this._decompress(e,t,(i,o)=>{s(),r(i,o)})})}compress(e,t,r){Ki.add(s=>{this._compress(e,t,(i,o)=>{s(),r(i,o)})})}_decompress(e,t,r){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Os.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Os.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Zi]=this,this._inflate[qt]=0,this._inflate[cn]=[],this._inflate.on("error",Uy),this._inflate.on("data",Zd)}this._inflate[es]=r,this._inflate.write(e),t&&this._inflate.write(Dy),this._inflate.flush(()=>{let i=this._inflate[ts];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=Bd.concat(this._inflate[cn],this._inflate[qt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[qt]=0,this._inflate[cn]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,t,r){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Os.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Os.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[qt]=0,this._deflate[cn]=[],this._deflate.on("data",Ly)}this._deflate[es]=r,this._deflate.write(e),this._deflate.flush(Os.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Bd.concat(this._deflate[cn],this._deflate[qt]);t&&(i=new zy(i.buffer,i.byteOffset,i.length-4)),this._deflate[es]=null,this._deflate[qt]=0,this._deflate[cn]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};Hd.exports=Ba;function Ly(n){this[cn].push(n),this[qt]+=n.length}function Zd(n){if(this[qt]+=n.length,this[Zi]._maxPayload<1||this[qt]<=this[Zi]._maxPayload){this[cn].push(n);return}this[ts]=new RangeError("Max payload size exceeded"),this[ts].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ts][Kd]=1009,this.removeListener("data",Zd),this.reset()}function Uy(n){if(this[Zi]._inflate=null,this[ts]){this[es](this[ts]);return}n[Kd]=1007,this[es](n)}});var rs=ne((kk,Hi)=>{"use strict";var{isUtf8:Gd}=require("buffer"),{hasBlob:qy}=Ut(),Fy=[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 By(n){return n>=1e3&&n<=1014&&n!==1004&&n!==1005&&n!==1006||n>=3e3&&n<=4999}function Ka(n){let e=n.length,t=0;for(;t<e;)if((n[t]&128)===0)t++;else if((n[t]&224)===192){if(t+1===e||(n[t+1]&192)!==128||(n[t]&254)===192)return!1;t+=2}else if((n[t]&240)===224){if(t+2>=e||(n[t+1]&192)!==128||(n[t+2]&192)!==128||n[t]===224&&(n[t+1]&224)===128||n[t]===237&&(n[t+1]&224)===160)return!1;t+=3}else if((n[t]&248)===240){if(t+3>=e||(n[t+1]&192)!==128||(n[t+2]&192)!==128||(n[t+3]&192)!==128||n[t]===240&&(n[t+1]&240)===128||n[t]===244&&n[t+1]>143||n[t]>244)return!1;t+=4}else return!1;return!0}function Ky(n){return qy&&typeof n=="object"&&typeof n.arrayBuffer=="function"&&typeof n.type=="string"&&typeof n.stream=="function"&&(n[Symbol.toStringTag]==="Blob"||n[Symbol.toStringTag]==="File")}Hi.exports={isBlob:Ky,isValidStatusCode:By,isValidUTF8:Ka,tokenChars:Fy};if(Gd)Hi.exports.isValidUTF8=function(n){return n.length<24?Ka(n):Gd(n)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let n=require("utf-8-validate");Hi.exports.isValidUTF8=function(e){return e.length<32?Ka(e):n(e)}}catch{}});var Wa=ne((Sk,eh)=>{"use strict";var{Writable:Zy}=require("stream"),Vd=ns(),{BINARY_TYPES:Hy,EMPTY_BUFFER:Wd,kStatusCode:Gy,kWebSocket:Vy}=Ut(),{concat:Za,toArrayBuffer:Wy,unmask:Jy}=js(),{isValidStatusCode:Yy,isValidUTF8:Jd}=rs(),Gi=Buffer[Symbol.species],tt=0,Yd=1,Xd=2,Qd=3,Ha=4,Ga=5,Vi=6,Va=class extends Zy{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Hy[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[Vy]=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=tt}_write(e,t,r){if(this._opcode===8&&this._state==tt)return r();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){r(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new Gi(r.buffer,r.byteOffset+e,r.length-e),new Gi(r.buffer,r.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let r=this._buffers[0],s=t.length-e;e>=r.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new Gi(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case tt:this.getInfo(e);break;case Yd:this.getPayloadLength16(e);break;case Xd:this.getPayloadLength64(e);break;case Qd:this.getMask();break;case Ha:this.getData(e);break;case Ga:case Vi: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 r=(t[0]&64)===64;if(r&&!this._extensions[Vd.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(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(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=Yd:this._payloadLength===127?this._state=Xd: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),r=t.readUInt32BE(0);if(r>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=r*Math.pow(2,32)+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=Qd:this._state=Ha}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Ha}getData(e){let t=Wd;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&&Jy(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let r=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(r);return}if(this._compressed){this._state=Ga,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Vd.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===tt&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=tt;return}let t=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=Za(r,t):this._binaryType==="arraybuffer"?s=Wy(Za(r,t)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=tt):(this._state=Vi,setImmediate(()=>{this.emit("message",s,!0),this._state=tt,this.startLoop(e)}))}else{let s=Za(r,t);if(!this._skipUTF8Validation&&!Jd(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Ga||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=tt):(this._state=Vi,setImmediate(()=>{this.emit("message",s,!1),this._state=tt,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Wd),this.end();else{let r=e.readUInt16BE(0);if(!Yy(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new Gi(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Jd(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",r,s),this.end()}this._state=tt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=tt):(this._state=Vi,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=tt,this.startLoop(t)}))}createError(e,t,r,s,i){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[Gy]=s,o}};eh.exports=Va});var Xa=ne((xk,rh)=>{"use strict";var{Duplex:Tk}=require("stream"),{randomFillSync:Xy}=require("crypto"),{types:{isUint8Array:Qy}}=require("util"),th=ns(),{EMPTY_BUFFER:ev,kWebSocket:tv,NOOP:nv}=Ut(),{isBlob:ss,isValidStatusCode:rv}=rs(),{mask:nh,toBuffer:mr}=js(),nt=Symbol("kByteLength"),sv=Buffer.alloc(4),Wi=8*1024,gr,is=Wi,ct=0,iv=1,ov=2,Ja=class n{constructor(e,t,r){this._extensions=t||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=ct,this.onerror=nv,this[tv]=void 0}static frame(e,t){let r,s=!1,i=2,o=!1;t.mask&&(r=t.maskBuffer||sv,t.generateMask?t.generateMask(r):(is===Wi&&(gr===void 0&&(gr=Buffer.alloc(Wi)),Xy(gr,0,Wi),is=0),r[0]=gr[is++],r[1]=gr[is++],r[2]=gr[is++],r[3]=gr[is++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!t.mask||o)&&t[nt]!==void 0?a=t[nt]:(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]=r[0],c[i-3]=r[1],c[i-2]=r[2],c[i-1]=r[3],o?[c,e]:s?(nh(e,r,c,i,a),[c]):(nh(e,r,e,0,a),[c,e])):[c,e]}close(e,t,r,s){let i;if(e===void 0)i=ev;else{if(typeof e!="number"||!rv(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(Qy(t))i.set(t,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[nt]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ct?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(n.frame(i,o),s)}ping(e,t,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):ss(e)?(s=e.size,i=!1):(e=mr(e),s=e.length,i=mr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[nt]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};ss(e)?this._state!==ct?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==ct?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(n.frame(e,o),r)}pong(e,t,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):ss(e)?(s=e.size,i=!1):(e=mr(e),s=e.length,i=mr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[nt]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};ss(e)?this._state!==ct?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==ct?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(n.frame(e,o),r)}send(e,t,r){let s=this._extensions[th.extensionName],i=t.binary?2:1,o=t.compress,a,u;typeof e=="string"?(a=Buffer.byteLength(e),u=!1):ss(e)?(a=e.size,u=!1):(e=mr(e),a=e.length,u=mr.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={[nt]:a,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:u,rsv1:o};ss(e)?this._state!==ct?this.enqueue([this.getBlobData,e,this._compress,c,r]):this.getBlobData(e,this._compress,c,r):this._state!==ct?this.enqueue([this.dispatch,e,this._compress,c,r]):this.dispatch(e,this._compress,c,r)}getBlobData(e,t,r,s){this._bufferedBytes+=r[nt],this._state=ov,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Ya,this,a,s);return}this._bufferedBytes-=r[nt];let o=mr(i);t?this.dispatch(o,t,r,s):(this._state=ct,this.sendFrame(n.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(av,this,i,s)})}dispatch(e,t,r,s){if(!t){this.sendFrame(n.frame(e,r),s);return}let i=this._extensions[th.extensionName];this._bufferedBytes+=r[nt],this._state=iv,i.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");Ya(this,u,s);return}this._bufferedBytes-=r[nt],this._state=ct,r.readOnly=!1,this.sendFrame(n.frame(a,r),s),this.dequeue()})}dequeue(){for(;this._state===ct&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][nt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][nt],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)}};rh.exports=Ja;function Ya(n,e,t){typeof t=="function"&&t(e);for(let r=0;r<n._queue.length;r++){let s=n._queue[r],i=s[s.length-1];typeof i=="function"&&i(e)}}function av(n,e,t){Ya(n,e,t),n.onerror(e)}});var hh=ne((Ck,dh)=>{"use strict";var{kForOnEventAttribute:Ns,kListener:Qa}=Ut(),sh=Symbol("kCode"),ih=Symbol("kData"),oh=Symbol("kError"),ah=Symbol("kMessage"),lh=Symbol("kReason"),os=Symbol("kTarget"),uh=Symbol("kType"),ch=Symbol("kWasClean"),Ft=class{constructor(e){this[os]=null,this[uh]=e}get target(){return this[os]}get type(){return this[uh]}};Object.defineProperty(Ft.prototype,"target",{enumerable:!0});Object.defineProperty(Ft.prototype,"type",{enumerable:!0});var yr=class extends Ft{constructor(e,t={}){super(e),this[sh]=t.code===void 0?0:t.code,this[lh]=t.reason===void 0?"":t.reason,this[ch]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[sh]}get reason(){return this[lh]}get wasClean(){return this[ch]}};Object.defineProperty(yr.prototype,"code",{enumerable:!0});Object.defineProperty(yr.prototype,"reason",{enumerable:!0});Object.defineProperty(yr.prototype,"wasClean",{enumerable:!0});var as=class extends Ft{constructor(e,t={}){super(e),this[oh]=t.error===void 0?null:t.error,this[ah]=t.message===void 0?"":t.message}get error(){return this[oh]}get message(){return this[ah]}};Object.defineProperty(as.prototype,"error",{enumerable:!0});Object.defineProperty(as.prototype,"message",{enumerable:!0});var Ms=class extends Ft{constructor(e,t={}){super(e),this[ih]=t.data===void 0?null:t.data}get data(){return this[ih]}};Object.defineProperty(Ms.prototype,"data",{enumerable:!0});var lv={addEventListener(n,e,t={}){for(let s of this.listeners(n))if(!t[Ns]&&s[Qa]===e&&!s[Ns])return;let r;if(n==="message")r=function(i,o){let a=new Ms("message",{data:o?i:i.toString()});a[os]=this,Ji(e,this,a)};else if(n==="close")r=function(i,o){let a=new yr("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[os]=this,Ji(e,this,a)};else if(n==="error")r=function(i){let o=new as("error",{error:i,message:i.message});o[os]=this,Ji(e,this,o)};else if(n==="open")r=function(){let i=new Ft("open");i[os]=this,Ji(e,this,i)};else return;r[Ns]=!!t[Ns],r[Qa]=e,t.once?this.once(n,r):this.on(n,r)},removeEventListener(n,e){for(let t of this.listeners(n))if(t[Qa]===e&&!t[Ns]){this.removeListener(n,t);break}}};dh.exports={CloseEvent:yr,ErrorEvent:as,Event:Ft,EventTarget:lv,MessageEvent:Ms};function Ji(n,e,t){typeof n=="object"&&n.handleEvent?n.handleEvent.call(n,t):n.call(e,t)}});var Yi=ne((Ik,fh)=>{"use strict";var{tokenChars:zs}=rs();function St(n,e,t){n[e]===void 0?n[e]=[t]:n[e].push(t)}function uv(n){let e=Object.create(null),t=Object.create(null),r=!1,s=!1,i=!1,o,a,u=-1,c=-1,f=-1,p=0;for(;p<n.length;p++)if(c=n.charCodeAt(p),o===void 0)if(f===-1&&zs[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 b=n.slice(u,f);c===44?(St(e,b,t),t=Object.create(null)):o=b,u=f=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(a===void 0)if(f===-1&&zs[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),St(t,n.slice(u,f),!0),c===44&&(St(e,o,t),t=Object.create(null),o=void 0),u=f=-1}else if(c===61&&u!==-1&&f===-1)a=n.slice(u,p),u=f=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(s){if(zs[c]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:r||(r=!0),s=!1}else if(i)if(zs[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&&n.charCodeAt(p-1)===61)i=!0;else if(f===-1&&zs[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 b=n.slice(u,f);r&&(b=b.replace(/\\/g,""),r=!1),St(t,a,b),c===44&&(St(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=n.slice(u,f);return o===void 0?St(e,v,t):(a===void 0?St(t,v,!0):r?St(t,a,v.replace(/\\/g,"")):St(t,a,v),St(e,o,t)),e}function cv(n){return Object.keys(n).map(e=>{let t=n[e];return Array.isArray(t)||(t=[t]),t.map(r=>[e].concat(Object.keys(r).map(s=>{let i=r[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}fh.exports={format:cv,parse:uv}});var to=ne((Ak,xh)=>{"use strict";var dv=require("events"),hv=require("https"),fv=require("http"),gh=require("net"),pv=require("tls"),{randomBytes:mv,createHash:gv}=require("crypto"),{Duplex:Rk,Readable:Ek}=require("stream"),{URL:el}=require("url"),dn=ns(),yv=Wa(),vv=Xa(),{isBlob:bv}=rs(),{BINARY_TYPES:ph,CLOSE_TIMEOUT:wv,EMPTY_BUFFER:Xi,GUID:_v,kForOnEventAttribute:tl,kListener:kv,kStatusCode:Sv,kWebSocket:we,NOOP:yh}=Ut(),{EventTarget:{addEventListener:Tv,removeEventListener:xv}}=hh(),{format:Cv,parse:Iv}=Yi(),{toBuffer:Rv}=js(),vh=Symbol("kAborted"),nl=[8,13],Bt=["CONNECTING","OPEN","CLOSING","CLOSED"],Ev=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,pe=class n extends dv{constructor(e,t,r){super(),this._binaryType=ph[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Xi,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=n.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?(r=t,t=[]):t=[t]),bh(this,e,t,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){ph.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,r){let s=new yv({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new vv(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[we]=this,i[we]=this,e[we]=this,s.on("conclude",Pv),s.on("drain",jv),s.on("error",Ov),s.on("message",Nv),s.on("ping",Mv),s.on("pong",zv),i.onerror=Dv,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",kh),e.on("data",eo),e.on("end",Sh),e.on("error",Th),this._readyState=n.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[dn.extensionName]&&this._extensions[dn.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){Ke(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===n.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=n.CLOSING,this._sender.close(e,t,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),_h(this)}}pause(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,r){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=t=void 0):typeof t=="function"&&(r=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){rl(this,e,r);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Xi,t,r)}pong(e,t,r){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=t=void 0):typeof t=="function"&&(r=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){rl(this,e,r);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Xi,t,r)}resume(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,r){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(r=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){rl(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[dn.extensionName]||(s.compress=!1),this._sender.send(e||Xi,s,r)}terminate(){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){Ke(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=n.CLOSING,this._socket.destroy())}}};Object.defineProperty(pe,"CONNECTING",{enumerable:!0,value:Bt.indexOf("CONNECTING")});Object.defineProperty(pe.prototype,"CONNECTING",{enumerable:!0,value:Bt.indexOf("CONNECTING")});Object.defineProperty(pe,"OPEN",{enumerable:!0,value:Bt.indexOf("OPEN")});Object.defineProperty(pe.prototype,"OPEN",{enumerable:!0,value:Bt.indexOf("OPEN")});Object.defineProperty(pe,"CLOSING",{enumerable:!0,value:Bt.indexOf("CLOSING")});Object.defineProperty(pe.prototype,"CLOSING",{enumerable:!0,value:Bt.indexOf("CLOSING")});Object.defineProperty(pe,"CLOSED",{enumerable:!0,value:Bt.indexOf("CLOSED")});Object.defineProperty(pe.prototype,"CLOSED",{enumerable:!0,value:Bt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(n=>{Object.defineProperty(pe.prototype,n,{enumerable:!0})});["open","error","close","message"].forEach(n=>{Object.defineProperty(pe.prototype,`on${n}`,{enumerable:!0,get(){for(let e of this.listeners(n))if(e[tl])return e[kv];return null},set(e){for(let t of this.listeners(n))if(t[tl]){this.removeListener(n,t);break}typeof e=="function"&&this.addEventListener(n,e,{[tl]:!0})}})});pe.prototype.addEventListener=Tv;pe.prototype.removeEventListener=xv;xh.exports=pe;function bh(n,e,t,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:wv,protocolVersion:nl[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(n._autoPong=s.autoPong,n._closeTimeout=s.closeTimeout,!nl.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${nl.join(", ")})`);let i;if(e instanceof el)i=e;else try{i=new el(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),n._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(n._redirects===0)throw x;Qi(n,x);return}let c=o?443:80,f=mv(16).toString("base64"),p=o?hv.request:fv.request,v=new Set,b;if(s.createConnection=s.createConnection||(o?$v:Av),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&&(b=new dn({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=Cv({[dn.extensionName]:b.offer()})),t.length){for(let x of t){if(typeof x!="string"||!Ev.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(n._redirects===0){n._originalIpc=a,n._originalSecure=o,n._originalHostOrSocketPath=a?s.socketPath:i.host;let x=r&&r.headers;if(r={...r,headers:{}},x)for(let[P,I]of Object.entries(x))r.headers[P.toLowerCase()]=I}else if(n.listenerCount("redirect")===0){let x=a?n._originalIpc?s.socketPath===n._originalHostOrSocketPath:!1:n._originalIpc?!1:i.host===n._originalHostOrSocketPath;(!x||n._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,x||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),T=n._req=p(s),n._redirects&&n.emit("redirect",n.url,T)}else T=n._req=p(s);s.timeout&&T.on("timeout",()=>{Ke(n,T,"Opening handshake has timed out")}),T.on("error",x=>{T===null||T[vh]||(T=n._req=null,Qi(n,x))}),T.on("response",x=>{let P=x.headers.location,I=x.statusCode;if(P&&s.followRedirects&&I>=300&&I<400){if(++n._redirects>s.maxRedirects){Ke(n,T,"Maximum redirects exceeded");return}T.abort();let w;try{w=new el(P,e)}catch{let M=new SyntaxError(`Invalid URL: ${P}`);Qi(n,M);return}bh(n,w,t,r)}else n.emit("unexpected-response",T,x)||Ke(n,T,`Unexpected server response: ${x.statusCode}`)}),T.on("upgrade",(x,P,I)=>{if(n.emit("upgrade",x),n.readyState!==pe.CONNECTING)return;T=n._req=null;let w=x.headers.upgrade;if(w===void 0||w.toLowerCase()!=="websocket"){Ke(n,P,"Invalid Upgrade header");return}let B=gv("sha1").update(f+_v).digest("base64");if(x.headers["sec-websocket-accept"]!==B){Ke(n,P,"Invalid Sec-WebSocket-Accept header");return}let M=x.headers["sec-websocket-protocol"],D;if(M!==void 0?v.size?v.has(M)||(D="Server sent an invalid subprotocol"):D="Server sent a subprotocol but none was requested":v.size&&(D="Server sent no subprotocol"),D){Ke(n,P,D);return}M&&(n._protocol=M);let W=x.headers["sec-websocket-extensions"];if(W!==void 0){if(!b){Ke(n,P,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let d;try{d=Iv(W)}catch{Ke(n,P,"Invalid Sec-WebSocket-Extensions header");return}let m=Object.keys(d);if(m.length!==1||m[0]!==dn.extensionName){Ke(n,P,"Server indicated an extension that was not requested");return}try{b.accept(d[dn.extensionName])}catch{Ke(n,P,"Invalid Sec-WebSocket-Extensions header");return}n._extensions[dn.extensionName]=b}n.setSocket(P,I,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(T,n):T.end()}function Qi(n,e){n._readyState=pe.CLOSING,n._errorEmitted=!0,n.emit("error",e),n.emitClose()}function Av(n){return n.path=n.socketPath,gh.connect(n)}function $v(n){return n.path=void 0,!n.servername&&n.servername!==""&&(n.servername=gh.isIP(n.host)?"":n.host),pv.connect(n)}function Ke(n,e,t){n._readyState=pe.CLOSING;let r=new Error(t);Error.captureStackTrace(r,Ke),e.setHeader?(e[vh]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Qi,n,r)):(e.destroy(r),e.once("error",n.emit.bind(n,"error")),e.once("close",n.emitClose.bind(n)))}function rl(n,e,t){if(e){let r=bv(e)?e.size:Rv(e).length;n._socket?n._sender._bufferedBytes+=r:n._bufferedAmount+=r}if(t){let r=new Error(`WebSocket is not open: readyState ${n.readyState} (${Bt[n.readyState]})`);process.nextTick(t,r)}}function Pv(n,e){let t=this[we];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=n,t._socket[we]!==void 0&&(t._socket.removeListener("data",eo),process.nextTick(wh,t._socket),n===1005?t.close():t.close(n,e))}function jv(){let n=this[we];n.isPaused||n._socket.resume()}function Ov(n){let e=this[we];e._socket[we]!==void 0&&(e._socket.removeListener("data",eo),process.nextTick(wh,e._socket),e.close(n[Sv])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n))}function mh(){this[we].emitClose()}function Nv(n,e){this[we].emit("message",n,e)}function Mv(n){let e=this[we];e._autoPong&&e.pong(n,!this._isServer,yh),e.emit("ping",n)}function zv(n){this[we].emit("pong",n)}function wh(n){n.resume()}function Dv(n){let e=this[we];e.readyState!==pe.CLOSED&&(e.readyState===pe.OPEN&&(e._readyState=pe.CLOSING,_h(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n)))}function _h(n){n._closeTimer=setTimeout(n._socket.destroy.bind(n._socket),n._closeTimeout)}function kh(){let n=this[we];if(this.removeListener("close",kh),this.removeListener("data",eo),this.removeListener("end",Sh),n._readyState=pe.CLOSING,!this._readableState.endEmitted&&!n._closeFrameReceived&&!n._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);n._receiver.write(e)}n._receiver.end(),this[we]=void 0,clearTimeout(n._closeTimer),n._receiver._writableState.finished||n._receiver._writableState.errorEmitted?n.emitClose():(n._receiver.on("error",mh),n._receiver.on("finish",mh))}function eo(n){this[we]._receiver.write(n)||this.pause()}function Sh(){let n=this[we];n._readyState=pe.CLOSING,n._receiver.end(),this.end()}function Th(){let n=this[we];this.removeListener("error",Th),this.on("error",yh),n&&(n._readyState=pe.CLOSING,this.destroy())}});var Eh=ne((Pk,Rh)=>{"use strict";var $k=to(),{Duplex:Lv}=require("stream");function Ch(n){n.emit("close")}function Uv(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Ih(n){this.removeListener("error",Ih),this.destroy(),this.listenerCount("error")===0&&this.emit("error",n)}function qv(n,e){let t=!0,r=new Lv({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return n.on("message",function(i,o){let a=!o&&r._readableState.objectMode?i.toString():i;r.push(a)||n.pause()}),n.once("error",function(i){r.destroyed||(t=!1,r.destroy(i))}),n.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(s,i){if(n.readyState===n.CLOSED){i(s),process.nextTick(Ch,r);return}let o=!1;n.once("error",function(u){o=!0,i(u)}),n.once("close",function(){o||i(s),process.nextTick(Ch,r)}),t&&n.terminate()},r._final=function(s){if(n.readyState===n.CONNECTING){n.once("open",function(){r._final(s)});return}n._socket!==null&&(n._socket._writableState.finished?(s(),r._readableState.endEmitted&&r.destroy()):(n._socket.once("finish",function(){s()}),n.close()))},r._read=function(){n.isPaused&&n.resume()},r._write=function(s,i,o){if(n.readyState===n.CONNECTING){n.once("open",function(){r._write(s,i,o)});return}n.send(s,o)},r.on("end",Uv),r.on("error",Ih),r}Rh.exports=qv});var sl=ne((jk,Ah)=>{"use strict";var{tokenChars:Fv}=rs();function Bv(n){let e=new Set,t=-1,r=-1,s=0;for(s;s<n.length;s++){let o=n.charCodeAt(s);if(r===-1&&Fv[o]===1)t===-1&&(t=s);else if(s!==0&&(o===32||o===9))r===-1&&t!==-1&&(r=s);else if(o===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${s}`);r===-1&&(r=s);let a=n.slice(t,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),t=r=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(t===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let i=n.slice(t,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}Ah.exports={parse:Bv}});var zh=ne((Nk,Mh)=>{"use strict";var Kv=require("events"),no=require("http"),{Duplex:Ok}=require("stream"),{createHash:Zv}=require("crypto"),$h=Yi(),vr=ns(),Hv=sl(),Gv=to(),{CLOSE_TIMEOUT:Vv,GUID:Wv,kWebSocket:Jv}=Ut(),Yv=/^[+/0-9A-Za-z]{22}==$/,Ph=0,jh=1,Nh=2,il=class extends Kv{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:Vv,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Gv,...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=no.createServer((r,s)=>{let i=no.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 r=this.emit.bind(this,"connection");this._removeListeners=Xv(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Ph}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(Ds,this);return}if(e&&this.once("close",e),this._state!==jh)if(this._state=jh,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(Ds,this):process.nextTick(Ds,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{Ds(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,r,s){t.on("error",Oh);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){br(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){br(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!Yv.test(i)){br(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){br(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Ls(t,400);return}let u=e.headers["sec-websocket-protocol"],c=new Set;if(u!==void 0)try{c=Hv.parse(u)}catch{br(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 vr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let b=$h.parse(f);b[vr.extensionName]&&(v.accept(b[vr.extensionName]),p[vr.extensionName]=v)}catch{br(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,(b,T,x,P)=>{if(!b)return Ls(t,T||401,x,P);this.completeUpgrade(p,i,c,e,t,r,s)});return}if(!this.options.verifyClient(v))return Ls(t,401)}this.completeUpgrade(p,i,c,e,t,r,s)}completeUpgrade(e,t,r,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[Jv])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Ph)return Ls(i,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Zv("sha1").update(t+Wv).digest("base64")}`],f=new this.options.WebSocket(null,void 0,this.options);if(r.size){let p=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;p&&(c.push(`Sec-WebSocket-Protocol: ${p}`),f._protocol=p)}if(e[vr.extensionName]){let p=e[vr.extensionName].params,v=$h.format({[vr.extensionName]:[p]});c.push(`Sec-WebSocket-Extensions: ${v}`),f._extensions=e}this.emit("headers",c,s),i.write(c.concat(`\r
|
|
256
256
|
`).join(`\r
|
|
257
|
-
`)),i.removeListener("error",Oh),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(Ds,this)})),a(f,s)}};Mh.exports=il;function
|
|
257
|
+
`)),i.removeListener("error",Oh),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(Ds,this)})),a(f,s)}};Mh.exports=il;function Xv(n,e){for(let t of Object.keys(e))n.on(t,e[t]);return function(){for(let r of Object.keys(e))n.removeListener(r,e[r])}}function Ds(n){n._state=Nh,n.emit("close")}function Oh(){this.destroy()}function Ls(n,e,t,r){t=t||no.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...r},n.once("finish",n.destroy),n.end(`HTTP/1.1 ${e} ${no.STATUS_CODES[e]}\r
|
|
258
258
|
`+Object.keys(r).map(s=>`${s}: ${r[s]}`).join(`\r
|
|
259
259
|
`)+`\r
|
|
260
260
|
\r
|
|
261
|
-
`+t)}function vr(n,e,t,r,s,i){if(n.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,vr),n.emit("wsClientError",o,t,e)}else Ls(t,r,s,i)}});var Vh={};Zs(Vh,{buildSetupReport:()=>yv,claudeLoggedIn:()=>Gh,repoDefaultBranch:()=>Hh});function Hh(n){let e=(...s)=>{try{return(0,ao.execFileSync)("git",["-C",n,...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 r=e("rev-parse","--abbrev-ref","HEAD");return r&&r!=="HEAD"?r:""}function Gh(n=Kh.default.homedir()){if(hn.default.existsSync(_r.default.join(n,".claude",".credentials.json")))return!0;try{return!!JSON.parse(hn.default.readFileSync(_r.default.join(n,".claude.json"),"utf8")).oauthAccount}catch{return!1}}async function yv(n,e){let t=!1,r="";if(Fs&&Date.now()-Fs.at<6e4)t=Fs.installed,r=Fs.version;else{try{let{stdout:o}=await gv(n.claudeBin,["--version"],{timeout:1e4});t=!0,r=o.trim().slice(0,60)}catch{t=!1}Fs={at:Date.now(),installed:t,version:r}}let s=e.map(o=>{let a=n.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=hn.default.existsSync(a.path);return{repoName:o,mapped:!0,pathExists:u,isGit:u&&hn.default.existsSync(_r.default.join(a.path,".git")),claudeMd:u&&hn.default.existsSync(_r.default.join(a.path,"CLAUDE.md")),deployMd:u&&hn.default.existsSync(_r.default.join(a.path,"DEPLOY.md")),testMd:u&&hn.default.existsSync(_r.default.join(a.path,"TEST.md")),githubToken:!!Ie(n,o),githubTokenOwn:!!a.github?.token,defaultBranch:u?Hh(a.path):""}}),i=Object.values(n.repos).find(o=>o.github?.token);return{jiraConfigured:!!n.jira,jiraEmail:n.jira?.email??"",claude:{installed:t,version:r,loggedIn:Gh()},githubTokenSet:!!(n.github?.token||i),githubLogin:n.github?.login??i?.github?.login??"",deploysEnabled:n.deploy.enabled,jiraUserCount:Object.keys(n.jiraUsers).length,repos:s}}var ao,hn,Kh,_r,Zh,gv,Fs,Wh=Ks(()=>{"use strict";ao=require("node:child_process"),hn=E(require("node:fs"),1),Kh=E(require("node:os"),1),_r=E(require("node:path"),1),Zh=require("node:util");er();gv=(0,Zh.promisify)(ao.execFile);Fs=null});var dt=E(require("node:fs"),1),cl=E(require("node:os"),1),us=E(require("node:path"),1),Zt=require("node:child_process"),Bs=require("node:crypto"),fn=E(require("node:readline/promises"),1);var Rl=E(Il(),1),{program:Iv,createCommand:Rv,createArgument:Ev,createOption:Av,CommanderError:$v,InvalidArgumentError:Pv,InvalidOptionArgumentError:jv,Command:El,Argument:Ov,Option:Nv,Help:Mv}=Rl.default;var At=E(require("node:fs"),1),Qs=E(require("node:os"),1),ei=E(require("node:path"),1);var _={};Zs(_,{BRAND:()=>Zf,DIRTY:()=>mn,EMPTY_PATH:()=>Sf,INVALID:()=>K,NEVER:()=>Ep,OK:()=>Te,ParseStatus:()=>ke,Schema:()=>Q,ZodAny:()=>Vt,ZodArray:()=>Et,ZodBigInt:()=>yn,ZodBoolean:()=>bn,ZodBranded:()=>ps,ZodCatch:()=>En,ZodDate:()=>vn,ZodDefault:()=>Rn,ZodDiscriminatedUnion:()=>Js,ZodEffects:()=>We,ZodEnum:()=>Cn,ZodError:()=>je,ZodFirstPartyTypeKind:()=>Z,ZodFunction:()=>Xs,ZodIntersection:()=>Sn,ZodIssueCode:()=>R,ZodLazy:()=>Tn,ZodLiteral:()=>xn,ZodMap:()=>Er,ZodNaN:()=>$r,ZodNativeEnum:()=>In,ZodNever:()=>rt,ZodNull:()=>_n,ZodNullable:()=>pt,ZodNumber:()=>gn,ZodObject:()=>Oe,ZodOptional:()=>Ge,ZodParsedType:()=>O,ZodPipeline:()=>ms,ZodPromise:()=>Wt,ZodReadonly:()=>An,ZodRecord:()=>Ys,ZodSchema:()=>Q,ZodSet:()=>Ar,ZodString:()=>Gt,ZodSymbol:()=>Ir,ZodTransformer:()=>We,ZodTuple:()=>ft,ZodType:()=>Q,ZodUndefined:()=>wn,ZodUnion:()=>kn,ZodUnknown:()=>Rt,ZodVoid:()=>Rr,addIssueToContext:()=>j,any:()=>ep,array:()=>sp,bigint:()=>Wf,boolean:()=>Ul,coerce:()=>Rp,custom:()=>zl,date:()=>Jf,datetimeRegex:()=>Nl,defaultErrorMap:()=>Ct,discriminatedUnion:()=>lp,effect:()=>wp,enum:()=>yp,function:()=>pp,getErrorMap:()=>Tr,getParsedType:()=>ht,instanceof:()=>Gf,intersection:()=>up,isAborted:()=>Vs,isAsync:()=>xr,isDirty:()=>Ws,isValid:()=>Ht,late:()=>Hf,lazy:()=>mp,literal:()=>gp,makeIssue:()=>fs,map:()=>hp,nan:()=>Vf,nativeEnum:()=>bp,never:()=>np,null:()=>Qf,nullable:()=>kp,number:()=>Ll,object:()=>ip,objectUtil:()=>Co,oboolean:()=>Ip,onumber:()=>Cp,optional:()=>_p,ostring:()=>xp,pipeline:()=>Tp,preprocess:()=>Sp,promise:()=>vp,quotelessJson:()=>wf,record:()=>dp,set:()=>fp,setErrorMap:()=>kf,strictObject:()=>op,string:()=>Dl,symbol:()=>Yf,transformer:()=>wp,tuple:()=>cp,undefined:()=>Xf,union:()=>ap,unknown:()=>tp,util:()=>te,void:()=>rp});var te;(function(n){n.assertEqual=s=>{};function e(s){}n.assertIs=e;function t(s){throw new Error}n.assertNever=t,n.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},n.getValidEnumValues=s=>{let i=n.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),o={};for(let a of i)o[a]=s[a];return n.objectValues(o)},n.objectValues=s=>n.objectKeys(s).map(function(i){return s[i]}),n.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},n.find=(s,i)=>{for(let o of s)if(i(o))return o},n.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}n.joinValues=r,n.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(te||(te={}));var Co;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(Co||(Co={}));var O=te.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ht=n=>{switch(typeof n){case"undefined":return O.undefined;case"string":return O.string;case"number":return Number.isNaN(n)?O.nan:O.number;case"boolean":return O.boolean;case"function":return O.function;case"bigint":return O.bigint;case"symbol":return O.symbol;case"object":return Array.isArray(n)?O.array:n===null?O.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?O.promise:typeof Map<"u"&&n instanceof Map?O.map:typeof Set<"u"&&n instanceof Set?O.set:typeof Date<"u"&&n instanceof Date?O.date:O.object;default:return O.unknown}};var R=te.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),wf=n=>JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:"),je=class n extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let 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},r={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)r._errors.push(t(o));else{let a=r,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),r}static assert(e){if(!(e instanceof n))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,te.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},r=[];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 r.push(e(s));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}};je.create=n=>new je(n);var _f=(n,e)=>{let t;switch(n.code){case R.invalid_type:n.received===O.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case R.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,te.jsonStringifyReplacer)}`;break;case R.unrecognized_keys:t=`Unrecognized key(s) in object: ${te.joinValues(n.keys,", ")}`;break;case R.invalid_union:t="Invalid input";break;case R.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${te.joinValues(n.options)}`;break;case R.invalid_enum_value:t=`Invalid enum value. Expected ${te.joinValues(n.options)}, received '${n.received}'`;break;case R.invalid_arguments:t="Invalid function arguments";break;case R.invalid_return_type:t="Invalid function return type";break;case R.invalid_date:t="Invalid date";break;case R.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:te.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case R.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case R.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case R.custom:t="Invalid input";break;case R.invalid_intersection_types:t="Intersection results could not be merged";break;case R.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case R.not_finite:t="Number must be finite";break;default:t=e.defaultError,te.assertNever(n)}return{message:t}},Ct=_f;var Al=Ct;function kf(n){Al=n}function Tr(){return Al}var fs=n=>{let{data:e,path:t,errorMaps:r,issueData:s}=n,i=[...t,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let a="",u=r.filter(c=>!!c).slice().reverse();for(let c of u)a=c(o,{data:e,defaultError:a}).message;return{...s,path:i,message:a}},Sf=[];function j(n,e){let t=Tr(),r=fs({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===Ct?void 0:Ct].filter(s=>!!s)});n.common.issues.push(r)}var ke=class n{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let r=[];for(let s of t){if(s.status==="aborted")return K;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let s of t){let i=await s.key,o=await s.value;r.push({key:i,value:o})}return n.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let s of t){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return K;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(r[i.value]=o.value)}return{status:e.value,value:r}}},K=Object.freeze({status:"aborted"}),mn=n=>({status:"dirty",value:n}),Te=n=>({status:"valid",value:n}),Vs=n=>n.status==="aborted",Ws=n=>n.status==="dirty",Ht=n=>n.status==="valid",xr=n=>typeof Promise<"u"&&n instanceof Promise;var U;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e?.message})(U||(U={}));var Ve=class{constructor(e,t,r,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},$l=(n,e)=>{if(Ht(e))return{success:!0,data:e.value};if(!n.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 je(n.common.issues);return this._error=t,this._error}}};function J(n){if(!n)return{};let{errorMap:e,invalid_type_error:t,required_error:r,description:s}=n;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,a)=>{let{message:u}=n;return o.code==="invalid_enum_value"?{message:u??a.defaultError}:typeof a.data>"u"?{message:u??r??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:u??t??a.defaultError}},description:s}}var Q=class{get description(){return this._def.description}_getType(e){return ht(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ht(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ke,ctx:{common:e.parent.common,data:e.data,parsedType:ht(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(xr(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 r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ht(e)},s=this._parseSync({data:e,path:r.path,parent:r});return $l(r,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ht(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return Ht(r)?{value:r.value}:{issues:t.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(r=>Ht(r)?{value:r.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ht(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(xr(s)?s:Promise.resolve(s));return $l(r,i)}refine(e,t){let r=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.custom,...r(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((r,s)=>e(r)?!0:(s.addIssue(typeof t=="function"?t(r,s):t),!1))}_refinement(e){return new We({schema:this,typeName:Z.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return Ge.create(this,this._def)}nullable(){return pt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Et.create(this)}promise(){return Wt.create(this,this._def)}or(e){return kn.create([this,e],this._def)}and(e){return Sn.create(this,e,this._def)}transform(e){return new We({...J(this._def),schema:this,typeName:Z.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Rn({...J(this._def),innerType:this,defaultValue:t,typeName:Z.ZodDefault})}brand(){return new ps({typeName:Z.ZodBranded,type:this,...J(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new En({...J(this._def),innerType:this,catchValue:t,typeName:Z.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ms.create(this,e)}readonly(){return An.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Tf=/^c[^\s-]{8,}$/i,xf=/^[0-9a-z]+$/,Cf=/^[0-9A-HJKMNP-TV-Z]{26}$/i,If=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Rf=/^[a-z0-9_-]{21}$/i,Ef=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Af=/^[-+]?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)?)??$/,$f=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Pf="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Io,jf=/^(?:(?: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])$/,Of=/^(?:(?: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])$/,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]))$/,Mf=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,zf=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Df=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,jl="((\\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])))",Lf=new RegExp(`^${jl}$`);function Ol(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);let t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Uf(n){return new RegExp(`^${Ol(n)}$`)}function Nl(n){let e=`${jl}T${Ol(n)}`,t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function qf(n,e){return!!((e==="v4"||!e)&&jf.test(n)||(e==="v6"||!e)&&Nf.test(n))}function Ff(n,e){if(!Ef.test(n))return!1;try{let[t]=n.split(".");if(!t)return!1;let r=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function Bf(n,e){return!!((e==="v4"||!e)&&Of.test(n)||(e==="v6"||!e)&&Mf.test(n))}var Gt=class n extends Q{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==O.string){let i=this._getOrReturnCtx(e);return j(i,{code:R.invalid_type,expected:O.string,received:i.parsedType}),K}let r=new ke,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),j(s,{code:R.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),j(s,{code:R.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(s=this._getOrReturnCtx(e,s),o?j(s,{code:R.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&j(s,{code:R.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")$f.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"email",code:R.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Io||(Io=new RegExp(Pf,"u")),Io.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"emoji",code:R.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")If.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"uuid",code:R.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")Rf.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"nanoid",code:R.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")Tf.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"cuid",code:R.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")xf.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"cuid2",code:R.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")Cf.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"ulid",code:R.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),j(s,{validation:"url",code:R.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"regex",code:R.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),j(s,{code:R.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),j(s,{code:R.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),j(s,{code:R.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Nl(i).test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{code:R.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?Lf.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{code:R.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Uf(i).test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{code:R.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?Af.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"duration",code:R.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?qf(e.data,i.version)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"ip",code:R.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?Ff(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"jwt",code:R.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?Bf(e.data,i.version)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"cidr",code:R.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?zf.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"base64",code:R.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?Df.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"base64url",code:R.invalid_string,message:i.message}),r.dirty()):te.assertNever(i);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(s=>e.test(s),{validation:t,code:R.invalid_string,...U.errToObj(r)})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...U.errToObj(e)})}url(e){return this._addCheck({kind:"url",...U.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...U.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...U.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...U.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...U.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...U.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...U.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...U.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...U.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...U.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...U.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...U.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...U.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...U.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...U.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...U.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...U.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...U.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...U.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...U.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...U.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...U.errToObj(t)})}nonempty(e){return this.min(1,U.errToObj(e))}trim(){return new n({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new n({...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}};Gt.create=n=>new Gt({checks:[],typeName:Z.ZodString,coerce:n?.coerce??!1,...J(n)});function Kf(n,e){let t=(n.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=t>r?t:r,i=Number.parseInt(n.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var gn=class n extends Q{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==O.number){let i=this._getOrReturnCtx(e);return j(i,{code:R.invalid_type,expected:O.number,received:i.parsedType}),K}let r,s=new ke;for(let i of this._def.checks)i.kind==="int"?te.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),j(r,{code:R.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),j(r,{code:R.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),j(r,{code:R.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Kf(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),j(r,{code:R.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),j(r,{code:R.not_finite,message:i.message}),s.dirty()):te.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,U.toString(t))}gt(e,t){return this.setLimit("min",e,!1,U.toString(t))}lte(e,t){return this.setLimit("max",e,!0,U.toString(t))}lt(e,t){return this.setLimit("max",e,!1,U.toString(t))}setLimit(e,t,r,s){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:U.toString(s)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:U.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:U.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:U.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:U.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:U.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:U.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:U.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:U.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:U.toString(e)})}get minValue(){let e=null;for(let 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"&&te.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(t===null||r.value>t)&&(t=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}};gn.create=n=>new gn({checks:[],typeName:Z.ZodNumber,coerce:n?.coerce||!1,...J(n)});var yn=class n extends Q{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==O.bigint)return this._getInvalidInput(e);let r,s=new ke;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),j(r,{code:R.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),j(r,{code:R.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),j(r,{code:R.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):te.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return j(t,{code:R.invalid_type,expected:O.bigint,received:t.parsedType}),K}gte(e,t){return this.setLimit("min",e,!0,U.toString(t))}gt(e,t){return this.setLimit("min",e,!1,U.toString(t))}lte(e,t){return this.setLimit("max",e,!0,U.toString(t))}lt(e,t){return this.setLimit("max",e,!1,U.toString(t))}setLimit(e,t,r,s){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:U.toString(s)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:U.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:U.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:U.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:U.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:U.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}};yn.create=n=>new yn({checks:[],typeName:Z.ZodBigInt,coerce:n?.coerce??!1,...J(n)});var bn=class extends Q{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==O.boolean){let r=this._getOrReturnCtx(e);return j(r,{code:R.invalid_type,expected:O.boolean,received:r.parsedType}),K}return Te(e.data)}};bn.create=n=>new bn({typeName:Z.ZodBoolean,coerce:n?.coerce||!1,...J(n)});var vn=class n extends Q{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==O.date){let i=this._getOrReturnCtx(e);return j(i,{code:R.invalid_type,expected:O.date,received:i.parsedType}),K}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return j(i,{code:R.invalid_date}),K}let r=new ke,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),j(s,{code:R.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),j(s,{code:R.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):te.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:U.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:U.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}};vn.create=n=>new vn({checks:[],coerce:n?.coerce||!1,typeName:Z.ZodDate,...J(n)});var Ir=class extends Q{_parse(e){if(this._getType(e)!==O.symbol){let r=this._getOrReturnCtx(e);return j(r,{code:R.invalid_type,expected:O.symbol,received:r.parsedType}),K}return Te(e.data)}};Ir.create=n=>new Ir({typeName:Z.ZodSymbol,...J(n)});var wn=class extends Q{_parse(e){if(this._getType(e)!==O.undefined){let r=this._getOrReturnCtx(e);return j(r,{code:R.invalid_type,expected:O.undefined,received:r.parsedType}),K}return Te(e.data)}};wn.create=n=>new wn({typeName:Z.ZodUndefined,...J(n)});var _n=class extends Q{_parse(e){if(this._getType(e)!==O.null){let r=this._getOrReturnCtx(e);return j(r,{code:R.invalid_type,expected:O.null,received:r.parsedType}),K}return Te(e.data)}};_n.create=n=>new _n({typeName:Z.ZodNull,...J(n)});var Vt=class extends Q{constructor(){super(...arguments),this._any=!0}_parse(e){return Te(e.data)}};Vt.create=n=>new Vt({typeName:Z.ZodAny,...J(n)});var Rt=class extends Q{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Te(e.data)}};Rt.create=n=>new Rt({typeName:Z.ZodUnknown,...J(n)});var rt=class extends Q{_parse(e){let t=this._getOrReturnCtx(e);return j(t,{code:R.invalid_type,expected:O.never,received:t.parsedType}),K}};rt.create=n=>new rt({typeName:Z.ZodNever,...J(n)});var Rr=class extends Q{_parse(e){if(this._getType(e)!==O.undefined){let r=this._getOrReturnCtx(e);return j(r,{code:R.invalid_type,expected:O.void,received:r.parsedType}),K}return Te(e.data)}};Rr.create=n=>new Rr({typeName:Z.ZodVoid,...J(n)});var Et=class n extends Q{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==O.array)return j(t,{code:R.invalid_type,expected:O.array,received:t.parsedType}),K;if(s.exactLength!==null){let o=t.data.length>s.exactLength.value,a=t.data.length<s.exactLength.value;(o||a)&&(j(t,{code:o?R.too_big:R.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}),r.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(j(t,{code:R.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(j(t,{code:R.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>s.type._parseAsync(new Ve(t,o,t.path,a)))).then(o=>ke.mergeArray(r,o));let i=[...t.data].map((o,a)=>s.type._parseSync(new Ve(t,o,t.path,a)));return ke.mergeArray(r,i)}get element(){return this._def.type}min(e,t){return new n({...this._def,minLength:{value:e,message:U.toString(t)}})}max(e,t){return new n({...this._def,maxLength:{value:e,message:U.toString(t)}})}length(e,t){return new n({...this._def,exactLength:{value:e,message:U.toString(t)}})}nonempty(e){return this.min(1,e)}};Et.create=(n,e)=>new Et({type:n,minLength:null,maxLength:null,exactLength:null,typeName:Z.ZodArray,...J(e)});function Cr(n){if(n instanceof Oe){let e={};for(let t in n.shape){let r=n.shape[t];e[t]=Ge.create(Cr(r))}return new Oe({...n._def,shape:()=>e})}else return n instanceof Et?new Et({...n._def,type:Cr(n.element)}):n instanceof Ge?Ge.create(Cr(n.unwrap())):n instanceof pt?pt.create(Cr(n.unwrap())):n instanceof ft?ft.create(n.items.map(e=>Cr(e))):n}var Oe=class n extends Q{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=te.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==O.object){let c=this._getOrReturnCtx(e);return j(c,{code:R.invalid_type,expected:O.object,received:c.parsedType}),K}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof rt&&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 Ve(s,p,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof rt){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&&(j(s,{code:R.unrecognized_keys,keys:a}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let f of a){let p=s.data[f];u.push({key:{status:"valid",value:f},value:c._parse(new Ve(s,p,s.path,f)),alwaysSet:f in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let c=[];for(let f of u){let p=await f.key,b=await f.value;c.push({key:p,value:b,alwaysSet:f.alwaysSet})}return c}).then(c=>ke.mergeObjectSync(r,c)):ke.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(e){return U.errToObj,new n({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{let s=this._def.errorMap?.(t,r).message??r.defaultError;return t.code==="unrecognized_keys"?{message:U.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new n({...this._def,unknownKeys:"strip"})}passthrough(){return new n({...this._def,unknownKeys:"passthrough"})}extend(e){return new n({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new n({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Z.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new n({...this._def,catchall:e})}pick(e){let t={};for(let r of te.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new n({...this._def,shape:()=>t})}omit(e){let t={};for(let r of te.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new n({...this._def,shape:()=>t})}deepPartial(){return Cr(this)}partial(e){let t={};for(let r of te.objectKeys(this.shape)){let s=this.shape[r];e&&!e[r]?t[r]=s:t[r]=s.optional()}return new n({...this._def,shape:()=>t})}required(e){let t={};for(let r of te.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Ge;)i=i._def.innerType;t[r]=i}return new n({...this._def,shape:()=>t})}keyof(){return Ml(te.objectKeys(this.shape))}};Oe.create=(n,e)=>new Oe({shape:()=>n,unknownKeys:"strip",catchall:rt.create(),typeName:Z.ZodObject,...J(e)});Oe.strictCreate=(n,e)=>new Oe({shape:()=>n,unknownKeys:"strict",catchall:rt.create(),typeName:Z.ZodObject,...J(e)});Oe.lazycreate=(n,e)=>new Oe({shape:n,unknownKeys:"strip",catchall:rt.create(),typeName:Z.ZodObject,...J(e)});var kn=class extends Q{_parse(e){let{ctx:t}=this._processInputParams(e),r=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 je(a.ctx.common.issues));return j(t,{code:R.invalid_union,unionErrors:o}),K}if(t.common.async)return Promise.all(r.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 r){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 je(u));return j(t,{code:R.invalid_union,unionErrors:a}),K}}get options(){return this._def.options}};kn.create=(n,e)=>new kn({options:n,typeName:Z.ZodUnion,...J(e)});var It=n=>n instanceof Tn?It(n.schema):n instanceof We?It(n.innerType()):n instanceof xn?[n.value]:n instanceof Cn?n.options:n instanceof In?te.objectValues(n.enum):n instanceof Rn?It(n._def.innerType):n instanceof wn?[void 0]:n instanceof _n?[null]:n instanceof Ge?[void 0,...It(n.unwrap())]:n instanceof pt?[null,...It(n.unwrap())]:n instanceof ps||n instanceof An?It(n.unwrap()):n instanceof En?It(n._def.innerType):[],Js=class n extends Q{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==O.object)return j(t,{code:R.invalid_type,expected:O.object,received:t.parsedType}),K;let r=this.discriminator,s=t.data[r],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}):(j(t,{code:R.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),K)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let s=new Map;for(let i of t){let o=It(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 n({typeName:Z.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...J(r)})}};function Ro(n,e){let t=ht(n),r=ht(e);if(n===e)return{valid:!0,data:n};if(t===O.object&&r===O.object){let s=te.objectKeys(e),i=te.objectKeys(n).filter(a=>s.indexOf(a)!==-1),o={...n,...e};for(let a of i){let u=Ro(n[a],e[a]);if(!u.valid)return{valid:!1};o[a]=u.data}return{valid:!0,data:o}}else if(t===O.array&&r===O.array){if(n.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<n.length;i++){let o=n[i],a=e[i],u=Ro(o,a);if(!u.valid)return{valid:!1};s.push(u.data)}return{valid:!0,data:s}}else return t===O.date&&r===O.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}var Sn=class extends Q{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),s=(i,o)=>{if(Vs(i)||Vs(o))return K;let a=Ro(i.value,o.value);return a.valid?((Ws(i)||Ws(o))&&t.dirty(),{status:t.value,value:a.data}):(j(r,{code:R.invalid_intersection_types}),K)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Sn.create=(n,e,t)=>new Sn({left:n,right:e,typeName:Z.ZodIntersection,...J(t)});var ft=class n extends Q{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==O.array)return j(r,{code:R.invalid_type,expected:O.array,received:r.parsedType}),K;if(r.data.length<this._def.items.length)return j(r,{code:R.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),K;!this._def.rest&&r.data.length>this._def.items.length&&(j(r,{code:R.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...r.data].map((o,a)=>{let u=this._def.items[a]||this._def.rest;return u?u._parse(new Ve(r,o,r.path,a)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>ke.mergeArray(t,o)):ke.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new n({...this._def,rest:e})}};ft.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ft({items:n,typeName:Z.ZodTuple,rest:null,...J(e)})};var Ys=class n extends Q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==O.object)return j(r,{code:R.invalid_type,expected:O.object,received:r.parsedType}),K;let s=[],i=this._def.keyType,o=this._def.valueType;for(let a in r.data)s.push({key:i._parse(new Ve(r,a,r.path,a)),value:o._parse(new Ve(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?ke.mergeObjectAsync(t,s):ke.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,r){return t instanceof Q?new n({keyType:e,valueType:t,typeName:Z.ZodRecord,...J(r)}):new n({keyType:Gt.create(),valueType:e,typeName:Z.ZodRecord,...J(t)})}},Er=class extends Q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==O.map)return j(r,{code:R.invalid_type,expected:O.map,received:r.parsedType}),K;let s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([a,u],c)=>({key:s._parse(new Ve(r,a,r.path,[c,"key"])),value:i._parse(new Ve(r,u,r.path,[c,"value"]))}));if(r.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 K;(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 K;(c.status==="dirty"||f.status==="dirty")&&t.dirty(),a.set(c.value,f.value)}return{status:t.value,value:a}}}};Er.create=(n,e,t)=>new Er({valueType:e,keyType:n,typeName:Z.ZodMap,...J(t)});var Ar=class n extends Q{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==O.set)return j(r,{code:R.invalid_type,expected:O.set,received:r.parsedType}),K;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(j(r,{code:R.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(j(r,{code:R.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 K;f.status==="dirty"&&t.dirty(),c.add(f.value)}return{status:t.value,value:c}}let a=[...r.data.values()].map((u,c)=>i._parse(new Ve(r,u,r.path,c)));return r.common.async?Promise.all(a).then(u=>o(u)):o(a)}min(e,t){return new n({...this._def,minSize:{value:e,message:U.toString(t)}})}max(e,t){return new n({...this._def,maxSize:{value:e,message:U.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Ar.create=(n,e)=>new Ar({valueType:n,minSize:null,maxSize:null,typeName:Z.ZodSet,...J(e)});var Xs=class n extends Q{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==O.function)return j(t,{code:R.invalid_type,expected:O.function,received:t.parsedType}),K;function r(a,u){return fs({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Tr(),Ct].filter(c=>!!c),issueData:{code:R.invalid_arguments,argumentsError:u}})}function s(a,u){return fs({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Tr(),Ct].filter(c=>!!c),issueData:{code:R.invalid_return_type,returnTypeError:u}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof Wt){let a=this;return Te(async function(...u){let c=new je([]),f=await a._def.args.parseAsync(u,i).catch(v=>{throw c.addIssue(r(u,v)),c}),p=await Reflect.apply(o,this,f);return await a._def.returns._def.type.parseAsync(p,i).catch(v=>{throw c.addIssue(s(p,v)),c})})}else{let a=this;return Te(function(...u){let c=a._def.args.safeParse(u,i);if(!c.success)throw new je([r(u,c.error)]);let f=Reflect.apply(o,this,c.data),p=a._def.returns.safeParse(f,i);if(!p.success)throw new je([s(f,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new n({...this._def,args:ft.create(e).rest(Rt.create())})}returns(e){return new n({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new n({args:e||ft.create([]).rest(Rt.create()),returns:t||Rt.create(),typeName:Z.ZodFunction,...J(r)})}},Tn=class extends Q{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})}};Tn.create=(n,e)=>new Tn({getter:n,typeName:Z.ZodLazy,...J(e)});var xn=class extends Q{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return j(t,{received:t.data,code:R.invalid_literal,expected:this._def.value}),K}return{status:"valid",value:e.data}}get value(){return this._def.value}};xn.create=(n,e)=>new xn({value:n,typeName:Z.ZodLiteral,...J(e)});function Ml(n,e){return new Cn({values:n,typeName:Z.ZodEnum,...J(e)})}var Cn=class n extends Q{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),r=this._def.values;return j(t,{expected:te.joinValues(r),received:t.parsedType,code:R.invalid_type}),K}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return j(t,{received:t.data,code:R.invalid_enum_value,options:r}),K}return Te(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 n.create(e,{...this._def,...t})}exclude(e,t=this._def){return n.create(this.options.filter(r=>!e.includes(r)),{...this._def,...t})}};Cn.create=Ml;var In=class extends Q{_parse(e){let t=te.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==O.string&&r.parsedType!==O.number){let s=te.objectValues(t);return j(r,{expected:te.joinValues(s),received:r.parsedType,code:R.invalid_type}),K}if(this._cache||(this._cache=new Set(te.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=te.objectValues(t);return j(r,{received:r.data,code:R.invalid_enum_value,options:s}),K}return Te(e.data)}get enum(){return this._def.values}};In.create=(n,e)=>new In({values:n,typeName:Z.ZodNativeEnum,...J(e)});var Wt=class extends Q{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==O.promise&&t.common.async===!1)return j(t,{code:R.invalid_type,expected:O.promise,received:t.parsedType}),K;let r=t.parsedType===O.promise?t.data:Promise.resolve(t.data);return Te(r.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};Wt.create=(n,e)=>new Wt({type:n,typeName:Z.ZodPromise,...J(e)});var We=class extends Q{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Z.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{j(r,o),o.fatal?t.abort():t.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(r.data,i);if(r.common.async)return Promise.resolve(o).then(async a=>{if(t.value==="aborted")return K;let u=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return u.status==="aborted"?K:u.status==="dirty"?mn(u.value):t.value==="dirty"?mn(u.value):u});{if(t.value==="aborted")return K;let a=this._def.schema._parseSync({data:o,path:r.path,parent:r});return a.status==="aborted"?K:a.status==="dirty"?mn(a.value):t.value==="dirty"?mn(a.value):a}}if(s.type==="refinement"){let o=a=>{let u=s.refinement(a,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?K:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?K:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.value,value:a.value}))))}if(s.type==="transform")if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Ht(o))return K;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:r.data,path:r.path,parent:r}).then(o=>Ht(o)?Promise.resolve(s.transform(o.value,i)).then(a=>({status:t.value,value:a})):K);te.assertNever(s)}};We.create=(n,e,t)=>new We({schema:n,typeName:Z.ZodEffects,effect:e,...J(t)});We.createWithPreprocess=(n,e,t)=>new We({schema:e,effect:{type:"preprocess",transform:n},typeName:Z.ZodEffects,...J(t)});var Ge=class extends Q{_parse(e){return this._getType(e)===O.undefined?Te(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ge.create=(n,e)=>new Ge({innerType:n,typeName:Z.ZodOptional,...J(e)});var pt=class extends Q{_parse(e){return this._getType(e)===O.null?Te(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};pt.create=(n,e)=>new pt({innerType:n,typeName:Z.ZodNullable,...J(e)});var Rn=class extends Q{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return t.parsedType===O.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Rn.create=(n,e)=>new Rn({innerType:n,typeName:Z.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...J(e)});var En=class extends Q{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return xr(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new je(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new je(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};En.create=(n,e)=>new En({innerType:n,typeName:Z.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...J(e)});var $r=class extends Q{_parse(e){if(this._getType(e)!==O.nan){let r=this._getOrReturnCtx(e);return j(r,{code:R.invalid_type,expected:O.nan,received:r.parsedType}),K}return{status:"valid",value:e.data}}};$r.create=n=>new $r({typeName:Z.ZodNaN,...J(n)});var Zf=Symbol("zod_brand"),ps=class extends Q{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}},ms=class n extends Q{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?K:i.status==="dirty"?(t.dirty(),mn(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?K:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,t){return new n({in:e,out:t,typeName:Z.ZodPipeline})}},An=class extends Q{_parse(e){let t=this._def.innerType._parse(e),r=s=>(Ht(s)&&(s.value=Object.freeze(s.value)),s);return xr(t)?t.then(s=>r(s)):r(t)}unwrap(){return this._def.innerType}};An.create=(n,e)=>new An({innerType:n,typeName:Z.ZodReadonly,...J(e)});function Pl(n,e){let t=typeof n=="function"?n(e):typeof n=="string"?{message:n}:n;return typeof t=="string"?{message:t}:t}function zl(n,e={},t){return n?Vt.create().superRefine((r,s)=>{let i=n(r);if(i instanceof Promise)return i.then(o=>{if(!o){let a=Pl(e,r),u=a.fatal??t??!0;s.addIssue({code:"custom",...a,fatal:u})}});if(!i){let o=Pl(e,r),a=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:a})}}):Vt.create()}var Hf={object:Oe.lazycreate},Z;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(Z||(Z={}));var Gf=(n,e={message:`Input not instance of ${n.name}`})=>zl(t=>t instanceof n,e),Dl=Gt.create,Ll=gn.create,Vf=$r.create,Wf=yn.create,Ul=bn.create,Jf=vn.create,Yf=Ir.create,Xf=wn.create,Qf=_n.create,ep=Vt.create,tp=Rt.create,np=rt.create,rp=Rr.create,sp=Et.create,ip=Oe.create,op=Oe.strictCreate,ap=kn.create,lp=Js.create,up=Sn.create,cp=ft.create,dp=Ys.create,hp=Er.create,fp=Ar.create,pp=Xs.create,mp=Tn.create,gp=xn.create,yp=Cn.create,bp=In.create,vp=Wt.create,wp=We.create,_p=Ge.create,kp=pt.create,Sp=We.createWithPreprocess,Tp=ms.create,xp=()=>Dl().optional(),Cp=()=>Ll().optional(),Ip=()=>Ul().optional(),Rp={string:(n=>Gt.create({...n,coerce:!0})),number:(n=>gn.create({...n,coerce:!0})),boolean:(n=>bn.create({...n,coerce:!0})),bigint:(n=>yn.create({...n,coerce:!0})),date:(n=>vn.create({...n,coerce:!0}))};var Ep=K;var ql=_.object({baseUrl:_.string().url(),email:_.string().email(),apiToken:_.string().min(1)}),Eo=_.object({controlPlaneUrl:_.string().url(),runnerId:_.string().optional(),runnerToken:_.string().optional(),runnerName:_.string().default(Qs.default.hostname()),jira:ql.optional(),repos:_.record(_.object({path:_.string(),jira:ql.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 re(){let n=process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR;if(n)return n;let e=ei.default.join(Qs.default.homedir(),".config","allwright"),t=ei.default.join(Qs.default.homedir(),".config","ticketpilot");return!At.default.existsSync(e)&&At.default.existsSync(t)?t:e}function $t(){return ei.default.join(re(),"runner.json")}function ye(){let n=$t();if(!At.default.existsSync(n))return null;let e=JSON.parse(At.default.readFileSync(n,"utf8"));return Eo.parse(e)}function ge(n){let e=re();At.default.mkdirSync(e,{recursive:!0,mode:448});let t=$t(),r=t+".tmp";At.default.writeFileSync(r,JSON.stringify(n,null,2)+`
|
|
261
|
+
`+t)}function br(n,e,t,r,s,i){if(n.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,br),n.emit("wsClientError",o,t,e)}else Ls(t,r,s,i)}});var Vh={};Zs(Vh,{buildSetupReport:()=>yb,claudeLoggedIn:()=>Gh,repoDefaultBranch:()=>Hh});function Hh(n){let e=(...s)=>{try{return(0,ao.execFileSync)("git",["-C",n,...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 r=e("rev-parse","--abbrev-ref","HEAD");return r&&r!=="HEAD"?r:""}function Gh(n=Kh.default.homedir()){if(hn.default.existsSync(_r.default.join(n,".claude",".credentials.json")))return!0;try{return!!JSON.parse(hn.default.readFileSync(_r.default.join(n,".claude.json"),"utf8")).oauthAccount}catch{return!1}}async function yb(n,e){let t=!1,r="";if(Fs&&Date.now()-Fs.at<6e4)t=Fs.installed,r=Fs.version;else{try{let{stdout:o}=await gb(n.claudeBin,["--version"],{timeout:1e4});t=!0,r=o.trim().slice(0,60)}catch{t=!1}Fs={at:Date.now(),installed:t,version:r}}let s=e.map(o=>{let a=n.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=hn.default.existsSync(a.path);return{repoName:o,mapped:!0,pathExists:u,isGit:u&&hn.default.existsSync(_r.default.join(a.path,".git")),claudeMd:u&&hn.default.existsSync(_r.default.join(a.path,"CLAUDE.md")),deployMd:u&&hn.default.existsSync(_r.default.join(a.path,"DEPLOY.md")),testMd:u&&hn.default.existsSync(_r.default.join(a.path,"TEST.md")),githubToken:!!Ie(n,o),githubTokenOwn:!!a.github?.token,defaultBranch:u?Hh(a.path):""}}),i=Object.values(n.repos).find(o=>o.github?.token);return{jiraConfigured:!!n.jira,jiraEmail:n.jira?.email??"",claude:{installed:t,version:r,loggedIn:Gh()},githubTokenSet:!!(n.github?.token||i),githubLogin:n.github?.login??i?.github?.login??"",deploysEnabled:n.deploy.enabled,jiraUserCount:Object.keys(n.jiraUsers).length,repos:s}}var ao,hn,Kh,_r,Zh,gb,Fs,Wh=Ks(()=>{"use strict";ao=require("node:child_process"),hn=E(require("node:fs"),1),Kh=E(require("node:os"),1),_r=E(require("node:path"),1),Zh=require("node:util");er();gb=(0,Zh.promisify)(ao.execFile);Fs=null});var dt=E(require("node:fs"),1),cl=E(require("node:os"),1),us=E(require("node:path"),1),Zt=require("node:child_process"),Bs=require("node:crypto"),fn=E(require("node:readline/promises"),1);var Rl=E(Il(),1),{program:Ib,createCommand:Rb,createArgument:Eb,createOption:Ab,CommanderError:$b,InvalidArgumentError:Pb,InvalidOptionArgumentError:jb,Command:El,Argument:Ob,Option:Nb,Help:Mb}=Rl.default;var At=E(require("node:fs"),1),Qs=E(require("node:os"),1),ei=E(require("node:path"),1);var _={};Zs(_,{BRAND:()=>Zf,DIRTY:()=>mn,EMPTY_PATH:()=>Sf,INVALID:()=>K,NEVER:()=>Ep,OK:()=>Te,ParseStatus:()=>ke,Schema:()=>Q,ZodAny:()=>Vt,ZodArray:()=>Et,ZodBigInt:()=>yn,ZodBoolean:()=>vn,ZodBranded:()=>ps,ZodCatch:()=>En,ZodDate:()=>bn,ZodDefault:()=>Rn,ZodDiscriminatedUnion:()=>Js,ZodEffects:()=>We,ZodEnum:()=>Cn,ZodError:()=>je,ZodFirstPartyTypeKind:()=>Z,ZodFunction:()=>Xs,ZodIntersection:()=>Sn,ZodIssueCode:()=>R,ZodLazy:()=>Tn,ZodLiteral:()=>xn,ZodMap:()=>Er,ZodNaN:()=>$r,ZodNativeEnum:()=>In,ZodNever:()=>rt,ZodNull:()=>_n,ZodNullable:()=>pt,ZodNumber:()=>gn,ZodObject:()=>Oe,ZodOptional:()=>Ge,ZodParsedType:()=>O,ZodPipeline:()=>ms,ZodPromise:()=>Wt,ZodReadonly:()=>An,ZodRecord:()=>Ys,ZodSchema:()=>Q,ZodSet:()=>Ar,ZodString:()=>Gt,ZodSymbol:()=>Ir,ZodTransformer:()=>We,ZodTuple:()=>ft,ZodType:()=>Q,ZodUndefined:()=>wn,ZodUnion:()=>kn,ZodUnknown:()=>Rt,ZodVoid:()=>Rr,addIssueToContext:()=>j,any:()=>ep,array:()=>sp,bigint:()=>Wf,boolean:()=>Ul,coerce:()=>Rp,custom:()=>zl,date:()=>Jf,datetimeRegex:()=>Nl,defaultErrorMap:()=>Ct,discriminatedUnion:()=>lp,effect:()=>wp,enum:()=>yp,function:()=>pp,getErrorMap:()=>Tr,getParsedType:()=>ht,instanceof:()=>Gf,intersection:()=>up,isAborted:()=>Vs,isAsync:()=>xr,isDirty:()=>Ws,isValid:()=>Ht,late:()=>Hf,lazy:()=>mp,literal:()=>gp,makeIssue:()=>fs,map:()=>hp,nan:()=>Vf,nativeEnum:()=>vp,never:()=>np,null:()=>Qf,nullable:()=>kp,number:()=>Ll,object:()=>ip,objectUtil:()=>Co,oboolean:()=>Ip,onumber:()=>Cp,optional:()=>_p,ostring:()=>xp,pipeline:()=>Tp,preprocess:()=>Sp,promise:()=>bp,quotelessJson:()=>wf,record:()=>dp,set:()=>fp,setErrorMap:()=>kf,strictObject:()=>op,string:()=>Dl,symbol:()=>Yf,transformer:()=>wp,tuple:()=>cp,undefined:()=>Xf,union:()=>ap,unknown:()=>tp,util:()=>te,void:()=>rp});var te;(function(n){n.assertEqual=s=>{};function e(s){}n.assertIs=e;function t(s){throw new Error}n.assertNever=t,n.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},n.getValidEnumValues=s=>{let i=n.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),o={};for(let a of i)o[a]=s[a];return n.objectValues(o)},n.objectValues=s=>n.objectKeys(s).map(function(i){return s[i]}),n.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},n.find=(s,i)=>{for(let o of s)if(i(o))return o},n.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}n.joinValues=r,n.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(te||(te={}));var Co;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(Co||(Co={}));var O=te.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ht=n=>{switch(typeof n){case"undefined":return O.undefined;case"string":return O.string;case"number":return Number.isNaN(n)?O.nan:O.number;case"boolean":return O.boolean;case"function":return O.function;case"bigint":return O.bigint;case"symbol":return O.symbol;case"object":return Array.isArray(n)?O.array:n===null?O.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?O.promise:typeof Map<"u"&&n instanceof Map?O.map:typeof Set<"u"&&n instanceof Set?O.set:typeof Date<"u"&&n instanceof Date?O.date:O.object;default:return O.unknown}};var R=te.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),wf=n=>JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:"),je=class n extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let 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},r={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)r._errors.push(t(o));else{let a=r,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),r}static assert(e){if(!(e instanceof n))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,te.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},r=[];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 r.push(e(s));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}};je.create=n=>new je(n);var _f=(n,e)=>{let t;switch(n.code){case R.invalid_type:n.received===O.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case R.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,te.jsonStringifyReplacer)}`;break;case R.unrecognized_keys:t=`Unrecognized key(s) in object: ${te.joinValues(n.keys,", ")}`;break;case R.invalid_union:t="Invalid input";break;case R.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${te.joinValues(n.options)}`;break;case R.invalid_enum_value:t=`Invalid enum value. Expected ${te.joinValues(n.options)}, received '${n.received}'`;break;case R.invalid_arguments:t="Invalid function arguments";break;case R.invalid_return_type:t="Invalid function return type";break;case R.invalid_date:t="Invalid date";break;case R.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:te.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case R.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case R.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case R.custom:t="Invalid input";break;case R.invalid_intersection_types:t="Intersection results could not be merged";break;case R.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case R.not_finite:t="Number must be finite";break;default:t=e.defaultError,te.assertNever(n)}return{message:t}},Ct=_f;var Al=Ct;function kf(n){Al=n}function Tr(){return Al}var fs=n=>{let{data:e,path:t,errorMaps:r,issueData:s}=n,i=[...t,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let a="",u=r.filter(c=>!!c).slice().reverse();for(let c of u)a=c(o,{data:e,defaultError:a}).message;return{...s,path:i,message:a}},Sf=[];function j(n,e){let t=Tr(),r=fs({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===Ct?void 0:Ct].filter(s=>!!s)});n.common.issues.push(r)}var ke=class n{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let r=[];for(let s of t){if(s.status==="aborted")return K;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let s of t){let i=await s.key,o=await s.value;r.push({key:i,value:o})}return n.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let s of t){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return K;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(r[i.value]=o.value)}return{status:e.value,value:r}}},K=Object.freeze({status:"aborted"}),mn=n=>({status:"dirty",value:n}),Te=n=>({status:"valid",value:n}),Vs=n=>n.status==="aborted",Ws=n=>n.status==="dirty",Ht=n=>n.status==="valid",xr=n=>typeof Promise<"u"&&n instanceof Promise;var U;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e?.message})(U||(U={}));var Ve=class{constructor(e,t,r,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},$l=(n,e)=>{if(Ht(e))return{success:!0,data:e.value};if(!n.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 je(n.common.issues);return this._error=t,this._error}}};function J(n){if(!n)return{};let{errorMap:e,invalid_type_error:t,required_error:r,description:s}=n;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,a)=>{let{message:u}=n;return o.code==="invalid_enum_value"?{message:u??a.defaultError}:typeof a.data>"u"?{message:u??r??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:u??t??a.defaultError}},description:s}}var Q=class{get description(){return this._def.description}_getType(e){return ht(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ht(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ke,ctx:{common:e.parent.common,data:e.data,parsedType:ht(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(xr(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 r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ht(e)},s=this._parseSync({data:e,path:r.path,parent:r});return $l(r,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ht(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return Ht(r)?{value:r.value}:{issues:t.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(r=>Ht(r)?{value:r.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ht(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(xr(s)?s:Promise.resolve(s));return $l(r,i)}refine(e,t){let r=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.custom,...r(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((r,s)=>e(r)?!0:(s.addIssue(typeof t=="function"?t(r,s):t),!1))}_refinement(e){return new We({schema:this,typeName:Z.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return Ge.create(this,this._def)}nullable(){return pt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Et.create(this)}promise(){return Wt.create(this,this._def)}or(e){return kn.create([this,e],this._def)}and(e){return Sn.create(this,e,this._def)}transform(e){return new We({...J(this._def),schema:this,typeName:Z.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Rn({...J(this._def),innerType:this,defaultValue:t,typeName:Z.ZodDefault})}brand(){return new ps({typeName:Z.ZodBranded,type:this,...J(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new En({...J(this._def),innerType:this,catchValue:t,typeName:Z.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ms.create(this,e)}readonly(){return An.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Tf=/^c[^\s-]{8,}$/i,xf=/^[0-9a-z]+$/,Cf=/^[0-9A-HJKMNP-TV-Z]{26}$/i,If=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Rf=/^[a-z0-9_-]{21}$/i,Ef=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Af=/^[-+]?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)?)??$/,$f=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Pf="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Io,jf=/^(?:(?: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])$/,Of=/^(?:(?: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])$/,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]))$/,Mf=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,zf=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Df=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,jl="((\\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])))",Lf=new RegExp(`^${jl}$`);function Ol(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);let t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Uf(n){return new RegExp(`^${Ol(n)}$`)}function Nl(n){let e=`${jl}T${Ol(n)}`,t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function qf(n,e){return!!((e==="v4"||!e)&&jf.test(n)||(e==="v6"||!e)&&Nf.test(n))}function Ff(n,e){if(!Ef.test(n))return!1;try{let[t]=n.split(".");if(!t)return!1;let r=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function Bf(n,e){return!!((e==="v4"||!e)&&Of.test(n)||(e==="v6"||!e)&&Mf.test(n))}var Gt=class n extends Q{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==O.string){let i=this._getOrReturnCtx(e);return j(i,{code:R.invalid_type,expected:O.string,received:i.parsedType}),K}let r=new ke,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),j(s,{code:R.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),j(s,{code:R.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(s=this._getOrReturnCtx(e,s),o?j(s,{code:R.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&j(s,{code:R.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")$f.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"email",code:R.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Io||(Io=new RegExp(Pf,"u")),Io.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"emoji",code:R.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")If.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"uuid",code:R.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")Rf.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"nanoid",code:R.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")Tf.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"cuid",code:R.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")xf.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"cuid2",code:R.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")Cf.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"ulid",code:R.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),j(s,{validation:"url",code:R.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"regex",code:R.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),j(s,{code:R.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),j(s,{code:R.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),j(s,{code:R.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Nl(i).test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{code:R.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?Lf.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{code:R.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Uf(i).test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{code:R.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?Af.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"duration",code:R.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?qf(e.data,i.version)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"ip",code:R.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?Ff(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"jwt",code:R.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?Bf(e.data,i.version)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"cidr",code:R.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?zf.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"base64",code:R.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?Df.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"base64url",code:R.invalid_string,message:i.message}),r.dirty()):te.assertNever(i);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(s=>e.test(s),{validation:t,code:R.invalid_string,...U.errToObj(r)})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...U.errToObj(e)})}url(e){return this._addCheck({kind:"url",...U.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...U.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...U.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...U.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...U.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...U.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...U.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...U.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...U.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...U.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...U.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...U.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...U.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...U.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...U.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...U.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...U.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...U.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...U.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...U.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...U.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...U.errToObj(t)})}nonempty(e){return this.min(1,U.errToObj(e))}trim(){return new n({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new n({...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}};Gt.create=n=>new Gt({checks:[],typeName:Z.ZodString,coerce:n?.coerce??!1,...J(n)});function Kf(n,e){let t=(n.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=t>r?t:r,i=Number.parseInt(n.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var gn=class n extends Q{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==O.number){let i=this._getOrReturnCtx(e);return j(i,{code:R.invalid_type,expected:O.number,received:i.parsedType}),K}let r,s=new ke;for(let i of this._def.checks)i.kind==="int"?te.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),j(r,{code:R.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),j(r,{code:R.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),j(r,{code:R.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Kf(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),j(r,{code:R.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),j(r,{code:R.not_finite,message:i.message}),s.dirty()):te.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,U.toString(t))}gt(e,t){return this.setLimit("min",e,!1,U.toString(t))}lte(e,t){return this.setLimit("max",e,!0,U.toString(t))}lt(e,t){return this.setLimit("max",e,!1,U.toString(t))}setLimit(e,t,r,s){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:U.toString(s)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:U.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:U.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:U.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:U.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:U.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:U.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:U.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:U.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:U.toString(e)})}get minValue(){let e=null;for(let 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"&&te.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(t===null||r.value>t)&&(t=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}};gn.create=n=>new gn({checks:[],typeName:Z.ZodNumber,coerce:n?.coerce||!1,...J(n)});var yn=class n extends Q{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==O.bigint)return this._getInvalidInput(e);let r,s=new ke;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),j(r,{code:R.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),j(r,{code:R.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),j(r,{code:R.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):te.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return j(t,{code:R.invalid_type,expected:O.bigint,received:t.parsedType}),K}gte(e,t){return this.setLimit("min",e,!0,U.toString(t))}gt(e,t){return this.setLimit("min",e,!1,U.toString(t))}lte(e,t){return this.setLimit("max",e,!0,U.toString(t))}lt(e,t){return this.setLimit("max",e,!1,U.toString(t))}setLimit(e,t,r,s){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:U.toString(s)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:U.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:U.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:U.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:U.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:U.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}};yn.create=n=>new yn({checks:[],typeName:Z.ZodBigInt,coerce:n?.coerce??!1,...J(n)});var vn=class extends Q{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==O.boolean){let r=this._getOrReturnCtx(e);return j(r,{code:R.invalid_type,expected:O.boolean,received:r.parsedType}),K}return Te(e.data)}};vn.create=n=>new vn({typeName:Z.ZodBoolean,coerce:n?.coerce||!1,...J(n)});var bn=class n extends Q{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==O.date){let i=this._getOrReturnCtx(e);return j(i,{code:R.invalid_type,expected:O.date,received:i.parsedType}),K}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return j(i,{code:R.invalid_date}),K}let r=new ke,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),j(s,{code:R.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),j(s,{code:R.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):te.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:U.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:U.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}};bn.create=n=>new bn({checks:[],coerce:n?.coerce||!1,typeName:Z.ZodDate,...J(n)});var Ir=class extends Q{_parse(e){if(this._getType(e)!==O.symbol){let r=this._getOrReturnCtx(e);return j(r,{code:R.invalid_type,expected:O.symbol,received:r.parsedType}),K}return Te(e.data)}};Ir.create=n=>new Ir({typeName:Z.ZodSymbol,...J(n)});var wn=class extends Q{_parse(e){if(this._getType(e)!==O.undefined){let r=this._getOrReturnCtx(e);return j(r,{code:R.invalid_type,expected:O.undefined,received:r.parsedType}),K}return Te(e.data)}};wn.create=n=>new wn({typeName:Z.ZodUndefined,...J(n)});var _n=class extends Q{_parse(e){if(this._getType(e)!==O.null){let r=this._getOrReturnCtx(e);return j(r,{code:R.invalid_type,expected:O.null,received:r.parsedType}),K}return Te(e.data)}};_n.create=n=>new _n({typeName:Z.ZodNull,...J(n)});var Vt=class extends Q{constructor(){super(...arguments),this._any=!0}_parse(e){return Te(e.data)}};Vt.create=n=>new Vt({typeName:Z.ZodAny,...J(n)});var Rt=class extends Q{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Te(e.data)}};Rt.create=n=>new Rt({typeName:Z.ZodUnknown,...J(n)});var rt=class extends Q{_parse(e){let t=this._getOrReturnCtx(e);return j(t,{code:R.invalid_type,expected:O.never,received:t.parsedType}),K}};rt.create=n=>new rt({typeName:Z.ZodNever,...J(n)});var Rr=class extends Q{_parse(e){if(this._getType(e)!==O.undefined){let r=this._getOrReturnCtx(e);return j(r,{code:R.invalid_type,expected:O.void,received:r.parsedType}),K}return Te(e.data)}};Rr.create=n=>new Rr({typeName:Z.ZodVoid,...J(n)});var Et=class n extends Q{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==O.array)return j(t,{code:R.invalid_type,expected:O.array,received:t.parsedType}),K;if(s.exactLength!==null){let o=t.data.length>s.exactLength.value,a=t.data.length<s.exactLength.value;(o||a)&&(j(t,{code:o?R.too_big:R.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}),r.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(j(t,{code:R.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(j(t,{code:R.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>s.type._parseAsync(new Ve(t,o,t.path,a)))).then(o=>ke.mergeArray(r,o));let i=[...t.data].map((o,a)=>s.type._parseSync(new Ve(t,o,t.path,a)));return ke.mergeArray(r,i)}get element(){return this._def.type}min(e,t){return new n({...this._def,minLength:{value:e,message:U.toString(t)}})}max(e,t){return new n({...this._def,maxLength:{value:e,message:U.toString(t)}})}length(e,t){return new n({...this._def,exactLength:{value:e,message:U.toString(t)}})}nonempty(e){return this.min(1,e)}};Et.create=(n,e)=>new Et({type:n,minLength:null,maxLength:null,exactLength:null,typeName:Z.ZodArray,...J(e)});function Cr(n){if(n instanceof Oe){let e={};for(let t in n.shape){let r=n.shape[t];e[t]=Ge.create(Cr(r))}return new Oe({...n._def,shape:()=>e})}else return n instanceof Et?new Et({...n._def,type:Cr(n.element)}):n instanceof Ge?Ge.create(Cr(n.unwrap())):n instanceof pt?pt.create(Cr(n.unwrap())):n instanceof ft?ft.create(n.items.map(e=>Cr(e))):n}var Oe=class n extends Q{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=te.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==O.object){let c=this._getOrReturnCtx(e);return j(c,{code:R.invalid_type,expected:O.object,received:c.parsedType}),K}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof rt&&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 Ve(s,p,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof rt){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&&(j(s,{code:R.unrecognized_keys,keys:a}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let f of a){let p=s.data[f];u.push({key:{status:"valid",value:f},value:c._parse(new Ve(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=>ke.mergeObjectSync(r,c)):ke.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(e){return U.errToObj,new n({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{let s=this._def.errorMap?.(t,r).message??r.defaultError;return t.code==="unrecognized_keys"?{message:U.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new n({...this._def,unknownKeys:"strip"})}passthrough(){return new n({...this._def,unknownKeys:"passthrough"})}extend(e){return new n({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new n({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Z.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new n({...this._def,catchall:e})}pick(e){let t={};for(let r of te.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new n({...this._def,shape:()=>t})}omit(e){let t={};for(let r of te.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new n({...this._def,shape:()=>t})}deepPartial(){return Cr(this)}partial(e){let t={};for(let r of te.objectKeys(this.shape)){let s=this.shape[r];e&&!e[r]?t[r]=s:t[r]=s.optional()}return new n({...this._def,shape:()=>t})}required(e){let t={};for(let r of te.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Ge;)i=i._def.innerType;t[r]=i}return new n({...this._def,shape:()=>t})}keyof(){return Ml(te.objectKeys(this.shape))}};Oe.create=(n,e)=>new Oe({shape:()=>n,unknownKeys:"strip",catchall:rt.create(),typeName:Z.ZodObject,...J(e)});Oe.strictCreate=(n,e)=>new Oe({shape:()=>n,unknownKeys:"strict",catchall:rt.create(),typeName:Z.ZodObject,...J(e)});Oe.lazycreate=(n,e)=>new Oe({shape:n,unknownKeys:"strip",catchall:rt.create(),typeName:Z.ZodObject,...J(e)});var kn=class extends Q{_parse(e){let{ctx:t}=this._processInputParams(e),r=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 je(a.ctx.common.issues));return j(t,{code:R.invalid_union,unionErrors:o}),K}if(t.common.async)return Promise.all(r.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 r){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 je(u));return j(t,{code:R.invalid_union,unionErrors:a}),K}}get options(){return this._def.options}};kn.create=(n,e)=>new kn({options:n,typeName:Z.ZodUnion,...J(e)});var It=n=>n instanceof Tn?It(n.schema):n instanceof We?It(n.innerType()):n instanceof xn?[n.value]:n instanceof Cn?n.options:n instanceof In?te.objectValues(n.enum):n instanceof Rn?It(n._def.innerType):n instanceof wn?[void 0]:n instanceof _n?[null]:n instanceof Ge?[void 0,...It(n.unwrap())]:n instanceof pt?[null,...It(n.unwrap())]:n instanceof ps||n instanceof An?It(n.unwrap()):n instanceof En?It(n._def.innerType):[],Js=class n extends Q{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==O.object)return j(t,{code:R.invalid_type,expected:O.object,received:t.parsedType}),K;let r=this.discriminator,s=t.data[r],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}):(j(t,{code:R.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),K)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let s=new Map;for(let i of t){let o=It(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 n({typeName:Z.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...J(r)})}};function Ro(n,e){let t=ht(n),r=ht(e);if(n===e)return{valid:!0,data:n};if(t===O.object&&r===O.object){let s=te.objectKeys(e),i=te.objectKeys(n).filter(a=>s.indexOf(a)!==-1),o={...n,...e};for(let a of i){let u=Ro(n[a],e[a]);if(!u.valid)return{valid:!1};o[a]=u.data}return{valid:!0,data:o}}else if(t===O.array&&r===O.array){if(n.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<n.length;i++){let o=n[i],a=e[i],u=Ro(o,a);if(!u.valid)return{valid:!1};s.push(u.data)}return{valid:!0,data:s}}else return t===O.date&&r===O.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}var Sn=class extends Q{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),s=(i,o)=>{if(Vs(i)||Vs(o))return K;let a=Ro(i.value,o.value);return a.valid?((Ws(i)||Ws(o))&&t.dirty(),{status:t.value,value:a.data}):(j(r,{code:R.invalid_intersection_types}),K)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Sn.create=(n,e,t)=>new Sn({left:n,right:e,typeName:Z.ZodIntersection,...J(t)});var ft=class n extends Q{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==O.array)return j(r,{code:R.invalid_type,expected:O.array,received:r.parsedType}),K;if(r.data.length<this._def.items.length)return j(r,{code:R.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),K;!this._def.rest&&r.data.length>this._def.items.length&&(j(r,{code:R.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...r.data].map((o,a)=>{let u=this._def.items[a]||this._def.rest;return u?u._parse(new Ve(r,o,r.path,a)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>ke.mergeArray(t,o)):ke.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new n({...this._def,rest:e})}};ft.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ft({items:n,typeName:Z.ZodTuple,rest:null,...J(e)})};var Ys=class n extends Q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==O.object)return j(r,{code:R.invalid_type,expected:O.object,received:r.parsedType}),K;let s=[],i=this._def.keyType,o=this._def.valueType;for(let a in r.data)s.push({key:i._parse(new Ve(r,a,r.path,a)),value:o._parse(new Ve(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?ke.mergeObjectAsync(t,s):ke.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,r){return t instanceof Q?new n({keyType:e,valueType:t,typeName:Z.ZodRecord,...J(r)}):new n({keyType:Gt.create(),valueType:e,typeName:Z.ZodRecord,...J(t)})}},Er=class extends Q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==O.map)return j(r,{code:R.invalid_type,expected:O.map,received:r.parsedType}),K;let s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([a,u],c)=>({key:s._parse(new Ve(r,a,r.path,[c,"key"])),value:i._parse(new Ve(r,u,r.path,[c,"value"]))}));if(r.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 K;(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 K;(c.status==="dirty"||f.status==="dirty")&&t.dirty(),a.set(c.value,f.value)}return{status:t.value,value:a}}}};Er.create=(n,e,t)=>new Er({valueType:e,keyType:n,typeName:Z.ZodMap,...J(t)});var Ar=class n extends Q{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==O.set)return j(r,{code:R.invalid_type,expected:O.set,received:r.parsedType}),K;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(j(r,{code:R.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(j(r,{code:R.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 K;f.status==="dirty"&&t.dirty(),c.add(f.value)}return{status:t.value,value:c}}let a=[...r.data.values()].map((u,c)=>i._parse(new Ve(r,u,r.path,c)));return r.common.async?Promise.all(a).then(u=>o(u)):o(a)}min(e,t){return new n({...this._def,minSize:{value:e,message:U.toString(t)}})}max(e,t){return new n({...this._def,maxSize:{value:e,message:U.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Ar.create=(n,e)=>new Ar({valueType:n,minSize:null,maxSize:null,typeName:Z.ZodSet,...J(e)});var Xs=class n extends Q{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==O.function)return j(t,{code:R.invalid_type,expected:O.function,received:t.parsedType}),K;function r(a,u){return fs({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Tr(),Ct].filter(c=>!!c),issueData:{code:R.invalid_arguments,argumentsError:u}})}function s(a,u){return fs({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Tr(),Ct].filter(c=>!!c),issueData:{code:R.invalid_return_type,returnTypeError:u}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof Wt){let a=this;return Te(async function(...u){let c=new je([]),f=await a._def.args.parseAsync(u,i).catch(b=>{throw c.addIssue(r(u,b)),c}),p=await Reflect.apply(o,this,f);return await a._def.returns._def.type.parseAsync(p,i).catch(b=>{throw c.addIssue(s(p,b)),c})})}else{let a=this;return Te(function(...u){let c=a._def.args.safeParse(u,i);if(!c.success)throw new je([r(u,c.error)]);let f=Reflect.apply(o,this,c.data),p=a._def.returns.safeParse(f,i);if(!p.success)throw new je([s(f,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new n({...this._def,args:ft.create(e).rest(Rt.create())})}returns(e){return new n({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new n({args:e||ft.create([]).rest(Rt.create()),returns:t||Rt.create(),typeName:Z.ZodFunction,...J(r)})}},Tn=class extends Q{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})}};Tn.create=(n,e)=>new Tn({getter:n,typeName:Z.ZodLazy,...J(e)});var xn=class extends Q{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return j(t,{received:t.data,code:R.invalid_literal,expected:this._def.value}),K}return{status:"valid",value:e.data}}get value(){return this._def.value}};xn.create=(n,e)=>new xn({value:n,typeName:Z.ZodLiteral,...J(e)});function Ml(n,e){return new Cn({values:n,typeName:Z.ZodEnum,...J(e)})}var Cn=class n extends Q{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),r=this._def.values;return j(t,{expected:te.joinValues(r),received:t.parsedType,code:R.invalid_type}),K}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return j(t,{received:t.data,code:R.invalid_enum_value,options:r}),K}return Te(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 n.create(e,{...this._def,...t})}exclude(e,t=this._def){return n.create(this.options.filter(r=>!e.includes(r)),{...this._def,...t})}};Cn.create=Ml;var In=class extends Q{_parse(e){let t=te.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==O.string&&r.parsedType!==O.number){let s=te.objectValues(t);return j(r,{expected:te.joinValues(s),received:r.parsedType,code:R.invalid_type}),K}if(this._cache||(this._cache=new Set(te.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=te.objectValues(t);return j(r,{received:r.data,code:R.invalid_enum_value,options:s}),K}return Te(e.data)}get enum(){return this._def.values}};In.create=(n,e)=>new In({values:n,typeName:Z.ZodNativeEnum,...J(e)});var Wt=class extends Q{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==O.promise&&t.common.async===!1)return j(t,{code:R.invalid_type,expected:O.promise,received:t.parsedType}),K;let r=t.parsedType===O.promise?t.data:Promise.resolve(t.data);return Te(r.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};Wt.create=(n,e)=>new Wt({type:n,typeName:Z.ZodPromise,...J(e)});var We=class extends Q{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Z.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{j(r,o),o.fatal?t.abort():t.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(r.data,i);if(r.common.async)return Promise.resolve(o).then(async a=>{if(t.value==="aborted")return K;let u=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return u.status==="aborted"?K:u.status==="dirty"?mn(u.value):t.value==="dirty"?mn(u.value):u});{if(t.value==="aborted")return K;let a=this._def.schema._parseSync({data:o,path:r.path,parent:r});return a.status==="aborted"?K:a.status==="dirty"?mn(a.value):t.value==="dirty"?mn(a.value):a}}if(s.type==="refinement"){let o=a=>{let u=s.refinement(a,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?K:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?K:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.value,value:a.value}))))}if(s.type==="transform")if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Ht(o))return K;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:r.data,path:r.path,parent:r}).then(o=>Ht(o)?Promise.resolve(s.transform(o.value,i)).then(a=>({status:t.value,value:a})):K);te.assertNever(s)}};We.create=(n,e,t)=>new We({schema:n,typeName:Z.ZodEffects,effect:e,...J(t)});We.createWithPreprocess=(n,e,t)=>new We({schema:e,effect:{type:"preprocess",transform:n},typeName:Z.ZodEffects,...J(t)});var Ge=class extends Q{_parse(e){return this._getType(e)===O.undefined?Te(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ge.create=(n,e)=>new Ge({innerType:n,typeName:Z.ZodOptional,...J(e)});var pt=class extends Q{_parse(e){return this._getType(e)===O.null?Te(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};pt.create=(n,e)=>new pt({innerType:n,typeName:Z.ZodNullable,...J(e)});var Rn=class extends Q{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return t.parsedType===O.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Rn.create=(n,e)=>new Rn({innerType:n,typeName:Z.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...J(e)});var En=class extends Q{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return xr(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new je(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new je(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};En.create=(n,e)=>new En({innerType:n,typeName:Z.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...J(e)});var $r=class extends Q{_parse(e){if(this._getType(e)!==O.nan){let r=this._getOrReturnCtx(e);return j(r,{code:R.invalid_type,expected:O.nan,received:r.parsedType}),K}return{status:"valid",value:e.data}}};$r.create=n=>new $r({typeName:Z.ZodNaN,...J(n)});var Zf=Symbol("zod_brand"),ps=class extends Q{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}},ms=class n extends Q{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?K:i.status==="dirty"?(t.dirty(),mn(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?K:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,t){return new n({in:e,out:t,typeName:Z.ZodPipeline})}},An=class extends Q{_parse(e){let t=this._def.innerType._parse(e),r=s=>(Ht(s)&&(s.value=Object.freeze(s.value)),s);return xr(t)?t.then(s=>r(s)):r(t)}unwrap(){return this._def.innerType}};An.create=(n,e)=>new An({innerType:n,typeName:Z.ZodReadonly,...J(e)});function Pl(n,e){let t=typeof n=="function"?n(e):typeof n=="string"?{message:n}:n;return typeof t=="string"?{message:t}:t}function zl(n,e={},t){return n?Vt.create().superRefine((r,s)=>{let i=n(r);if(i instanceof Promise)return i.then(o=>{if(!o){let a=Pl(e,r),u=a.fatal??t??!0;s.addIssue({code:"custom",...a,fatal:u})}});if(!i){let o=Pl(e,r),a=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:a})}}):Vt.create()}var Hf={object:Oe.lazycreate},Z;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(Z||(Z={}));var Gf=(n,e={message:`Input not instance of ${n.name}`})=>zl(t=>t instanceof n,e),Dl=Gt.create,Ll=gn.create,Vf=$r.create,Wf=yn.create,Ul=vn.create,Jf=bn.create,Yf=Ir.create,Xf=wn.create,Qf=_n.create,ep=Vt.create,tp=Rt.create,np=rt.create,rp=Rr.create,sp=Et.create,ip=Oe.create,op=Oe.strictCreate,ap=kn.create,lp=Js.create,up=Sn.create,cp=ft.create,dp=Ys.create,hp=Er.create,fp=Ar.create,pp=Xs.create,mp=Tn.create,gp=xn.create,yp=Cn.create,vp=In.create,bp=Wt.create,wp=We.create,_p=Ge.create,kp=pt.create,Sp=We.createWithPreprocess,Tp=ms.create,xp=()=>Dl().optional(),Cp=()=>Ll().optional(),Ip=()=>Ul().optional(),Rp={string:(n=>Gt.create({...n,coerce:!0})),number:(n=>gn.create({...n,coerce:!0})),boolean:(n=>vn.create({...n,coerce:!0})),bigint:(n=>yn.create({...n,coerce:!0})),date:(n=>bn.create({...n,coerce:!0}))};var Ep=K;var ql=_.object({baseUrl:_.string().url(),email:_.string().email(),apiToken:_.string().min(1)}),Eo=_.object({controlPlaneUrl:_.string().url(),runnerId:_.string().optional(),runnerToken:_.string().optional(),runnerName:_.string().default(Qs.default.hostname()),jira:ql.optional(),repos:_.record(_.object({path:_.string(),jira:ql.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 re(){let n=process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR;if(n)return n;let e=ei.default.join(Qs.default.homedir(),".config","allwright"),t=ei.default.join(Qs.default.homedir(),".config","ticketpilot");return!At.default.existsSync(e)&&At.default.existsSync(t)?t:e}function $t(){return ei.default.join(re(),"runner.json")}function ye(){let n=$t();if(!At.default.existsSync(n))return null;let e=JSON.parse(At.default.readFileSync(n,"utf8"));return Eo.parse(e)}function ge(n){let e=re();At.default.mkdirSync(e,{recursive:!0,mode:448});let t=$t(),r=t+".tmp";At.default.writeFileSync(r,JSON.stringify(n,null,2)+`
|
|
262
262
|
`,{mode:384}),At.default.renameSync(r,t),At.default.chmodSync(t,384)}function ti(n,e){return`${n}:${e}`}function $n(n,e,t){return n.environments[ti(e,t)]?.secrets??{}}function se(){let n=ye();if(!n)throw new Error(`No runner config found at ${$t()}. Run \`allwright init\` first.`);return n}var ni=require("node:child_process"),Le=E(require("node:fs"),1),ri=E(require("node:path"),1);var Ap=new Set(["runner.log","runner.pid"]);function $p(n){return Le.default.readdirSync(n).filter(e=>!Ap.has(e)&&!/\.bak-\d+$/.test(e)).sort()}function Fl(n){let e=re();if(!Le.default.existsSync(e))throw new Error(`nothing to export - ${e} does not exist`);let t=$p(e);if(!t.length)throw new Error(`nothing to export - ${e} is empty`);let r=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),s=ri.default.resolve(n||`ticketpilot-backup-${r}.tgz`);return Le.default.writeFileSync(s,"",{mode:384}),(0,ni.execFileSync)("tar",["-czf",s,"-C",e,...t]),Le.default.chmodSync(s,384),{file:s,entries:t}}function Bl(n){let e=ri.default.resolve(n);if(!Le.default.existsSync(e))throw new Error(`backup file not found: ${e}`);let t=(0,ni.execFileSync)("tar",["-tzf",e],{encoding:"utf8"}).split(`
|
|
263
263
|
`).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 r=re(),s;Le.default.existsSync(r)&&Le.default.readdirSync(r).length&&(s=`${r}.bak-${Date.now()}`,Le.default.renameSync(r,s)),Le.default.mkdirSync(r,{recursive:!0,mode:448}),(0,ni.execFileSync)("tar",["-xzf",e,"-C",r]);for(let i of Le.default.readdirSync(r)){let o=ri.default.join(r,i);Le.default.statSync(o).isFile()&&Le.default.chmodSync(o,384)}return{restored:t.map(i=>i.replace(/\/$/,"")).sort(),previousDir:s}}var Pr=E(require("node:fs"),1),Jt=E(require("node:path"),1),si=".ticketpilot-attachments",Pp=15*1024*1024,jp=50*1024*1024,Kl=20;function Zl(n,e){let t=Jt.default.basename(n).replace(/[^\w.\- ()]/g,"_").replace(/^\.+/,"").slice(-100)||"file",r=t,s=1;for(;e.has(r);)r=`${s++}-${t}`;return e.add(r),r}async function jr(n,e,t,r){if(!e.length)return"";let s=Jt.default.join(t,si);Pr.default.mkdirSync(s,{recursive:!0});let i=new Set,o=[],a=0;for(let u of e){if(o.length>=Kl){r("warn",`attachment cap reached (${Kl} files) - skipping the rest`);break}if(u.size>Pp){r("warn",`skipping attachment "${u.filename}" - ${Mp(u.size)} MB exceeds the 15 MB limit`);continue}if(a+u.size>jp){r("warn",`attachment size budget reached - skipping "${u.filename}" and the rest`);break}try{let c=await n.downloadAttachment(u.contentUrl),f=Zl(u.filename,i);Pr.default.writeFileSync(Jt.default.join(s,f),c),a+=c.length,o.push(`- ${si}/${f} (${u.mimeType||"unknown type"}, ${Ao(c.length)} KB)`),r("info",`Downloaded attachment "${u.filename}" (${Ao(c.length)} KB)`)}catch(c){r("warn",`could not download attachment "${u.filename}": ${c instanceof Error?c.message:c}`)}}return o.length?`
|
|
264
264
|
|
|
@@ -270,7 +270,7 @@ Read them with the Read tool when relevant; images (screenshots) can be viewed d
|
|
|
270
270
|
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:
|
|
271
271
|
${i.join(`
|
|
272
272
|
`)}
|
|
273
|
-
Read them with the Read tool; images can be viewed directly.`,dir:r}}var Ao=n=>Math.max(1,Math.round(n/1024)),Mp=n=>Math.round(n/(1024*1024)*10)/10;var xe=E(require("node:fs"),1),oi=E(require("node:path"),1);function Or(){return oi.default.join(re(),"runner.pid")}function ii(){return oi.default.join(re(),"runner.log")}function Gl(){xe.default.mkdirSync(re(),{recursive:!0,mode:448});let n=xe.default.openSync(ii(),"a",384);try{xe.default.chmodSync(ii(),384)}catch{}return n}function Pn(){let n=Or();if(!xe.default.existsSync(n))return null;let e=Number(xe.default.readFileSync(n,"utf8").trim());return Number.isFinite(e)&&e>0?e:null}function jn(n){try{return process.kill(n,0),!0}catch{return!1}}function Vl(n){xe.default.mkdirSync(re(),{recursive:!0,mode:448}),xe.default.writeFileSync(Or(),String(n),{mode:384})}function Wl(n){Pn()===n&&xe.default.rmSync(Or(),{force:!0})}function $o(){return oi.default.join(re(),"runner.lock")}function gs(){let n=$o();if(!xe.default.existsSync(n))return null;let e=Number(xe.default.readFileSync(n,"utf8").trim());return!Number.isFinite(e)||e<=0||e===process.pid?null:jn(e)?e:null}function Jl(){let n=gs();return n?{ok:!1,pid:n}:(xe.default.mkdirSync(re(),{recursive:!0,mode:448}),xe.default.writeFileSync($o(),String(process.pid),{mode:384}),{ok:!0})}function Po(){try{let n=$o();xe.default.existsSync(n)&&Number(xe.default.readFileSync(n,"utf8").trim())===process.pid&&xe.default.rmSync(n,{force:!0})}catch{}}var pi=E(require("node:fs"),1),_s=E(require("node:path"),1),_u=E(Se(),1);async function ku(n,e){let t=await fetch(new URL("/api/runners/enroll",n.controlPlaneUrl),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enrollToken:e,name:n.runnerName,platform:`${process.platform}/${process.arch}`,runnerVersion:mi})});if(!t.ok){let i=await t.text().catch(()=>"");throw new Error(`enrollment failed (${t.status}): ${i.slice(0,300)}`)}let r=_u.EnrollResponse.parse(await t.json()),s={...n,runnerId:r.runnerId,runnerToken:r.runnerToken};return ge(s),s}function lg(){try{let n=process.argv[1]?pi.default.realpathSync(process.argv[1]):"";for(let e of[_s.default.dirname(n),_s.default.dirname(_s.default.dirname(n))]){let t=_s.default.join(e,"package.json");if(!pi.default.existsSync(t))continue;let r=JSON.parse(pi.default.readFileSync(t,"utf8")).version;if(typeof r=="string"&&r)return r}}catch{}return"0.0.0"}var mi=lg();
|
|
273
|
+
Read them with the Read tool; images can be viewed directly.`,dir:r}}var Ao=n=>Math.max(1,Math.round(n/1024)),Mp=n=>Math.round(n/(1024*1024)*10)/10;var xe=E(require("node:fs"),1),oi=E(require("node:path"),1);function Or(){return oi.default.join(re(),"runner.pid")}function ii(){return oi.default.join(re(),"runner.log")}function Gl(){xe.default.mkdirSync(re(),{recursive:!0,mode:448});let n=xe.default.openSync(ii(),"a",384);try{xe.default.chmodSync(ii(),384)}catch{}return n}function Pn(){let n=Or();if(!xe.default.existsSync(n))return null;let e=Number(xe.default.readFileSync(n,"utf8").trim());return Number.isFinite(e)&&e>0?e:null}function jn(n){try{return process.kill(n,0),!0}catch{return!1}}function Vl(n){xe.default.mkdirSync(re(),{recursive:!0,mode:448}),xe.default.writeFileSync(Or(),String(n),{mode:384})}function Wl(n){Pn()===n&&xe.default.rmSync(Or(),{force:!0})}function $o(){return oi.default.join(re(),"runner.lock")}function gs(){let n=$o();if(!xe.default.existsSync(n))return null;let e=Number(xe.default.readFileSync(n,"utf8").trim());return!Number.isFinite(e)||e<=0||e===process.pid?null:jn(e)?e:null}function Jl(){let n=gs();return n?{ok:!1,pid:n}:(xe.default.mkdirSync(re(),{recursive:!0,mode:448}),xe.default.writeFileSync($o(),String(process.pid),{mode:384}),{ok:!0})}function Po(){try{let n=$o();xe.default.existsSync(n)&&Number(xe.default.readFileSync(n,"utf8").trim())===process.pid&&xe.default.rmSync(n,{force:!0})}catch{}}var pi=E(require("node:fs"),1),_s=E(require("node:path"),1),_u=E(Se(),1);async function ku(n,e){let t=await fetch(new URL("/api/runners/enroll",n.controlPlaneUrl),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enrollToken:e,name:n.runnerName,platform:`${process.platform}/${process.arch}`,runnerVersion:mi})});if(!t.ok){let i=await t.text().catch(()=>"");throw new Error(`enrollment failed (${t.status}): ${i.slice(0,300)}`)}let r=_u.EnrollResponse.parse(await t.json()),s={...n,runnerId:r.runnerId,runnerToken:r.runnerToken};return ge(s),s}function lg(){try{let n=process.argv[1]?pi.default.realpathSync(process.argv[1]):"";for(let e of[_s.default.dirname(n),_s.default.dirname(_s.default.dirname(n))]){let t=_s.default.join(e,"package.json");if(!pi.default.existsSync(t))continue;let r=JSON.parse(pi.default.readFileSync(t,"utf8")).version;if(typeof r=="string"&&r)return r}}catch{}return"0.0.0"}var mi=lg();vt();var Pu="Posted automatically by Allwright",ug=["Posted automatically by TicketPilot"],bt=n=>n.includes(Pu)||ug.some(e=>n.includes(e));var Ae=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,r){let s=new URL(t,this.auth.baseUrl).toString(),i=await fetch(s,{method:e,headers:this.headers(),body:r===void 0?void 0:JSON.stringify(r)});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`Jira ${e} ${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 r=await this.userSearch(e,t);return r.length||!e.includes("@")?r: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`),r=new Map;for(let i of t??[])for(let o of i.statuses??[])o.name&&!r.has(o.name)&&r.set(o.name,o.statusCategory?.key??"indeterminate");let s=i=>i==="new"?0:i==="done"?2:1;return[...r.entries()].sort((i,o)=>s(i[1])-s(o[1])).map(([i])=>i)}async searchEpics(e,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 r=(await this.request("GET",`/rest/agile/1.0/board?projectKeyOrId=${encodeURIComponent(e)}`)).values?.[0]?.id;if(!r)return null;let i=((await this.request("GET",`/rest/agile/1.0/board/${r}/configuration`)).columnConfig?.columns??[]).filter(o=>(o.statuses??[]).length>0&&o.name).map(o=>({name:o.name,statusIds:(o.statuses??[]).map(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`),r;try{r=await this.listAllComments(e)}catch{r=t.fields.comment?.comments??[]}let s=r.map(o=>({id:o.id??"",author:o.author?.displayName??"unknown",authorAccountId:o.author?.accountId??null,created:o.created,body:$u(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:$u(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),r=t.total??t.comments.length;if(r<=t.comments.length)return t.comments;let s=Math.max(0,r-200),i=s===0?[...t.comments]:[];for(;i.length<Math.min(r,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 r=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}/comment?startAt=${t}&maxResults=100`);return{comments:r.comments??[],total:r.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 r=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}?expand=changelog&fields=status`),s=t.toLowerCase(),i=null;for(let o of r.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,r,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:ea(r),...i?{parent:{key:i}}:{}}})).key}}async addAttachments(e,t){if(!t.length)return;let r=new FormData;for(let a of t)r.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:r});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:ea(t)})}async addComment(e,t){let r=`${t}
|
|
274
274
|
|
|
275
275
|
---
|
|
276
276
|
_${Pu} - never treated as a trigger._`;await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/comment`,{body:ea(r)})}async editLabels(e,t){let r=[...(t.add??[]).map(s=>({add:s})),...(t.remove??[]).map(s=>({remove:s}))];await this.request("PUT",`/rest/api/3/issue/${encodeURIComponent(e)}`,{update:{labels:r}})}async getTransitions(e){return((await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}/transitions`)).transitions??[]).map(r=>({id:r.id,name:r.name}))}async transition(e,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 $u(n){if(!n)return"";let e=[],t=r=>{r.text&&e.push(r.text),r.type==="hardBreak"&&e.push(`
|
|
@@ -280,7 +280,7 @@ _${Pu} - never treated as a trigger._`;await this.request("POST",`/rest/api/3/is
|
|
|
280
280
|
`).trim()}function ea(n){let e=n.replace(/\r\n/g,`
|
|
281
281
|
`).split(`
|
|
282
282
|
`),t=[],r=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(;r<e.length;){let i=e[r];if(i.trim()===""){r++;continue}let o=i.match(/^```(\w*)\s*$/);if(o){let p=[];for(r++;r<e.length&&!/^```\s*$/.test(e[r]);)p.push(e[r]),r++;r++,t.push({type:"codeBlock",attrs:o[1]?{language:o[1]}:{},content:[{type:"text",text:p.join(`
|
|
283
|
-
`)||" "}]});continue}let a=i.match(/^(#{1,6})\s+(.*)$/);if(a){t.push({type:"heading",attrs:{level:a[1].length},content:s(a[2])}),r++;continue}if(i.match(/^\s*[-*]\s+(.*)$/)){let p=[];for(;r<e.length;){let
|
|
283
|
+
`)||" "}]});continue}let a=i.match(/^(#{1,6})\s+(.*)$/);if(a){t.push({type:"heading",attrs:{level:a[1].length},content:s(a[2])}),r++;continue}if(i.match(/^\s*[-*]\s+(.*)$/)){let p=[];for(;r<e.length;){let v=e[r].match(/^\s*[-*]\s+(.*)$/);if(!v)break;p.push({type:"listItem",content:[{type:"paragraph",content:s(v[1])}]}),r++}t.push({type:"bulletList",content:p});continue}if(i.match(/^\s*\d+[.)]\s+(.*)$/)){let p=[];for(;r<e.length;){let v=e[r].match(/^\s*\d+[.)]\s+(.*)$/);if(!v)break;p.push({type:"listItem",content:[{type:"paragraph",content:s(v[1])}]}),r++}t.push({type:"orderedList",content:p});continue}let f=[i];for(r++;r<e.length&&e[r].trim()!==""&&!/^(#{1,6}\s|```|\s*[-*]\s|\s*\d+[.)]\s)/.test(e[r]);)f.push(e[r]),r++;t.push({type:"paragraph",content:s(f.join(" "))})}return{type:"doc",version:1,content:t}}function ju(n,e,t){let r=n.repos[e]?.jira??n.jira;if(!r)return{kind:"legacy"};let s=t.trim().toLowerCase();if(!s)return{kind:"legacy"};if(s===r.email.toLowerCase())return{kind:"self"};let i=n.jiraUsers[s];return i?{kind:"user",creds:{baseUrl:r.baseUrl,email:i.email,apiToken:i.apiToken}}:{kind:"missing",error:`Jira actions from Allwright post under YOUR OWN Atlassian identity, and no Jira credential is set up for ${s} on the runner yet. Ask your admin to run this on the runner machine:
|
|
284
284
|
|
|
285
285
|
allwright jira user-add ${s}
|
|
286
286
|
|
|
@@ -349,7 +349,7 @@ Explore the repository first - entry points, routes, storage, tests - then audit
|
|
|
349
349
|
"fix": "<2-4 sentences: concrete fix, specific to this code>"}]}
|
|
350
350
|
\`\`\`
|
|
351
351
|
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 Zu(n){let t=n.match(/```(?:json)?\s*(\{[\s\S]*\})\s*```(?![\s\S]*```)/)?.[1]??n.match(/\{[\s\S]*"findings"[\s\S]*\}/)?.[0];if(!t)return{error:"the agent's report contained no JSON block"};let r;try{r=JSON.parse(t)}catch{return{error:"the agent's JSON report did not parse"}}if(!Array.isArray(r.findings))return{error:"the report has no findings array"};let s=[],i=0,o=new Set;for(let a of r.findings.slice(0,25)){let u=dg(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 r.summary=="string"?r.summary.trim().slice(0,2e3):"",findings:s,dropped:i}}function dg(n){if(typeof n!="object"||n===null)return null;let e=n,t=typeof e.severity=="string"?e.severity.toLowerCase():"",r=Array.isArray(e.evidence)?e.evidence.filter(i=>typeof i=="object"&&i!==null).map(i=>({file:typeof i.file=="string"?i.file:"",...Bu(i.line)?{line:Bu(i.line)}:{},note:typeof i.note=="string"?i.note:""})).filter(i=>i.file):[],s=typeof e.ruleId=="string"?e.ruleId.trim().toUpperCase():"";return{id:hg(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:r,fix:typeof e.fix=="string"?e.fix.slice(0,2e3):""}}function Bu(n){let e=typeof n=="number"?n:typeof n=="string"?parseInt(n,10):NaN;return Number.isInteger(e)&&e>0?e:void 0}function hg(n){return n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"finding"}function fg(n){try{let e=oa.default.readFileSync(n,"utf8");return e?e.split(`
|
|
352
|
-
`).length:0}catch{return null}}function Hu(n,e){let t=Si.default.resolve(n),r=[],s=[],i=0;for(let o of e){let a=[];for(let u of o.evidence){let c=u.file.trim().replace(/^\.\//,""),f=Si.default.resolve(t,c);if(f!==t&&!f.startsWith(t+Si.default.sep))continue;let p;try{p=oa.default.statSync(f)}catch{continue}if(p.isFile()){if(u.line!==void 0){let
|
|
352
|
+
`).length:0}catch{return null}}function Hu(n,e){let t=Si.default.resolve(n),r=[],s=[],i=0;for(let o of e){let a=[];for(let u of o.evidence){let c=u.file.trim().replace(/^\.\//,""),f=Si.default.resolve(t,c);if(f!==t&&!f.startsWith(t+Si.default.sep))continue;let p;try{p=oa.default.statSync(f)}catch{continue}if(p.isFile()){if(u.line!==void 0){let v=fg(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}r.push({...o,evidence:a})}return{findings:r,droppedFindings:s,correctedLines:i}}var Ts=E(require("node:fs"),1),aa=E(require("node:path"),1),Gu=E(Se(),1);var pg=20;function Vu(){return aa.default.join(re(),"audits.json")}function Zr(){try{return{byProject:JSON.parse(Ts.default.readFileSync(Vu(),"utf8")).byProject??{}}}catch{return{byProject:{}}}}function Wu(n){let e=Vu();Ts.default.mkdirSync(aa.default.dirname(e),{recursive:!0,mode:448});let t=e+".tmp";Ts.default.writeFileSync(t,JSON.stringify(n,null,2),{mode:384}),Ts.default.renameSync(t,e)}function Ju(n,e){let t=Zr(),r=t.byProject[n]??[];r.unshift(Gu.AuditRecord.parse(e)),t.byProject[n]=r.slice(0,pg),Wu(t)}function Yu(n){return(Zr().byProject[n]??[]).map(e=>{let t={};for(let r of e.findings)t[r.severity]=(t[r.severity]??0)+1;return{id:e.id,role:e.role,createdAt:e.createdAt,findingCount:e.findings.length,bySeverity:t}})}function Xu(n,e){let t=Zr(),r=e?Date.parse(e):NaN,s={};for(let i of n){let o=(t.byProject[i]??[]).filter(u=>!Number.isFinite(r)||Date.parse(u.createdAt)>=r);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 la(n,e,t){let r=Zr(),i=(r.byProject[n]??[]).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 Wu(r),i}function Qu(n,e){return(Zr().byProject[n]??[]).find(s=>s.role===e&&(s.scope?.kind??"repo")==="repo")?.createdAt??null}function ec(n,e){return(Zr().byProject[n]??[]).find(t=>t.id===e)??null}vt();var $e=E(require("node:fs"),1),wt=E(require("node:path"),1),sc=E(Se(),1);var zt=E(require("node:fs"),1),ua=E(require("node:path"),1),mg=25e4,gg=2e5,tc=`# Incident ledger
|
|
353
353
|
|
|
354
354
|
Machine-written facts about this repository's runs: what failed, what
|
|
355
355
|
resolved it. Appended by the Allwright runner; humans may edit freely.
|
|
@@ -361,7 +361,7 @@ Newest entries are at the bottom.
|
|
|
361
361
|
`),yg(t)}catch{}}function xs(n,e){try{return zt.default.readFileSync(ca(n),"utf8").includes(`\xB7 ${e} \xB7`)}catch{return!1}}function yg(n){if(zt.default.statSync(n).size<=mg)return;let r=zt.default.readFileSync(n,"utf8").slice(-gg),s=r.indexOf(`
|
|
362
362
|
## `),i=s===-1?r:r.slice(s+1);zt.default.writeFileSync(n,tc+`*(older entries were rotated out)*
|
|
363
363
|
|
|
364
|
-
`+i)}function nc(n){try{return zt.default.readFileSync(ca(n),"utf8")}catch{return null}}var
|
|
364
|
+
`+i)}function nc(n){try{return zt.default.readFileSync(ca(n),"utf8")}catch{return null}}var vg=`# Security baseline - what to check in any repo
|
|
365
365
|
|
|
366
366
|
Every rule has a stable id. Findings must cite the id they violate.
|
|
367
367
|
|
|
@@ -404,7 +404,7 @@ Every rule has a stable id. Findings must cite the id they violate.
|
|
|
404
404
|
- **SEC-042** TLS/redirect handling that downgrades to http.
|
|
405
405
|
|
|
406
406
|
Prioritize by real exploitability in THIS codebase, not by rule order.
|
|
407
|
-
`,
|
|
407
|
+
`,bg=`# Test gaps - what to check in any repo
|
|
408
408
|
|
|
409
409
|
Every rule has a stable id. Findings must cite the id they violate.
|
|
410
410
|
|
|
@@ -517,7 +517,7 @@ deviations.
|
|
|
517
517
|
|
|
518
518
|
Summarize with an overall verdict: is this repository HEALTHY for its
|
|
519
519
|
purpose, and what are the 2-3 structural moves with the best payoff?
|
|
520
|
-
`,rc={security:[{name:"baseline.md",content:
|
|
520
|
+
`,rc={security:[{name:"baseline.md",content:vg},{name:"gdpr.md",content:wg}],testing:[{name:"test-gaps.md",content:bg}],architecture:[{name:"architecture-health.md",content:_g}],implement:[]},kg=["You are auditing code you can READ but never run or change.","You are auditing test coverage by READING code and tests","\\`area\\`"];function da(n){return wt.default.join(re(),"knowledge",n)}function ic(n,e){return wt.default.join(n,".ticketpilot","knowledge",`${e}.md`)}function ha(n,e){return wt.default.join(n,".ticketpilot","lessons",`${e}.md`)}function oc(n,e){let t=[],r=da(n),s=[];if($e.default.existsSync(r)){for(let u of $e.default.readdirSync(r)){if(!u.endsWith(".md"))continue;let c=wt.default.join(r,u),f=$e.default.readFileSync(c,"utf8");if(kg.some(p=>f.includes(p))&&rc[n].map(v=>v.name).includes(u)&&!f.includes("SEC-0")&&!f.includes("TEST-0")&&!f.includes("GDPR-0")){$e.default.rmSync(c);continue}s.push(u)}s.sort()}let i=new Set(s);for(let u of rc[n])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:$e.default.readFileSync(wt.default.join(r,u),"utf8").slice(0,3e4),editable:!0});let o=ic(e,n);$e.default.existsSync(o)&&t.push({level:"project",source:"pack",name:`${n}.md`,content:$e.default.readFileSync(o,"utf8").slice(0,3e4),editable:!0});let a=ha(e,n);return $e.default.existsSync(a)&&t.push({level:"project",source:"lessons",name:`${n}.md`,content:$e.default.readFileSync(a,"utf8").slice(0,2e4),editable:!0}),t}function xi(n,e){let t=oc(n,e);return{packs:t.filter(r=>r.source==="pack").map(r=>({name:`${r.level}/${r.name}`,content:r.content})),lessons:t.find(r=>r.source==="lessons")?.content??"",layers:t}}function fa(n,e,t,r="project"){let s=r==="org"?wt.default.join(da(e),"org-lessons.md"):ha(n,e);$e.default.mkdirSync(wt.default.dirname(s),{recursive:!0});let i=$e.default.existsSync(s)?"":`# ${e} lessons (${r} level)
|
|
521
521
|
|
|
522
522
|
Human-confirmed corrections and rules. `+(e==="implement"?`Every implement run on this repo reads this BEFORE starting work.
|
|
523
523
|
|
|
@@ -529,31 +529,31 @@ Human-confirmed corrections and rules. `+(e==="implement"?`Every implement run o
|
|
|
529
529
|
Finding \`${n.id}\` [${n.severity}] was marked **${e}**`+(r?` by ${r}`:"")+`.${t?` Reason: ${t}`:""}
|
|
530
530
|
`+(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 lc(n,e){return`## ${new Date().toISOString().slice(0,10)} \xB7 taught${e?` by ${e}`:""}
|
|
531
531
|
${n.trim()}`}function uc(n){let e=[];for(let r of sc.KnowledgeRole.options)for(let s of oc(r,n))e.push({role:r,...s});let t=nc(n);return t&&e.push({role:"implement",level:"project",source:"memory",name:"incidents.md",content:t.slice(-3e4),editable:!1}),e}function cc(n,e,t,r,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"?wt.default.join(da(e),s):r==="lessons"?ha(n,e):ic(n,e);$e.default.mkdirSync(wt.default.dirname(o),{recursive:!0}),$e.default.writeFileSync(o,i,{mode:t==="org"?384:420})}var pa=()=>new Date().toISOString(),y={info:n=>console.log(`${pa()} [info] ${n}`),warn:n=>console.warn(`${pa()} [warn] ${n}`),error:n=>console.error(`${pa()} [error] ${n}`)};var dc=require("node:child_process"),hc=E(require("node:fs"),1),fc=E(require("node:path"),1);function Hr(n){for(let e of["TEST.md","TESTING.md","docs/TEST.md"]){let t=fc.default.join(n,e);if(hc.default.existsSync(t))return t}return null}function Gr(n){let e=[];for(let t of n.matchAll(/```(?:bash|sh|shell)?\s*\n([\s\S]*?)```/g))for(let r of t[1].split(`
|
|
532
|
-
`)){let s=r.trim();!s||s.startsWith("#")||e.push(s)}return e.slice(0,10)}async function nr(n,e,t={}){let r=[],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,dc.spawn)("bash",["-lc",i],{cwd:n,env:{...process.env,CI:"1",FORCE_COLOR:"0"}}),f="",p=
|
|
533
|
-
[killed: timed out]`},s);c.on("close",
|
|
532
|
+
`)){let s=r.trim();!s||s.startsWith("#")||e.push(s)}return e.slice(0,10)}async function nr(n,e,t={}){let r=[],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,dc.spawn)("bash",["-lc",i],{cwd:n,env:{...process.env,CI:"1",FORCE_COLOR:"0"}}),f="",p=b=>{f+=b.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+=`
|
|
533
|
+
[killed: timed out]`},s);c.on("close",b=>{clearTimeout(v),u({command:i,exitCode:b??-1,durationMs:Date.now()-o,tail:f.slice(-4e3)})}),c.on("error",b=>{clearTimeout(v),u({command:i,exitCode:-1,durationMs:Date.now()-o,tail:String(b)})})});t.onProgress?.(`exit ${a.exitCode} in ${Math.round(a.durationMs/1e3)}s: ${i}`),r.push(a)}return r}async function Vr(n){let{packs:e,lessons:t}=xi(n.role,n.repoPath);if(!e.length)return{ok:!1,error:`no knowledge packs found for the ${n.role} role - add markdown files under ~/.config/ticketpilot/knowledge/${n.role}/ on the runner`};let r="";if(n.scope.kind==="ticket"&&n.scope.ref){let p=n.scope.ref,v="";try{let T=await n.jira.getIssue(p);v=`Ticket ${p}: ${T.summary}
|
|
534
534
|
|
|
535
|
-
${T.description}`.slice(0,4e3)}catch{
|
|
535
|
+
${T.description}`.slice(0,4e3)}catch{v=`Ticket ${p} (could not fetch its text from Jira).`}let b=await Ho(n.repoPath,p).catch(()=>null);if(b){let{base:T,stat:x,diff:P}=await wi(n.repoPath,b).catch(()=>({base:"",stat:"",diff:""}));r=`${v}
|
|
536
536
|
|
|
537
|
-
Its implementation branch \`${
|
|
537
|
+
Its implementation branch \`${b}\` vs \`${T}\`:
|
|
538
538
|
\`\`\`
|
|
539
539
|
${x}\`\`\`
|
|
540
540
|
\`\`\`diff
|
|
541
541
|
${P}
|
|
542
|
-
\`\`\``}else r=`${
|
|
542
|
+
\`\`\``}else r=`${v}
|
|
543
543
|
|
|
544
|
-
No implementation branch found for ${p} - audit the parts of the codebase this ticket touches or would touch.`}else if(n.scope.kind==="branch"&&n.scope.ref){let{base:p,stat:
|
|
544
|
+
No implementation branch found for ${p} - audit the parts of the codebase this ticket touches or would touch.`}else if(n.scope.kind==="branch"&&n.scope.ref){let{base:p,stat:v,diff:b}=await wi(n.repoPath,n.scope.ref);r=`The diff of \`${n.scope.ref}\` vs \`${p}\`:
|
|
545
545
|
\`\`\`
|
|
546
|
-
${
|
|
546
|
+
${v}\`\`\`
|
|
547
547
|
\`\`\`diff
|
|
548
|
-
${
|
|
549
|
-
\`\`\``}let s,i;if(n.role==="testing"){let p=Hr(n.repoPath),
|
|
550
|
-
(exit ${
|
|
551
|
-
${
|
|
548
|
+
${b}
|
|
549
|
+
\`\`\``}let s,i;if(n.role==="testing"){let p=Hr(n.repoPath),v=p?Gr(pc.default.readFileSync(p,"utf8")):[];v.length&&(y.info(`Audit (testing): executing ${v.length} TEST.md command(s)`),i=await nr(n.repoPath,v,{onProgress:b=>y.info(`[test-run] ${b}`)}),s=i.map(b=>`$ ${b.command}
|
|
550
|
+
(exit ${b.exitCode}, ${Math.round(b.durationMs/1e3)}s)
|
|
551
|
+
${b.tail.slice(-2e3)}`).join(`
|
|
552
552
|
|
|
553
553
|
---
|
|
554
554
|
|
|
555
|
-
`))}let o=n.model||n.agent.adapter.deepModel,a=await n.agent.adapter.run({repoPath:n.repoPath,prompt:Ku(n.role,e,t,{scopeNote:r,testResults:s}),timeoutSeconds:480,bin:n.agent.bin,mode:"read_only",maxTurns:120,sessionId:(0,ma.randomUUID)(),model:o,onLog:(p,b)=>{p==="agent"&&y.info(`[audit:${n.role}] ${b.slice(0,160)}`)}}),u=Zu(a.resultText);if("error"in u)return{ok:!1,error:u.error};let c=Hu(n.repoPath,u.findings);for(let p of c.droppedFindings)y.warn(`[audit:${n.role}] dropped "${p.title}" - cited files do not exist: `+p.files.join(", "));let f={id:(0,ma.randomUUID)(),role:n.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:n.scope,...i?{testRun:i}:{}};return Ju(n.projectId,f),y.info(`Audit (${n.role}${n.scope.kind!=="repo"?` \xB7 ${n.scope.kind}:${n.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 hr=E(Se(),1);var Ia=E(require("node:fs"),1),ji=E(require("node:path"),1),Oi=require("node:crypto"),Be=E(Se(),1);var rr=E(Se(),1);var ga=E(require("node:fs"),1),mc=E(require("node:os"),1),Ci=E(require("node:path"),1),gc=require("node:child_process"),yc=E(require("node:readline"),1),bc=E(Se(),1),Sg=4e3,Tg={read_only:["Read(./**)","Glob(./**)","Grep(./**)"],edit_no_shell:["Read(./**)","Glob(./**)","Grep(./**)","Edit(./**)","Write(./**)"]};function xg(n){if(process.env.ANTHROPIC_API_KEY)return"API key";let e=n??Ci.default.join(mc.default.homedir(),".claude");try{if(ga.default.existsSync(Ci.default.join(e,".credentials.json"))||ga.default.existsSync(Ci.default.join(e,"credentials.json")))return"subscription"}catch{}return"unknown"}async function Cg(n){let e=["-p","--output-format","stream-json","--verbose","--allowedTools",Tg[n.mode].join(","),"--max-turns",String(n.maxTurns??60),...n.model?["--model",n.model]:[],...n.resume?["--resume",n.sessionId]:["--session-id",n.sessionId]],t=xg(n.configDir);return t!=="unknown"&&n.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(r=>{let s=(0,gc.spawn)(n.bin,e,{cwd:n.repoPath,env:n.configDir?{...process.env,CLAUDE_CONFIG_DIR:n.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(!n.onUsage)return;let w=Date.now();w-f<Sg||(f=w,n.onUsage({inputTokens:a,outputTokens:u,cacheReadTokens:c,turns:o}))},b=!1,v=()=>{b||(b=!0,clearTimeout(x),n.signal?.removeEventListener("abort",T),r(i))},T=()=>{i.cancelled=!0,i.error="stopped from the dashboard",n.onLog("error",i.error),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),3e3).unref()};n.signal?.addEventListener("abort",T,{once:!0});let x=setTimeout(()=>{i.timedOut=!0,i.error=`run exceeded ${n.timeoutSeconds}s wall-clock limit`,n.onLog("error",i.error),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),5e3).unref()},n.timeoutSeconds*1e3);s.stdin.write(n.prompt),s.stdin.end(),yc.default.createInterface({input:s.stdout}).on("line",w=>{if(!w.trim())return;let B;try{B=JSON.parse(w)}catch{n.onLog("agent",w.slice(0,1e3));return}if(B.type==="system"&&B.subtype==="init")i.model=typeof B.model=="string"?B.model:void 0,n.onLog("info",`Claude Code session started (model: ${B.model??"default"})`);else if(B.type==="assistant"){o+=1;let M=B.message?.usage;M&&(a+=Number(M.input_tokens??0)+Number(M.cache_creation_input_tokens??0),u+=Number(M.output_tokens??0),c+=Number(M.cache_read_input_tokens??0),p());for(let D of B.message?.content??[])if(D.type==="text"&&D.text?.trim())n.onLog("agent",D.text.trim().slice(0,4e3));else if(D.type==="tool_use"){let W=D.input??{},d=["file_path","path","pattern","command","description","url"].map(g=>typeof W[g]=="string"?`${g}=${W[g]}`:null).filter(Boolean).join(" "),m=JSON.stringify(W).slice(0,400);n.onLog("info",`tool ${D.name} ${d?`${d} `:""}${m}`)}}else B.type==="result"&&(i.costUsd=Number(B.total_cost_usd??0),i.inputTokens=Number(B.usage?.input_tokens??0)+Number(B.usage?.cache_creation_input_tokens??0),i.outputTokens=Number(B.usage?.output_tokens??0),a=Math.max(i.inputTokens,a),u=Math.max(i.outputTokens,u),i.inputTokens=a,i.outputTokens=u,c=Number(B.usage?.cache_read_input_tokens??c),i.cacheReadTokens=c,n.onUsage&&(n.onUsage({inputTokens:a,outputTokens:u,cacheReadTokens:c,costUsd:i.costUsd,turns:o}),f=Date.now()),B.subtype==="success"&&!B.is_error?(i.ok=!0,i.resultText=String(B.result??"")):B.subtype==="error_max_turns"?(i.turnLimitHit=!0,i.error=`hit the ${n.maxTurns??60}-turn limit before finishing`):(i.error=String(B.result??B.subtype??"unknown Claude Code error"),/rate.?limit|usage limit|limit (reached|exceeded)|overloaded/i.test(i.error)&&(i.error=`Claude usage limit hit for this account - the run will work again once the limit window resets. Original error: ${i.error.slice(0,400)}`)))});let I="";s.stderr.on("data",w=>{I=(I+w.toString()).slice(-2e3)}),s.on("error",w=>{i.error=`failed to start ${n.bin}: ${w.message}`,n.onLog("error",i.error),v()}),s.on("close",w=>{!i.ok&&!i.error&&(i.error=i.timedOut?i.error:`claude exited with code ${w}${I?`: ${I.slice(-500)}`:""}`),v()})})}var Ii={id:"claude-code",displayName:"Claude Code",fastModel:"claude-sonnet-5",deepModel:"claude-fable-5",capabilities:bc.REGISTERED_AGENTS.find(n=>n.id==="claude-code").capabilities,run:Cg};var vc=require("node:child_process"),wc=E(require("node:readline"),1),_c=E(Se(),1);async function Ig(n){if(n.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(n.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",n.repoPath,...n.model?["--model",n.model]:[],"-"];return new Promise(t=>{let r=(0,vc.spawn)(n.bin,e,{cwd:n.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 ${n.timeoutSeconds}s wall-clock limit`,n.onLog("error",s.error),r.kill("SIGTERM"),setTimeout(()=>r.kill("SIGKILL"),5e3).unref()},n.timeoutSeconds*1e3);r.stdin.write(n.prompt),r.stdin.end(),wc.default.createInterface({input:r.stdout}).on("line",p=>{if(!p.trim())return;let b;try{b=JSON.parse(p)}catch{n.onLog("agent",p.slice(0,1e3));return}let v=b.item??b.msg??b,T=v?.type??b.type,x=v?.text??v?.message??"";T==="agent_message"&&typeof x=="string"&&x.trim()?(i=x,n.onLog("agent",x.trim().slice(0,4e3))):T==="command_execution"||T==="exec_command_begin"?n.onLog("info",`tool ${String(v?.command??"").slice(0,300)}`):T==="error"&&typeof x=="string"&&x&&n.onLog("error",x.slice(0,1e3))});let f="";r.stderr.on("data",p=>{f=(f+p.toString()).slice(-2e3)}),r.on("error",p=>{s.error=`failed to start ${n.bin}: ${p.message} - is the Codex CLI installed and logged in?`,n.onLog("error",s.error),a()}),r.on("close",p=>{p===0&&i.trim()?(s.ok=!0,s.resultText=i):s.error||(s.error=`codex exited with code ${p}`+(i?"":" and produced no answer")+(f?`: ${f.slice(-500)}`:"")),a()})})}var ya={id:"codex",fastModel:"",deepModel:"",displayName:"OpenAI Codex CLI (experimental)",capabilities:_c.REGISTERED_AGENTS.find(n=>n.id==="codex").capabilities,run:Ig};var Rg={[Ii.id]:Ii,[ya.id]:ya};function qe(n){return Rg[n||rr.DEFAULT_AGENT_ID]??null}function ze(n,e){return!e||e===Ii.id?n.claudeBin:n.agents[e]?.bin??e}function un(n,e){let t=qe(n);if(!t)return`no agent adapter named "${n}" on this runner - update the runner, or set the rule's agent to "${rr.DEFAULT_AGENT_ID}"`;let r=(0,rr.missingAgentCapabilities)(t.id,e);return r&&r.length?`agent "${t.displayName}" cannot run ${e} rules: it cannot guarantee ${r.join(", ")}. Allwright refuses rather than weakening the isolation silently.`:null}function Fe(n,e,t){let r=e.defaultAgent||rr.DEFAULT_AGENT_ID,s=qe(r);if(!s)return{error:`this project's default agent "${r}" is not on this runner - update the runner, or change the project's agent`};let i=(0,rr.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:ze(n,s.id)}}function Dt(n,e){return n.replace(/\{\{(\w+)\}\}/g,(t,r)=>r in e?e[r]:t)}var $c=E(Se(),1);at();er();bt();var Pe=E(require("node:fs"),1),Wr=E(require("node:path"),1);var Ag=_.object({runId:_.string(),issueKey:_.string(),repoName:_.string(),owner:_.string(),repo:_.string(),prNumber:_.number().int(),prUrl:_.string(),branch:_.string(),headSha:_.string(),doneLabel:_.string(),failedLabel:_.string(),jiraTransition:_.string().optional(),mergeOnApprove:_.boolean().default(!1),mergeMethod:_.enum(["squash","merge","rebase"]).default("squash"),autoMerge:_.boolean().default(!1),nextDecisionSeq:_.number().int().default(1e5),changesRequestedNotified:_.boolean().optional(),conflictNotified:_.boolean().optional(),agentConfigDir:_.string().optional()}),$g=_.record(Ag),Pg=_.object({runId:_.string(),issueKey:_.string(),issueSummary:_.string().default(""),projectId:_.string(),repoName:_.string(),environmentName:_.string(),requestedBy:_.string().default(""),createdAt:_.string()}),jg=_.record(Pg),Og=_.object({runId:_.string(),issueKey:_.string(),kind:_.enum(["plan","implement"]),repoPath:_.string(),sessionId:_.string(),doneLabel:_.string(),failedLabel:_.string(),timeoutSeconds:_.number(),createdAt:_.string(),questionsPostedAt:_.string(),rounds:_.number().int().default(1),nextLogSeq:_.number().int().nonnegative().default(0),baseRepoPath:_.string().optional(),repoName:_.string().optional(),branch:_.string().optional(),baseBranch:_.string().optional(),jiraTransition:_.string().optional(),jiraTransitionOnMerge:_.string().optional(),requireApproval:_.boolean().optional(),maxTurns:_.number().int().optional(),runTests:_.boolean().default(!0),mergeOnApprove:_.boolean().default(!1),mergeMethod:_.enum(["squash","merge","rebase"]).default("squash"),autoMerge:_.boolean().default(!1),issueSummary:_.string().default(""),claudeConfigDir:_.string().optional(),agent:_.string().optional(),model:_.string().optional(),actorEmail:_.string().optional()}),Ng=_.object({runId:_.string(),issueKey:_.string(),issueSummary:_.string().default(""),repoName:_.string(),baseRepoPath:_.string(),branch:_.string(),baseBranch:_.string(),headSha:_.string(),requireApproval:_.boolean(),mergeOnApprove:_.boolean().default(!1),mergeMethod:_.enum(["squash","merge","rebase"]).default("squash"),autoMerge:_.boolean().default(!1),doneLabel:_.string(),failedLabel:_.string(),jiraTransition:_.string().optional(),jiraTransitionOnMerge:_.string().optional(),actorEmail:_.string().optional(),resultSummary:_.string().default(""),prSummary:_.string().default(""),costUsd:_.number().default(0),nextLogSeq:_.number().int().default(1e5),createdAt:_.string()}),Mg=_.record(Ng),zg=_.object({runId:_.string(),issueKey:_.string(),repoName:_.string(),owner:_.string(),repo:_.string(),prNumber:_.number().int(),prUrl:_.string(),jiraTransitionOnMerge:_.string().default(""),createdAt:_.string()}),Dg=_.record(zg),Lg=_.record(Og);function kc(){return Wr.default.join(re(),"pending-runs.json")}function ba(){return Wr.default.join(re(),"pending-deploys.json")}function va(){return Wr.default.join(re(),"pending-inputs.json")}function wa(){return Wr.default.join(re(),"merge-watch.json")}function _a(){return Wr.default.join(re(),"pending-pushes.json")}function ka(){let n=_a();if(!Pe.default.existsSync(n))return{};try{return Mg.parse(JSON.parse(Pe.default.readFileSync(n,"utf8")))}catch{return{}}}function Ri(n){let e=ka();e[n.runId]=n,Lt(_a(),e)}function Ei(n){return ka()[n]??null}function Sa(n){let e=ka();n in e&&(delete e[n],Lt(_a(),e))}function Ai(){let n=wa();if(!Pe.default.existsSync(n))return{};try{return Dg.parse(JSON.parse(Pe.default.readFileSync(n,"utf8")))}catch{return{}}}function Sc(n){let e=Ai();e[n.runId]=n,Lt(wa(),e)}function Cs(n){let e=Ai();n in e&&(delete e[n],Lt(wa(),e))}function Is(){let n=kc();if(!Pe.default.existsSync(n))return{};try{return $g.parse(JSON.parse(Pe.default.readFileSync(n,"utf8")))}catch{return{}}}function Lt(n,e){Pe.default.mkdirSync(re(),{recursive:!0,mode:448});let t=n+".tmp";Pe.default.writeFileSync(t,JSON.stringify(e,null,2)+`
|
|
556
|
-
`,{mode:384}),Pe.default.renameSync(t,n),Pe.default.chmodSync(n,384)}function Tc(n){Lt(kc(),n)}function lt(n){let e=Is();e[n.runId]=n,Tc(e)}function Jr(n){return Is()[n]??null}function ir(n){let e=Is();n in e&&(delete e[n],Tc(e))}function Ta(){let n=
|
|
555
|
+
`))}let o=n.model||n.agent.adapter.deepModel,a=await n.agent.adapter.run({repoPath:n.repoPath,prompt:Ku(n.role,e,t,{scopeNote:r,testResults:s}),timeoutSeconds:480,bin:n.agent.bin,mode:"read_only",maxTurns:120,sessionId:(0,ma.randomUUID)(),model:o,onLog:(p,v)=>{p==="agent"&&y.info(`[audit:${n.role}] ${v.slice(0,160)}`)}}),u=Zu(a.resultText);if("error"in u)return{ok:!1,error:u.error};let c=Hu(n.repoPath,u.findings);for(let p of c.droppedFindings)y.warn(`[audit:${n.role}] dropped "${p.title}" - cited files do not exist: `+p.files.join(", "));let f={id:(0,ma.randomUUID)(),role:n.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:n.scope,...i?{testRun:i}:{}};return Ju(n.projectId,f),y.info(`Audit (${n.role}${n.scope.kind!=="repo"?` \xB7 ${n.scope.kind}:${n.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 hr=E(Se(),1);var Ia=E(require("node:fs"),1),ji=E(require("node:path"),1),Oi=require("node:crypto"),Be=E(Se(),1);var rr=E(Se(),1);var ga=E(require("node:fs"),1),mc=E(require("node:os"),1),Ci=E(require("node:path"),1),gc=require("node:child_process"),yc=E(require("node:readline"),1),vc=E(Se(),1),Sg=4e3,Tg={read_only:["Read(./**)","Glob(./**)","Grep(./**)"],edit_no_shell:["Read(./**)","Glob(./**)","Grep(./**)","Edit(./**)","Write(./**)"]};function xg(n){if(process.env.ANTHROPIC_API_KEY)return"API key";let e=n??Ci.default.join(mc.default.homedir(),".claude");try{if(ga.default.existsSync(Ci.default.join(e,".credentials.json"))||ga.default.existsSync(Ci.default.join(e,"credentials.json")))return"subscription"}catch{}return"unknown"}async function Cg(n){let e=["-p","--output-format","stream-json","--verbose","--allowedTools",Tg[n.mode].join(","),"--max-turns",String(n.maxTurns??60),...n.model?["--model",n.model]:[],...n.resume?["--resume",n.sessionId]:["--session-id",n.sessionId]],t=xg(n.configDir);return t!=="unknown"&&n.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(r=>{let s=(0,gc.spawn)(n.bin,e,{cwd:n.repoPath,env:n.configDir?{...process.env,CLAUDE_CONFIG_DIR:n.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(!n.onUsage)return;let w=Date.now();w-f<Sg||(f=w,n.onUsage({inputTokens:a,outputTokens:u,cacheReadTokens:c,turns:o}))},v=!1,b=()=>{v||(v=!0,clearTimeout(x),n.signal?.removeEventListener("abort",T),r(i))},T=()=>{i.cancelled=!0,i.error="stopped from the dashboard",n.onLog("error",i.error),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),3e3).unref()};n.signal?.addEventListener("abort",T,{once:!0});let x=setTimeout(()=>{i.timedOut=!0,i.error=`run exceeded ${n.timeoutSeconds}s wall-clock limit`,n.onLog("error",i.error),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),5e3).unref()},n.timeoutSeconds*1e3);s.stdin.write(n.prompt),s.stdin.end(),yc.default.createInterface({input:s.stdout}).on("line",w=>{if(!w.trim())return;let B;try{B=JSON.parse(w)}catch{n.onLog("agent",w.slice(0,1e3));return}if(B.type==="system"&&B.subtype==="init")i.model=typeof B.model=="string"?B.model:void 0,n.onLog("info",`Claude Code session started (model: ${B.model??"default"})`);else if(B.type==="assistant"){o+=1;let M=B.message?.usage;M&&(a+=Number(M.input_tokens??0)+Number(M.cache_creation_input_tokens??0),u+=Number(M.output_tokens??0),c+=Number(M.cache_read_input_tokens??0),p());for(let D of B.message?.content??[])if(D.type==="text"&&D.text?.trim())n.onLog("agent",D.text.trim().slice(0,4e3));else if(D.type==="tool_use"){let W=D.input??{},d=["file_path","path","pattern","command","description","url"].map(g=>typeof W[g]=="string"?`${g}=${W[g]}`:null).filter(Boolean).join(" "),m=JSON.stringify(W).slice(0,400);n.onLog("info",`tool ${D.name} ${d?`${d} `:""}${m}`)}}else B.type==="result"&&(i.costUsd=Number(B.total_cost_usd??0),i.inputTokens=Number(B.usage?.input_tokens??0)+Number(B.usage?.cache_creation_input_tokens??0),i.outputTokens=Number(B.usage?.output_tokens??0),a=Math.max(i.inputTokens,a),u=Math.max(i.outputTokens,u),i.inputTokens=a,i.outputTokens=u,c=Number(B.usage?.cache_read_input_tokens??c),i.cacheReadTokens=c,n.onUsage&&(n.onUsage({inputTokens:a,outputTokens:u,cacheReadTokens:c,costUsd:i.costUsd,turns:o}),f=Date.now()),B.subtype==="success"&&!B.is_error?(i.ok=!0,i.resultText=String(B.result??"")):B.subtype==="error_max_turns"?(i.turnLimitHit=!0,i.error=`hit the ${n.maxTurns??60}-turn limit before finishing`):(i.error=String(B.result??B.subtype??"unknown Claude Code error"),/rate.?limit|usage limit|limit (reached|exceeded)|overloaded/i.test(i.error)&&(i.error=`Claude usage limit hit for this account - the run will work again once the limit window resets. Original error: ${i.error.slice(0,400)}`)))});let I="";s.stderr.on("data",w=>{I=(I+w.toString()).slice(-2e3)}),s.on("error",w=>{i.error=`failed to start ${n.bin}: ${w.message}`,n.onLog("error",i.error),b()}),s.on("close",w=>{!i.ok&&!i.error&&(i.error=i.timedOut?i.error:`claude exited with code ${w}${I?`: ${I.slice(-500)}`:""}`),b()})})}var Ii={id:"claude-code",displayName:"Claude Code",fastModel:"claude-sonnet-5",deepModel:"claude-fable-5",capabilities:vc.REGISTERED_AGENTS.find(n=>n.id==="claude-code").capabilities,run:Cg};var bc=require("node:child_process"),wc=E(require("node:readline"),1),_c=E(Se(),1);async function Ig(n){if(n.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(n.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",n.repoPath,...n.model?["--model",n.model]:[],"-"];return new Promise(t=>{let r=(0,bc.spawn)(n.bin,e,{cwd:n.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 ${n.timeoutSeconds}s wall-clock limit`,n.onLog("error",s.error),r.kill("SIGTERM"),setTimeout(()=>r.kill("SIGKILL"),5e3).unref()},n.timeoutSeconds*1e3);r.stdin.write(n.prompt),r.stdin.end(),wc.default.createInterface({input:r.stdout}).on("line",p=>{if(!p.trim())return;let v;try{v=JSON.parse(p)}catch{n.onLog("agent",p.slice(0,1e3));return}let b=v.item??v.msg??v,T=b?.type??v.type,x=b?.text??b?.message??"";T==="agent_message"&&typeof x=="string"&&x.trim()?(i=x,n.onLog("agent",x.trim().slice(0,4e3))):T==="command_execution"||T==="exec_command_begin"?n.onLog("info",`tool ${String(b?.command??"").slice(0,300)}`):T==="error"&&typeof x=="string"&&x&&n.onLog("error",x.slice(0,1e3))});let f="";r.stderr.on("data",p=>{f=(f+p.toString()).slice(-2e3)}),r.on("error",p=>{s.error=`failed to start ${n.bin}: ${p.message} - is the Codex CLI installed and logged in?`,n.onLog("error",s.error),a()}),r.on("close",p=>{p===0&&i.trim()?(s.ok=!0,s.resultText=i):s.error||(s.error=`codex exited with code ${p}`+(i?"":" and produced no answer")+(f?`: ${f.slice(-500)}`:"")),a()})})}var ya={id:"codex",fastModel:"",deepModel:"",displayName:"OpenAI Codex CLI (experimental)",capabilities:_c.REGISTERED_AGENTS.find(n=>n.id==="codex").capabilities,run:Ig};var Rg={[Ii.id]:Ii,[ya.id]:ya};function qe(n){return Rg[n||rr.DEFAULT_AGENT_ID]??null}function ze(n,e){return!e||e===Ii.id?n.claudeBin:n.agents[e]?.bin??e}function un(n,e){let t=qe(n);if(!t)return`no agent adapter named "${n}" on this runner - update the runner, or set the rule's agent to "${rr.DEFAULT_AGENT_ID}"`;let r=(0,rr.missingAgentCapabilities)(t.id,e);return r&&r.length?`agent "${t.displayName}" cannot run ${e} rules: it cannot guarantee ${r.join(", ")}. Allwright refuses rather than weakening the isolation silently.`:null}function Fe(n,e,t){let r=e.defaultAgent||rr.DEFAULT_AGENT_ID,s=qe(r);if(!s)return{error:`this project's default agent "${r}" is not on this runner - update the runner, or change the project's agent`};let i=(0,rr.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:ze(n,s.id)}}function Dt(n,e){return n.replace(/\{\{(\w+)\}\}/g,(t,r)=>r in e?e[r]:t)}var $c=E(Se(),1);at();er();vt();var Pe=E(require("node:fs"),1),Wr=E(require("node:path"),1);var Ag=_.object({runId:_.string(),issueKey:_.string(),repoName:_.string(),owner:_.string(),repo:_.string(),prNumber:_.number().int(),prUrl:_.string(),branch:_.string(),headSha:_.string(),doneLabel:_.string(),failedLabel:_.string(),jiraTransition:_.string().optional(),mergeOnApprove:_.boolean().default(!1),mergeMethod:_.enum(["squash","merge","rebase"]).default("squash"),autoMerge:_.boolean().default(!1),nextDecisionSeq:_.number().int().default(1e5),changesRequestedNotified:_.boolean().optional(),conflictNotified:_.boolean().optional(),agentConfigDir:_.string().optional()}),$g=_.record(Ag),Pg=_.object({runId:_.string(),issueKey:_.string(),issueSummary:_.string().default(""),projectId:_.string(),repoName:_.string(),environmentName:_.string(),requestedBy:_.string().default(""),createdAt:_.string()}),jg=_.record(Pg),Og=_.object({runId:_.string(),issueKey:_.string(),kind:_.enum(["plan","implement"]),repoPath:_.string(),sessionId:_.string(),doneLabel:_.string(),failedLabel:_.string(),timeoutSeconds:_.number(),createdAt:_.string(),questionsPostedAt:_.string(),rounds:_.number().int().default(1),nextLogSeq:_.number().int().nonnegative().default(0),baseRepoPath:_.string().optional(),repoName:_.string().optional(),branch:_.string().optional(),baseBranch:_.string().optional(),jiraTransition:_.string().optional(),jiraTransitionOnMerge:_.string().optional(),requireApproval:_.boolean().optional(),maxTurns:_.number().int().optional(),runTests:_.boolean().default(!0),mergeOnApprove:_.boolean().default(!1),mergeMethod:_.enum(["squash","merge","rebase"]).default("squash"),autoMerge:_.boolean().default(!1),issueSummary:_.string().default(""),claudeConfigDir:_.string().optional(),agent:_.string().optional(),model:_.string().optional(),actorEmail:_.string().optional()}),Ng=_.object({runId:_.string(),issueKey:_.string(),issueSummary:_.string().default(""),repoName:_.string(),baseRepoPath:_.string(),branch:_.string(),baseBranch:_.string(),headSha:_.string(),requireApproval:_.boolean(),mergeOnApprove:_.boolean().default(!1),mergeMethod:_.enum(["squash","merge","rebase"]).default("squash"),autoMerge:_.boolean().default(!1),doneLabel:_.string(),failedLabel:_.string(),jiraTransition:_.string().optional(),jiraTransitionOnMerge:_.string().optional(),actorEmail:_.string().optional(),resultSummary:_.string().default(""),prSummary:_.string().default(""),costUsd:_.number().default(0),nextLogSeq:_.number().int().default(1e5),createdAt:_.string()}),Mg=_.record(Ng),zg=_.object({runId:_.string(),issueKey:_.string(),repoName:_.string(),owner:_.string(),repo:_.string(),prNumber:_.number().int(),prUrl:_.string(),jiraTransitionOnMerge:_.string().default(""),createdAt:_.string()}),Dg=_.record(zg),Lg=_.record(Og);function kc(){return Wr.default.join(re(),"pending-runs.json")}function va(){return Wr.default.join(re(),"pending-deploys.json")}function ba(){return Wr.default.join(re(),"pending-inputs.json")}function wa(){return Wr.default.join(re(),"merge-watch.json")}function _a(){return Wr.default.join(re(),"pending-pushes.json")}function ka(){let n=_a();if(!Pe.default.existsSync(n))return{};try{return Mg.parse(JSON.parse(Pe.default.readFileSync(n,"utf8")))}catch{return{}}}function Ri(n){let e=ka();e[n.runId]=n,Lt(_a(),e)}function Ei(n){return ka()[n]??null}function Sa(n){let e=ka();n in e&&(delete e[n],Lt(_a(),e))}function Ai(){let n=wa();if(!Pe.default.existsSync(n))return{};try{return Dg.parse(JSON.parse(Pe.default.readFileSync(n,"utf8")))}catch{return{}}}function Sc(n){let e=Ai();e[n.runId]=n,Lt(wa(),e)}function Cs(n){let e=Ai();n in e&&(delete e[n],Lt(wa(),e))}function Is(){let n=kc();if(!Pe.default.existsSync(n))return{};try{return $g.parse(JSON.parse(Pe.default.readFileSync(n,"utf8")))}catch{return{}}}function Lt(n,e){Pe.default.mkdirSync(re(),{recursive:!0,mode:448});let t=n+".tmp";Pe.default.writeFileSync(t,JSON.stringify(e,null,2)+`
|
|
556
|
+
`,{mode:384}),Pe.default.renameSync(t,n),Pe.default.chmodSync(n,384)}function Tc(n){Lt(kc(),n)}function lt(n){let e=Is();e[n.runId]=n,Tc(e)}function Jr(n){return Is()[n]??null}function ir(n){let e=Is();n in e&&(delete e[n],Tc(e))}function Ta(){let n=va();if(!Pe.default.existsSync(n))return{};try{return jg.parse(JSON.parse(Pe.default.readFileSync(n,"utf8")))}catch{return{}}}function xc(n){let e=Ta();e[n.runId]=n,Lt(va(),e)}function $i(n){return Ta()[n]??null}function Pi(n){let e=Ta();n in e&&(delete e[n],Lt(va(),e))}function Yr(){let n=ba();if(!Pe.default.existsSync(n))return{};try{return Lg.parse(JSON.parse(Pe.default.readFileSync(n,"utf8")))}catch{return{}}}function Cc(n){let e=Yr();e[n.runId]=n,Lt(ba(),e)}function _t(n){let e=Yr();n in e&&(delete e[n],Lt(ba(),e))}var Ug=`
|
|
557
557
|
|
|
558
558
|
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.`,qg=`
|
|
559
559
|
|
|
@@ -583,7 +583,7 @@ This repository has working rules taught to Allwright - follow them:
|
|
|
583
583
|
Lessons from earlier runs on this repository (human-confirmed - follow them BEFORE writing code, they exist because a run got this wrong once):
|
|
584
584
|
`+o}return r}catch{return""}}function Ra(n){return Ia.default.existsSync(ji.default.join(n,"DESIGN.md"))?`
|
|
585
585
|
|
|
586
|
-
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 Pc=5,Rc=2,Zg=8,Ec=2,Hg="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 Rs(n,e,t,r){let s=Date.now(),i="";r&&(i=await r().catch(()=>""));let o=await n.run(e),a=0,u="",c=r?Zg:Rc;for(;!o.ok&&o.turnLimitHit&&!o.cancelled&&n.capabilities.sessionResume;){if(a>=c){u=`resume cap (${c}) reached`;break}if(r&&a>=Rc){let p=await r().catch(()=>""),
|
|
586
|
+
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 Pc=5,Rc=2,Zg=8,Ec=2,Hg="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 Rs(n,e,t,r){let s=Date.now(),i="";r&&(i=await r().catch(()=>""));let o=await n.run(e),a=0,u="",c=r?Zg:Rc;for(;!o.ok&&o.turnLimitHit&&!o.cancelled&&n.capabilities.sessionResume;){if(a>=c){u=`resume cap (${c}) reached`;break}if(r&&a>=Rc){let p=await r().catch(()=>""),v=p!==""&&p!==i;if(i=p,!v){u="the last resume produced no new work";break}if(Date.now()-s>e.timeoutSeconds*Ec*1e3){u=`wall-clock budget (${Ec}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 n.run({...e,prompt:Hg,resume:!0});f.costUsd+=o.costUsd,f.inputTokens+=o.inputTokens,f.outputTokens+=o.outputTokens,o=f}return!o.ok&&o.turnLimitHit&&n.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 Ca=new Map;function jc(n){let e=Ca.get(n);return e?(e.abort(),!0):!1}async function Qr(n,e,t,r,s){let i=new AbortController;Ca.set(n,i);try{return await Rs(e,{...t,signal:i.signal},r,s)}finally{Ca.delete(n)}}function or(n,e,t=0){let r=t;return{emit:(a,u)=>{e.send({type:"run.log",runId:n,seq:r++,ts:new Date().toISOString(),level:a,message:u}),a!=="agent"&&y.info(`[run ${n}] ${u}`)},setStatus:(a,u={})=>{e.send({type:"run.status",runId:n,status:a,...u})},sendUsage:a=>{e.send({type:"run.usage",runId:n,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:()=>r}}async function Ni(n){return n.rule.action.type==="implement"?Wg(n):n.rule.action.type==="respond"?Vg(n):Gg(n)}async function Gg(n){let{emit:e,setStatus:t,sendUsage:r,nextSeq:s}=or(n.runId,n.transport),{trigger:i}=n.rule,o=n.rule.action;if(o.type!=="plan_only")return;let a=un(o.agent,o.type);if(a){e("error",a),await Xr(n,a),t("failed",{error:a});return}let u=(0,Oi.randomUUID)();try{t("running"),e("info",`Run started for ${n.issueKey} (rule "${n.rule.name}", plan-only)`),e("info",`Fetching ${n.issueKey} from Jira`);let c=await n.jira.getIssue(n.issueKey),f=Dt(o.promptTemplate,{issueKey:c.key,summary:c.summary,description:c.description||"(no description)",comments:As(c.comments)})+await jr(n.jira,c.attachments,n.repoPath,e)+Ra(n.repoPath);e("info",`Starting Claude Code in ${n.repoPath} - read-only tools, path-jailed to the repo, timeout ${o.timeoutSeconds}s`);let p=await Qr(n.runId,qe(o.agent),{repoPath:n.repoPath,prompt:f,timeoutSeconds:o.timeoutSeconds,bin:ze(n.cfg,o.agent),configDir:n.claudeConfigDir,mode:"read_only",model:o.model||void 0,sessionId:u,onLog:(T,x)=>e(T,x),onUsage:r},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 Xr(n,T),t(p.timedOut?"timed_out":"failed",{error:T,...p.cancelled?{errorKind:"guard"}:{},...v});return}let b=$s(p.resultText);if(b){await Mi({kind:"plan",runId:n.runId,issueKey:n.issueKey,repoPath:n.repoPath,sessionId:u,doneLabel:i.doneLabel,failedLabel:i.failedLabel,timeoutSeconds:o.timeoutSeconds,jira:n.jira,nextLogSeq:s(),rounds:1,claudeConfigDir:n.claudeConfigDir,agent:o.agent,model:o.model},b,e,t,v);return}await Nc({runId:n.runId,issueKey:n.issueKey,doneLabel:i.doneLabel,jira:n.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 Xr(n,f),t("failed",{error:f})}finally{Yt(n.repoPath)}}async function Oc(n,e,t,r){let{emit:s,setStatus:i,sendUsage:o,nextSeq:a}=or(n.runId,r.transport,n.nextLogSeq);try{i("running"),s("info",`Reply received on ${n.issueKey} - continuing run \`${n.runId}\``);let u=Hc(e)+await jr(r.jiraFor(n.repoName??""),t,n.repoPath,s),c=await Qr(n.runId,qe(n.agent),{repoPath:n.repoPath,prompt:u,timeoutSeconds:n.timeoutSeconds,bin:ze(r.cfg,n.agent??""),configDir:n.claudeConfigDir,mode:"read_only",model:n.model||void 0,sessionId:n.sessionId,resume:!0,onLog:(v,b)=>s(v,b),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 kt(r.jiraFor(n.repoName??""),n.issueKey,n.runId,n.failedLabel,v),_t(n.runId),i(c.timedOut?"timed_out":"failed",{error:v,...c.cancelled?{errorKind:"guard"}:{},...f});return}let p=$s(c.resultText);if(p){if(n.rounds>=Pc){await Gc(r.jiraFor(n.repoName??""),n,s,i,f);return}await Mi({kind:"plan",runId:n.runId,issueKey:n.issueKey,repoPath:n.repoPath,sessionId:n.sessionId,doneLabel:n.doneLabel,failedLabel:n.failedLabel,timeoutSeconds:n.timeoutSeconds,jira:r.jiraFor(n.repoName??""),nextLogSeq:a(),rounds:n.rounds+1,createdAt:n.createdAt,claudeConfigDir:n.claudeConfigDir,actorEmail:n.actorEmail,agent:n.agent,model:n.model},p,s,i,f);return}await Nc({runId:n.runId,issueKey:n.issueKey,doneLabel:n.doneLabel,jira:r.jiraFor(n.repoName??""),resultText:c.resultText,costFields:f,emit:s,setStatus:i}),_t(n.runId)}catch(u){let c=u instanceof Error?u.message:String(u);s("error",`Run failed: ${c}`),await kt(r.jiraFor(n.repoName??""),n.issueKey,n.runId,n.failedLabel,c),_t(n.runId),i("failed",{error:c})}finally{Yt(n.repoPath)}}async function Nc(n){let{runId:e,issueKey:t,doneLabel:r,jira:s,resultText:i,costFields:o,emit:a,setStatus:u}=n;u("posting",o),a("info",`Posting plan to ${t} (${i.length} chars)`);let c=`
|
|
587
587
|
|
|
588
588
|
---
|
|
589
589
|
_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:[r],remove:[Be.NEEDS_INPUT_LABEL]}),a("info",`Labeled ${t} with "${r}"`),u("succeeded",{...o,resultSummary:ar(i)}),a("info",`Run succeeded \xB7 $${o.costUsd.toFixed(4)}`)}async function Vg(n){let{emit:e,setStatus:t,sendUsage:r}=or(n.runId,n.transport),s=n.rule.action;if(s.type!=="respond")return;let i=un(s.agent,s.type);if(i){e("error",i),await n.jira.addComment(n.issueKey,`**Allwright could not answer this question.**
|
|
@@ -594,10 +594,10 @@ Error: ${f.slice(0,800)}
|
|
|
594
594
|
|
|
595
595
|
Ask again in a new comment to retry. (run \`${n.runId}\`)`).catch(p=>y.error(`could not post answer failure to ${n.issueKey}: ${p}`)),t(u.timedOut?"timed_out":"failed",{error:f,...u.cancelled?{errorKind:"guard"}:{},...c});return}t("posting",c),e("info",`Posting answer to ${n.issueKey} (${u.resultText.length} chars)`),await n.jira.addComment(n.issueKey,u.resultText),t("succeeded",{...c,resultSummary:ar(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{Yt(n.repoPath)}}async function Mc(n,e,t,r){let s=`${e}-wip`;try{return Yt(n),await Yn(n,`WIP: turn limit exhausted (Allwright run ${t})`),await qo(n,s),r("info",`Partial work preserved on branch "${s}"`),s}catch(i){return r("warn",`could not preserve partial work: ${i instanceof Error?i.message:i}`),null}}function zc(n){return`
|
|
596
596
|
|
|
597
|
-
Partial work from this run is saved on branch \`${n}\` - 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 Wg(n){let{emit:e,setStatus:t,sendUsage:r,nextSeq:s}=or(n.runId,n.transport),{trigger:i}=n.rule,o=n.rule.action;if(o.type!=="implement")return;let a=un(o.agent,o.type);if(a){e("error",a),await Xr(n,a),t("failed",{error:a});return}let u=ji.default.join(Mt(),n.runId),c=Dt(o.branchTemplate,{issueKey:n.issueKey}),f=(0,Oi.randomUUID)(),p=!1,
|
|
597
|
+
Partial work from this run is saved on branch \`${n}\` - 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 Wg(n){let{emit:e,setStatus:t,sendUsage:r,nextSeq:s}=or(n.runId,n.transport),{trigger:i}=n.rule,o=n.rule.action;if(o.type!=="implement")return;let a=un(o.agent,o.type);if(a){e("error",a),await Xr(n,a),t("failed",{error:a});return}let u=ji.default.join(Mt(),n.runId),c=Dt(o.branchTemplate,{issueKey:n.issueKey}),f=(0,Oi.randomUUID)(),p=!1,v=!1;try{if(!ki(ye()??n.cfg,n.project.repoName,n.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&&!n.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 ${n.issueKey} (rule "${n.rule.name}", implement)`),o.jiraTransitionOnStart)try{await n.jira.transitionByName(n.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(M){e("warn",`Jira start transition failed: ${M instanceof Error?M.message:M} - continuing anyway`)}let b=await Qn(n.repoPath);if(e("info",`Repo origin: ${b}`),!it(b))throw new Error(`origin "${b}" is not a GitHub remote - implement mode supports GitHub only`);e("info",`Fetching ${n.issueKey} from Jira`);let T=await n.jira.getIssue(n.issueKey),x=n.continueBranch?c:o.baseBranch;e("info",n.continueBranch?`Continuing branch "${c}" from origin/${c} (autopilot batch)`:`Preparing worktree on branch "${c}" from origin/${o.baseBranch}`),await on(n.repoPath,x),await Bo(n.repoPath,c),await Ko(n.repoPath,u,c,x),p=!0;let P=Dt(o.promptTemplate,{issueKey:T.key,summary:T.summary,description:T.description||"(no description)",comments:As(T.comments)})+await jr(n.jira,T.attachments,u,e)+Ra(u)+Kg(n.repoPath)+Ug+qg+(n.project.goLiveIssueKey?Fg:"")+(o.writeTests?$c.WRITE_TESTS_PROMPT:"")+(o.updateMemory?Be.MEMORY_UPDATE_PROMPT:"");e("info",`Starting Claude Code in the worktree - edit tools enabled, path-jailed, no shell, timeout ${o.timeoutSeconds}s`);let I=await Qr(n.runId,qe(o.agent),{repoPath:u,prompt:P,timeoutSeconds:o.timeoutSeconds,bin:ze(n.cfg,o.agent),configDir:n.claudeConfigDir,mode:"edit_no_shell",model:o.model||void 0,maxTurns:o.maxTurns,sessionId:f,onLog:(M,D)=>e(M,D),onUsage:r},e,()=>vi(u)),w={costUsd:I.costUsd,inputTokens:I.inputTokens,outputTokens:I.outputTokens,billingMode:I.billingMode,model:I.model};if(!I.ok){let M=I.error??"Claude Code failed";e("error",`Run failed: ${M}`);let D=M;if(I.turnLimitHit){let W=await Mc(u,c,n.runId,e);W&&(D+=zc(W))}ot(n.repoPath,{issueKey:n.issueKey,runId:n.runId,title:"implement failed",detail:M.slice(0,500)}),await Xr(n,D),t(I.timedOut?"timed_out":"failed",{error:M,...I.cancelled?{errorKind:"guard"}:{},...w});return}let B=$s(I.resultText);if(B){v=!0,await Mi({kind:"implement",runId:n.runId,issueKey:n.issueKey,repoPath:u,sessionId:f,doneLabel:i.doneLabel,failedLabel:i.failedLabel,timeoutSeconds:o.timeoutSeconds,jira:n.jira,nextLogSeq:s(),rounds:1,claudeConfigDir:n.claudeConfigDir,agent:o.agent,model:o.model,actorEmail:n.actorEmail,baseRepoPath:n.repoPath,repoName:n.project.repoName,branch:c,baseBranch:o.baseBranch,jiraTransition:o.jiraTransition,jiraTransitionOnMerge:o.jiraTransitionOnMerge,requireApproval:o.requireApproval,mergeOnApprove:o.mergeOnApprove,mergeMethod:o.mergeMethod,autoMerge:o.autoMerge,runTests:o.runTests,maxTurns:o.maxTurns,issueSummary:T.summary},B,e,t,w);return}Yt(u),await Lc({runId:n.runId,issueKey:n.issueKey,issueSummary:T.summary,worktreePath:u,agentConfigDir:n.claudeConfigDir,baseRepoPath:n.repoPath,branch:c,baseBranch:o.baseBranch,jiraTransition:o.jiraTransition,jiraTransitionOnMerge:o.jiraTransitionOnMerge,requireApproval:o.requireApproval,doneLabel:i.doneLabel,failedLabel:i.failedLabel,repoName:n.project.repoName,jira:n.jira,cfg:n.cfg,actorEmail:n.actorEmail,resultText:I.resultText,costFields:w,runTests:o.runTests,fixSession:{sessionId:f,agent:o.agent,model:o.model,timeoutSeconds:o.timeoutSeconds,maxTurns:o.maxTurns},sendUsage:r,mergeOnApprove:o.mergeOnApprove,mergeMethod:o.mergeMethod,autoMerge:o.autoMerge,emit:e,setStatus:t})}catch(b){let T=b instanceof Error?b.message:String(b);e("error",`Run failed: ${T}`),ot(n.repoPath,{issueKey:n.issueKey,runId:n.runId,title:"implement failed",detail:T.slice(0,500)}),await Xr(n,T),t("failed",{error:T})}finally{p&&!v&&await yt(n.repoPath,u).catch(()=>{})}}async function Dc(n,e,t,r){let{emit:s,setStatus:i,sendUsage:o,nextSeq:a}=or(n.runId,r.transport,n.nextLogSeq),u=n.repoPath,c=!1;try{if(!ki(ye()??r.cfg,n.repoName??"",n.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 ${n.issueKey} - continuing run \`${n.runId}\``);let f=Hc(e)+await jr(r.jiraFor(n.repoName??""),t,u,s),p=await Qr(n.runId,qe(n.agent),{repoPath:u,prompt:f,timeoutSeconds:n.timeoutSeconds,bin:ze(r.cfg,n.agent??""),configDir:n.claudeConfigDir,mode:"edit_no_shell",model:n.model||void 0,maxTurns:n.maxTurns??120,sessionId:n.sessionId,resume:!0,onLog:(T,x)=>s(T,x),onUsage:o},s,()=>vi(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&&n.branch){let P=await Mc(u,n.branch,n.runId,s);P&&(x+=zc(P))}await kt(r.jiraFor(n.repoName??""),n.issueKey,n.runId,n.failedLabel,x),_t(n.runId),i(p.timedOut?"timed_out":"failed",{error:T,...p.cancelled?{errorKind:"guard"}:{},...v});return}let b=$s(p.resultText);if(b){if(n.rounds>=Pc){await Gc(r.jiraFor(n.repoName??""),n,s,i,v);return}c=!0,await Mi({kind:"implement",runId:n.runId,issueKey:n.issueKey,repoPath:u,sessionId:n.sessionId,doneLabel:n.doneLabel,failedLabel:n.failedLabel,timeoutSeconds:n.timeoutSeconds,jira:r.jiraFor(n.repoName??""),nextLogSeq:a(),rounds:n.rounds+1,createdAt:n.createdAt,claudeConfigDir:n.claudeConfigDir,actorEmail:n.actorEmail,agent:n.agent,model:n.model,baseRepoPath:n.baseRepoPath,repoName:n.repoName,branch:n.branch,baseBranch:n.baseBranch,jiraTransition:n.jiraTransition,jiraTransitionOnMerge:n.jiraTransitionOnMerge,requireApproval:n.requireApproval,mergeOnApprove:n.mergeOnApprove,mergeMethod:n.mergeMethod,autoMerge:n.autoMerge,runTests:n.runTests,maxTurns:n.maxTurns,issueSummary:n.issueSummary},b,s,i,v);return}Yt(u),await Lc({runId:n.runId,issueKey:n.issueKey,issueSummary:n.issueSummary,worktreePath:u,agentConfigDir:n.claudeConfigDir,baseRepoPath:n.baseRepoPath??u,branch:n.branch,baseBranch:n.baseBranch,jiraTransition:n.jiraTransition,requireApproval:n.requireApproval??!0,doneLabel:n.doneLabel,failedLabel:n.failedLabel,repoName:n.repoName,jira:r.jiraFor(n.repoName??""),cfg:r.cfg,actorEmail:n.actorEmail,resultText:p.resultText,costFields:v,runTests:n.runTests,fixSession:{sessionId:n.sessionId,agent:n.agent??"",model:n.model,timeoutSeconds:n.timeoutSeconds,maxTurns:n.maxTurns},sendUsage:o,mergeOnApprove:n.mergeOnApprove,mergeMethod:n.mergeMethod,autoMerge:n.autoMerge??!1,emit:s,setStatus:i}),_t(n.runId)}catch(f){let p=f instanceof Error?f.message:String(f);s("error",`Run failed: ${p}`),await kt(r.jiraFor(n.repoName??""),n.issueKey,n.runId,n.failedLabel,p),_t(n.runId),i("failed",{error:p})}finally{c||await yt(n.baseRepoPath??u,u).catch(()=>{})}}async function Lc(n){let{runId:e,issueKey:t,issueSummary:r,worktreePath:s,baseRepoPath:i,branch:o,baseBranch:a,jiraTransition:u,jiraTransitionOnMerge:c,requireApproval:f,doneLabel:p,failedLabel:v,repoName:b,jira:T,cfg:x,actorEmail:P,runTests:I,mergeOnApprove:w,mergeMethod:B,autoMerge:M,resultText:D,costFields:W,emit:d,setStatus:m}=n,g=await Fr(s);g.deleted.length&&d("info",`Deleted ${g.deleted.length} file(s) listed in ${Nt}: `+g.deleted.slice(0,10).join(", ")+(g.deleted.length>10?", \u2026":""));for(let le of g.refused)d("warn",`${Nt} entry refused: ${le}`);d("info","Committing changes"),await Yn(s,`${t}: ${r}
|
|
598
598
|
|
|
599
|
-
Allwright run ${e}`);let C=await an(s,a);if(!C.ok){let le=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 ${rn}/${sn})`;d("error",le),await kt(T,t,e,
|
|
600
|
-
${ue.tail.slice(-1500)}`));let Sr="";if(De.length&&n.fixSession){let ue=await Yg({runId:e,issueKey:t,worktreePath:s,baseBranch:a,fixSession:n.fixSession,agentConfigDir:n.agentConfigDir,cfg:x,failed:De,emit:d,sendUsage:n.sendUsage,baseCost:N});if(N.costUsd+=ue.cost.costUsd,N.inputTokens+=ue.cost.inputTokens,N.outputTokens+=ue.cost.outputTokens,ue.outcome==="cancelled"){let Ze="stopped by a person during the automatic test-fix attempt - nothing was pushed";d("warn",Ze),Ri({runId:e,issueKey:t,issueSummary:r,mergeOnApprove:w,mergeMethod:B,autoMerge:M,repoName:
|
|
599
|
+
Allwright run ${e}`);let C=await an(s,a);if(!C.ok){let le=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 ${rn}/${sn})`;d("error",le),await kt(T,t,e,v,le),m("failed",{error:le,errorKind:"guard",...W});return}d("info",`Diff: ${C.files} file(s), +${C.insertions}/-${C.deletions}`);let N={...W},G="",V="",ee,z,L;if(I){let le=Hr(s);if(!le)d("info","No TEST.md in this repo - skipping the test run (nothing documented to run)");else{let ve=Gr(Ia.default.readFileSync(le,"utf8"));if(!ve.length)d("info",`${ji.default.basename(le)} lists no commands - nothing to run`);else{d("info",`Running ${ve.length} documented test command(s) - no tokens, plain shell`);let Ee=await nr(s,ve,{perCommandTimeoutMs:15*6e4}),De=Ee.filter(ue=>ue.exitCode!==0),lo=De.length;for(let ue of Ee)d(ue.exitCode===0?"info":"warn",`${ue.exitCode===0?"PASS":"FAIL"} ${ue.command} (exit ${ue.exitCode})`+(ue.exitCode===0?"":`
|
|
600
|
+
${ue.tail.slice(-1500)}`));let Sr="";if(De.length&&n.fixSession){let ue=await Yg({runId:e,issueKey:t,worktreePath:s,baseBranch:a,fixSession:n.fixSession,agentConfigDir:n.agentConfigDir,cfg:x,failed:De,emit:d,sendUsage:n.sendUsage,baseCost:N});if(N.costUsd+=ue.cost.costUsd,N.inputTokens+=ue.cost.inputTokens,N.outputTokens+=ue.cost.outputTokens,ue.outcome==="cancelled"){let Ze="stopped by a person during the automatic test-fix attempt - nothing was pushed";d("warn",Ze),Ri({runId:e,issueKey:t,issueSummary:r,mergeOnApprove:w,mergeMethod:B,autoMerge:M,repoName:b,baseRepoPath:i,branch:o,baseBranch:a,headSha:await Qe(s),requireApproval:f,doneLabel:p,failedLabel:v,jiraTransition:u,jiraTransitionOnMerge:c,actorEmail:P,resultSummary:Ac(D),prSummary:xa(D)??"",costUsd:N.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),await kt(T,t,e,v,`${Ze}. The commit survived on the runner - "Retry push" on the run's dashboard page ships it without a new agent run.`),m("failed",{error:Ze,errorKind:"guard",retryAvailable:!0,...N});return}if(ue.outcome==="committed"){V=ue.resultText,d("info",`Re-running ${ve.length} documented test command(s) after the fix`),Ee=await nr(s,ve,{perCommandTimeoutMs:15*6e4}),De=Ee.filter(Ze=>Ze.exitCode!==0);for(let Ze of Ee)d(Ze.exitCode===0?"info":"warn",`${Ze.exitCode===0?"PASS":"FAIL"} ${Ze.command} (exit ${Ze.exitCode})`+(Ze.exitCode===0?"":`
|
|
601
601
|
${Ze.tail.slice(-1500)}`));Sr=De.length?`One automatic same-session fix attempt ran; the results above are AFTER it. First pass: ${lo} failure(s). ${ue.note}`:`The first pass had ${lo} failure(s); one automatic same-session fix attempt resolved them. ${ue.note}`}else Sr=ue.note}ee=De.slice(0,20).map(ue=>({command:ue.command.slice(0,500),exitCode:ue.exitCode,tail:ue.tail.slice(-4e3)})),z=Ee.length-De.length,L=Ee.length,G=`
|
|
602
602
|
|
|
603
603
|
### Tests
|
|
@@ -610,11 +610,11 @@ All ${Ee.length} passed.`)+(Sr?`
|
|
|
610
610
|
|
|
611
611
|
${Sr}`:""),De.length&&d("warn",`${De.length} test command(s) failed - the PR will say so; review before merging`),lo>0&&ot(i,{issueKey:t,runId:e,title:De.length?`TEST.md commands failing at PR (${De.length} of ${Ee.length})`:"TEST.md failures fixed by same-session retry",detail:Ee.map(ue=>`${ue.exitCode===0?"PASS":"FAIL"} ${ue.command}`).join(`
|
|
612
612
|
`)+(Sr?`
|
|
613
|
-
${Sr}`:"")})}}}let oe=await Qn(s),fe=it(oe);if(!fe){let le=`origin "${oe}" is not a GitHub remote - implement mode supports GitHub only`;d("error",le),await kt(T,t,e,
|
|
613
|
+
${Sr}`:"")})}}}let oe=await Qn(s),fe=it(oe);if(!fe){let le=`origin "${oe}" is not a GitHub remote - implement mode supports GitHub only`;d("error",le),await kt(T,t,e,v,le),m("failed",{error:le,...W});return}let de=await Qe(s),ae=Ac(D),pn=(V?xa(V):null)??xa(D);try{await Uc({gitDir:s,ownerRepo:fe,runId:e,issueKey:t,issueSummary:r,agentConfigDir:n.agentConfigDir,branch:o,baseBranch:a,jiraTransition:u,jiraTransitionOnMerge:c,requireApproval:f,doneLabel:p,failedLabel:v,repoName:b,jira:T,cfg:x,actorEmail:P,mergeOnApprove:w,mergeMethod:B,autoMerge:M,summary:ae,prSummary:pn??void 0,cost:N,testReport:G,failedTests:ee,testsPassed:z,testsTotal:L,goLiveDraft:(V?Ic(V):null)??Ic(D)??void 0,emit:d,setStatus:m})}catch(le){let ve=le instanceof Error?le.message:String(le);Ri({runId:e,issueKey:t,issueSummary:r,mergeOnApprove:w,mergeMethod:B,autoMerge:M,repoName:b,baseRepoPath:i,branch:o,baseBranch:a,headSha:de,requireApproval:f,doneLabel:p,failedLabel:v,jiraTransition:u,jiraTransitionOnMerge:c,actorEmail:P,resultSummary:ae,prSummary:pn??"",costUsd:N.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),d("error",`Run failed: ${ve}`),d("info",`The commit itself survived on the runner (branch ${o}) - fix the cause, then use "Retry push" on this run's dashboard page.`),await kt(T,t,e,v,`${ve}
|
|
614
614
|
|
|
615
|
-
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:
|
|
615
|
+
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:ve,retryAvailable:!0,...N})}}var Jg={costUsd:0,inputTokens:0,outputTokens:0};async function Yg(n){let{runId:e,issueKey:t,worktreePath:r,baseBranch:s,fixSession:i,cfg:o,failed:a,emit:u,sendUsage:c,baseCost:f}=n,p=qe(i.agent);if(!p?.capabilities.sessionResume){let I=`No automatic fix attempt: the ${i.agent||"configured"} adapter cannot resume sessions.`;return u("info",I),{outcome:"skipped",note:I,cost:Jg}}u("info",`${a.length} test command(s) failed - resuming the same agent session for one fix attempt (same session = cached context, not a re-explore)`);let v=await Qe(r),b=await Qr(e,p,{repoPath:r,prompt:Bg(a),timeoutSeconds:i.timeoutSeconds,bin:ze(o,i.agent),configDir:n.agentConfigDir,mode:"edit_no_shell",model:i.model||void 0,maxTurns:Math.min(i.maxTurns??120,60),sessionId:i.sessionId,resume:!0,onLog:(I,w)=>u(I,w),onUsage:c?I=>c({...I,inputTokens:f.inputTokens+I.inputTokens,outputTokens:f.outputTokens+I.outputTokens,costUsd:I.costUsd===void 0?void 0:f.costUsd+I.costUsd}):void 0},u),T={costUsd:b.costUsd,inputTokens:b.inputTokens,outputTokens:b.outputTokens};if(b.cancelled)return{outcome:"cancelled",cost:T};if(!b.ok){let I=`One automatic fix attempt did not complete (${b.error??"agent error"}) - the results above are from the original work.`;return u("warn",I),{outcome:"agent_failed",note:I,cost:T}}if($s(b.resultText)){let I="One automatic fix attempt asked for human input instead of fixing - the original commit ships unchanged; answer on the PR instead.";return u("warn",I),{outcome:"agent_failed",note:I,cost:T}}let x=await Fr(r);for(let I of x.refused)u("warn",`${Nt} entry refused: ${I}`);try{await Yn(r,`${t}: fix failing TEST.md commands
|
|
616
616
|
|
|
617
|
-
Allwright run ${e} (automatic test-fix attempt)`)}catch{let I=`An automatic fix attempt concluded no code change was warranted: ${ar(
|
|
617
|
+
Allwright run ${e} (automatic test-fix attempt)`)}catch{let I=`An automatic fix attempt concluded no code change was warranted: ${ar(b.resultText)}`;return u("info",I),{outcome:"no_changes",note:I,cost:T}}let P=await an(r,s);if(!P.ok){await Br(r,v);let I=P.forbidden.length?`An automatic fix attempt touched protected paths (${P.forbidden.slice(0,3).join(", ")}) and was discarded - the results above are from the original work.`:"An automatic fix attempt pushed the diff past the safety limits and was discarded - the results above are from the original work.";return u("warn",I),{outcome:"reverted",note:I,cost:T}}return{outcome:"committed",note:`Fix attempt: ${ar(b.resultText)}`,resultText:b.resultText,cost:T}}async function Uc(n){let{gitDir:e,ownerRepo:t,runId:r,issueKey:s,issueSummary:i,mergeOnApprove:o,mergeMethod:a,autoMerge:u,branch:c,baseBranch:f,jiraTransition:p,jiraTransitionOnMerge:v,requireApproval:b,doneLabel:T,failedLabel:x,repoName:P,jira:I,cfg:w,actorEmail:B,summary:M,prSummary:D,cost:W,testReport:d,emit:m,setStatus:g}=n;m("info",`Pushing ${c} to origin`),await Xn(e,c);let C=await bi(e,c),G=`${D?.trim()?`${D.trim()}
|
|
618
618
|
|
|
619
619
|
<details>
|
|
620
620
|
<summary>Technical details</summary>
|
|
@@ -625,23 +625,27 @@ ${M}
|
|
|
625
625
|
|
|
626
626
|
---
|
|
627
627
|
Jira: ${new URL(`/browse/${s}`,w.jira?.baseUrl??"").toString()}
|
|
628
|
-
_Allwright implement run \`${r}\` \xB7 cost $${W.costUsd.toFixed(4)}. `+(d?"Tests were run by the runner, not the agent._":"The agent has no shell and no tests were run here - review accordingly._");m("info","Opening pull request");let V=ki(ye()??w,P,B);V.source==="user"&&m("info",`PR will be authored with ${B}'s own GitHub token`);let z=await new Re(V.token).createPullRequest(t.owner,t.repo,{title:`${s}: ${i}`.slice(0,250),head:c,base:f,body:G});m("info",`PR ready: ${z.url}`),Sc({runId:r,issueKey:s,repoName:P,owner:t.owner,repo:t.repo,prNumber:z.number,prUrl:z.url,jiraTransitionOnMerge:
|
|
628
|
+
_Allwright implement run \`${r}\` \xB7 cost $${W.costUsd.toFixed(4)}. `+(d?"Tests were run by the runner, not the agent._":"The agent has no shell and no tests were run here - review accordingly._");m("info","Opening pull request");let V=ki(ye()??w,P,B);V.source==="user"&&m("info",`PR will be authored with ${B}'s own GitHub token`);let z=await new Re(V.token).createPullRequest(t.owner,t.repo,{title:`${s}: ${i}`.slice(0,250),head:c,base:f,body:G});m("info",`PR ready: ${z.url}`),Sc({runId:r,issueKey:s,repoName:P,owner:t.owner,repo:t.repo,prNumber:z.number,prUrl:z.url,jiraTransitionOnMerge:v??"",createdAt:new Date().toISOString()}),g("posting",W);let L={nextDecisionSeq:1e5,runId:r,issueKey:s,repoName:P,owner:t.owner,repo:t.repo,prNumber:z.number,prUrl:z.url,branch:c,headSha:C,doneLabel:T,failedLabel:x,jiraTransition:p,mergeOnApprove:o,mergeMethod:a,autoMerge:u,agentConfigDir:n.agentConfigDir};if(b)lt(L),await I.addComment(s,`**Allwright opened a pull request for review.**
|
|
629
629
|
|
|
630
630
|
PR: ${z.url}
|
|
631
631
|
|
|
632
632
|
Approve the PR on GitHub OR on the Allwright dashboard - either completes the run. Rejecting on the dashboard closes the PR and deletes the branch. (run \`${r}\`)`),g("awaiting_approval",{...W,prUrl:z.url,headSha:C,resultSummary:ar(D?.trim()||M),retryAvailable:!1,...n.failedTests!==void 0?{failedTests:n.failedTests}:{},...n.testsPassed!==void 0?{testsPassed:n.testsPassed}:{},...n.testsTotal!==void 0?{testsTotal:n.testsTotal}:{},...n.goLiveDraft!==void 0?{goLiveDraft:n.goLiveDraft}:{}}),m("info",`Awaiting approval on the dashboard \xB7 $${W.costUsd.toFixed(4)}`);else{if(u){m("info",`Auto-merging PR #${z.number} (${a})`);let fe=Ie(w,P),de=fe?await new Re(fe).mergePullRequest(t.owner,t.repo,z.number,a,{sha:C,title:`${s} (#${z.number})`}):{merged:!1,reason:"no GitHub token applies to this repo"};de.merged?m("info",`PR #${z.number} merged`):(m("warn",`Auto-merge did not go through - ${de.reason}. The PR stays open.`),await I.addComment(s,`**Allwright:** the work is done and the PR is open, but auto-merge did not go through - ${de.reason}
|
|
633
633
|
|
|
634
|
-
PR: ${z.url}`))}let oe=(ye()??w).repos[P]?.path;oe&&xs(oe,s)&&ot(oe,{issueKey:s,runId:r,title:"shipped after earlier failure",detail:`PR ${z.url} merged/opened straight-through.`}),await qc({jira:I,issueKey:s},L,m),g("succeeded",{...W,prUrl:z.url,headSha:C,resultSummary:ar(D?.trim()||M),retryAvailable:!1,...n.failedTests!==void 0?{failedTests:n.failedTests}:{},...n.testsPassed!==void 0?{testsPassed:n.testsPassed}:{},...n.testsTotal!==void 0?{testsTotal:n.testsTotal}:{},...n.goLiveDraft!==void 0?{goLiveDraft:n.goLiveDraft}:{}}),m("info",`Run succeeded \xB7 ${z.url} \xB7 $${W.costUsd.toFixed(4)}`)}}async function qc(n,e,t){let r=null;if(e.jiraTransition)try{await n.jira.transitionByName(e.issueKey,e.jiraTransition)?t("info",`Jira transition "${e.jiraTransition}" applied`):(r=`no transition named "${e.jiraTransition}" is available from this ticket's current status - the PR is fine, but move the ticket manually`,t("warn",r))}catch(
|
|
634
|
+
PR: ${z.url}`))}let oe=(ye()??w).repos[P]?.path;oe&&xs(oe,s)&&ot(oe,{issueKey:s,runId:r,title:"shipped after earlier failure",detail:`PR ${z.url} merged/opened straight-through.`}),await qc({jira:I,issueKey:s},L,m),g("succeeded",{...W,prUrl:z.url,headSha:C,resultSummary:ar(D?.trim()||M),retryAvailable:!1,...n.failedTests!==void 0?{failedTests:n.failedTests}:{},...n.testsPassed!==void 0?{testsPassed:n.testsPassed}:{},...n.testsTotal!==void 0?{testsTotal:n.testsTotal}:{},...n.goLiveDraft!==void 0?{goLiveDraft:n.goLiveDraft}:{}}),m("info",`Run succeeded \xB7 ${z.url} \xB7 $${W.costUsd.toFixed(4)}`)}}async function qc(n,e,t){let r=null;if(e.jiraTransition)try{await n.jira.transitionByName(e.issueKey,e.jiraTransition)?t("info",`Jira transition "${e.jiraTransition}" applied`):(r=`no transition named "${e.jiraTransition}" is available from this ticket's current status - the PR is fine, but move the ticket manually`,t("warn",r))}catch(i){r=`Jira transition failed: ${i instanceof Error?i.message:i}`,t("warn",r)}let s=e.mergeOnApprove;return await n.jira.addComment(e.issueKey,(s?`**Allwright: implementation complete - the pull request was merged.**
|
|
635
635
|
|
|
636
|
-
PR: ${e.prUrl}
|
|
636
|
+
PR: ${e.prUrl}`:`**Allwright: the change is approved, but NOT merged yet.**
|
|
637
|
+
|
|
638
|
+
PR: ${e.prUrl}
|
|
639
|
+
|
|
640
|
+
This rule is set to "my team merges on GitHub", so Allwright deliberately did not merge. Nothing ships until someone merges that pull request. To have Allwright merge on approval instead, turn on "Merge the PR when I approve" in the rule.`)+(r?`
|
|
637
641
|
|
|
638
642
|
Note: ${r}`:"")+`
|
|
639
643
|
|
|
640
644
|
(run \`${e.runId}\`)`),await n.jira.editLabels(e.issueKey,{add:[e.doneLabel],remove:[Be.NEEDS_INPUT_LABEL]}),r}async function Es(n,e,t){let r=Jr(e);if(!r){y.warn(`run.approved for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:s,setStatus:i}=Kc(n,e);try{let o=Ie(ye()??n.cfg,r.repoName);if(!o)throw new Error("GitHub token missing on this runner");let a=new Re(o);s("info",`Approval received for ${r.issueKey} - verifying PR state`);let u=await a.getPullRequest(r.owner,r.repo,r.prNumber);if(!u)throw new Error(`PR #${r.prNumber} no longer exists on GitHub`);if(u.state==="closed"&&!u.merged)throw new Error(`PR #${r.prNumber} was closed on GitHub without merging`);let c=t??r.headSha;if(u.state==="open"&&u.headSha!==c){let f=`PR #${r.prNumber} changed since review started (${c.slice(0,7)} \u2192 ${u.headSha.slice(0,7)}) - approval not applied. Re-review the PR and approve again.`;s("warn",f),await n.jiraFor(r.repoName??"").addComment(r.issueKey,`**Allwright:** ${f}`),i("awaiting_approval",{prUrl:r.prUrl,headSha:u.headSha,resultSummary:f});return}if(r.mergeOnApprove&&u.state==="open"&&!u.merged){s("info",`Merging PR #${r.prNumber} (${r.mergeMethod})`);let f=await a.mergePullRequest(r.owner,r.repo,r.prNumber,r.mergeMethod,{sha:c,title:`${r.issueKey} (#${r.prNumber})`});if(!f.merged){let p=`Approved, but the merge did not go through - ${f.reason}`;s("warn",p),await n.jiraFor(r.repoName??"").addComment(r.issueKey,`**Allwright:** ${p}
|
|
641
645
|
|
|
642
|
-
PR: ${r.prUrl}`),i("awaiting_approval",{prUrl:r.prUrl,headSha:u.headSha,resultSummary:p});return}s("info",`PR #${r.prNumber} merged`)}{let f=(ye()??n.cfg).repos[r.repoName??""]?.path;f&&xs(f,r.issueKey)&&ot(f,{issueKey:r.issueKey,runId:e,title:"shipped after earlier failure",detail:`PR ${r.prUrl} approved and completed.`})}await qc({jira:n.jiraFor(r.repoName??""),issueKey:r.issueKey},r,s),i("succeeded",{prUrl:r.prUrl}),s("info","Run completed after approval"),ir(e)}catch(o){let a=o instanceof Error?o.message:String(o);s("error",`Approval handling failed: ${a}`),await Zc(n,r,a),i("failed",{error:a}),ir(e)}}async function Fc(n,e){let t=Jr(e);if(!t){y.warn(`run.rejected for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:r,setStatus:s}=Kc(n,e);try{let i=Ie(ye()??n.cfg,t.repoName);if(!i)throw new Error("GitHub token missing on this runner");let o=new Re(i);r("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 n.jiraFor(t.repoName??"").addComment(t.issueKey,`**Allwright: changes rejected.**
|
|
646
|
+
PR: ${r.prUrl}`),i("awaiting_approval",{prUrl:r.prUrl,headSha:u.headSha,resultSummary:p});return}s("info",`PR #${r.prNumber} merged`)}{let f=(ye()??n.cfg).repos[r.repoName??""]?.path;f&&xs(f,r.issueKey)&&ot(f,{issueKey:r.issueKey,runId:e,title:"shipped after earlier failure",detail:`PR ${r.prUrl} approved and completed.`})}await qc({jira:n.jiraFor(r.repoName??""),issueKey:r.issueKey},r,s),i("succeeded",{prUrl:r.prUrl,...r.mergeOnApprove?{}:{resultSummary:"Approved, but the PR was NOT merged - this rule leaves merging to your team on GitHub. Nothing ships until someone merges it."}}),s("info",r.mergeOnApprove?"Run completed after approval":'Run completed after approval - the PR is still OPEN because this rule does not merge on approval. Merge it on GitHub, or turn on "Merge the PR when I approve" in the rule.'),ir(e)}catch(o){let a=o instanceof Error?o.message:String(o);s("error",`Approval handling failed: ${a}`),await Zc(n,r,a),i("failed",{error:a}),ir(e)}}async function Fc(n,e){let t=Jr(e);if(!t){y.warn(`run.rejected for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:r,setStatus:s}=Kc(n,e);try{let i=Ie(ye()??n.cfg,t.repoName);if(!i)throw new Error("GitHub token missing on this runner");let o=new Re(i);r("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 n.jiraFor(t.repoName??"").addComment(t.issueKey,`**Allwright: changes rejected.**
|
|
643
647
|
|
|
644
|
-
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 n.jiraFor(t.repoName??"").editLabels(t.issueKey,{add:[t.failedLabel]}),s("failed",{error:"rejected by user"}),r("info","PR closed, branch deleted, ticket labeled"),ir(e)}catch(i){let o=i instanceof Error?i.message:String(i);r("error",`Rejection handling failed: ${o}`),await Zc(n,t,o),s("failed",{error:o}),ir(e)}}async function Bc(n,e){let t=Ei(e);if(!t){y.warn(`run.retryPush for ${e}: no retry record (already pushed, or invalidated?)`);let{emit:a,setStatus:u,sendUsage:c}=or(e,n.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:r,setStatus:s,sendUsage:i,nextSeq:o}=or(e,n.transport,t.nextLogSeq);try{let a=await
|
|
648
|
+
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 n.jiraFor(t.repoName??"").editLabels(t.issueKey,{add:[t.failedLabel]}),s("failed",{error:"rejected by user"}),r("info","PR closed, branch deleted, ticket labeled"),ir(e)}catch(i){let o=i instanceof Error?i.message:String(i);r("error",`Rejection handling failed: ${o}`),await Zc(n,t,o),s("failed",{error:o}),ir(e)}}async function Bc(n,e){let t=Ei(e);if(!t){y.warn(`run.retryPush for ${e}: no retry record (already pushed, or invalidated?)`);let{emit:a,setStatus:u,sendUsage:c}=or(e,n.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:r,setStatus:s,sendUsage:i,nextSeq:o}=or(e,n.transport,t.nextLogSeq);try{let a=await bi(t.baseRepoPath,t.branch);if(a!==t.headSha){r("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.`),Sa(e),s("failed",{retryAvailable:!1});return}let u=await Qn(t.baseRepoPath),c=it(u);if(!c)throw new Error(`origin "${u}" is not a GitHub remote`);r("info",`Retry push for ${t.issueKey}: branch ${t.branch} at ${t.headSha.slice(0,7)}`);let f=n.jiraFor(t.repoName);await Uc({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",autoMerge:t.autoMerge??!1,doneLabel:t.doneLabel,failedLabel:t.failedLabel,repoName:t.repoName,jira:f,cfg:ye()??n.cfg,actorEmail:t.actorEmail,summary:t.resultSummary,prSummary:t.prSummary||void 0,cost:{costUsd:t.costUsd},emit:r,setStatus:s}),Sa(e),await f.editLabels(t.issueKey,{remove:[t.failedLabel]}).catch(()=>{})}catch(a){let u=a instanceof Error?a.message:String(a);r("error",`Retry push failed: ${u}`),Ri({...t,nextLogSeq:o()}),s("failed",{error:u,retryAvailable:!0})}}function Kc(n,e){let t=1e5;return{emit:(i,o)=>{n.transport.send({type:"run.log",runId:e,seq:t++,ts:new Date().toISOString(),level:i,message:o}),i!=="agent"&&y.info(`[run ${e}] ${o}`)},setStatus:(i,o={})=>{n.transport.send({type:"run.status",runId:e,status:i,...o})}}}async function Zc(n,e,t){try{await n.jiraFor(e.repoName??"").addComment(e.issueKey,`**Allwright could not complete the approval decision.**
|
|
645
649
|
|
|
646
650
|
Error: ${t.slice(0,800)}
|
|
647
651
|
|
|
@@ -664,7 +668,7 @@ Reply with your answers in a comment on this ticket - this run will pick up righ
|
|
|
664
668
|
Error: ${s.slice(0,800)}
|
|
665
669
|
|
|
666
670
|
This ticket has been labeled \`${r}\` and will not be retried automatically. To retry, fix the cause and remove the \`${r}\` label. (run \`${t}\`)`),await n.editLabels(e,{add:[r],remove:[Be.NEEDS_INPUT_LABEL]})}catch(i){y.error(`could not post failure comment to ${e}: ${i}`)}}function Ac(n){let e=n.split(/\n##\s*(?:PR summary|Go-live draft)\s*\n/i)[0],t=/##\s*Summary of changes\s*\n([\s\S]*)$/i.exec(e);return(t?t[1]:e).trim().slice(0,8e3)||"(no summary provided)"}function xa(n){let e=/##\s*PR summary\s*\n([\s\S]*?)(?=\n##\s|$)/i.exec(n),t=e?e[1].trim():"";return t?t.slice(0,2e3):null}function ar(n){for(let e of n.split(`
|
|
667
|
-
`)){let t=e.replace(/^#+\s*/,"").trim();if(t.length>10)return t.slice(0,200)}return n.slice(0,200)}var ur=E(require("node:fs"),1);var lr=E(require("node:path"),1),cr=require("node:child_process"),Aa=E(require("node:readline"),1),$a=require("node:crypto"),dr=E(Se(),1);var ed=E(Se(),1);
|
|
671
|
+
`)){let t=e.replace(/^#+\s*/,"").trim();if(t.length>10)return t.slice(0,200)}return n.slice(0,200)}var ur=E(require("node:fs"),1);var lr=E(require("node:path"),1),cr=require("node:child_process"),Aa=E(require("node:readline"),1),$a=require("node:crypto"),dr=E(Se(),1);var ed=E(Se(),1);vt();at();er();var Vc=4e3,Xg=4e3;function Wc(n,e){n("warn",`${e.length} step(s) still need YOU - Allwright deliberately did not run these:
|
|
668
672
|
`+e.map(t=>` ${t.command}${t.why?` # ${t.why}`:""}`).join(`
|
|
669
673
|
`))}function Pa(n){let e=0;return{emit:(s,i)=>{n.transport.send({type:"run.log",runId:n.runId,seq:e++,ts:new Date().toISOString(),level:s,message:i.slice(0,Xg)}),s!=="agent"&&y.info(`[deploy ${n.runId}] ${i}`)},setStatus:(s,i={})=>{n.transport.send({type:"run.status",runId:n.runId,status:s,...i})}}}var Qg=/^\s*(?:ALLWRIGHT|TICKETPILOT)[-\s]MANUAL:\s*(.+)$/i;function ey(n){let e=Qg.exec(n);if(!e)return null;let[t,...r]=e[1].split(/\s+#\s+/),s=t.trim();return s?{command:s.slice(0,500),why:r.join(" # ").trim().slice(0,300)}:null}async function zi(n){let{emit:e,setStatus:t}=Pa(n),r=n.environment;try{let s=ty(n);if(s){e("error",s),await ut(n,`**Allwright could not deploy to \`${r.name}\`.**
|
|
670
674
|
|
|
@@ -682,9 +686,9 @@ ${w}
|
|
|
682
686
|
|
|
683
687
|
Allwright run ${n.runId}`);if(!w.ok){e("error",w.reason??"merge failed"),await ut(n,`**Allwright deploy to \`${r.name}\` failed before running anything.**
|
|
684
688
|
|
|
685
|
-
${w.reason}`),t("failed",{error:w.reason});return}w.alreadyMerged?e("info",`"${I}" is already in "${r.branch}" - nothing to merge`):(e("info",`Pushing "${r.branch}" to origin`),await Xo(u,r.branch))}let f=await Qe(u).catch(()=>"");f&&e("info",`Deploying commit ${f.slice(0,10)}`);let p=sy(u,r.workdir),
|
|
689
|
+
${w.reason}`),t("failed",{error:w.reason});return}w.alreadyMerged?e("info",`"${I}" is already in "${r.branch}" - nothing to merge`):(e("info",`Pushing "${r.branch}" to origin`),await Xo(u,r.branch))}let f=await Qe(u).catch(()=>"");f&&e("info",`Deploying commit ${f.slice(0,10)}`);let p=sy(u,r.workdir),v={...process.env,...s,ALLWRIGHT_ENVIRONMENT:r.name,ALLWRIGHT_ISSUE_KEY:n.issueKey,ALLWRIGHT_RUN_ID:n.runId,ALLWRIGHT_DEPLOY_REF:f,ALLWRIGHT_BRANCH:r.branch,TICKETPILOT_ENVIRONMENT:r.name,TICKETPILOT_ISSUE_KEY:n.issueKey,TICKETPILOT_RUN_ID:n.runId,TICKETPILOT_DEPLOY_REF:f,TICKETPILOT_BRANCH:r.branch},b=0,T=r.timeoutSeconds*1e3;for(let[I,w]of r.steps.entries()){let B=T-(Date.now()-o);if(B<=0){let D=`deploy exceeded its ${r.timeoutSeconds}s budget before step ${I+1}`;e("error",D),await ut(n,`**Allwright deploy to \`${r.name}\` timed out.**
|
|
686
690
|
|
|
687
|
-
${D}`),t("timed_out",{error:D,deployedRef:f});return}e("info",`\u25B6 step ${I+1}/${r.steps.length}: ${w.name}`);let M=await iy({command:w.run,cwd:p,env:
|
|
691
|
+
${D}`),t("timed_out",{error:D,deployedRef:f});return}e("info",`\u25B6 step ${I+1}/${r.steps.length}: ${w.name}`);let M=await iy({command:w.run,cwd:p,env:v,timeoutMs:B,onLine:(D,W)=>{b++;let d=ey(W);d&&a.length<20&&a.push(d),b===Vc&&e("warn","(output truncated - deploy log limit reached)"),!(b>=Vc)&&e(D,i(W))}});if(M.timedOut){let D=`step "${w.name}" hit the ${r.timeoutSeconds}s deploy budget and was killed`;e("error",D),await ut(n,`**Allwright deploy to \`${r.name}\` timed out.**
|
|
688
692
|
|
|
689
693
|
${D}`),t("timed_out",{error:D,deployedRef:f});return}if(M.code!==0){if(w.continueOnError){e("warn",`step "${w.name}" exited ${M.code} - continuing (marked continue-on-error)`);continue}let D="";try{D=i(await Fo(u))}catch{}let W=`step ${I+1} "${w.name}" failed with exit code ${M.code}`+(M.tail?`: ${i(M.tail)}`:"")+(D?`
|
|
690
694
|
|
|
@@ -745,37 +749,37 @@ ${n.map(t=>` ${t}`).join(`
|
|
|
745
749
|
${c.run}`).join(`
|
|
746
750
|
`),failedStep:n.failedStep||"(unknown)",errorText:n.errorText||"(no error text recorded)",machineContext:e}),r=await n.agent.adapter.run({repoPath:n.repoPath,prompt:t,timeoutSeconds:240,bin:n.agent.bin,mode:"read_only",maxTurns:40,sessionId:(0,$a.randomUUID)(),onLog:()=>{}});if(!r.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:r.error??"the agent produced no output"};let s=cd(r.resultText),i=r.resultText.split(/```/)[0]?.trim()??"",a=/```(?:markdown|md)\s*\n([\s\S]*?)```/i.exec(r.resultText)?.[1]?.trim()??"",u=a?Di(n.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: "${r.resultText.trim().slice(0,200).replace(/\s+/g," ")}\u2026"`}}async function ud(n){let e=Di(n.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=od(n.cfg,n.repoName,n.environmentName,e.content),r=Dt(dr.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE,{envName:n.environmentName,docPath:e.path,docContent:e.content,notes:n.notes.trim()||"(nothing specified)",machineContext:t}),s=await n.agent.adapter.run({repoPath:n.repoPath,prompt:r,timeoutSeconds:n.timeoutSeconds,bin:n.agent.bin,mode:"read_only",maxTurns:30,sessionId:(0,$a.randomUUID)(),onLog:()=>{}});if(!s.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:s.error??"Claude Code produced no output"};let i=cd(s.resultText);return i?{ok:!0,...i}:(y.warn(`deploy step suggestion could not be parsed. Claude's raw answer follows:
|
|
747
751
|
`+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 cd(n){for(let e of hy(n)){let t;try{t=JSON.parse(e)}catch{continue}let r=ay.safeParse(fy(t));if(r.success&&r.data.steps.length||r.success&&r.data.notes.trim())return r.data}return null}function hy(n){let e=[];for(let s of n.matchAll(/```[a-zA-Z0-9_-]*[ \t]*\r?\n([\s\S]*?)```/g))s[1].trim()&&e.push(s[1]);let t=n.indexOf("{"),r=n.lastIndexOf("}");return t>=0&&r>t&&e.push(n.slice(t,r+1)),e}function fy(n){if(!n||typeof n!="object")return n;let e=n,r=(Array.isArray(n)?n: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:Qc(o,a),run:o.trim()}:null;if(!o||typeof o!="object")return null;let u=o,c=Ea(u.run,u.command,u.cmd,u.script,u.shell);return c?{name:(Ea(u.name,u.title,u.description)??Qc(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:r.slice(0,50),requiredSecrets:i.slice(0,50),notes:Ea(e.notes,e.note,e.explanation)??""}}function Ea(...n){for(let e of n)if(typeof e=="string"&&e.trim())return e.trim()}function Qc(n,e){return(n.split(`
|
|
748
|
-
`)[0].trim()||`Step ${e+1}`).slice(0,120)}
|
|
752
|
+
`)[0].trim()||`Step ${e+1}`).slice(0,120)}vt();at();er();function Li(n,e){if(!n.componentRoutes.length)return{project:n};let t=e.filter(Boolean);if(!t.length)return{error:`no Jira component set - project "${n.name}" routes by component (${n.componentRoutes.map(i=>i.component).join(", ")}); set one on the ticket`};let r=n.componentRoutes.filter(i=>t.includes(i.component));if(!r.length)return{error:`component(s) [${t.join(", ")}] not mapped - known: `+n.componentRoutes.map(i=>`${i.component}\u2192${i.repoName}`).join(", ")};let s=new Set(r.map(i=>i.repoName));return s.size>1?{error:`components map to DIFFERENT repos (${[...s].join(", ")}) - ambiguous, refusing`}:{project:{...n,repoName:r[0].repoName}}}var dd=24*3600*1e3,Ui=14,py=Ui*24*3600*1e3,my=new Set(["to","on","this","the","a","an","env","environment","please","now","it"]),qi=class{constructor(e,t,r){this.cfg=e;this.jiraFor=t;this.transport=r}cfg;jiraFor;transport;projects=[];rules=[];environments=[];inFlight=new Set;autopilotPausedUntil=0;get busyCount(){return Math.max(this.inFlight.size,this.activeWork)}activeWork=0;get idle(){return!this.ticking&&this.inFlight.size===0&&this.activeWork===0}repoQueues=new Map;envQueues=new Map;timer=null;ticking=!1;paused=!1;jiraOf(e){return this.jiraFor(e.repoName)}routingWarned=new Set;warnRoutingOnce(e,t){this.routingWarned.has(e)||(this.routingWarned.add(e),y.warn(`Component routing refused - ${t}`))}resolveClaudeProfile(e,t){if(!t)return;let r=this.cfg.claudeProfiles[t]?.configDir;return!r&&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.`}),y.warn(`run ${e}: claude profile "${t}" missing locally - using default login`)),r}setConfig(e,t,r=!1,s=[]){this.projects=e,this.rules=t,this.environments=s;let i=t.filter(o=>o.enabled).length;y.info(`config synced: ${e.length} project(s), ${t.length} rule(s) (${i} enabled), ${s.length} environment(s)`),r!==this.paused&&(y.info(r?"polling paused from the dashboard":"polling resumed from the dashboard"),this.paused=r)}start(){let e=this.cfg.pollIntervalSeconds*1e3;this.timer=setInterval(()=>{this.tick()},e),this.tick(),y.info(`polling Jira every ${this.cfg.pollIntervalSeconds}s`)}stop(){this.timer&&clearInterval(this.timer)}lastScheduleCheck=0;auditInFlight=!1;async runScheduledAudits(){if(!(!this.cfg.auditSchedules.length||this.auditInFlight)&&!(Date.now()-this.lastScheduleCheck<15*6e4)){this.lastScheduleCheck=Date.now();for(let e of this.cfg.auditSchedules){let t=this.projects.find(s=>s.repoName===e.repoName);if(!t)continue;let r=Qu(t.id,e.role);if(!(r&&Date.now()-new Date(r).getTime()<e.intervalHours*36e5)){this.auditInFlight=!0;try{y.info(`Scheduled ${e.role} audit of ${e.repoName} starting (every ${e.intervalHours}h)`);let s=Fe(this.cfg,t,"assist");if("error"in s){y.warn(`Scheduled audit skipped: ${s.error}`);continue}let i=await Vr({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;y.info(`Scheduled audit done: ${o} finding(s) - drift visible on the Audits page`)}else y.warn(`Scheduled audit failed: ${i.error}`)}catch(s){y.warn(`Scheduled audit crashed: ${s instanceof Error?s.message:String(s)}`)}finally{this.auditInFlight=!1}break}}}}async tick(){if(!(this.ticking||this.paused||!this.transport.connected)){this.ticking=!0;try{await this.runScheduledAudits(),await this.sweepMergedPRs(),await this.sweepGitHubApprovals();let e=new Set;for(let t of this.rules){if(!t.enabled)continue;let r=this.projects.find(i=>i.id===t.projectId);if(!r)continue;let s=this.cfg.repos[r.repoName];if(!s){y.warn(`rule "${t.name}": no local path for repo "${r.repoName}" - run: allwright repo add "${r.repoName}" /path/to/checkout`);continue}t.action.type==="deploy"?await this.pollDeployRule(t,r,s.path):t.action.type==="respond"?await this.pollRespondRule(t,r,s.path):(e.has(r.id)||(e.add(r.id),await this.sweepNeedsInput(r)),t.trigger.type==="comment_keyword"&&await this.sweepRevisions(t,r),await this.pollRule(t,r,s.path))}await this.pullAutopilotWork()}catch(e){y.warn(`poll tick failed: ${e instanceof Error?e.message:e}`)}finally{this.ticking=!1}}}async pullAutopilotWork(){if(this.inFlight.size>0||this.autopilotPausedUntil>Date.now())return;let e=await this.transport.requestAutopilotNext();if(!e?.ok)return;if(e.pausedUntil){let T=Date.parse(e.pausedUntil);Number.isFinite(T)&&(this.autopilotPausedUntil=T);return}let t=e.item;if(!t)return;let r=this.rules.find(T=>T.id===t.ruleId&&T.enabled),s=this.projects.find(T=>T.id===t.projectId);if(!r||!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=Li(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||t.autoMerge?{...r,action:r.action.type==="implement"?{...r.action,...t.baseOverride?{baseBranch:t.baseOverride}:{},...t.branchOverride?{branchTemplate:t.branchOverride}:{},...t.autoMerge?{requireApproval:!1,autoMerge:!0}:{}}:r.action}:r;y.info(`autopilot: taking ${t.issueKey} (${r.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:r.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=`${r.id}:${t.issueKey}`;this.inFlight.add(v);let b=this.resolveClaudeProfile(p.runId,p.claudeProfile);this.enqueueForRepo(a.path,async()=>{try{await Ni({runId:p.runId,rule:u,project:o,issueKey:t.issueKey,repoPath:a.path,cfg:this.cfg,jira:c,transport:this.transport,claudeConfigDir:b,actorEmail:p.actorEmail,continueBranch:t.continueBranch})}finally{this.inFlight.delete(v)}})}async sweepGitHubApprovals(){let e=Object.values(Is());if(!e.length)return;let t=ye()??this.cfg,r=new Map,s=i=>{let o=Ie(t,i);if(!o)return null;let a=r.get(o);return a||r.set(o,a=new Re(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(b){y.warn(`review check failed for ${i.owner}/${i.repo}#${i.prNumber}: ${b instanceof Error?b.message:b}`);continue}if(!c)continue;let f={cfg:this.cfg,jiraFor:this.jiraFor,transport:this.transport};if(c.merged){y.info(`PR #${i.prNumber} for ${i.issueKey} was merged on GitHub - completing the run`),this.inFlight.add(a);try{await Es(f,i.runId,c.headSha)}finally{this.inFlight.delete(a)}continue}if(c.state==="closed"){y.info(`PR #${i.prNumber} for ${i.issueKey} was closed unmerged on GitHub - failing the run`);let b=this.jiraFor(i.repoName),T=`PR #${i.prNumber} was closed on GitHub without merging`;await b.addComment(i.issueKey,`**Allwright: the pull request for this ticket was closed on GitHub without merging.**
|
|
749
753
|
|
|
750
754
|
PR: ${i.prUrl}
|
|
751
755
|
|
|
752
|
-
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
|
|
756
|
+
The run is marked failed. Remove the \`${i.failedLabel}\` label (or hit Retry on the Allwright board) to implement again. (run \`${i.runId}\`)`).catch(()=>{}),await b.editLabels(i.issueKey,{add:[i.failedLabel]}).catch(()=>{}),this.transport.send({type:"run.status",runId:i.runId,status:"failed",error:T}),ir(i.runId);continue}c.mergeableState==="dirty"?(this.transport.send({type:"run.pr.conflict",runId:i.runId,conflicted:!0}),i.conflictNotified||(await this.jiraFor(i.repoName).addComment(i.issueKey,`**Allwright: the pull request for this ticket has merge conflicts.** The base branch moved after this change was built, so GitHub cannot merge it as-is.
|
|
753
757
|
|
|
754
758
|
PR: ${i.prUrl}
|
|
755
759
|
|
|
756
|
-
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,lt(i),y.info(`merge conflicts on PR #${i.prNumber} for ${i.issueKey} - ticket notified`))):c.mergeableState!==null&&c.mergeableState!=="unknown"&&(this.transport.send({type:"run.pr.conflict",runId:i.runId,conflicted:!1}),i.conflictNotified&&(i.conflictNotified=!1,lt(i)));let p=u.filter(
|
|
760
|
+
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,lt(i),y.info(`merge conflicts on PR #${i.prNumber} for ${i.issueKey} - ticket notified`))):c.mergeableState!==null&&c.mergeableState!=="unknown"&&(this.transport.send({type:"run.pr.conflict",runId:i.runId,conflicted:!1}),i.conflictNotified&&(i.conflictNotified=!1,lt(i)));let p=u.filter(b=>b.state==="APPROVED"||b.state==="CHANGES_REQUESTED").sort((b,T)=>b.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}).
|
|
757
761
|
|
|
758
762
|
PR: ${i.prUrl}
|
|
759
763
|
|
|
760
|
-
Reply to the review on GitHub, or reject the run on the Allwright dashboard and re-trigger with new instructions. (run \`${i.runId}\`)`).catch(()=>{}),lt({...i,changesRequestedNotified:!0}),y.info(`changes requested on PR #${i.prNumber} for ${i.issueKey} - ticket notified`));continue}if(
|
|
764
|
+
Reply to the review on GitHub, or reject the run on the Allwright dashboard and re-trigger with new instructions. (run \`${i.runId}\`)`).catch(()=>{}),lt({...i,changesRequestedNotified:!0}),y.info(`changes requested on PR #${i.prNumber} for ${i.issueKey} - ticket notified`));continue}if(v.commitId===c.headSha){y.info(`PR #${i.prNumber} for ${i.issueKey} approved on GitHub by ${v.user} - completing the run`),this.inFlight.add(a);try{await Es(f,i.runId,v.commitId)}catch(b){y.warn(`github-approval completion failed for ${i.runId}: ${b instanceof Error?b.message:b}`)}finally{this.inFlight.delete(a)}}}}}async sweepMergedPRs(){let e=Object.values(Ai());if(!e.length)return;let t=ye()??this.cfg,r=new Map,s=a=>{let u=Ie(t,a);if(!u)return null;let c=r.get(u);return c||r.set(u,c=new Re(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){y.warn(`merge watch for ${a.issueKey} PR #${a.prNumber} is over 30 days old - dropping`),Cs(a.runId);continue}let c;try{c=await u.getPullRequest(a.owner,a.repo,a.prNumber)}catch(v){y.warn(`merge check failed for ${a.owner}/${a.repo}#${a.prNumber}: ${v instanceof Error?v.message:v}`);continue}if(!c){Cs(a.runId);continue}if(c.state==="open")continue;if(!c.merged){Cs(a.runId);continue}let f=this.jiraFor(a.repoName),p="";if(a.jiraTransitionOnMerge)try{p=await f.transitionByName(a.issueKey,a.jiraTransitionOnMerge)?`
|
|
761
765
|
|
|
762
766
|
Ticket moved to **${a.jiraTransitionOnMerge}**.`:`
|
|
763
767
|
|
|
764
|
-
Note: no transition named "${a.jiraTransitionOnMerge}" is available from this ticket's current status - move it manually.`}catch(
|
|
768
|
+
Note: no transition named "${a.jiraTransitionOnMerge}" is available from this ticket's current status - move it manually.`}catch(v){p=`
|
|
765
769
|
|
|
766
|
-
Note: the "${a.jiraTransitionOnMerge}" transition failed: ${
|
|
770
|
+
Note: the "${a.jiraTransitionOnMerge}" transition failed: ${v instanceof Error?v.message:v}`}try{await f.addComment(a.issueKey,`**Allwright: the pull request for this ticket was merged.**
|
|
767
771
|
|
|
768
772
|
PR: ${a.prUrl} (merged at \`${c.headSha.slice(0,10)}\`)${p}
|
|
769
773
|
|
|
770
|
-
(run \`${a.runId}\`)`)}catch(
|
|
774
|
+
(run \`${a.runId}\`)`)}catch(v){y.warn(`could not post merge comment to ${a.issueKey}: ${v instanceof Error?v.message:v}`);continue}y.info(`PR #${a.prNumber} for ${a.issueKey} merged - ticket updated`),Cs(a.runId)}}async sweepNeedsInput(e){let t;try{t=await this.jiraOf(e).search(`project = "${e.jiraProjectKey}" AND labels = "${hr.NEEDS_INPUT_LABEL}"`,10)}catch(s){y.warn(`needs-input sweep failed for ${e.jiraProjectKey}: ${s instanceof Error?s.message:s}`);return}if(!t.length)return;let r=Yr();for(let s of t){let i=Object.values(r).filter(a=>a.issueKey===s.key);if(!i.length){await this.jiraOf(e).editLabels(s.key,{remove:[hr.NEEDS_INPUT_LABEL]}).catch(()=>{}),y.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()>py){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){y.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=>!bt(T.body)&&new Date(T.created).getTime()>c);if(!f.length)continue;let p=As(f),v=o.attachments;this.inFlight.add(u),y.info(`reply received on ${s.key} - resuming run ${a.runId}`),await this.jiraOf(e).editLabels(s.key,{remove:[hr.NEEDS_INPUT_LABEL]}).catch(T=>{y.warn(`could not remove needs-input label on ${s.key}: ${T}`)});let b={jiraFor:this.jiraFor,transport:this.transport,cfg:this.cfg};a.kind==="implement"?this.enqueueForRepo(a.baseRepoPath??a.repoPath,async()=>{try{await Dc(a,p,v,b)}finally{this.inFlight.delete(u)}}):this.enqueueForRepo(a.repoPath,async()=>{try{await Oc(a,p,v,b)}finally{this.inFlight.delete(u)}})}}}async abandonStaleInput(e,t){y.warn(`${e.issueKey}: needs-input unanswered for over ${Ui}d - abandoning run ${e.runId}`);try{await this.jiraOf(t).addComment(e.issueKey,`**Allwright gave up waiting for an answer.**
|
|
771
775
|
|
|
772
|
-
No reply arrived within ${Ui} 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:[hr.NEEDS_INPUT_LABEL]})}catch(r){y.warn(`could not post staleness notice for ${e.issueKey}: ${r}`)}e.kind==="implement"&&await yt(e.baseRepoPath??e.repoPath,e.repoPath).catch(()=>{}),_t(e.runId),this.transport.send({type:"run.status",runId:e.runId,status:"failed",error:`no reply within ${Ui} days`})}async pollRule(e,t,r){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=Li(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?r:this.cfg.repos[u.repoName]?.path;if(!c){this.warnRoutingOnce(`${e.id}:${i.issueKey}:path`,`${i.issueKey}: routed to repo "${u.repoName}" but it has no local checkout - run: allwright repo add "${u.repoName}" /path/to/checkout`);continue}let f=await this.transport.claimRun({ruleId:e.id,issueKey:i.issueKey,issueSummary:i.summary,triggerFingerprint:i.fingerprint,triggeredByAccountId:i.triggeredByAccountId});if(!f.accepted||!f.runId){f.reason!=="duplicate"&&y.warn(`claim rejected for ${i.issueKey}: ${f.reason??"unknown"}`);continue}this.inFlight.add(o),y.info(`claimed run ${f.runId} for ${i.issueKey}`+(u.repoName!==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 Ni({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,r){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()-dd;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)||
|
|
776
|
+
No reply arrived within ${Ui} 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:[hr.NEEDS_INPUT_LABEL]})}catch(r){y.warn(`could not post staleness notice for ${e.issueKey}: ${r}`)}e.kind==="implement"&&await yt(e.baseRepoPath??e.repoPath,e.repoPath).catch(()=>{}),_t(e.runId),this.transport.send({type:"run.status",runId:e.runId,status:"failed",error:`no reply within ${Ui} days`})}async pollRule(e,t,r){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=Li(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?r:this.cfg.repos[u.repoName]?.path;if(!c){this.warnRoutingOnce(`${e.id}:${i.issueKey}:path`,`${i.issueKey}: routed to repo "${u.repoName}" but it has no local checkout - run: allwright repo add "${u.repoName}" /path/to/checkout`);continue}let f=await this.transport.claimRun({ruleId:e.id,issueKey:i.issueKey,issueSummary:i.summary,triggerFingerprint:i.fingerprint,triggeredByAccountId:i.triggeredByAccountId});if(!f.accepted||!f.runId){f.reason!=="duplicate"&&y.warn(`claim rejected for ${i.issueKey}: ${f.reason??"unknown"}`);continue}this.inFlight.add(o),y.info(`claimed run ${f.runId} for ${i.issueKey}`+(u.repoName!==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 Ni({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,r){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()-dd;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)||bt(f.body)||new Date(f.created).getTime()<a||!f.id)continue;let p=`respond:${f.id}`;if(this.inFlight.has(p))continue;let v=Li(t,u.components??[]);if("error"in v){this.warnRoutingOnce(`${e.id}:${u.key}`,`${u.key}: ${v.error}`);continue}let b=v.project,T=b.repoName===t.repoName?r:this.cfg.repos[b.repoName]?.path;if(!T){this.warnRoutingOnce(`${e.id}:${u.key}:path`,`${u.key}: routed to repo "${b.repoName}" but it has no local checkout - run: allwright repo add "${b.repoName}" /path/to/checkout`);continue}let x=await this.transport.claimRun({ruleId:e.id,issueKey:u.key,issueSummary:u.summary,triggerFingerprint:`question by ${f.author} at ${f.created}`,dedupKey:`respond:comment:${f.id}`,triggeredByAccountId:f.authorAccountId??void 0});if(!x.accepted||!x.runId){x.reason!=="duplicate"&&y.warn(`respond claim rejected for ${u.key}: ${x.reason??"unknown"}`);continue}this.inFlight.add(p),y.info(`claimed respond run ${x.runId}: ${u.key} (comment ${f.id})`+(b.repoName!==t.repoName?` (routed \u2192 ${b.repoName})`:"")+(x.claudeProfile?` (claude profile "${x.claudeProfile}")`:""));let P={author:f.author,body:f.body},I=this.resolveClaudeProfile(x.runId,x.claudeProfile);this.enqueueForRepo(T,async()=>{try{await Ni({runId:x.runId,rule:e,project:b,issueKey:u.key,repoPath:T,cfg:this.cfg,jira:this.jiraOf(b),transport:this.transport,question:P,claudeConfigDir:I,actorEmail:x.actorEmail})}finally{this.inFlight.delete(p)}})}}}async sweepRevisions(e,t){let r=e.trigger;if(r.type!=="comment_keyword")return;let s;try{s=await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND labels = "${r.doneLabel}" AND updated >= "-2d"`,10)}catch(o){y.warn(`revision sweep failed for ${t.jiraProjectKey}: ${o instanceof Error?o.message:o}`);return}let i=r.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)bt(f.body)&&(u=Math.max(u??0,new Date(f.created).getTime()));if(u===null||!a.comments.some(f=>!bt(f.body)&&f.body.toLowerCase().includes(i)&&new Date(f.created).getTime()>u))continue;await this.jiraOf(t).editLabels(o.key,{remove:[r.doneLabel]}),y.info(`revision requested on ${o.key} (new "${r.keyword}" after completion) - done label removed, rule will re-fire`)}catch(a){y.warn(`revision check failed for ${o.key}: ${a instanceof Error?a.message:a}`)}}async pollDeployRule(e,t,r){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.**
|
|
773
777
|
|
|
774
778
|
${a.reason}`+(i.requestedByAccountId?`
|
|
775
779
|
|
|
776
780
|
Jira account id: \`${i.requestedByAccountId}\``:"")+`
|
|
777
781
|
|
|
778
|
-
(run \`${a.runId}\`)`).catch(c=>y.warn(`could not post refusal to ${i.issueKey}: ${c}`)),y.warn(`deploy refused for ${i.issueKey}: ${a.reason}`)):a.reason&&y.warn(`deploy claim rejected for ${i.issueKey}: ${a.reason}`);continue}let u=a.environment;this.inFlight.add(o),y.info(`claimed deploy ${a.runId}: ${i.issueKey} \u2192 ${u.name}`),this.enqueue(this.envQueues,u.id,async()=>{try{await zi({runId:a.runId,project:t,environment:u,issueKey:i.issueKey,issueSummary:i.summary,repoPath:r,cfg:this.cfg,jira:this.jiraOf(t),transport:this.transport,requestedBy:i.requestedByDisplayName})}finally{this.inFlight.delete(o)}})}}async matchCommentDeploys(e,t){let r=e.trigger,s=e.action;if(r.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=r.keyword.toLowerCase(),a=Date.now()-dd,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
|
|
782
|
+
(run \`${a.runId}\`)`).catch(c=>y.warn(`could not post refusal to ${i.issueKey}: ${c}`)),y.warn(`deploy refused for ${i.issueKey}: ${a.reason}`)):a.reason&&y.warn(`deploy claim rejected for ${i.issueKey}: ${a.reason}`);continue}let u=a.environment;this.inFlight.add(o),y.info(`claimed deploy ${a.runId}: ${i.issueKey} \u2192 ${u.name}`),this.enqueue(this.envQueues,u.id,async()=>{try{await zi({runId:a.runId,project:t,environment:u,issueKey:i.issueKey,issueSummary:i.summary,repoPath:r,cfg:this.cfg,jira:this.jiraOf(t),transport:this.transport,requestedBy:i.requestedByDisplayName})}finally{this.inFlight.delete(o)}})}}async matchCommentDeploys(e,t){let r=e.trigger,s=e.action;if(r.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=r.keyword.toLowerCase(),a=Date.now()-dd,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 b of v.comments){if(!b.body.toLowerCase().includes(o)||bt(b.body)||new Date(b.created).getTime()<a||!b.id)continue;let T=s.envSelection==="fixed"?c:gy(b.body,r.keyword,u);f.push({issueKey:p.key,summary:p.summary,environmentName:T,requestedByAccountId:b.authorAccountId??void 0,requestedByDisplayName:b.author,dedupKey:`deploy:comment:${b.id}`,fingerprint:`comment "${r.keyword}" by ${b.author} at ${b.created}`+(T?` \u2192 ${T}`:"")})}}return f}async matchStatusDeploys(e,t){let r=e.trigger,s=e.action;if(r.type!=="status_changed"||s.type!=="deploy")return[];let i=await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND status = "${r.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,r.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 "${r.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 r=e.trigger;if(r.type!=="label_added")return[];let s=`project = "${t.jiraProjectKey}" AND labels = "${r.label}" AND labels not in ("${r.doneLabel}", "${r.failedLabel}", "${hr.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 "${r.label}" matched at ${new Date().toISOString()}`}))}async matchCommentTrigger(e,t){let r=e.trigger;if(r.type!=="comment_keyword")return[];let s=`project = "${t.jiraProjectKey}" AND updated >= "-2d" AND (labels IS EMPTY OR labels not in ("${r.doneLabel}", "${r.failedLabel}", "${hr.NEEDS_INPUT_LABEL}")) ORDER BY updated DESC`,i=await this.jiraOf(t).search(s,10),o=r.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)&&!bt(p.body));f&&a.push({issueKey:u.key,components:u.components,summary:u.summary,fingerprint:`comment keyword "${r.keyword}" by ${f.author} at ${f.created}`,triggeredByAccountId:f.authorAccountId??void 0})}return a}async diagnoseRule(e,t){let r=e.trigger;if(e.action.type==="deploy"){let u=r.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(r.type==="status_changed")return{matchedCount:(await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND status = "${r.status}"`,50)).length,excludedCount:0,excludedSample:[]};if(r.type==="label_added"){let[u,c]=await Promise.all([this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND labels = "${r.label}" AND labels not in ("${r.doneLabel}", "${r.failedLabel}")`,50),this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND labels = "${r.label}" AND labels in ("${r.doneLabel}", "${r.failedLabel}")`,50)]);return{matchedCount:u.length,excludedCount:c.length,excludedSample:c.slice(0,5).map(f=>f.key)}}let s=r.keyword.toLowerCase(),[i,o]=await Promise.all([this.matchCommentTrigger(e,t),this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND updated >= "-2d" AND labels in ("${r.doneLabel}", "${r.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,r){let i=(e.get(t)??Promise.resolve()).then(async()=>{this.activeWork++;try{await r()}finally{this.activeWork--}}).catch(o=>{y.error(`run crashed: ${o instanceof Error?o.stack:o}`)});e.set(t,i)}};function gy(n,e,t){let r=n.toLowerCase().indexOf(e.toLowerCase());if(r<0)return"";let i=n.slice(r+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(!my.has(o.toLowerCase()))return o;return""}var hd=E(require("node:fs"),1),fd=E(require("node:path"),1),Oa=require("node:crypto");vt();var yy=`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.
|
|
779
783
|
|
|
780
784
|
Rules:
|
|
781
785
|
- Edit ONLY the conflicted files listed below. Do not touch anything else, do not refactor, do not "improve" surrounding code.
|
|
@@ -787,7 +791,7 @@ Conflicted files:
|
|
|
787
791
|
`;async function pd(n){let{cfg:e,repoPath:t,branch:r,baseBranch:s,issueKey:i,onLog:o}=n,a=fd.default.join(Mt(),`conflict-${(0,Oa.randomUUID)().slice(0,8)}`),u=!1;try{o("info",`Preparing a worktree for ${r} to merge ${s} into it`),await ks(t,a,r),u=!0;let c=await Wo(a,s);if(c.ok&&c.alreadyUpToDate)return o("info",`${r} already contains ${s} - nothing to merge`),{ok:!0,freeOfCharge:!0,note:`This branch already contains ${s}, so there was nothing to merge - GitHub's conflict flag was out of date. Refresh the PR.`};if(!c.ok&&c.conflicts===null)return{ok:!1,note:`The merge could not even be started: ${c.reason}`};let f={},p=!1;if(!c.ok){let T=c.conflicts;o("info",`git merged everything except ${T.length} file(s): ${T.slice(0,20).join(", ")}`+(T.length>20?", \u2026":""));let x=qe(n.agentId);if(!x)return await ln(a),{ok:!1,note:`no adapter for agent "${n.agentId}" on this runner`};let P=un(n.agentId,"edit_no_shell");if(P)return await ln(a),{ok:!1,note:`${P} Resolve the conflicts yourself on branch ${r}, or use Rebuild on current base.`};o("info",`Asking ${x.displayName} to resolve only those files`);let I=-1,w=setInterval(()=>{Yo(a,T).then(D=>{let W=T.filter(d=>!D.includes(d));W.length!==I&&(I=W.length,o("info",`Conflict progress: ${W.length}/${T.length} resolved`+(W.length?` \xB7 clean: ${W.join(", ")}`:"")+(D.length?` \xB7 still conflicted: ${D.join(", ")}`:"")))}).catch(()=>{})},12e3),B=await Rs(x,{repoPath:a,prompt:yy+T.map(D=>`- ${D}`).join(`
|
|
788
792
|
`),timeoutSeconds:n.timeoutSeconds,bin:ze(e,n.agentId),configDir:n.configDir,mode:"edit_no_shell",sessionId:(0,Oa.randomUUID)(),onLog:(D,W)=>o(D,W)},(D,W)=>o(D==="warn"?"warn":D,W));if(clearInterval(w),f={costUsd:B.costUsd,inputTokens:B.inputTokens,outputTokens:B.outputTokens},!B.ok)return await ln(a),{ok:!1,...f,note:`The agent could not do the resolution: ${B.error??"it produced no output"}. Nothing was changed - the merge was rolled back. Fix that first, then Resolve again.`};p=!0;let M=await _i(a);if(M.length)return await ln(a),{ok:!1,...f,note:`The agent left conflict markers in ${M.slice(0,5).join(", ")}, so nothing was pushed and the merge was rolled back. Resolve it by hand on ${r}, or use Rebuild on current base to redo the ticket against today's base.`};await Jo(a,`${i}: merge ${s}, conflicts resolved by the agent
|
|
789
793
|
|
|
790
|
-
Resolved via Allwright`)}let
|
|
794
|
+
Resolved via Allwright`)}let v=await an(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 ${rn}/${sn})`;return await ln(a),{ok:!1,...f,note:`Nothing was pushed: ${T}. The merge was rolled back.`}}await Xn(a,r);let b=await Qe(a);return o("info",`Pushed the merge to ${r} (${b.slice(0,7)})`),{ok:!0,...f,freeOfCharge:!p,headSha:b,note:p?`Merged ${s} into ${r}; the agent resolved the overlapping files. The PR is the same one - review the merge commit, then approve.`:`Merged ${s} into ${r} cleanly - no agent was needed, so this cost nothing. The PR is the same one; review and approve.`}}catch(c){return await ln(a).catch(()=>{}),{ok:!1,note:`Could not resolve the conflict: ${c instanceof Error?c.message.slice(0,300):String(c)}`}}finally{u&&(await yt(t,a).catch(()=>{}),hd.default.rmSync(a,{recursive:!0,force:!0}))}}var Na=E(require("node:fs"),1),md=E(require("node:path"),1),Ma=require("node:crypto");vt();function vy(n,e){let t=e.map(r=>`$ ${r.command} (exit ${r.exitCode})
|
|
791
795
|
${r.tail.slice(-2e3)}`).join(`
|
|
792
796
|
|
|
793
797
|
`);return`You are on the pull-request branch for ticket ${n}. The work itself is done and under review - do NOT redo or extend it. The repository's documented TEST.md commands were executed by the runner and ${e.length} failed:
|
|
@@ -800,10 +804,10 @@ Your ONLY job is to make these commands pass, with the smallest change possible.
|
|
|
800
804
|
- If a failure is clearly pre-existing on the base branch and unrelated to this PR's change, leave the code alone and say so in one sentence.
|
|
801
805
|
- Do not ask questions; if you cannot fix something safely, say what you found and stop.
|
|
802
806
|
- You have no shell; the runner re-runs every documented command after you finish.
|
|
803
|
-
End with one short paragraph stating exactly what you changed, or why you changed nothing.`}async function gd(n){let{cfg:e,repoPath:t,branch:r,baseBranch:s,issueKey:i,failedTests:o,onLog:a}=n,u=md.default.join(Mt(),`testfix-${(0,Ma.randomUUID)().slice(0,8)}`),c=!1;try{let f=qe(n.agentId);if(!f)return{ok:!1,note:`no adapter for agent "${n.agentId}" on this runner`};let p=un(n.agentId,"edit_no_shell");if(p)return{ok:!1,note:p};a("info",`Preparing a worktree on ${r} for the test fix`),await on(t,r),await ks(t,u,r),c=!0,await Br(u,`origin/${r}`);let
|
|
807
|
+
End with one short paragraph stating exactly what you changed, or why you changed nothing.`}async function gd(n){let{cfg:e,repoPath:t,branch:r,baseBranch:s,issueKey:i,failedTests:o,onLog:a}=n,u=md.default.join(Mt(),`testfix-${(0,Ma.randomUUID)().slice(0,8)}`),c=!1;try{let f=qe(n.agentId);if(!f)return{ok:!1,note:`no adapter for agent "${n.agentId}" on this runner`};let p=un(n.agentId,"edit_no_shell");if(p)return{ok:!1,note:p};a("info",`Preparing a worktree on ${r} for the test fix`),await on(t,r),await ks(t,u,r),c=!0,await Br(u,`origin/${r}`);let v=await Qe(u);a("info",`Asking ${f.displayName} to fix ${o.length} failing test command(s) - narrow prompt, failure output included, no re-exploration`);let b=await Rs(f,{repoPath:u,prompt:vy(i,o),timeoutSeconds:n.timeoutSeconds,bin:ze(e,n.agentId),configDir:n.configDir,mode:"edit_no_shell",maxTurns:60,sessionId:(0,Ma.randomUUID)(),onLog:(d,m)=>a(d,m)},(d,m)=>a(d==="warn"?"warn":d,m)),T={costUsd:b.costUsd,inputTokens:b.inputTokens,outputTokens:b.outputTokens};if(!b.ok)return{ok:!1,...T,note:`The fix agent could not run: ${b.error??"it produced no output"}. Nothing was changed or pushed.`};let x=await Fr(u);for(let d of x.refused)a("warn",`${Nt} entry refused: ${d}`);let P=!0;try{await Yn(u,`${i}: fix failing TEST.md commands
|
|
804
808
|
|
|
805
|
-
Allwright test-fix run`)}catch{P=!1}if(!P){let d=`The agent changed nothing - its own conclusion: ${
|
|
806
|
-
${g.tail.slice(-1500)}`));w=m.filter(g=>g.exitCode!==0).slice(0,20).map(g=>({command:g.command.slice(0,500),exitCode:g.exitCode,tail:g.tail.slice(-4e3)})),M=m.length,B=m.length-w.length}}await Xn(u,r);let W=await Qe(u);return a("info",`Pushed the fix to ${r} (${W.slice(0,7)})`),{ok:!0,...T,headSha:W,remaining:w,testsPassed:B,testsTotal:M,note:w.length?`The fix was pushed, but ${w.length} command(s) still fail - output is in the run log. The PR is the same one; review the new commit.`:"All documented test commands pass now. The PR is the same one - review the fix commit, then approve."}}catch(f){return{ok:!1,note:`Could not fix the tests: ${f instanceof Error?f.message.slice(0,300):String(f)}`}}finally{c&&(await yt(t,u).catch(()=>{}),Na.default.rmSync(u,{recursive:!0,force:!0}))}}at();var fr=E(require("node:fs"),1),
|
|
809
|
+
Allwright test-fix run`)}catch{P=!1}if(!P){let d=`The agent changed nothing - its own conclusion: ${b.resultText.trim().slice(0,400)||"(no explanation given)"}`;return a("info",d),{ok:!0,...T,remaining:o,note:d}}let I=await an(u,s);if(!I.ok){await Br(u,v);let d=I.forbidden.length?`the fixed result touches protected paths (${I.forbidden.slice(0,5).join(", ")})`:`the fixed result is too large (${I.files} files, ${I.insertions+I.deletions} lines; limits ${rn}/${sn})`;return{ok:!1,...T,note:`Nothing was pushed: ${d}. The fix commit was discarded; the PR is unchanged.`}}let w=o,B,M,D=Hr(u);if(D){let d=Gr(Na.default.readFileSync(D,"utf8"));if(d.length){a("info",`Re-running ${d.length} documented test command(s)`);let m=await nr(u,d,{perCommandTimeoutMs:15*6e4});for(let g of m)a(g.exitCode===0?"info":"warn",`${g.exitCode===0?"PASS":"FAIL"} ${g.command} (exit ${g.exitCode})`+(g.exitCode===0?"":`
|
|
810
|
+
${g.tail.slice(-1500)}`));w=m.filter(g=>g.exitCode!==0).slice(0,20).map(g=>({command:g.command.slice(0,500),exitCode:g.exitCode,tail:g.tail.slice(-4e3)})),M=m.length,B=m.length-w.length}}await Xn(u,r);let W=await Qe(u);return a("info",`Pushed the fix to ${r} (${W.slice(0,7)})`),{ok:!0,...T,headSha:W,remaining:w,testsPassed:B,testsTotal:M,note:w.length?`The fix was pushed, but ${w.length} command(s) still fail - output is in the run log. The PR is the same one; review the new commit.`:"All documented test commands pass now. The PR is the same one - review the fix commit, then approve."}}catch(f){return{ok:!1,note:`Could not fix the tests: ${f instanceof Error?f.message.slice(0,300):String(f)}`}}finally{c&&(await yt(t,u).catch(()=>{}),Na.default.rmSync(u,{recursive:!0,force:!0}))}}at();var fr=E(require("node:fs"),1),vd=E(require("node:path"),1);var by=_.object({role:_.enum(["user","agent"]),text:_.string(),steps:_.array(_.string()).default([])}),wy=_.object({sessionId:_.string(),projectId:_.string(),title:_.string().default(""),updatedAt:_.string(),messages:_.array(by).default([])}),_y=_.record(wy),ky=10,Sy=200,yd=2e4,Ty=30,xy=2e3;function bd(){return vd.default.join(re(),"chat-sessions.json")}function za(){let n=bd();if(!fr.default.existsSync(n))return{};try{return _y.parse(JSON.parse(fr.default.readFileSync(n,"utf8")))}catch{return{}}}function Cy(n){fr.default.mkdirSync(re(),{recursive:!0,mode:448});let e=bd(),t=e+".tmp";fr.default.writeFileSync(t,JSON.stringify(n,null,2)+`
|
|
807
811
|
`,{mode:384}),fr.default.renameSync(t,e),fr.default.chmodSync(e,384)}function wd(n,e,t,r,s=[]){let i=za(),a=i[e]??{sessionId:e,projectId:n,title:t.slice(0,80),updatedAt:new Date().toISOString(),messages:[]};a.messages.push({role:"user",text:t.slice(0,yd),steps:[]},{role:"agent",text:r.slice(0,yd),steps:s.slice(0,Ty).map(c=>c.slice(0,xy))}),a.messages=a.messages.slice(-Sy),a.updatedAt=new Date().toISOString(),i[e]=a;let u=Object.values(i).filter(c=>c.projectId===a.projectId).sort((c,f)=>f.updatedAt.localeCompare(c.updatedAt));for(let c of u.slice(ky))delete i[c.sessionId];Cy(i)}function _d(n){return Object.values(za()).filter(e=>e.projectId===n).sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt)).map(e=>({sessionId:e.sessionId,title:e.title,updatedAt:e.updatedAt,messageCount:e.messages.length}))}function Ps(n){return za()[n]??null}var kd=36,Sd=60;function Td(n){let e=n.toLowerCase();return e?e.includes("[1m]")||e.includes("-1m")?1e6:e.includes("haiku")||e.includes("sonnet")||e.includes("opus")||e.includes("fable")?2e5:0:0}var Iy=`This conversation is being COMPACTED: it continues in a fresh window that will only have your summary, so anything you leave out is gone. Summarize it now under these headings, in under 500 words total:
|
|
808
812
|
Goal: what the user is trying to achieve.
|
|
809
813
|
Decided: choices already made, including ones you talked them out of - each as one line.
|
|
@@ -823,10 +827,10 @@ TWO OPTIONAL BLOCKS, for the dashboard's benefit. Never mention them in your pro
|
|
|
823
827
|
["\u2026", "\u2026"]
|
|
824
828
|
\`\`\`
|
|
825
829
|
1 to 3 short suggestions, written AS THE USER (first person, imperative) - they are typed into the user's box, not yours. Skip the block entirely when nothing obvious follows; a wrong guess costs the user more than no guess.
|
|
826
|
-
Never emit both blocks in one reply, and never let either replace the actual answer.`;var pr=E(require("node:fs"),1),et=E(require("node:path"),1),Da=300,Ry=4,Id=512*1024,Ey=new Set([".git","node_modules","dist","build","out",".next","vendor","coverage",".venv","venv","__pycache__",".turbo",".cache"]),Rd=/\.mdx?$/i;function Ed(n){let e=et.default.resolve(n),t=[],r=(s,i)=>{if(i>Ry||t.length>=Da)return;let o;try{o=pr.default.readdirSync(s,{withFileTypes:!0})}catch{return}for(let a of o){if(t.length>=Da)return;if(!a.isFile()||!Rd.test(a.name))continue;let u=et.default.join(s,a.name);try{let c=pr.default.statSync(u);t.push({path:et.default.relative(e,u).split(et.default.sep).join("/"),sizeBytes:c.size,updatedAt:c.mtime.toISOString()})}catch{}}for(let a of o){if(t.length>=Da)return;!a.isDirectory()||a.isSymbolicLink()||Ey.has(a.name)||a.name.startsWith(".")||r(et.default.join(s,a.name),i+1)}};return r(e,0),t}function Ad(n,e){let t=et.default.resolve(n);if(!Rd.test(e))return{ok:!1,error:"only markdown files can be opened here"};let r=et.default.resolve(t,e);if(r!==t&&!r.startsWith(t+et.default.sep))return{ok:!1,error:"that path is outside the project checkout"};let s;try{s=pr.default.realpathSync(r)}catch{return{ok:!1,error:"file not found in this checkout"}}let i=(()=>{try{return pr.default.realpathSync(t)}catch{return t}})();if(s!==i&&!s.startsWith(i+et.default.sep))return{ok:!1,error:"that path links outside the project checkout"};let o;try{o=pr.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=pr.default.readFileSync(s,"utf8"),u=Buffer.byteLength(a,"utf8")>Id;return{ok:!0,path:et.default.relative(i,s).split(et.default.sep).join("/"),content:u?a.slice(0,Id):a,truncated:u}}catch(a){return{ok:!1,error:a instanceof Error?a.message:"could not read the file"}}}var Kt=E(Se(),1);var Fi=E(require("node:fs"),1),$d=E(require("node:path"),1);var Ay=_.object({id:_.string(),name:_.string().default(""),jiraProjectKey:_.string().default(""),repoName:_.string().default(""),jiraSiteUrl:_.string().default("")}),$y=_.array(Ay);function Pd(){return $d.default.join(re(),"synced-projects.json")}function jd(n){try{let e=n.map(t=>({id:t.id,name:t.name,jiraProjectKey:t.jiraProjectKey,repoName:t.repoName,jiraSiteUrl:t.jiraSiteUrl??""}));Fi.default.mkdirSync(re(),{recursive:!0}),Fi.default.writeFileSync(Pd(),JSON.stringify(e,null,2),{mode:384})}catch{}}function Py(){try{let n=$y.safeParse(JSON.parse(Fi.default.readFileSync(Pd(),"utf8")));return n.success?n.data:[]}catch{return[]}}function Od(n){return Py().find(e=>e.repoName===n)??null}var Qb=E(Eh(),1),ev=E(Yi(),1),tv=E(ns(),1),nv=E(Wa(),1),rv=E(Xa(),1),sv=E(sl(),1),Dh=E(to(),1),iv=E(zh(),1);var ol=Dh.default;var Us=E(require("node:crypto"),1),Tt=E(Se(),1);function ov(n){let e=n&&typeof n=="object"&&"name"in n?String(n.name):null;return e?`"${e}"`:"(unnamed)"}function al(n,e,t,r){n.push(`dropped ${e} ${t} - this runner is out of date and does not understand it yet (${r}). Update the runner (npm install -g @ticketpilot/runner) to pick it up.`)}function av(n){if(!n||typeof n!="object"||n.type!=="config")return null;let e=n,t=[],r=[];for(let a of Array.isArray(e.projects)?e.projects:[]){let u=Tt.ProjectConfig.safeParse(a);u.success?r.push(u.data):al(t,"project","",u.error.issues[0]?.message??"invalid shape")}let s=[];for(let a of Array.isArray(e.rules)?e.rules:[]){let u=Tt.RuleConfig.safeParse(a);u.success?s.push(u.data):al(t,"rule",ov(a),u.error.issues[0]?.message??"invalid shape")}let i=[];for(let a of Array.isArray(e.environments)?e.environments:[]){let u=Tt.EnvironmentConfig.safeParse(a);u.success?i.push(u.data):al(t,"environment","",u.error.issues[0]?.message??"invalid shape")}return{msg:{type:"config",projects:r,rules:s,environments:i,pollingPaused:typeof e.pollingPaused=="boolean"?e.pollingPaused:!1},warnings:t}}var lv=2e4,uv=6e4,cv=5e3,ro=class{constructor(e,t,r,s){this.wsUrl=e;this.runnerToken=t;this.meta=r;this.events=s}wsUrl;runnerToken;meta;events;ws=null;queue=[];pending=new Map;backoffMs=1e3;heartbeat=null;closed=!1;bootAnnounced=!1;start(){this.closed=!1,this.connect()}stop(){this.closed=!0,this.heartbeat&&clearInterval(this.heartbeat),this.ws?.close()}get connected(){return this.ws?.readyState===ol.OPEN}connect(){if(this.closed)return;y.info(`connecting to control plane at ${this.wsUrl}`);let e=new ol(this.wsUrl,{headers:{authorization:`Bearer ${this.runnerToken}`}});this.ws=e,e.on("open",()=>{this.backoffMs=1e3,this.sendNow({type:"hello",protocolVersion:Tt.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 r of t)this.sendNow(r);this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=setInterval(()=>{this.send({type:"heartbeat",ts:new Date().toISOString()})},lv)}),e.on("message",t=>{let r;try{r=JSON.parse(t.toString())}catch(i){y.warn(`ignoring malformed server message (bad JSON): ${i}`);return}let s;try{s=(0,Tt.parseServerMsg)(r)}catch(i){let o=av(r);if(!o){y.warn(`ignoring malformed server message: ${i}`);return}for(let a of o.warnings)y.warn(a);y.warn(`config push had ${o.warnings.length} ${o.warnings.length===1?"entry":"entries"} this runner doesn't understand - applied everything else instead of dropping the whole config`),s=o.msg}this.handle(s)}),e.on("close",t=>{if(this.heartbeat&&clearInterval(this.heartbeat),t===4001)y.error("control plane rejected this runner version (protocol mismatch). Update with: npm install -g @ticketpilot/runner");else if(t===4003){y.error("this runner has been revoked from the control plane UI. Re-enroll with a fresh token if this was not intended."),this.closed=!0;return}if(this.closed)return;let r=Math.random()*.3+.85,s=Math.round(this.backoffMs*r);y.warn(`disconnected (code ${t}); reconnecting in ${Math.round(s/1e3)}s`),setTimeout(()=>this.connect(),s),this.backoffMs=Math.min(this.backoffMs*2,uv)}),e.on("error",t=>{y.warn(`websocket error: ${t.message}`)})}handle(e){if(e.type==="hello.ack"){this.bootAnnounced=!0,y.info(`connected as runner "${e.runnerName}" (${e.runnerId})`);return}if(e.type==="run.claim.result"||e.type==="deploy.claim.result"||e.type==="autopilot.next.result"){let 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==="run.testfix")return this.events.onTestFix(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>=cv){let t=this.queue.findIndex(r=>r.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(),r=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!r||r.type!=="run.claim.result"?{accepted:!1,reason:"claim timed out"}:{accepted:r.accepted,runId:r.runId,reason:r.reason,claudeProfile:r.claudeProfile,actorEmail:r.actorEmail}}async requestAutopilotNext(){if(!this.connected)return null;let e=Us.default.randomUUID(),t=await new Promise(r=>{let s=setTimeout(()=>{this.pending.delete(e),r(null)},15e3);this.pending.set(e,{resolve:r,timer:s}),this.sendNow({type:"autopilot.next",requestId:e})});return!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(),r=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!r||r.type!=="deploy.claim.result"?{accepted:!1,reason:"deploy authorization timed out"}:{accepted:r.accepted,runId:r.runId,environment:r.environment,reason:r.reason,code:r.code}}sendDeploySuggestResult(e,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??"",contextTokens:t.contextTokens??0,contextLimit:t.contextLimit??0,compacted:t.compacted??!1,compactedMessages:t.compactedMessages??0})}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,messages:t.messages.map(r=>({...r,steps:r.steps??[]}))})}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})}sendTestFixResult(e,t){this.send({type:"run.testfix.result",requestId:e,ok:t.ok,note:t.note??"",headSha:t.headSha??"",remaining:t.remaining??[],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,r){this.send({type:"project.test.result",requestId:e,ok:t,checks:this.withFixDefaults(r)})}sendRuleDiagnoseResult(e,t){this.send({type:"rule.diagnose.result",requestId:e,...t,checks:this.withFixDefaults(t.checks)})}};var so=E(require("node:fs"),1),ls=E(require("node:path"),1),Uh=require("node:child_process"),dv=/\.mdx?$/i,Lh=6,hv=/^[\w.\- ()]+$/;function fv(n,e){let t=e.trim().replace(/\\/g,"/").replace(/^\.\//,"");if(!t)return{ok:!1,error:"empty path"};if(ls.default.isAbsolute(t))return{ok:!1,error:"path must be repo-relative"};if(!dv.test(t))return{ok:!1,error:"only markdown files (.md) can be saved"};let r=t.split("/");if(r.length>Lh)return{ok:!1,error:`path deeper than ${Lh} levels`};for(let o of r)if(o==="."||o===".."||!hv.test(o))return{ok:!1,error:`invalid path segment "${o}"`};if(r[0]===".git")return{ok:!1,error:"cannot write under .git"};let s=ls.default.resolve(n),i=ls.default.resolve(s,t);return i!==s&&!i.startsWith(s+ls.default.sep)?{ok:!1,error:"path escapes the checkout"}:{ok:!0,abs:i,rel:t}}async function ll(n){let e=fv(n.repoPath,n.relPath);if(!e.ok)return{ok:!1,error:e.error};if(so.default.existsSync(e.abs)&&!n.overwrite)return{ok:!1,error:`${e.rel} already exists in this checkout`};so.default.mkdirSync(ls.default.dirname(e.abs),{recursive:!0}),so.default.writeFileSync(e.abs,n.content.endsWith(`
|
|
830
|
+
Never emit both blocks in one reply, and never let either replace the actual answer.`;var pr=E(require("node:fs"),1),et=E(require("node:path"),1),Da=300,Ry=4,Id=512*1024,Ey=new Set([".git","node_modules","dist","build","out",".next","vendor","coverage",".venv","venv","__pycache__",".turbo",".cache"]),Rd=/\.mdx?$/i;function Ed(n){let e=et.default.resolve(n),t=[],r=(s,i)=>{if(i>Ry||t.length>=Da)return;let o;try{o=pr.default.readdirSync(s,{withFileTypes:!0})}catch{return}for(let a of o){if(t.length>=Da)return;if(!a.isFile()||!Rd.test(a.name))continue;let u=et.default.join(s,a.name);try{let c=pr.default.statSync(u);t.push({path:et.default.relative(e,u).split(et.default.sep).join("/"),sizeBytes:c.size,updatedAt:c.mtime.toISOString()})}catch{}}for(let a of o){if(t.length>=Da)return;!a.isDirectory()||a.isSymbolicLink()||Ey.has(a.name)||a.name.startsWith(".")||r(et.default.join(s,a.name),i+1)}};return r(e,0),t}function Ad(n,e){let t=et.default.resolve(n);if(!Rd.test(e))return{ok:!1,error:"only markdown files can be opened here"};let r=et.default.resolve(t,e);if(r!==t&&!r.startsWith(t+et.default.sep))return{ok:!1,error:"that path is outside the project checkout"};let s;try{s=pr.default.realpathSync(r)}catch{return{ok:!1,error:"file not found in this checkout"}}let i=(()=>{try{return pr.default.realpathSync(t)}catch{return t}})();if(s!==i&&!s.startsWith(i+et.default.sep))return{ok:!1,error:"that path links outside the project checkout"};let o;try{o=pr.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=pr.default.readFileSync(s,"utf8"),u=Buffer.byteLength(a,"utf8")>Id;return{ok:!0,path:et.default.relative(i,s).split(et.default.sep).join("/"),content:u?a.slice(0,Id):a,truncated:u}}catch(a){return{ok:!1,error:a instanceof Error?a.message:"could not read the file"}}}var Kt=E(Se(),1);var Fi=E(require("node:fs"),1),$d=E(require("node:path"),1);var Ay=_.object({id:_.string(),name:_.string().default(""),jiraProjectKey:_.string().default(""),repoName:_.string().default(""),jiraSiteUrl:_.string().default("")}),$y=_.array(Ay);function Pd(){return $d.default.join(re(),"synced-projects.json")}function jd(n){try{let e=n.map(t=>({id:t.id,name:t.name,jiraProjectKey:t.jiraProjectKey,repoName:t.repoName,jiraSiteUrl:t.jiraSiteUrl??""}));Fi.default.mkdirSync(re(),{recursive:!0}),Fi.default.writeFileSync(Pd(),JSON.stringify(e,null,2),{mode:384})}catch{}}function Py(){try{let n=$y.safeParse(JSON.parse(Fi.default.readFileSync(Pd(),"utf8")));return n.success?n.data:[]}catch{return[]}}function Od(n){return Py().find(e=>e.repoName===n)??null}var Qv=E(Eh(),1),eb=E(Yi(),1),tb=E(ns(),1),nb=E(Wa(),1),rb=E(Xa(),1),sb=E(sl(),1),Dh=E(to(),1),ib=E(zh(),1);var ol=Dh.default;var Us=E(require("node:crypto"),1),Tt=E(Se(),1);function ob(n){let e=n&&typeof n=="object"&&"name"in n?String(n.name):null;return e?`"${e}"`:"(unnamed)"}function al(n,e,t,r){n.push(`dropped ${e} ${t} - this runner is out of date and does not understand it yet (${r}). Update the runner (npm install -g @ticketpilot/runner) to pick it up.`)}function ab(n){if(!n||typeof n!="object"||n.type!=="config")return null;let e=n,t=[],r=[];for(let a of Array.isArray(e.projects)?e.projects:[]){let u=Tt.ProjectConfig.safeParse(a);u.success?r.push(u.data):al(t,"project","",u.error.issues[0]?.message??"invalid shape")}let s=[];for(let a of Array.isArray(e.rules)?e.rules:[]){let u=Tt.RuleConfig.safeParse(a);u.success?s.push(u.data):al(t,"rule",ob(a),u.error.issues[0]?.message??"invalid shape")}let i=[];for(let a of Array.isArray(e.environments)?e.environments:[]){let u=Tt.EnvironmentConfig.safeParse(a);u.success?i.push(u.data):al(t,"environment","",u.error.issues[0]?.message??"invalid shape")}return{msg:{type:"config",projects:r,rules:s,environments:i,pollingPaused:typeof e.pollingPaused=="boolean"?e.pollingPaused:!1},warnings:t}}var lb=2e4,ub=6e4,cb=5e3,ro=class{constructor(e,t,r,s){this.wsUrl=e;this.runnerToken=t;this.meta=r;this.events=s}wsUrl;runnerToken;meta;events;ws=null;queue=[];pending=new Map;backoffMs=1e3;heartbeat=null;closed=!1;bootAnnounced=!1;start(){this.closed=!1,this.connect()}stop(){this.closed=!0,this.heartbeat&&clearInterval(this.heartbeat),this.ws?.close()}get connected(){return this.ws?.readyState===ol.OPEN}connect(){if(this.closed)return;y.info(`connecting to control plane at ${this.wsUrl}`);let e=new ol(this.wsUrl,{headers:{authorization:`Bearer ${this.runnerToken}`}});this.ws=e,e.on("open",()=>{this.backoffMs=1e3,this.sendNow({type:"hello",protocolVersion:Tt.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 r of t)this.sendNow(r);this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=setInterval(()=>{this.send({type:"heartbeat",ts:new Date().toISOString()})},lb)}),e.on("message",t=>{let r;try{r=JSON.parse(t.toString())}catch(i){y.warn(`ignoring malformed server message (bad JSON): ${i}`);return}let s;try{s=(0,Tt.parseServerMsg)(r)}catch(i){let o=ab(r);if(!o){y.warn(`ignoring malformed server message: ${i}`);return}for(let a of o.warnings)y.warn(a);y.warn(`config push had ${o.warnings.length} ${o.warnings.length===1?"entry":"entries"} this runner doesn't understand - applied everything else instead of dropping the whole config`),s=o.msg}this.handle(s)}),e.on("close",t=>{if(this.heartbeat&&clearInterval(this.heartbeat),t===4001)y.error("control plane rejected this runner version (protocol mismatch). Update with: npm install -g @ticketpilot/runner");else if(t===4003){y.error("this runner has been revoked from the control plane UI. Re-enroll with a fresh token if this was not intended."),this.closed=!0;return}if(this.closed)return;let r=Math.random()*.3+.85,s=Math.round(this.backoffMs*r);y.warn(`disconnected (code ${t}); reconnecting in ${Math.round(s/1e3)}s`),setTimeout(()=>this.connect(),s),this.backoffMs=Math.min(this.backoffMs*2,ub)}),e.on("error",t=>{y.warn(`websocket error: ${t.message}`)})}handle(e){if(e.type==="hello.ack"){this.bootAnnounced=!0,y.info(`connected as runner "${e.runnerName}" (${e.runnerId})`);return}if(e.type==="run.claim.result"||e.type==="deploy.claim.result"||e.type==="autopilot.next.result"){let 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==="run.testfix")return this.events.onTestFix(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>=cb){let t=this.queue.findIndex(r=>r.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(),r=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!r||r.type!=="run.claim.result"?{accepted:!1,reason:"claim timed out"}:{accepted:r.accepted,runId:r.runId,reason:r.reason,claudeProfile:r.claudeProfile,actorEmail:r.actorEmail}}async requestAutopilotNext(){if(!this.connected)return null;let e=Us.default.randomUUID(),t=await new Promise(r=>{let s=setTimeout(()=>{this.pending.delete(e),r(null)},15e3);this.pending.set(e,{resolve:r,timer:s}),this.sendNow({type:"autopilot.next",requestId:e})});return!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(),r=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!r||r.type!=="deploy.claim.result"?{accepted:!1,reason:"deploy authorization timed out"}:{accepted:r.accepted,runId:r.runId,environment:r.environment,reason:r.reason,code:r.code}}sendDeploySuggestResult(e,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??"",contextTokens:t.contextTokens??0,contextLimit:t.contextLimit??0,compacted:t.compacted??!1,compactedMessages:t.compactedMessages??0})}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,messages:t.messages.map(r=>({...r,steps:r.steps??[]}))})}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})}sendTestFixResult(e,t){this.send({type:"run.testfix.result",requestId:e,ok:t.ok,note:t.note??"",headSha:t.headSha??"",remaining:t.remaining??[],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,r){this.send({type:"project.test.result",requestId:e,ok:t,checks:this.withFixDefaults(r)})}sendRuleDiagnoseResult(e,t){this.send({type:"rule.diagnose.result",requestId:e,...t,checks:this.withFixDefaults(t.checks)})}};var so=E(require("node:fs"),1),ls=E(require("node:path"),1),Uh=require("node:child_process"),db=/\.mdx?$/i,Lh=6,hb=/^[\w.\- ()]+$/;function fb(n,e){let t=e.trim().replace(/\\/g,"/").replace(/^\.\//,"");if(!t)return{ok:!1,error:"empty path"};if(ls.default.isAbsolute(t))return{ok:!1,error:"path must be repo-relative"};if(!db.test(t))return{ok:!1,error:"only markdown files (.md) can be saved"};let r=t.split("/");if(r.length>Lh)return{ok:!1,error:`path deeper than ${Lh} levels`};for(let o of r)if(o==="."||o===".."||!hb.test(o))return{ok:!1,error:`invalid path segment "${o}"`};if(r[0]===".git")return{ok:!1,error:"cannot write under .git"};let s=ls.default.resolve(n),i=ls.default.resolve(s,t);return i!==s&&!i.startsWith(s+ls.default.sep)?{ok:!1,error:"path escapes the checkout"}:{ok:!0,abs:i,rel:t}}async function ll(n){let e=fb(n.repoPath,n.relPath);if(!e.ok)return{ok:!1,error:e.error};if(so.default.existsSync(e.abs)&&!n.overwrite)return{ok:!1,error:`${e.rel} already exists in this checkout`};so.default.mkdirSync(ls.default.dirname(e.abs),{recursive:!0}),so.default.writeFileSync(e.abs,n.content.endsWith(`
|
|
827
831
|
`)?n.content:n.content+`
|
|
828
|
-
`);let t=s=>new Promise((i,o)=>{(0,Uh.execFile)("git",["-C",n.repoPath,...s],{timeout:12e4},(a,u,c)=>a?o(new Error(c||a.message)):i())}),r="";try{await t(["add",e.rel]),await t(["-c","user.name=Allwright","-c","user.email=runner@allwright.local","commit","-m",n.commitMessage]);try{await t(["push"]),r="committed and pushed to the repo"}catch(s){r="committed locally, but push failed: "+(s instanceof Error?s.message.slice(0,200):"unknown")+" - push it from the server when convenient"}}catch(s){r="file written, but commit failed: "+(s instanceof Error?s.message.slice(0,200):"unknown")+" - commit it from the server when convenient"}return{ok:!0,note:r}}var wr=E(require("node:fs"),1),ul=E(require("node:path"),1),io=require("node:child_process"),Fh=require("node:util");er();bt();var Bh=E(Se(),1),qh=(0,Fh.promisify)(io.execFile);function pv(n){try{return new URL(n).host}catch{return n}}function mv(n){try{return(0,io.execFileSync)("git",["-C",n,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim()}catch{return null}}async function oo(n,e,t=[],r){let s=[],i=n.repos[e.repoName]?.jira,o=i??n.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=pv(o.baseUrl),b=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 ${b} is for ${p}.`,fix:[`allwright jira set "${e.repoName}"`],fixNote:`"${e.repoName}" in that command is this project's REPO NAME - the label that ties the project here to a checkout on the server (the same one used with allwright repo add). Not the Jira key, not a folder path. The command asks for three things for ${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 v=new Ae(o);try{let T=await v.myself();s.push({name:"jira-auth",ok:!0,detail:`authenticated as ${T.displayName} on ${p} (${b})`});try{await v.search(`project = "${e.jiraProjectKey}" ORDER BY created DESC`,1),s.push({name:"jira-project",ok:!0,detail:`project ${e.jiraProjectKey} is readable on ${p}`})}catch(x){s.push({name:"jira-project",ok:!1,detail:`cannot read project ${e.jiraProjectKey} on ${p}: ${qs(x)}`})}}catch(T){s.push({name:"jira-auth",ok:!1,detail:`Jira auth failed on ${p}: ${qs(T)}`})}}}let u=n.repos[e.repoName];if(u&&wr.default.existsSync(u.path)){let p=ul.default.join(u.path,"CLAUDE.md"),b=wr.default.existsSync(p)&&wr.default.readFileSync(p,"utf8").trim().length>0;s.push({name:"memory-file",kind:"content",ok:b,detail:b?"CLAUDE.md present - the agent has project memory":"MISSING: CLAUDE.md at the repo root. Rules can't be enabled until the project has a memory file - it is what makes every run smarter than the last.",...b?{}:{fixNote:"No command needed: the setup step below this one drafts CLAUDE.md by reading the repo, shows it to you, and commits it when you approve. Writing it by hand works too - any honest description of what the project is and how it is built beats an empty file."}});let v=Di(u.path);s.push({name:"deploy-doc",kind:"content",ok:v!==null,detail:v?`${v.path} present - deploy suggestions will follow it`:"MISSING: DEPLOY.md (or .ticketpilot/deploy.md). Environments can't be created until the repo documents how it deploys.",...v?{}:{fixNote:"Only needed if this project will deploy from Allwright. The setup wizard can draft DEPLOY.md the same way it drafts CLAUDE.md - describe how you deploy today (the commands you actually run), and the agent proposes steps a human saves. Skip it if you only want tickets to become pull requests."}})}if(!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(!wr.default.existsSync(u.path))s.push({name:"repo-path",ok:!1,detail:`path does not exist: ${u.path}`});else{let p=wr.default.existsSync(ul.default.join(u.path,".git"));s.push({name:"repo-path",ok:!0,detail:`${u.path}${p?" (git checkout)":" (warning: not a git checkout)"}`})}let c=[...new Set([e.defaultAgent||"claude-code",...r??[]])];for(let p of c){let b=ze(n,p),v=p==="claude-code"?"claude-code":`agent:${p}`;try{let{stdout:T}=await qh(b,["--version"],{timeout:15e3});s.push({name:v,ok:!0,detail:T.trim().slice(0,100)})}catch(T){s.push({name:v,ok:!1,detail:`cannot run "${b}" for agent "${p}": ${qs(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 qh("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: ${qs(p)}`})}let f=Ie(n,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 ${Bh.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(()=>(at(),sr)),b=new p(f),v=await b.whoami(),T=u&&wr.default.existsSync(u.path)?mv(u.path):null,x=T?it(T):null;if(!x)s.push({name:"github-token",ok:!0,detail:`authenticated as ${v} - repo access not checked (no local checkout yet)`});else{let P=await b.repoAccess(x.owner,x.repo);s.push({name:"github-token",ok:P.ok&&P.canPush,detail:P.ok?P.canPush?`${v} has push access to ${x.owner}/${x.repo}`:`${v} can read ${x.owner}/${x.repo} but NOT push to it - implement rules will fail at the push`:`${v} cannot see ${x.owner}/${x.repo}: ${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:qs(p)})}if(t.length){n.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 b=$n(n,e.repoName,p.name),v=p.requiredSecrets.filter(T=>!b[T]&&!process.env[T]);s.push({name:`env:${p.name}`,ok:v.length===0,detail:v.length?`missing secret(s): ${v.join(", ")} - allwright env set "${e.repoName}" "${p.name}" ${v[0]}=...`:`${p.steps.length} step(s), ${p.requiredSecrets.length} secret(s) present`+(p.branch?`, deploys origin/${p.branch}`:"")})}}return s}function qs(n){return(n instanceof Error?n.message:String(n)).slice(0,300)}var _e=new El;_e.name("allwright").description("Allwright runner - runs on YOUR machine, holds YOUR credentials locally, connects outbound-only to the control plane. Your Jira token, Anthropic key and source code never leave this host.").version(mi);function Jh(n){y.info(`Create the token at ${Kt.GITHUB_TOKEN_PERMISSIONS.where}`);for(let e of Kt.GITHUB_TOKEN_PERMISSIONS.steps)y.info(` - ${e}`);y.info(Kt.GITHUB_TOKEN_PERMISSIONS.note),y.info(`Then paste it below for ${n}.`)}_e.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",cl.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 n=>{let e=fn.default.createInterface({input:process.stdin,output:process.stdout}),t=async(r,s,i=!1)=>{if(s)return s;let o=await e.question(`${r}: `);if(!o.trim())throw new Error(`${r} is required`);return o.trim()};try{let r=await t("Control plane URL",n.cpUrl),s=await t("Enrolment token (from the web UI)",n.enrollToken),i=await t("Jira base URL (https://yourorg.atlassian.net)",n.jiraUrl),o=await t("Jira account email",n.jiraEmail),a=await t("Jira API token (create at id.atlassian.com/manage-profile/security/api-tokens)",n.jiraToken,!0),u=Eo.parse({controlPlaneUrl:r,runnerName:n.name,jira:{baseUrl:i,email:o,apiToken:a}}),c=await new Ae(u.jira).myself();y.info(`Jira credential OK - authenticated as ${c.displayName}`),u=await ku(u,s),y.info(`Enrolled as runner "${u.runnerName}" (${u.runnerId})`),y.info(`Credentials saved to ${$t()} (mode 600, this machine only)`),y.info("Next: map your repo with `allwright repo add <repoName> <localPath>`, then `allwright start`")}finally{e.close()}});var dl=_e.command("repo").description("Map control-plane repo names to local checkouts");dl.command("add <repoName> <localPath>").description("Map a repo name (as configured in the web UI) to a local checkout path").action(async(n,e)=>{let t=se();t.repos[n]={path:e},ge(t),y.info(`mapped repo "${n}" -> ${e}`);try{let{originUrl:r}=await Promise.resolve().then(()=>(bt(),Au));y.info(` origin remote: ${await r(e)} - make sure this is the repo you meant`)}catch{y.warn(` could not read an origin remote at ${e} - is it a git checkout?`)}});dl.command("list").description("Show configured repo mappings").action(()=>{let n=se(),e=Object.entries(n.repos);if(!e.length)return y.info("no repos mapped yet");for(let[t,r]of e)y.info(`${t} -> ${r.path}`)});var Yh=_e.command("claude").description("Per-user Claude login profiles - each teammate's runs bill their OWN Claude account");Yh.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 n=>{if(!/^[a-zA-Z0-9._-]+$/.test(n))throw new Error("profile name: letters, digits, dots, dashes and underscores only");let e=se(),t=e.claudeProfiles[n]?.configDir??`${$t().replace(/runner\.json$/,"")}claude-profiles/${n}`;dt.default.mkdirSync(t,{recursive:!0,mode:448}),e.claudeProfiles[n]={configDir:t},ge(e),y.info(`profile "${n}" -> ${t}`),y.info("Opening Claude Code with this profile. In it: run /login, complete the browser flow"),y.info("with the account this profile belongs to, then exit Claude (ctrl+c twice or /exit).");let r=(0,Zt.spawn)(e.claudeBin,[],{env:{...process.env,CLAUDE_CONFIG_DIR:t},stdio:"inherit"});await new Promise(s=>r.on("exit",()=>s())),y.info(`Done. Assign it on the dashboard: Team -> the user -> Claude profile = "${n}".`),kr()});Yh.command("list").description("Show configured Claude profiles and whether each looks logged in").action(()=>{let n=se(),e=Object.entries(n.claudeProfiles);if(y.info("default: this OS user's own Claude login (no profile)"),!e.length)return y.info("no named profiles yet - allwright claude login <name>");for(let[t,r]of e){let s=dt.default.existsSync(r.configDir)&&dt.default.readdirSync(r.configDir).length>0;y.info(`${t} -> ${r.configDir} ${s?"(logged in)":"(NOT logged in yet)"}`)}});dl.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(n=>{let e=se();if(!e.repos[n]){let i=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${n}" - mapped repos: ${i}`)}let t=e.repos[n].path;delete e.repos[n];let r=Object.keys(e.environments).filter(i=>i.startsWith(`${n}:`));for(let i of r)delete e.environments[i];let s=e.auditSchedules.length;e.auditSchedules=e.auditSchedules.filter(i=>i.repoName!==n),ge(e),y.info(`Removed "${n}" (was ${t})`),r.length&&y.info(`Also removed ${r.length} environment secret set(s): ${r.join(", ")}`),e.auditSchedules.length!==s&&y.info("Also removed its audit schedule(s)"),y.info("The checkout on disk was NOT touched - remove it yourself if you want it gone."),y.info("Restart the runner to apply. Dashboard project (if any) is deleted separately there.")});var hl=_e.command("service").description("Run the runner as a system service (starts on boot, restarts on crash)");hl.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(n=>{if(n.print){y.info(`
|
|
829
|
-
`+ia(sa()));return}zu(y)});hl.command("uninstall").description("Stop and remove the systemd service (config/credentials untouched)").action(()=>Du(y));hl.command("status").description("systemctl status for the runner service").action(()=>{(0,Zt.spawn)("systemctl",["status","allwright","--no-pager"],{stdio:"inherit"}).on("exit",e=>process.exit(e??0))});_e.command("update").description("Update the runner to the latest published version (npm install -g allwright@latest). Restart the runner afterwards - and only when no runs are active.").action(async()=>{y.info("Updating: npm install -g allwright@latest");let n=(0,Zt.spawn)("npm",["install","-g","allwright@latest"],{stdio:"inherit"});await new Promise((e,t)=>{n.on("exit",r=>r===0?e():t(new Error(`npm exited with code ${r}`))),n.on("error",t)}),y.info("Updated. Restart the runner service to load the new version (check active runs first).")});var cs=_e.command("jira").description("Per-repo Jira site overrides - for projects living on a different Atlassian site");cs.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 n=>{let e=se();if(!e.repos[n]){let a=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${n}" - mapped repos: ${a}. Run \`allwright repo add\` first.`)}let t=Od(n),r=(t?.jiraSiteUrl??"").trim(),s=r?`https://${r}`:"",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 Ae(a).myself();if(e.repos[n].jira=a,ge(e),y.info(`The token already on this server works on ${r} - authenticated as ${u.displayName}. Saved it for "${n}"; nothing to type.`),t?.jiraProjectKey)try{await new Ae(a).search(`project = "${t.jiraProjectKey}"`,1),y.info(`Project ${t.jiraProjectKey} is readable with it.`)}catch{y.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.`)}kr();return}catch{y.info(`The token already on this server does not work on ${r} - asking for one that does.`)}}let o=fn.default.createInterface({input:process.stdin,output:process.stdout});try{let u=(await o.question(s?`Jira base URL [${s}]: `:"Jira base URL for this repo (https://yourorg.atlassian.net): ")).trim()||s,f=(await o.question(i?`Jira account email [${i}]: `:"Jira account email: ")).trim()||i,p=(await o.question("Jira API token (id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!u||!f||!p)throw new Error("all three values are required");let b={baseUrl:u,email:f,apiToken:p},v=await new Ae(b).myself();y.info(`Jira credential OK - authenticated as ${v.displayName} on ${u}`),e.repos[n].jira=b,ge(e),y.info(`Saved: repo "${n}" now polls ${u} (other repos keep the runner-wide credential)`),kr()}finally{o.close()}});cs.command("set-token").description("Replace the RUNNER-WIDE Jira credential (the one every repo without an override uses). Until now this was only set at init - and Atlassian API tokens expire, which surfaces as boards quietly going empty. Prompts on stdin; validated before saving; applies live, no restart.").action(async()=>{let n=se(),e=fn.default.createInterface({input:process.stdin,output:process.stdout});try{let t=n.jira?.baseUrl??"",r=n.jira?.email??"",s=(await e.question(t?`Jira base URL [${t}]: `:"Jira base URL (https://yourorg.atlassian.net): ")).trim()||t,i=(await e.question(r?`Jira account email [${r}]: `:"Jira account email: ")).trim()||r,o=(await e.question("Jira API token (id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!s||!i||!o)throw new Error("all three values are required");let a={baseUrl:s,email:i,apiToken:o},u=await new Ae(a).myself();n.jira=a,ge(n),y.info(`Jira credential OK - authenticated as ${u.displayName} on ${s}`),y.info(`Saved to ${$t()} (mode 600, this machine only). Repo overrides are untouched.`),kr()}finally{e.close()}});cs.command("show").description("Show which Jira site each repo uses (never prints tokens)").action(()=>{let n=se();y.info(`runner-wide: ${n.jira?`${n.jira.baseUrl} (${n.jira.email})`:"(not configured)"}`);for(let[e,t]of Object.entries(n.repos))y.info(`${e} -> ${t.jira?`${t.jira.baseUrl} (${t.jira.email})`:"(runner-wide credential)"}`)});cs.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 n=>{let e=se(),t=n.trim().toLowerCase();if(!t.includes("@"))throw new Error(`"${n}" doesn't look like an email`);let r=fn.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await r.question(`Their ATLASSIAN account email [${t}]: `)).trim()||t,i=(await r.question("Their Jira API token (they create it at id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!i)throw new Error("API token is required");let o=[e.jira,...Object.values(e.repos).map(c=>c.jira)].filter(c=>!!c),a=new Set,u=!1;for(let c of o)if(!a.has(c.baseUrl)){a.add(c.baseUrl);try{let f=await new Ae({baseUrl:c.baseUrl,email:s,apiToken:i}).myself();y.info(`${c.baseUrl}: OK - authenticated as ${f.displayName}`),u=!0}catch{y.warn(`${c.baseUrl}: this credential does NOT work there (fine if they don't use that site)`)}}if(!u)throw new Error("credential failed on every configured Jira site - nothing saved");e.jiraUsers[t]={email:s,apiToken:i},ge(e),y.info(`Saved. Dashboard actions by ${t} now post to Jira as ${s}. No restart needed.`)}finally{r.close()}});cs.command("user-list").description("Show which Allwright users have their own Jira credential here (never prints tokens)").action(()=>{let n=se(),e=Object.entries(n.jiraUsers);if(!e.length)return y.info("none yet - everyone's dashboard clicks require one: allwright jira user-add <their-ticketpilot-email>");for(let[t,r]of e)y.info(`${t} -> posts to Jira as ${r.email}`)});cs.command("user-remove <ticketpilotEmail>").description("Delete a person's stored Jira credential").action(n=>{let e=se(),t=n.trim().toLowerCase();if(!e.jiraUsers[t])throw new Error(`no credential stored for ${t}`);delete e.jiraUsers[t],ge(e),y.info(`Removed. Dashboard actions by ${t} will now be refused until a new credential is added.`)});var ds=_e.command("github").description("GitHub credential for implement-mode rules");ds.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 n=>{let e=fn.default.createInterface({input:process.stdin,output:process.stdout});try{let t=n.token??void Jh("every repo on this server")??(await e.question("GitHub token: ")).trim();if(!t)throw new Error("token is required");let{GitHubClient:r}=await Promise.resolve().then(()=>(at(),sr)),s=await new r(t).whoami(),i=se();i.github={token:t,login:s},ge(i),y.info(`GitHub token OK - authenticated as ${s}`),y.info(`Saved to ${$t()} (mode 600, this machine only)`)}finally{e.close()}});ds.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 n=>{let e=se();if(!e.repos[n]){let i=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${n}" - mapped repos: ${i}. Run \`allwright repo add\` first.`)}let t=e.github?.token,r=e.repos[n]?.path;if(t&&r&&dt.default.existsSync(r))try{let i=(0,Zt.execFileSync)("git",["-C",r,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim(),o=it(i);if(o){let{GitHubClient:a}=await Promise.resolve().then(()=>(at(),sr)),u=new a(t),c=await u.repoAccess(o.owner,o.repo);if(c.ok&&c.canPush){let f=await u.whoami();y.info(`The shared token on this server already has push access to ${o.owner}/${o.repo} as ${f} - "${n}" needs nothing of its own. Storing a second token here would only give you two to rotate.`),y.info("Want a separately revocable one anyway? Paste it at the prompt below; press Enter to leave things as they are.")}}}catch{}let s=fn.default.createInterface({input:process.stdin,output:process.stdout});try{Jh(`"${n}"`);let i=(await s.question(`GitHub token for "${n}": `)).trim();if(!i&&t){y.info(`Nothing changed - "${n}" keeps using the shared token.`);return}if(!i)throw new Error("token is required");let{GitHubClient:o}=await Promise.resolve().then(()=>(at(),sr)),a=await new o(i).whoami();e.repos[n].github={token:i,login:a},ge(e),y.info(`GitHub token OK - authenticated as ${a}`),y.info(`Saved: repo "${n}" now uses its own token (other repos keep the runner-wide one)`)}finally{s.close()}});ds.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 n=>{let e=se(),t=n.trim().toLowerCase();if(!t.includes("@"))throw new Error(`"${n}" doesn't look like an email`);let r=fn.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await r.question(`GitHub token for ${t}: `)).trim();if(!s)throw new Error("token is required");let{GitHubClient:i}=await Promise.resolve().then(()=>(at(),sr)),o=await new i(s).whoami();e.githubUsers[t]={token:s,login:o},ge(e),y.info(`GitHub token OK - authenticated as ${o}`),y.info(`Saved. Implement runs triggered by ${t} now open PRs as ${o}. No restart needed.`)}finally{r.close()}});ds.command("user-list").description("Show which Allwright users have their own GitHub token here (never prints tokens)").action(()=>{let n=se(),e=Object.entries(n.githubUsers);if(!e.length)return y.info("no per-user GitHub tokens - everyone's PRs use the repo/runner-wide token");for(let[t]of e)y.info(`${t} -> own GitHub token stored`)});ds.command("user-remove <ticketpilotEmail>").description("Delete a person's stored GitHub token (their runs fall back to the shared token)").action(n=>{let e=se(),t=n.trim().toLowerCase();if(!e.githubUsers[t])throw new Error(`no GitHub token stored for ${t}`);delete e.githubUsers[t],ge(e),y.info(`Removed. ${t}'s runs use the repo/runner-wide token again.`)});ds.command("show").description("Show which GitHub token each repo and person would use (never prints tokens)").action(()=>{let n=se();y.info(`runner-wide: ${n.github?.token?"token set":"(not configured)"}`);for(let[t,r]of Object.entries(n.repos))y.info(`${t} -> ${r.github?.token?"own repo token":"runner-wide token"}`);let e=Object.keys(n.githubUsers);y.info(e.length?`per-user tokens: ${e.join(", ")}`:"per-user tokens: (none)")});var fl=_e.command("audit").description("Recurring specialist audits on this runner");fl.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((n,e,t)=>{let r=se();if(!r.repos[n]){let i=Object.keys(r.repos).join(", ")||"(none)";throw new Error(`unknown repo "${n}" - 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");r.auditSchedules=[...r.auditSchedules.filter(i=>!(i.repoName===n&&i.role===e)),{repoName:n,role:e,intervalHours:s}],ge(r),y.info(`Scheduled: ${e} audit of "${n}" every ${s}h. Restart the runner to apply.`)});fl.command("schedules").description("List scheduled audits").action(()=>{let n=se();if(!n.auditSchedules.length)return y.info("no scheduled audits - allwright audit schedule <repo> <role> <hours>");for(let e of n.auditSchedules)y.info(`${e.repoName} \xB7 ${e.role} \xB7 every ${e.intervalHours}h`)});fl.command("unschedule <repoName> <role>").description("Remove a scheduled audit").action((n,e)=>{let t=se(),r=t.auditSchedules.length;if(t.auditSchedules=t.auditSchedules.filter(s=>!(s.repoName===n&&s.role===e)),t.auditSchedules.length===r)throw new Error("no such schedule");ge(t),y.info("Removed. Restart the runner to apply.")});var pl=_e.command("deploy").description("Deployment settings for this machine");pl.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 n=se();n.deploy={enabled:!0},ge(n),y.info("deployments ENABLED on this runner"),y.info("This runner will now execute the deploy steps configured for your environments. Review them in the dashboard before shipping to production."),kr()});pl.command("disable").description("Stop this runner from executing any deploy steps").action(()=>{let n=se();n.deploy={enabled:!1},ge(n),y.info("deployments DISABLED on this runner"),kr()});pl.command("status").description("Show whether deployments are enabled here, and which env secrets are stored").action(()=>{let n=se();y.info(`deployments: ${n.deploy.enabled?"enabled":"disabled"}`);let e=Object.entries(n.environments);if(!e.length)return y.info("no environment secrets stored");for(let[t,r]of e){let s=Object.keys(r.secrets);y.info(`${t}: ${s.length?s.join(", "):"(no secrets)"}`)}});var ml=_e.command("env").description("Per-environment deploy secrets. Values stay on this machine, like your Jira token.");ml.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((n,e,t)=>{let r=se(),s=ti(n,e),i=r.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)}r.environments[s]=i,ge(r),y.info(`stored ${o.length} secret(s) for ${s}: ${o.join(", ")}`),y.info(`Saved to ${$t()} (mode 600, this machine only)`),kr()});ml.command("unset <repoName> <envName> <names...>").description("Remove stored secrets for an environment").action((n,e,t)=>{let r=se(),s=ti(n,e),i=r.environments[s];if(!i)return y.info(`nothing stored for ${s}`);for(let o of t)delete i.secrets[o];r.environments[s]=i,ge(r),y.info(`removed ${t.join(", ")} from ${s}`)});ml.command("list").description("Show which environments have secrets stored here (names only, never values)").action(()=>{let n=se(),e=Object.entries(n.environments);if(!e.length)return y.info("no environment secrets stored");for(let[t,r]of e)y.info(`${t}: ${Object.keys(r.secrets).join(", ")||"(none)"}`)});_e.command("export [file]").description("Back up ALL runner state (config+secrets, knowledge, audits, chats) to one tarball").action(n=>{try{let e=Fl(n);y.info(`Backup written: ${e.file} (${e.entries.length} entries, mode 600)`),y.warn("This file CONTAINS YOUR SECRETS (Jira/GitHub tokens). Keep it private - anyone holding it can act as this runner."),y.info(`Restore on any machine with: allwright import ${us.default.basename(e.file)}`)}catch(e){y.error(e instanceof Error?e.message:String(e)),process.exitCode=1}});_e.command("import <file>").description("Restore runner state from an `export` tarball (existing config is kept as a .bak dir)").action(n=>{let e=Pn();if(e&&jn(e)){y.error("the runner is running - stop it first (systemctl stop allwright, or `allwright stop` for a pid-file daemon), then import."),process.exitCode=1;return}try{let t=Bl(n);y.info(`Restored ${t.restored.length} entries into ${re()}`),t.previousDir&&y.info(`Previous config kept at ${t.previousDir}`),y.info("Start the runner and it will reconnect with the restored identity.")}catch(t){y.error(t instanceof Error?t.message:String(t)),process.exitCode=1}});_e.command("test").description("Check local setup: Jira auth, repo mappings, Claude Code binary").action(async()=>{let n=se(),e=Object.keys(n.repos);if(!n.jira){y.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)"}],r=!0;for(let s of t){let i=await oo(n,s);for(let o of i){if(s.jiraProjectKey==="*"&&o.name==="jira-project")continue;let a=o.ok?"PASS":"FAIL";(o.ok?y.info:y.error)(`[${a}] ${o.name}: ${o.detail}`),r&&=o.ok}}r||(process.exitCode=1)});function kr(){let n=Pn();if(n&&jn(n)&&process.platform!=="win32")try{process.kill(n,"SIGHUP"),y.info("running runner reloaded its config live - no restart needed");return}catch{}y.info("No background runner found to reload. Under systemd: sudo systemctl kill -s HUP allwright - otherwise it applies on the next allwright start.")}function bv(n){if(!n.runnerToken)throw new Error("runner not enrolled - run `allwright init`");if(!n.jira)throw new Error("no Jira credentials - run `allwright init`");let e=Jl();e.ok||(y.warn(`another runner is already running on this machine (pid ${e.pid}). Two runner processes with one identity kick each other off the control plane every second. Stop the other one first: \`allwright stop\` (background runner) or \`sudo systemctl stop allwright\` (service).`),process.exit(1)),process.on("exit",Po);let t=new Ae(n.jira),r=new Map,s=d=>{let m=n.repos[d]?.jira;if(!m)return t;let g=r.get(d);return g||(g=new Ae(m),r.set(d,g)),g},i=new Map,o=(d,m)=>{let g=ju(ye()??n,d,m);switch(g.kind){case"legacy":return{jira:s(d),authored:!1};case"self":return{jira:s(d),authored:!0};case"missing":return{error:g.error};case"user":{let C=`${g.creds.baseUrl}:${g.creds.email}:${g.creds.apiToken.slice(-6)}`,N=i.get(C);return N||(N=new Ae(g.creds),i.set(C,N)),{jira:N,authored:!0}}}},a=new URL("/api/runner/ws",n.controlPlaneUrl);a.protocol=a.protocol==="https:"?"wss:":"ws:";let u=[],c=[],f=[],p,b=null,v={cfg:n,jiraFor:s,transport:null},T=new Set,x=d=>{let m=u.find(C=>C.id===d),g=m&&n.repos[m.repoName];return m&&g?{project:m,repoPath:g.path}:null},P=d=>{let m=u.find(N=>N.id===d),g=n.runnerName?`This runner ("${n.runnerName}")`:"This runner";if(!m)return`${g} does not know that project at all - it may have been deleted, or this runner has not synced yet.`;let C=Object.keys(n.repos).join(", ")||"(none)";return`${g} has no local checkout for "${m.name}" (repo "${m.repoName}"). Repos mapped here: ${C}. Either pin the project to the runner that HAS that repo (Dashboard \u2192 the project \u2192 Edit \u2192 Runner) - do this when several runners are online and the project is unpinned, because then the request goes to whichever one answers first - or map the repo on this machine: allwright repo add ${m.repoName} /path/to/checkout`},I={cfg:n,jiraFor:s,get transport(){return v.transport},lookup:(d,m)=>{let g=x(d),C=f.find(N=>N.projectId===d&&N.name===m);return g&&C?{...g,environment:C}:null}},w=new ro(a.toString(),n.runnerToken,{runnerVersion:mi},{onConfig:d=>{u=d.projects,jd(d.projects),c=d.rules,f=d.environments,p.setConfig(d.projects,d.rules,d.pollingPaused,d.environments)},onDeployFix:async d=>{let m=x(d.projectId);if(!m){w.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:P(d.projectId)});return}let g=Fe(n,m.project,"assist");if("error"in g){w.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:g.error});return}y.info(`investigating failed deploy of "${d.environmentName}" (step: ${d.failedStep||"?"})`);let C=await ld({agent:g,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,steps:d.steps,failedStep:d.failedStep,errorText:d.errorText,cfg:n});w.sendDeploySuggestResult(d.requestId,C)},onProjectTest:async d=>{let m=u.find(C=>C.id===d.projectId);if(!m){w.sendProjectTestResult(d.requestId,!1,[{name:"config",ok:!1,detail:"project not in this runner's synced config yet"}]);return}y.info(`running connection test for project "${m.name}"`);let g=await oo(ye()??n,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));w.sendProjectTestResult(d.requestId,g.every(C=>C.ok),g)},onRuleDiagnose:async d=>{let m=c.find(z=>z.id===d.ruleId),g=m&&u.find(z=>z.id===m.projectId);if(!m||!g){w.sendRuleDiagnoseResult(d.requestId,{checks:[{name:"config",ok:!1,detail:"rule not in this runner's synced config yet"}],matchedCount:0,excludedCount:0,excludedSample:[]});return}y.info(`diagnosing rule "${m.name}"`);let C=await oo(ye()??n,g,m.action.type==="deploy"?f.filter(z=>z.projectId===g.id):[]),N=m.action.type==="implement"?C:C.filter(z=>z.name!=="github-token"),{matchedCount:G,excludedCount:V,excludedSample:ee}=await p.diagnoseRule(m,g);w.sendRuleDiagnoseResult(d.requestId,{checks:N,matchedCount:G,excludedCount:V,excludedSample:ee})},onCancel:d=>{jc(d)?y.info(`run ${d} stopped from the dashboard`):y.warn(`cancel requested for run ${d}, but nothing is running under that id here - it likely finished already`)},onApproved:(d,m)=>{if(ja(d)){nd(I,d).catch(g=>y.error(`deploy approval crashed for ${d}: ${g instanceof Error?g.stack:g}`));return}Es(v,d,m).catch(g=>y.error(`approval handling crashed for ${d}: ${g instanceof Error?g.stack:g}`))},onRetryPush:d=>{let m=Ei(d),g=()=>Bc(v,d).catch(C=>y.error(`retry push crashed for ${d}: ${C instanceof Error?C.stack:C}`));m?p.runOnRepoQueue(m.baseRepoPath,g):g()},onRejected:d=>{if(ja(d)){rd(I,d).catch(m=>y.error(`deploy rejection crashed for ${d}: ${m instanceof Error?m.stack:m}`));return}Fc(v,d).catch(m=>y.error(`rejection handling crashed for ${d}: ${m instanceof Error?m.stack:m}`))},onDeployStart:d=>{let m=`${d.runId}#${d.attempt}`;if(T.has(m))return;T.add(m);let g=x(d.projectId);if(!g){let C=P(d.projectId);y.error(`deploy ${d.runId}: ${C}`),w.send({type:"run.status",runId:d.runId,status:"failed",error:C});return}y.info(`deploy ${d.runId} requested from the dashboard: ${d.issueKey} \u2192 ${d.environment.name}`),p.runOnEnvironmentQueue(d.environment.id,()=>zi({runId:d.runId,project:g.project,environment:d.environment,issueKey:d.issueKey,issueSummary:d.issueSummary,repoPath:g.repoPath,cfg:n,jira:s(g.project.repoName),transport:w,requestedBy:d.requestedBy}).catch(C=>y.error(`deploy crashed for ${d.runId}: ${C instanceof Error?C.stack:C}`)))},onDeploySuggest:async d=>{let m=x(d.projectId);if(!m){w.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:P(d.projectId)});return}let g=Fe(n,m.project,"assist");if("error"in g){w.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:g.error});return}y.info(`asking ${g.adapter.displayName} for "${d.environmentName}" deploy steps in ${m.repoPath}`);let C=await ud({agent:g,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,notes:d.notes,timeoutSeconds:d.timeoutSeconds,cfg:n});w.sendDeploySuggestResult(d.requestId,C)},onEnvPreflight:async d=>{let m=x(d.projectId);if(!m){w.sendEnvPreflightResult(d.requestId,{ok:!1,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project"}]});return}let g=await ad({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,steps:d.steps,requiredSecrets:d.requiredSecrets,workdir:d.workdir,branch:d.branch,publicUrl:d.publicUrl,cfg:n});w.sendEnvPreflightResult(d.requestId,g)},onChatTurn:async d=>{let m=x(d.projectId);if(!m){w.sendChatTurnResult(d.requestId,{ok:!1,sessionId:d.sessionId??"",reply:"",error:P(d.projectId)});return}let g=d.sessionId||(0,Bs.randomUUID)(),C=!d.sessionId,N=C?0:Ps(g)?.messages.length??0,G=!1,V=0,ee="";if(!C&&N>=kd){let le=await xd(m,g,n);if(le)G=!0,V=N,ee=le,g=(0,Bs.randomUUID)(),C=!0,y.info(`chat compacted: ${N} message(s) summarized into a fresh session`);else if(N>=Sd){w.sendChatTurnResult(d.requestId,{ok:!1,sessionId:g,reply:"",error:"this chat is very long and could not be compacted automatically - start a new chat (it keeps the repo knowledge; only the conversation resets)."});return}}let z=d.files.length?Hl(m.repoPath,d.requestId,d.files):null,L="```",oe=C?`You are the project assistant for "${m.project.name}" - this working directory is its repository, and you have read-only access.
|
|
832
|
+
`);let t=s=>new Promise((i,o)=>{(0,Uh.execFile)("git",["-C",n.repoPath,...s],{timeout:12e4},(a,u,c)=>a?o(new Error(c||a.message)):i())}),r="";try{await t(["add",e.rel]),await t(["-c","user.name=Allwright","-c","user.email=runner@allwright.local","commit","-m",n.commitMessage]);try{await t(["push"]),r="committed and pushed to the repo"}catch(s){r="committed locally, but push failed: "+(s instanceof Error?s.message.slice(0,200):"unknown")+" - push it from the server when convenient"}}catch(s){r="file written, but commit failed: "+(s instanceof Error?s.message.slice(0,200):"unknown")+" - commit it from the server when convenient"}return{ok:!0,note:r}}var wr=E(require("node:fs"),1),ul=E(require("node:path"),1),io=require("node:child_process"),Fh=require("node:util");er();vt();var Bh=E(Se(),1),qh=(0,Fh.promisify)(io.execFile);function pb(n){try{return new URL(n).host}catch{return n}}function mb(n){try{return(0,io.execFileSync)("git",["-C",n,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim()}catch{return null}}async function oo(n,e,t=[],r){let s=[],i=n.repos[e.repoName]?.jira,o=i??n.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=pb(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 b=new Ae(o);try{let T=await b.myself();s.push({name:"jira-auth",ok:!0,detail:`authenticated as ${T.displayName} on ${p} (${v})`});try{await b.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}: ${qs(x)}`})}}catch(T){s.push({name:"jira-auth",ok:!1,detail:`Jira auth failed on ${p}: ${qs(T)}`})}}}let u=n.repos[e.repoName];if(u&&wr.default.existsSync(u.path)){let p=ul.default.join(u.path,"CLAUDE.md"),v=wr.default.existsSync(p)&&wr.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 b=Di(u.path);s.push({name:"deploy-doc",kind:"content",ok:b!==null,detail:b?`${b.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.",...b?{}:{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(!wr.default.existsSync(u.path))s.push({name:"repo-path",ok:!1,detail:`path does not exist: ${u.path}`});else{let p=wr.default.existsSync(ul.default.join(u.path,".git"));s.push({name:"repo-path",ok:!0,detail:`${u.path}${p?" (git checkout)":" (warning: not a git checkout)"}`})}let c=[...new Set([e.defaultAgent||"claude-code",...r??[]])];for(let p of c){let v=ze(n,p),b=p==="claude-code"?"claude-code":`agent:${p}`;try{let{stdout:T}=await qh(v,["--version"],{timeout:15e3});s.push({name:b,ok:!0,detail:T.trim().slice(0,100)})}catch(T){s.push({name:b,ok:!1,detail:`cannot run "${v}" for agent "${p}": ${qs(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 qh("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: ${qs(p)}`})}let f=Ie(n,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 ${Bh.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(()=>(at(),sr)),v=new p(f),b=await v.whoami(),T=u&&wr.default.existsSync(u.path)?mb(u.path):null,x=T?it(T):null;if(!x)s.push({name:"github-token",ok:!0,detail:`authenticated as ${b} - 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?`${b} has push access to ${x.owner}/${x.repo}`:`${b} can read ${x.owner}/${x.repo} but NOT push to it - implement rules will fail at the push`:`${b} 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:qs(p)})}if(t.length){n.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=$n(n,e.repoName,p.name),b=p.requiredSecrets.filter(T=>!v[T]&&!process.env[T]);s.push({name:`env:${p.name}`,ok:b.length===0,detail:b.length?`missing secret(s): ${b.join(", ")} - allwright env set "${e.repoName}" "${p.name}" ${b[0]}=...`:`${p.steps.length} step(s), ${p.requiredSecrets.length} secret(s) present`+(p.branch?`, deploys origin/${p.branch}`:"")})}}return s}function qs(n){return(n instanceof Error?n.message:String(n)).slice(0,300)}var _e=new El;_e.name("allwright").description("Allwright runner - runs on YOUR machine, holds YOUR credentials locally, connects outbound-only to the control plane. Your Jira token, Anthropic key and source code never leave this host.").version(mi);function Jh(n){y.info(`Create the token at ${Kt.GITHUB_TOKEN_PERMISSIONS.where}`);for(let e of Kt.GITHUB_TOKEN_PERMISSIONS.steps)y.info(` - ${e}`);y.info(Kt.GITHUB_TOKEN_PERMISSIONS.note),y.info(`Then paste it below for ${n}.`)}_e.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",cl.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 n=>{let e=fn.default.createInterface({input:process.stdin,output:process.stdout}),t=async(r,s,i=!1)=>{if(s)return s;let o=await e.question(`${r}: `);if(!o.trim())throw new Error(`${r} is required`);return o.trim()};try{let r=await t("Control plane URL",n.cpUrl),s=await t("Enrolment token (from the web UI)",n.enrollToken),i=await t("Jira base URL (https://yourorg.atlassian.net)",n.jiraUrl),o=await t("Jira account email",n.jiraEmail),a=await t("Jira API token (create at id.atlassian.com/manage-profile/security/api-tokens)",n.jiraToken,!0),u=Eo.parse({controlPlaneUrl:r,runnerName:n.name,jira:{baseUrl:i,email:o,apiToken:a}}),c=await new Ae(u.jira).myself();y.info(`Jira credential OK - authenticated as ${c.displayName}`),u=await ku(u,s),y.info(`Enrolled as runner "${u.runnerName}" (${u.runnerId})`),y.info(`Credentials saved to ${$t()} (mode 600, this machine only)`),y.info("Next: map your repo with `allwright repo add <repoName> <localPath>`, then `allwright start`")}finally{e.close()}});var dl=_e.command("repo").description("Map control-plane repo names to local checkouts");dl.command("add <repoName> <localPath>").description("Map a repo name (as configured in the web UI) to a local checkout path").action(async(n,e)=>{let t=se();t.repos[n]={path:e},ge(t),y.info(`mapped repo "${n}" -> ${e}`);try{let{originUrl:r}=await Promise.resolve().then(()=>(vt(),Au));y.info(` origin remote: ${await r(e)} - make sure this is the repo you meant`)}catch{y.warn(` could not read an origin remote at ${e} - is it a git checkout?`)}});dl.command("list").description("Show configured repo mappings").action(()=>{let n=se(),e=Object.entries(n.repos);if(!e.length)return y.info("no repos mapped yet");for(let[t,r]of e)y.info(`${t} -> ${r.path}`)});var Yh=_e.command("claude").description("Per-user Claude login profiles - each teammate's runs bill their OWN Claude account");Yh.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 n=>{if(!/^[a-zA-Z0-9._-]+$/.test(n))throw new Error("profile name: letters, digits, dots, dashes and underscores only");let e=se(),t=e.claudeProfiles[n]?.configDir??`${$t().replace(/runner\.json$/,"")}claude-profiles/${n}`;dt.default.mkdirSync(t,{recursive:!0,mode:448}),e.claudeProfiles[n]={configDir:t},ge(e),y.info(`profile "${n}" -> ${t}`),y.info("Opening Claude Code with this profile. In it: run /login, complete the browser flow"),y.info("with the account this profile belongs to, then exit Claude (ctrl+c twice or /exit).");let r=(0,Zt.spawn)(e.claudeBin,[],{env:{...process.env,CLAUDE_CONFIG_DIR:t},stdio:"inherit"});await new Promise(s=>r.on("exit",()=>s())),y.info(`Done. Assign it on the dashboard: Team -> the user -> Claude profile = "${n}".`),kr()});Yh.command("list").description("Show configured Claude profiles and whether each looks logged in").action(()=>{let n=se(),e=Object.entries(n.claudeProfiles);if(y.info("default: this OS user's own Claude login (no profile)"),!e.length)return y.info("no named profiles yet - allwright claude login <name>");for(let[t,r]of e){let s=dt.default.existsSync(r.configDir)&&dt.default.readdirSync(r.configDir).length>0;y.info(`${t} -> ${r.configDir} ${s?"(logged in)":"(NOT logged in yet)"}`)}});dl.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(n=>{let e=se();if(!e.repos[n]){let i=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${n}" - mapped repos: ${i}`)}let t=e.repos[n].path;delete e.repos[n];let r=Object.keys(e.environments).filter(i=>i.startsWith(`${n}:`));for(let i of r)delete e.environments[i];let s=e.auditSchedules.length;e.auditSchedules=e.auditSchedules.filter(i=>i.repoName!==n),ge(e),y.info(`Removed "${n}" (was ${t})`),r.length&&y.info(`Also removed ${r.length} environment secret set(s): ${r.join(", ")}`),e.auditSchedules.length!==s&&y.info("Also removed its audit schedule(s)"),y.info("The checkout on disk was NOT touched - remove it yourself if you want it gone."),y.info("Restart the runner to apply. Dashboard project (if any) is deleted separately there.")});var hl=_e.command("service").description("Run the runner as a system service (starts on boot, restarts on crash)");hl.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(n=>{if(n.print){y.info(`
|
|
833
|
+
`+ia(sa()));return}zu(y)});hl.command("uninstall").description("Stop and remove the systemd service (config/credentials untouched)").action(()=>Du(y));hl.command("status").description("systemctl status for the runner service").action(()=>{(0,Zt.spawn)("systemctl",["status","allwright","--no-pager"],{stdio:"inherit"}).on("exit",e=>process.exit(e??0))});_e.command("update").description("Update the runner to the latest published version (npm install -g allwright@latest). Restart the runner afterwards - and only when no runs are active.").action(async()=>{y.info("Updating: npm install -g allwright@latest");let n=(0,Zt.spawn)("npm",["install","-g","allwright@latest"],{stdio:"inherit"});await new Promise((e,t)=>{n.on("exit",r=>r===0?e():t(new Error(`npm exited with code ${r}`))),n.on("error",t)}),y.info("Updated. Restart the runner service to load the new version (check active runs first).")});var cs=_e.command("jira").description("Per-repo Jira site overrides - for projects living on a different Atlassian site");cs.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 n=>{let e=se();if(!e.repos[n]){let a=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${n}" - mapped repos: ${a}. Run \`allwright repo add\` first.`)}let t=Od(n),r=(t?.jiraSiteUrl??"").trim(),s=r?`https://${r}`:"",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 Ae(a).myself();if(e.repos[n].jira=a,ge(e),y.info(`The token already on this server works on ${r} - authenticated as ${u.displayName}. Saved it for "${n}"; nothing to type.`),t?.jiraProjectKey)try{await new Ae(a).search(`project = "${t.jiraProjectKey}"`,1),y.info(`Project ${t.jiraProjectKey} is readable with it.`)}catch{y.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.`)}kr();return}catch{y.info(`The token already on this server does not work on ${r} - asking for one that does.`)}}let o=fn.default.createInterface({input:process.stdin,output:process.stdout});try{let 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},b=await new Ae(v).myself();y.info(`Jira credential OK - authenticated as ${b.displayName} on ${u}`),e.repos[n].jira=v,ge(e),y.info(`Saved: repo "${n}" now polls ${u} (other repos keep the runner-wide credential)`),kr()}finally{o.close()}});cs.command("set-token").description("Replace the RUNNER-WIDE Jira credential (the one every repo without an override uses). Until now this was only set at init - and Atlassian API tokens expire, which surfaces as boards quietly going empty. Prompts on stdin; validated before saving; applies live, no restart.").action(async()=>{let n=se(),e=fn.default.createInterface({input:process.stdin,output:process.stdout});try{let t=n.jira?.baseUrl??"",r=n.jira?.email??"",s=(await e.question(t?`Jira base URL [${t}]: `:"Jira base URL (https://yourorg.atlassian.net): ")).trim()||t,i=(await e.question(r?`Jira account email [${r}]: `:"Jira account email: ")).trim()||r,o=(await e.question("Jira API token (id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!s||!i||!o)throw new Error("all three values are required");let a={baseUrl:s,email:i,apiToken:o},u=await new Ae(a).myself();n.jira=a,ge(n),y.info(`Jira credential OK - authenticated as ${u.displayName} on ${s}`),y.info(`Saved to ${$t()} (mode 600, this machine only). Repo overrides are untouched.`),kr()}finally{e.close()}});cs.command("show").description("Show which Jira site each repo uses (never prints tokens)").action(()=>{let n=se();y.info(`runner-wide: ${n.jira?`${n.jira.baseUrl} (${n.jira.email})`:"(not configured)"}`);for(let[e,t]of Object.entries(n.repos))y.info(`${e} -> ${t.jira?`${t.jira.baseUrl} (${t.jira.email})`:"(runner-wide credential)"}`)});cs.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 n=>{let e=se(),t=n.trim().toLowerCase();if(!t.includes("@"))throw new Error(`"${n}" doesn't look like an email`);let r=fn.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await r.question(`Their ATLASSIAN account email [${t}]: `)).trim()||t,i=(await r.question("Their Jira API token (they create it at id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!i)throw new Error("API token is required");let o=[e.jira,...Object.values(e.repos).map(c=>c.jira)].filter(c=>!!c),a=new Set,u=!1;for(let c of o)if(!a.has(c.baseUrl)){a.add(c.baseUrl);try{let f=await new Ae({baseUrl:c.baseUrl,email:s,apiToken:i}).myself();y.info(`${c.baseUrl}: OK - authenticated as ${f.displayName}`),u=!0}catch{y.warn(`${c.baseUrl}: this credential does NOT work there (fine if they don't use that site)`)}}if(!u)throw new Error("credential failed on every configured Jira site - nothing saved");e.jiraUsers[t]={email:s,apiToken:i},ge(e),y.info(`Saved. Dashboard actions by ${t} now post to Jira as ${s}. No restart needed.`)}finally{r.close()}});cs.command("user-list").description("Show which Allwright users have their own Jira credential here (never prints tokens)").action(()=>{let n=se(),e=Object.entries(n.jiraUsers);if(!e.length)return y.info("none yet - everyone's dashboard clicks require one: allwright jira user-add <their-ticketpilot-email>");for(let[t,r]of e)y.info(`${t} -> posts to Jira as ${r.email}`)});cs.command("user-remove <ticketpilotEmail>").description("Delete a person's stored Jira credential").action(n=>{let e=se(),t=n.trim().toLowerCase();if(!e.jiraUsers[t])throw new Error(`no credential stored for ${t}`);delete e.jiraUsers[t],ge(e),y.info(`Removed. Dashboard actions by ${t} will now be refused until a new credential is added.`)});var ds=_e.command("github").description("GitHub credential for implement-mode rules");ds.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 n=>{let e=fn.default.createInterface({input:process.stdin,output:process.stdout});try{let t=n.token??void Jh("every repo on this server")??(await e.question("GitHub token: ")).trim();if(!t)throw new Error("token is required");let{GitHubClient:r}=await Promise.resolve().then(()=>(at(),sr)),s=await new r(t).whoami(),i=se();i.github={token:t,login:s},ge(i),y.info(`GitHub token OK - authenticated as ${s}`),y.info(`Saved to ${$t()} (mode 600, this machine only)`)}finally{e.close()}});ds.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 n=>{let e=se();if(!e.repos[n]){let i=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${n}" - mapped repos: ${i}. Run \`allwright repo add\` first.`)}let t=e.github?.token,r=e.repos[n]?.path;if(t&&r&&dt.default.existsSync(r))try{let i=(0,Zt.execFileSync)("git",["-C",r,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim(),o=it(i);if(o){let{GitHubClient:a}=await Promise.resolve().then(()=>(at(),sr)),u=new a(t),c=await u.repoAccess(o.owner,o.repo);if(c.ok&&c.canPush){let f=await u.whoami();y.info(`The shared token on this server already has push access to ${o.owner}/${o.repo} as ${f} - "${n}" needs nothing of its own. Storing a second token here would only give you two to rotate.`),y.info("Want a separately revocable one anyway? Paste it at the prompt below; press Enter to leave things as they are.")}}}catch{}let s=fn.default.createInterface({input:process.stdin,output:process.stdout});try{Jh(`"${n}"`);let i=(await s.question(`GitHub token for "${n}": `)).trim();if(!i&&t){y.info(`Nothing changed - "${n}" keeps using the shared token.`);return}if(!i)throw new Error("token is required");let{GitHubClient:o}=await Promise.resolve().then(()=>(at(),sr)),a=await new o(i).whoami();e.repos[n].github={token:i,login:a},ge(e),y.info(`GitHub token OK - authenticated as ${a}`),y.info(`Saved: repo "${n}" now uses its own token (other repos keep the runner-wide one)`)}finally{s.close()}});ds.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 n=>{let e=se(),t=n.trim().toLowerCase();if(!t.includes("@"))throw new Error(`"${n}" doesn't look like an email`);let r=fn.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await r.question(`GitHub token for ${t}: `)).trim();if(!s)throw new Error("token is required");let{GitHubClient:i}=await Promise.resolve().then(()=>(at(),sr)),o=await new i(s).whoami();e.githubUsers[t]={token:s,login:o},ge(e),y.info(`GitHub token OK - authenticated as ${o}`),y.info(`Saved. Implement runs triggered by ${t} now open PRs as ${o}. No restart needed.`)}finally{r.close()}});ds.command("user-list").description("Show which Allwright users have their own GitHub token here (never prints tokens)").action(()=>{let n=se(),e=Object.entries(n.githubUsers);if(!e.length)return y.info("no per-user GitHub tokens - everyone's PRs use the repo/runner-wide token");for(let[t]of e)y.info(`${t} -> own GitHub token stored`)});ds.command("user-remove <ticketpilotEmail>").description("Delete a person's stored GitHub token (their runs fall back to the shared token)").action(n=>{let e=se(),t=n.trim().toLowerCase();if(!e.githubUsers[t])throw new Error(`no GitHub token stored for ${t}`);delete e.githubUsers[t],ge(e),y.info(`Removed. ${t}'s runs use the repo/runner-wide token again.`)});ds.command("show").description("Show which GitHub token each repo and person would use (never prints tokens)").action(()=>{let n=se();y.info(`runner-wide: ${n.github?.token?"token set":"(not configured)"}`);for(let[t,r]of Object.entries(n.repos))y.info(`${t} -> ${r.github?.token?"own repo token":"runner-wide token"}`);let e=Object.keys(n.githubUsers);y.info(e.length?`per-user tokens: ${e.join(", ")}`:"per-user tokens: (none)")});var fl=_e.command("audit").description("Recurring specialist audits on this runner");fl.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((n,e,t)=>{let r=se();if(!r.repos[n]){let i=Object.keys(r.repos).join(", ")||"(none)";throw new Error(`unknown repo "${n}" - 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");r.auditSchedules=[...r.auditSchedules.filter(i=>!(i.repoName===n&&i.role===e)),{repoName:n,role:e,intervalHours:s}],ge(r),y.info(`Scheduled: ${e} audit of "${n}" every ${s}h. Restart the runner to apply.`)});fl.command("schedules").description("List scheduled audits").action(()=>{let n=se();if(!n.auditSchedules.length)return y.info("no scheduled audits - allwright audit schedule <repo> <role> <hours>");for(let e of n.auditSchedules)y.info(`${e.repoName} \xB7 ${e.role} \xB7 every ${e.intervalHours}h`)});fl.command("unschedule <repoName> <role>").description("Remove a scheduled audit").action((n,e)=>{let t=se(),r=t.auditSchedules.length;if(t.auditSchedules=t.auditSchedules.filter(s=>!(s.repoName===n&&s.role===e)),t.auditSchedules.length===r)throw new Error("no such schedule");ge(t),y.info("Removed. Restart the runner to apply.")});var pl=_e.command("deploy").description("Deployment settings for this machine");pl.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 n=se();n.deploy={enabled:!0},ge(n),y.info("deployments ENABLED on this runner"),y.info("This runner will now execute the deploy steps configured for your environments. Review them in the dashboard before shipping to production."),kr()});pl.command("disable").description("Stop this runner from executing any deploy steps").action(()=>{let n=se();n.deploy={enabled:!1},ge(n),y.info("deployments DISABLED on this runner"),kr()});pl.command("status").description("Show whether deployments are enabled here, and which env secrets are stored").action(()=>{let n=se();y.info(`deployments: ${n.deploy.enabled?"enabled":"disabled"}`);let e=Object.entries(n.environments);if(!e.length)return y.info("no environment secrets stored");for(let[t,r]of e){let s=Object.keys(r.secrets);y.info(`${t}: ${s.length?s.join(", "):"(no secrets)"}`)}});var ml=_e.command("env").description("Per-environment deploy secrets. Values stay on this machine, like your Jira token.");ml.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((n,e,t)=>{let r=se(),s=ti(n,e),i=r.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)}r.environments[s]=i,ge(r),y.info(`stored ${o.length} secret(s) for ${s}: ${o.join(", ")}`),y.info(`Saved to ${$t()} (mode 600, this machine only)`),kr()});ml.command("unset <repoName> <envName> <names...>").description("Remove stored secrets for an environment").action((n,e,t)=>{let r=se(),s=ti(n,e),i=r.environments[s];if(!i)return y.info(`nothing stored for ${s}`);for(let o of t)delete i.secrets[o];r.environments[s]=i,ge(r),y.info(`removed ${t.join(", ")} from ${s}`)});ml.command("list").description("Show which environments have secrets stored here (names only, never values)").action(()=>{let n=se(),e=Object.entries(n.environments);if(!e.length)return y.info("no environment secrets stored");for(let[t,r]of e)y.info(`${t}: ${Object.keys(r.secrets).join(", ")||"(none)"}`)});_e.command("export [file]").description("Back up ALL runner state (config+secrets, knowledge, audits, chats) to one tarball").action(n=>{try{let e=Fl(n);y.info(`Backup written: ${e.file} (${e.entries.length} entries, mode 600)`),y.warn("This file CONTAINS YOUR SECRETS (Jira/GitHub tokens). Keep it private - anyone holding it can act as this runner."),y.info(`Restore on any machine with: allwright import ${us.default.basename(e.file)}`)}catch(e){y.error(e instanceof Error?e.message:String(e)),process.exitCode=1}});_e.command("import <file>").description("Restore runner state from an `export` tarball (existing config is kept as a .bak dir)").action(n=>{let e=Pn();if(e&&jn(e)){y.error("the runner is running - stop it first (systemctl stop allwright, or `allwright stop` for a pid-file daemon), then import."),process.exitCode=1;return}try{let t=Bl(n);y.info(`Restored ${t.restored.length} entries into ${re()}`),t.previousDir&&y.info(`Previous config kept at ${t.previousDir}`),y.info("Start the runner and it will reconnect with the restored identity.")}catch(t){y.error(t instanceof Error?t.message:String(t)),process.exitCode=1}});_e.command("test").description("Check local setup: Jira auth, repo mappings, Claude Code binary").action(async()=>{let n=se(),e=Object.keys(n.repos);if(!n.jira){y.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)"}],r=!0;for(let s of t){let i=await oo(n,s);for(let o of i){if(s.jiraProjectKey==="*"&&o.name==="jira-project")continue;let a=o.ok?"PASS":"FAIL";(o.ok?y.info:y.error)(`[${a}] ${o.name}: ${o.detail}`),r&&=o.ok}}r||(process.exitCode=1)});function kr(){let n=Pn();if(n&&jn(n)&&process.platform!=="win32")try{process.kill(n,"SIGHUP"),y.info("running runner reloaded its config live - no restart needed");return}catch{}y.info("No background runner found to reload. Under systemd: sudo systemctl kill -s HUP allwright - otherwise it applies on the next allwright start.")}function vb(n){if(!n.runnerToken)throw new Error("runner not enrolled - run `allwright init`");if(!n.jira)throw new Error("no Jira credentials - run `allwright init`");let e=Jl();e.ok||(y.warn(`another runner is already running on this machine (pid ${e.pid}). Two runner processes with one identity kick each other off the control plane every second. Stop the other one first: \`allwright stop\` (background runner) or \`sudo systemctl stop allwright\` (service).`),process.exit(1)),process.on("exit",Po);let t=new Ae(n.jira),r=new Map,s=d=>{let m=n.repos[d]?.jira;if(!m)return t;let g=r.get(d);return g||(g=new Ae(m),r.set(d,g)),g},i=new Map,o=(d,m)=>{let g=ju(ye()??n,d,m);switch(g.kind){case"legacy":return{jira:s(d),authored:!1};case"self":return{jira:s(d),authored:!0};case"missing":return{error:g.error};case"user":{let C=`${g.creds.baseUrl}:${g.creds.email}:${g.creds.apiToken.slice(-6)}`,N=i.get(C);return N||(N=new Ae(g.creds),i.set(C,N)),{jira:N,authored:!0}}}},a=new URL("/api/runner/ws",n.controlPlaneUrl);a.protocol=a.protocol==="https:"?"wss:":"ws:";let u=[],c=[],f=[],p,v=null,b={cfg:n,jiraFor:s,transport:null},T=new Set,x=d=>{let m=u.find(C=>C.id===d),g=m&&n.repos[m.repoName];return m&&g?{project:m,repoPath:g.path}:null},P=d=>{let m=u.find(N=>N.id===d),g=n.runnerName?`This runner ("${n.runnerName}")`:"This runner";if(!m)return`${g} does not know that project at all - it may have been deleted, or this runner has not synced yet.`;let C=Object.keys(n.repos).join(", ")||"(none)";return`${g} has no local checkout for "${m.name}" (repo "${m.repoName}"). Repos mapped here: ${C}. Either pin the project to the runner that HAS that repo (Dashboard \u2192 the project \u2192 Edit \u2192 Runner) - do this when several runners are online and the project is unpinned, because then the request goes to whichever one answers first - or map the repo on this machine: allwright repo add ${m.repoName} /path/to/checkout`},I={cfg:n,jiraFor:s,get transport(){return b.transport},lookup:(d,m)=>{let g=x(d),C=f.find(N=>N.projectId===d&&N.name===m);return g&&C?{...g,environment:C}:null}},w=new ro(a.toString(),n.runnerToken,{runnerVersion:mi},{onConfig:d=>{u=d.projects,jd(d.projects),c=d.rules,f=d.environments,p.setConfig(d.projects,d.rules,d.pollingPaused,d.environments)},onDeployFix:async d=>{let m=x(d.projectId);if(!m){w.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:P(d.projectId)});return}let g=Fe(n,m.project,"assist");if("error"in g){w.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:g.error});return}y.info(`investigating failed deploy of "${d.environmentName}" (step: ${d.failedStep||"?"})`);let C=await ld({agent:g,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,steps:d.steps,failedStep:d.failedStep,errorText:d.errorText,cfg:n});w.sendDeploySuggestResult(d.requestId,C)},onProjectTest:async d=>{let m=u.find(C=>C.id===d.projectId);if(!m){w.sendProjectTestResult(d.requestId,!1,[{name:"config",ok:!1,detail:"project not in this runner's synced config yet"}]);return}y.info(`running connection test for project "${m.name}"`);let g=await oo(ye()??n,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));w.sendProjectTestResult(d.requestId,g.every(C=>C.ok),g)},onRuleDiagnose:async d=>{let m=c.find(z=>z.id===d.ruleId),g=m&&u.find(z=>z.id===m.projectId);if(!m||!g){w.sendRuleDiagnoseResult(d.requestId,{checks:[{name:"config",ok:!1,detail:"rule not in this runner's synced config yet"}],matchedCount:0,excludedCount:0,excludedSample:[]});return}y.info(`diagnosing rule "${m.name}"`);let C=await oo(ye()??n,g,m.action.type==="deploy"?f.filter(z=>z.projectId===g.id):[]),N=m.action.type==="implement"?C:C.filter(z=>z.name!=="github-token"),{matchedCount:G,excludedCount:V,excludedSample:ee}=await p.diagnoseRule(m,g);w.sendRuleDiagnoseResult(d.requestId,{checks:N,matchedCount:G,excludedCount:V,excludedSample:ee})},onCancel:d=>{jc(d)?y.info(`run ${d} stopped from the dashboard`):y.warn(`cancel requested for run ${d}, but nothing is running under that id here - it likely finished already`)},onApproved:(d,m)=>{if(ja(d)){nd(I,d).catch(g=>y.error(`deploy approval crashed for ${d}: ${g instanceof Error?g.stack:g}`));return}Es(b,d,m).catch(g=>y.error(`approval handling crashed for ${d}: ${g instanceof Error?g.stack:g}`))},onRetryPush:d=>{let m=Ei(d),g=()=>Bc(b,d).catch(C=>y.error(`retry push crashed for ${d}: ${C instanceof Error?C.stack:C}`));m?p.runOnRepoQueue(m.baseRepoPath,g):g()},onRejected:d=>{if(ja(d)){rd(I,d).catch(m=>y.error(`deploy rejection crashed for ${d}: ${m instanceof Error?m.stack:m}`));return}Fc(b,d).catch(m=>y.error(`rejection handling crashed for ${d}: ${m instanceof Error?m.stack:m}`))},onDeployStart:d=>{let m=`${d.runId}#${d.attempt}`;if(T.has(m))return;T.add(m);let g=x(d.projectId);if(!g){let C=P(d.projectId);y.error(`deploy ${d.runId}: ${C}`),w.send({type:"run.status",runId:d.runId,status:"failed",error:C});return}y.info(`deploy ${d.runId} requested from the dashboard: ${d.issueKey} \u2192 ${d.environment.name}`),p.runOnEnvironmentQueue(d.environment.id,()=>zi({runId:d.runId,project:g.project,environment:d.environment,issueKey:d.issueKey,issueSummary:d.issueSummary,repoPath:g.repoPath,cfg:n,jira:s(g.project.repoName),transport:w,requestedBy:d.requestedBy}).catch(C=>y.error(`deploy crashed for ${d.runId}: ${C instanceof Error?C.stack:C}`)))},onDeploySuggest:async d=>{let m=x(d.projectId);if(!m){w.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:P(d.projectId)});return}let g=Fe(n,m.project,"assist");if("error"in g){w.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:g.error});return}y.info(`asking ${g.adapter.displayName} for "${d.environmentName}" deploy steps in ${m.repoPath}`);let C=await ud({agent:g,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,notes:d.notes,timeoutSeconds:d.timeoutSeconds,cfg:n});w.sendDeploySuggestResult(d.requestId,C)},onEnvPreflight:async d=>{let m=x(d.projectId);if(!m){w.sendEnvPreflightResult(d.requestId,{ok:!1,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project"}]});return}let g=await ad({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,steps:d.steps,requiredSecrets:d.requiredSecrets,workdir:d.workdir,branch:d.branch,publicUrl:d.publicUrl,cfg:n});w.sendEnvPreflightResult(d.requestId,g)},onChatTurn:async d=>{let m=x(d.projectId);if(!m){w.sendChatTurnResult(d.requestId,{ok:!1,sessionId:d.sessionId??"",reply:"",error:P(d.projectId)});return}let g=d.sessionId||(0,Bs.randomUUID)(),C=!d.sessionId,N=C?0:Ps(g)?.messages.length??0,G=!1,V=0,ee="";if(!C&&N>=kd){let le=await xd(m,g,n);if(le)G=!0,V=N,ee=le,g=(0,Bs.randomUUID)(),C=!0,y.info(`chat compacted: ${N} message(s) summarized into a fresh session`);else if(N>=Sd){w.sendChatTurnResult(d.requestId,{ok:!1,sessionId:g,reply:"",error:"this chat is very long and could not be compacted automatically - start a new chat (it keeps the repo knowledge; only the conversation resets)."});return}}let z=d.files.length?Hl(m.repoPath,d.requestId,d.files):null,L="```",oe=C?`You are the project assistant for "${m.project.name}" - this working directory is its repository, and you have read-only access.
|
|
830
834
|
|
|
831
835
|
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.
|
|
832
836
|
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.
|
|
@@ -853,11 +857,11 @@ EXCEPTION - big requirements: when the user asks for an epic with sub-tickets, o
|
|
|
853
857
|
This conversation was already running and has been compacted. Everything agreed so far, in summary form - treat it as established, do not re-ask:
|
|
854
858
|
${ee}
|
|
855
859
|
`:"")+`
|
|
856
|
-
${d.userName||"The user"} says: ${d.message}`+(z?.section??""):`${d.userName||"The user"} says: ${d.message}`+(z?.section??""),fe=0,de=[],ae;try{let le=Fe(n,m.project,"chat");if("error"in le){w.sendChatTurnResult(d.requestId,{ok:!1,sessionId:g,reply:"",error:le.error});return}ae=await le.adapter.run({repoPath:m.repoPath,prompt:oe,timeoutSeconds:180,bin:le.bin,mode:"read_only",maxTurns:25,model:d.model||le.adapter.fastModel,sessionId:g,resume:!C,onLog:(
|
|
860
|
+
${d.userName||"The user"} says: ${d.message}`+(z?.section??""):`${d.userName||"The user"} says: ${d.message}`+(z?.section??""),fe=0,de=[],ae;try{let le=Fe(n,m.project,"chat");if("error"in le){w.sendChatTurnResult(d.requestId,{ok:!1,sessionId:g,reply:"",error:le.error});return}ae=await le.adapter.run({repoPath:m.repoPath,prompt:oe,timeoutSeconds:180,bin:le.bin,mode:"read_only",maxTurns:25,model:d.model||le.adapter.fastModel,sessionId:g,resume:!C,onLog:(ve,Ee)=>{ve==="agent"&&(de.push(Ee.slice(0,4e3)),w.send({type:"chat.stream",requestId:d.requestId,seq:fe++,text:Ee.slice(0,8e3)}))},onUsage:ve=>{w.send({type:"chat.usage",requestId:d.requestId,inputTokens:Math.round(ve.inputTokens),outputTokens:Math.round(ve.outputTokens),cacheReadTokens:ve.cacheReadTokens===void 0?void 0:Math.round(ve.cacheReadTokens),turns:ve.turns})}})}finally{z&&dt.default.rmSync(z.dir,{recursive:!0,force:!0})}if(ae.ok){let le=de.filter(ve=>ve.trim()&&!ae.resultText.trim().startsWith(ve.trim()));wd(d.projectId,g,d.message,ae.resultText,le)}let pn=(ae.inputTokens??0)+(ae.cacheReadTokens??0);w.sendChatTurnResult(d.requestId,{contextTokens:pn,contextLimit:Td(ae.model||d.model||""),compacted:G,compactedMessages:V,ok:ae.ok,sessionId:g,reply:ae.resultText,error:ae.ok?void 0:ae.error??"the agent produced no reply",inputTokens:ae.inputTokens,outputTokens:ae.outputTokens,cacheReadTokens:ae.cacheReadTokens,costUsd:ae.costUsd,model:ae.model??""})},onChatList:d=>{w.sendChatListResult(d.requestId,_d(d.projectId))},onRepoDocs:d=>{let m=x(d.projectId);if(!m){w.sendRepoDocsResult(d.requestId,{ok:!1,docs:[],error:P(d.projectId)});return}w.sendRepoDocsResult(d.requestId,{ok:!0,docs:Ed(m.repoPath)})},onRepoDocRead:d=>{let m=x(d.projectId);if(!m){w.sendRepoDocReadResult(d.requestId,{ok:!1,path:d.path,content:"",truncated:!1,error:P(d.projectId)});return}let g=Ad(m.repoPath,d.path);w.sendRepoDocReadResult(d.requestId,{ok:g.ok,path:g.ok?g.path:d.path,content:g.ok?g.content:"",truncated:g.ok?g.truncated:!1,error:g.ok?void 0:g.error})},onChatLoad:d=>{let m=Ps(d.sessionId);w.sendChatLoadResult(d.requestId,{ok:m!==null,projectId:m?.projectId??"",messages:m?.messages??[],error:m?void 0:"chat not found on this runner (pruned or never existed)"})},onBoardFetch:async d=>{let m=x(d.projectId);if(!m){w.sendBoardFetchResult(d.requestId,{ok:!1,columns:[],error:P(d.projectId)});return}try{let g=s(m.project.repoName),C;try{C=await g.searchBoard(`project = "${m.project.jiraProjectKey}" ORDER BY Rank ASC`,100)}catch{C=await g.searchBoard(`project = "${m.project.jiraProjectKey}" ORDER BY updated DESC`,100)}let N=await g.boardColumns(m.project.jiraProjectKey),G;if(N){G=N.map(z=>({name:z.name,issues:[]}));let ee=new Map;for(let z of C){let L=N.findIndex(fe=>fe.statusIds.includes(z.statusId)),oe={key:z.key,summary:z.summary,labels:z.labels};if(L>=0)G[L].issues.push(oe);else{let fe=ee.get(z.status)??[];fe.push(oe),ee.set(z.status,fe)}}for(let[z,L]of ee)G.push({name:z,issues:L})}else{let ee=de=>de.trim().toLowerCase(),z=new Map,L=new Map;for(let de of C){let ae=ee(de.status);z.has(ae)||z.set(ae,de.status.trim());let pn=L.get(ae)??[];pn.push({key:de.key,summary:de.summary,labels:de.labels}),L.set(ae,pn)}let oe=[];try{oe=await g.projectStatuses(m.project.jiraProjectKey)}catch{}let fe=[];for(let de of oe){let ae=ee(de);!fe.includes(ae)&&L.has(ae)&&fe.push(ae)}for(let de of L.keys())fe.includes(de)||fe.push(de);G=fe.map(de=>({name:z.get(de)??de,issues:L.get(de)??[]}))}let V=n.repos[m.project.repoName]?.jira??n.jira;w.sendBoardFetchResult(d.requestId,{ok:!0,browseBaseUrl:(V?.baseUrl??"").replace(/\/+$/,""),columns:G})}catch(g){w.sendBoardFetchResult(d.requestId,{ok:!1,columns:[],error:g instanceof Error?g.message:String(g)})}},onBoardTrigger:async d=>{let m=x(d.projectId);if(!m){w.sendBoardTriggerResult(d.requestId,{ok:!1,error:P(d.projectId)});return}try{let g=s(m.project.repoName),C=d.comment.trim()?o(m.project.repoName,d.requestedByEmail):{jira:g,authored:!1};if(C.error!==void 0){w.sendBoardTriggerResult(d.requestId,{ok:!1,error:C.error});return}if(d.reimplement){let N=await g.getIssue(d.issueKey),G=N.comments.filter(z=>bt(z.body)),V=G.length?Math.max(...G.map(z=>new Date(z.created).getTime())):0;if(!N.comments.some(z=>!bt(z.body)&&new Date(z.created).getTime()>V)){w.sendBoardTriggerResult(d.requestId,{ok:!1,error:`${d.issueKey} has nothing new since the last implementation - add a comment describing what should change, then hit Implement again. Re-running with the same ticket would just rebuild the same thing.`});return}await g.editLabels(d.issueKey,{remove:["agent-implemented"]})}d.removeLabel.trim()&&await g.editLabels(d.issueKey,{remove:[d.removeLabel.trim()]}),d.comment.trim()&&await C.jira.addTriggerComment(d.issueKey,`${d.comment.trim()}`+(!C.authored&&d.requestedBy?`
|
|
857
861
|
|
|
858
862
|
_(requested by ${d.requestedBy} via Allwright)_`:"")),y.info(`Board action on ${d.issueKey}`+(d.comment?` comment "${d.comment.trim()}"`:"")+(d.removeLabel?` -label ${d.removeLabel}`:"")+(d.requestedBy?` by ${d.requestedBy}`:"")),w.sendBoardTriggerResult(d.requestId,{ok:!0})}catch(g){w.sendBoardTriggerResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onChatCreateTicket:async d=>{let m=x(d.projectId);if(!m){w.sendChatCreateTicketResult(d.requestId,{ok:!1,issueKey:"",error:P(d.projectId)});return}try{let g=o(m.project.repoName,d.requestedByEmail);if(g.error!==void 0){w.sendChatCreateTicketResult(d.requestId,{ok:!1,issueKey:"",error:g.error});return}let C=`
|
|
859
863
|
|
|
860
864
|
---
|
|
861
865
|
_Created via Allwright Compose`+(!g.authored&&d.requestedBy?` by ${d.requestedBy}`:"")+", drafted with the project agent._";if(d.asEpic&&d.createAs!=="epic_with_children"&&d.children.length){let V=d.createAs==="separate_epics"?"Epic":"Task",ee=[];for(let z of d.children){let L=await g.jira.createIssue(m.project.jiraProjectKey,z.summary,(z.description||"(no description)")+C,V);ee.push(L.key)}y.info(`Compose created ${ee.length} standalone ${V.toLowerCase()}(s)`),w.sendChatCreateTicketResult(d.requestId,{ok:!0,issueKey:ee[0]??"",childKeys:ee});return}let{key:N}=await g.jira.createIssue(m.project.jiraProjectKey,d.summary,(d.description||"(no description)")+C,d.asEpic?"Epic":"Task");d.files.length&&await g.jira.addAttachments(N,d.files.map(V=>({name:V.name,content:Buffer.from(V.contentBase64,"base64")}))).then(()=>y.info(`Compose attached ${d.files.length} file(s) to ${N}`)).catch(V=>y.warn(`Compose could not attach files to ${N}: ${V instanceof Error?V.message:V}`));let G=[];if(d.asEpic){for(let V of d.children){let ee=await g.jira.createIssue(m.project.jiraProjectKey,V.summary,V.description||"(no description)","Task",N);G.push(ee.key)}y.info(`Compose created epic ${N} with ${G.length} child ticket(s)`),w.sendChatCreateTicketResult(d.requestId,{ok:!0,issueKey:N,childKeys:G});return}d.triggerComment.trim()&&await g.jira.addTriggerComment(N,`${d.triggerComment.trim()}`+(!g.authored&&d.requestedBy?`
|
|
862
866
|
|
|
863
|
-
_(requested by ${d.requestedBy} via Allwright)_`:"")),y.info(`Compose created ${N}`+(d.requestedBy?` for ${d.requestedBy}`:"")+(d.triggerComment?` with trigger "${d.triggerComment.trim()}"`:"")),w.sendChatCreateTicketResult(d.requestId,{ok:!0,issueKey:N})}catch(g){w.sendChatCreateTicketResult(d.requestId,{ok:!1,issueKey:"",error:g instanceof Error?g.message:String(g)})}},onAuditStart:async d=>{let m=x(d.projectId);if(!m){w.sendAuditStartResult(d.requestId,{ok:!1,error:P(d.projectId)});return}try{y.info(`Audit (${d.role}) starting on ${m.project.repoName}`+(d.scope.kind!=="repo"?` scoped to ${d.scope.kind}:${d.scope.ref}`:""));let g=Fe(n,m.project,"assist");if("error"in g){w.sendAuditStartResult(d.requestId,{ok:!1,error:g.error});return}let C=await Vr({projectId:d.projectId,repoPath:m.repoPath,role:d.role,scope:d.scope,model:d.model,agent:g,jira:s(m.project.repoName)});if(!C.ok){w.sendAuditStartResult(d.requestId,{ok:!1,error:C.error});return}w.sendAuditStartResult(d.requestId,{ok:!0,audit:C.audit})}catch(g){w.sendAuditStartResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onAuditList:async d=>{try{w.sendAuditListResult(d.requestId,{ok:!0,audits:Yu(d.projectId)})}catch(m){w.sendAuditListResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditGet:async d=>{try{let m=ec(d.projectId,d.auditId);if(!m){w.sendAuditGetResult(d.requestId,{ok:!1,error:"audit not found on this runner"});return}w.sendAuditGetResult(d.requestId,{ok:!0,audit:m})}catch(m){w.sendAuditGetResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditReview:async d=>{try{let m=la(d.projectId,d.auditId,{selected:d.selected,ticketed:d.ticketed,verdicts:d.verdicts,verdictBy:d.verdictBy});if(!m){w.sendAuditReviewResult(d.requestId,{ok:!1,error:"audit not found on this runner"});return}let g=x(d.projectId);if(g&&d.verdicts.length){let C=[];for(let N of d.verdicts){if(N.verdict==="valid"||m.lessonsWritten.includes(N.findingId))continue;let G=m.findings.find(V=>V.id===N.findingId);G&&(fa(g.repoPath,m.role,ac(G,N.verdict,N.note,d.verdictBy)),C.push(N.findingId),y.info(`Lesson written (${m.role}): ${N.verdict} - ${G.title.slice(0,60)}`))}C.length&&(m=la(d.projectId,d.auditId,{markLessonsWritten:C})??m)}w.sendAuditReviewResult(d.requestId,{ok:!0,audit:m})}catch(m){w.sendAuditReviewResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onKnowledgeList:async d=>{let m=x(d.projectId);if(!m){w.sendKnowledgeListResult(d.requestId,{ok:!1,error:P(d.projectId)});return}try{w.sendKnowledgeListResult(d.requestId,{ok:!0,files:uc(m.repoPath)})}catch(g){w.sendKnowledgeListResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onKnowledgeSave:async d=>{let m=x(d.projectId);if(!m){w.sendKnowledgeSaveResult(d.requestId,{ok:!1,error:P(d.projectId)});return}try{d.append?fa(m.repoPath,d.role,lc(d.content,d.by),d.level):cc(m.repoPath,d.role,d.level,d.source,d.name,d.content),y.info(`Knowledge ${d.append?"taught":"saved"}: ${d.role}/${d.level}/${d.name}`),w.sendKnowledgeSaveResult(d.requestId,{ok:!0})}catch(g){w.sendKnowledgeSaveResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onEpicList:async d=>{let m=x(d.projectId);if(!m){w.sendEpicListResult(d.requestId,{ok:!1,error:P(d.projectId)});return}try{let g=s(m.project.repoName);if(d.epicKey){let C=await g.epicChildren(d.epicKey);w.sendEpicListResult(d.requestId,{ok:!0,children:C})}else{let C=await g.searchEpics(m.project.jiraProjectKey);w.sendEpicListResult(d.requestId,{ok:!0,epics:C})}}catch(g){w.sendEpicListResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onEpicSuggest:async d=>{let m=x(d.projectId);if(!m){w.sendEpicSuggestResult(d.requestId,{ok:!1,error:P(d.projectId)});return}try{let g=s(m.project.repoName),C=await g.epicChildren(d.epicKey),N=Uu(C);if(!N.length){w.sendEpicSuggestResult(d.requestId,{ok:!1,error:`every child of ${d.epicKey} is already done or in an agent's hands - nothing to sequence`});return}if(N.length===1){w.sendEpicSuggestResult(d.requestId,{ok:!0,issueKey:N[0].key,reason:"It's the only pending ticket left in this epic.",considered:1});return}let G=await Promise.all(N.slice(0,12).map(async oe=>{try{let fe=await g.getIssue(oe.key);return{...oe,description:fe.description}}catch{return{...oe,description:""}}})),V=(await g.getIssue(d.epicKey).catch(()=>null))?.summary??"";y.info(`Epic suggest: weighing ${G.length} pending children of ${d.epicKey}`);let ee=Fe(n,m.project,"assist");if("error"in ee){w.sendEpicSuggestResult(d.requestId,{ok:!1,error:ee.error});return}let z=await ee.adapter.run({repoPath:m.repoPath,prompt:qu(d.epicKey,V,G),timeoutSeconds:150,bin:ee.bin,mode:"read_only",maxTurns:20,sessionId:(0,Bs.randomUUID)(),model:d.model||"claude-sonnet-5",onLog:()=>{}}),L=Fu(z.resultText,G.map(oe=>oe.key));if("error"in L){w.sendEpicSuggestResult(d.requestId,{ok:!1,error:L.error});return}y.info(`Epic suggest: ${d.epicKey} -> do ${L.issueKey} first`),w.sendEpicSuggestResult(d.requestId,{ok:!0,issueKey:L.issueKey,reason:L.reason,considered:G.length})}catch(g){w.sendEpicSuggestResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onTeamCreds:async d=>{try{let m=ye()??n;if(m.github?.token&&!m.github.login)try{let{GitHubClient:C}=await Promise.resolve().then(()=>(at(),sr));m.github.login=await new C(m.github.token).whoami(),ge(m)}catch{}let g=Ou(m,d.emails);w.sendTeamCredsResult(d.requestId,{ok:!0,...g})}catch(m){w.sendTeamCredsResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupStatus:async d=>{try{let m=ye()??n,{buildSetupReport:g}=await Promise.resolve().then(()=>(Wh(),Vh)),C=await g(m,d.repoNames);w.sendSetupStatusResult(d.requestId,{ok:!0,...C})}catch(m){w.sendSetupStatusResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdGenerate:async d=>{try{let m=x(d.projectId);if(!m){w.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=d.kind==="deploy"?"DEPLOY.md":d.kind==="design"?"DESIGN.md":"CLAUDE.md";y.info(`Setup: drafting ${g} for ${m.project.repoName}`);let C="Explore this repository and draft the content of a CLAUDE.md file for its repo root - the memory file AI agents read before working on tickets here. Cover: what the product does (one paragraph), the tech stack, how the code is organized (key directories and what lives in them), exact commands to install dependencies / build / run tests, code conventions worth following, and gotchas a newcomer would trip over. Under 150 lines, factual, no marketing language, nothing you cannot verify from the code. Reply with ONLY the file content - no preamble, no fences around the whole thing.",N='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.',G=`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.`,V=Fe(n,m.project,"assist");if("error"in V){w.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,content:"",error:V.error});return}let z=(await V.adapter.run({repoPath:m.repoPath,prompt:d.kind==="deploy"?N:d.kind==="design"?G:C,timeoutSeconds:240,bin:V.bin,mode:"read_only",maxTurns:40,sessionId:(0,Bs.randomUUID)(),onLog:()=>{}})).resultText.trim();if(!z){w.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:"the agent returned no content - try again"});return}w.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!0,content:z})}catch(m){w.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdSave:async d=>{try{let m=x(d.projectId);if(!m){w.sendSetupClaudeMdSaveResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=d.kind==="deploy"?"DEPLOY.md":d.kind==="design"?"DESIGN.md":"CLAUDE.md",C=await ll({repoPath:m.repoPath,relPath:g,content:d.content,overwrite:d.overwrite,commitMessage:`Add ${g} (agent-drafted, human-approved via Allwright)`});C.ok&&y.info(`Setup: wrote human-approved ${g} to ${m.repoPath}`),w.sendSetupClaudeMdSaveResult(d.requestId,C)}catch(m){w.sendSetupClaudeMdSaveResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRepoDocSave:async d=>{try{let m=x(d.projectId);if(!m){w.sendRepoDocSaveResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=await ll({repoPath:m.repoPath,relPath:d.relPath,content:d.content,overwrite:d.overwrite,commitMessage:`Add ${d.relPath.trim()} (written in Allwright Compose, human-approved)`});g.ok&&y.info(`Saved approved doc ${d.relPath} into ${m.repoPath}`),w.sendRepoDocSaveResult(d.requestId,g)}catch(m){w.sendRepoDocSaveResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditStats:d=>{try{w.sendAuditStatsResult(d.requestId,{ok:!0,byProject:Xu(d.projectIds,d.since)})}catch(m){w.sendAuditStatsResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRunnerUpdate:async d=>{if(!process.env.INVOCATION_ID){w.sendRunnerUpdateResult(d.requestId,{ok:!1,error:"this runner is not running as a systemd service, so it cannot restart itself after updating. On the machine run: allwright update && allwright stop && allwright start"});return}let m=()=>{y.info("Installing allwright@latest");let C=us.default.dirname(process.execPath),N=dt.default.existsSync(us.default.join(C,"npm"))?us.default.join(C,"npm"):"npm";(0,Zt.execFile)(N,["install","-g","allwright@latest"],{timeout:18e4,env:{...process.env,PATH:`${C}:${process.env.PATH??""}`}},(G,V,ee)=>{if(G){w.sendRunnerUpdateResult(d.requestId,{ok:!1,error:`npm install failed: ${(ee||G.message).slice(0,300)} - on the machine run: allwright update && sudo systemctl restart allwright`});return}w.sendRunnerUpdateResult(d.requestId,{ok:!0,note:"updated - restarting now, back in a few seconds"}),y.info("Update installed; exiting so systemd restarts on the new version"),setTimeout(()=>process.exit(0),1500)})};if(p.idle){m();return}if(b){w.sendRunnerUpdateResult(d.requestId,{ok:!0,scheduled:!0,note:"an update is already scheduled and will install once the current work finishes"});return}let g=p.busyCount;w.sendRunnerUpdateResult(d.requestId,{ok:!0,scheduled:!0,note:`scheduled - ${g} run(s)/deploy(s) active right now. Nothing is refused meanwhile; the install runs automatically as soon as this machine goes idle.`}),y.info(`Update scheduled: waiting for ${g} active run(s)/deploy(s) to finish`),b=setInterval(()=>{p.idle&&(clearInterval(b),b=null,m())},5e3)},onTestFix:async d=>{let m=g=>w.sendTestFixResult(d.requestId,{ok:!1,note:g});try{let g=Jr(d.runId);if(!g){m("this runner no longer has that PR on file - it may have been decided already");return}let C=n.repos[g.repoName];if(!C){m(`no local checkout mapped for "${g.repoName}" on this machine`);return}let N=Ie(n,g.repoName);if(!N){m("no GitHub token on this runner for that repo");return}let G=await new Re(N).getPullRequest(g.owner,g.repo,g.prNumber);if(!G){m("that pull request no longer exists on GitHub");return}if(G.merged||G.state==="closed"){m("that pull request is already merged or closed - there is nothing left to fix");return}let V=u.find(oe=>oe.repoName===g.repoName),ee=g.nextDecisionSeq??1e5,z=(oe,fe)=>{w.send({type:"run.log",runId:d.runId,seq:ee++,ts:new Date().toISOString(),level:oe,message:fe}),g.nextDecisionSeq=ee,lt(g)},L=await gd({cfg:n,repoPath:C.path,branch:g.branch,baseBranch:G.baseRef||"main",issueKey:g.issueKey,agentId:V?.defaultAgent||Kt.DEFAULT_AGENT_ID,configDir:g.agentConfigDir,failedTests:d.failedTests,timeoutSeconds:900,onLog:z});L.ok&&L.headSha&&(g.headSha=L.headSha,lt(g),w.send({type:"run.status",runId:d.runId,status:"awaiting_approval",headSha:L.headSha,failedTests:L.remaining??[],...L.testsPassed!==void 0?{testsPassed:L.testsPassed}:{},...L.testsTotal!==void 0?{testsTotal:L.testsTotal}:{},...L.costUsd!==void 0?{costUsd:L.costUsd}:{},...L.inputTokens!==void 0?{inputTokens:L.inputTokens}:{},...L.outputTokens!==void 0?{outputTokens:L.outputTokens}:{}})),ot(C.path,{issueKey:g.issueKey,runId:d.runId,title:L.ok?L.headSha?(L.remaining??[]).length?"dashboard test fix pushed, some commands still failing":"tests fixed from the dashboard":"dashboard test fix: agent changed nothing":"dashboard test fix failed",detail:L.note.slice(0,500)}),w.sendTestFixResult(d.requestId,L)}catch(g){m(g instanceof Error?g.message.slice(0,300):String(g))}},onResolveConflict:async d=>{let m=g=>w.sendResolveConflictResult(d.requestId,{ok:!1,note:g});try{let g=Jr(d.runId);if(!g){m("this runner no longer has that PR on file - it may have been decided already");return}let C=n.repos[g.repoName];if(!C){m(`no local checkout mapped for "${g.repoName}" on this machine`);return}let N=Ie(n,g.repoName);if(!N){m("no GitHub token on this runner for that repo");return}let G=await new Re(N).getPullRequest(g.owner,g.repo,g.prNumber);if(!G){m("that pull request no longer exists on GitHub");return}if(!G.baseRef){m("GitHub did not report the PR's base branch, so there is nothing to merge in");return}let V=u.find(oe=>oe.repoName===g.repoName),ee=g.nextDecisionSeq??1e5,z=(oe,fe)=>{w.send({type:"run.log",runId:d.runId,seq:ee++,ts:new Date().toISOString(),level:oe,message:fe}),g.nextDecisionSeq=ee,lt(g)},L=await pd({cfg:n,repoPath:C.path,branch:g.branch,baseBranch:G.baseRef,issueKey:g.issueKey,agentId:V?.defaultAgent||Kt.DEFAULT_AGENT_ID,configDir:g.agentConfigDir,timeoutSeconds:900,onLog:z});L.ok&&L.headSha&&(g.headSha=L.headSha,g.conflictNotified=!1,lt(g),w.send({type:"run.pr.conflict",runId:d.runId,conflicted:!1}),w.send({type:"run.status",runId:d.runId,status:"awaiting_approval",headSha:L.headSha,...L.costUsd!==void 0?{costUsd:L.costUsd}:{},...L.inputTokens!==void 0?{inputTokens:L.inputTokens}:{},...L.outputTokens!==void 0?{outputTokens:L.outputTokens}:{}})),w.sendResolveConflictResult(d.requestId,L)}catch(g){m(g instanceof Error?g.message.slice(0,300):String(g))}},onAgentProfiles:d=>{try{let m=C=>{try{return dt.default.existsSync(C)&&dt.default.readdirSync(C).length>0}catch{return!1}},g=Object.entries(n.claudeProfiles).map(([C,N])=>({agent:"claude-code",name:C,loggedIn:m(N.configDir)}));w.sendAgentProfilesResult(d.requestId,{ok:!0,profiles:g,defaultLoggedIn:m(us.default.join(cl.default.homedir(),".claude")),agentsWithoutProfiles:Kt.REGISTERED_AGENTS.filter(C=>!C.capabilities.loginProfiles).map(C=>C.id)})}catch(m){w.sendAgentProfilesResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onJiraUsers:async d=>{try{let m=await t.searchUsers(d.query);w.sendJiraUsersResult(d.requestId,{ok:!0,users:m})}catch(m){w.sendJiraUsersResult(d.requestId,{ok:!1,users:[],error:m instanceof Error?m.message:String(m)})}}});v.transport=w,p=new qi(n,s,w);let B=Object.values(Yr()).filter(d=>d.kind==="implement").map(d=>d.repoPath);Zo(Object.values(n.repos).map(d=>d.path),B).catch(()=>{}),w.start(),p.start();let M=()=>{y.info("shutting down"),b&&clearInterval(b),w.stop(),Wl(process.pid),Po(),process.exit(0)},D=!1,W=()=>{if(D){y.warn("second stop signal - exiting NOW; the interrupted run will be marked failed"),M();return}if(D=!0,p.stop(),p.idle){M();return}y.info(`stop requested - no new work will start; waiting for ${p.busyCount} active run(s)/deploy(s) to finish. Send the signal again to kill them immediately.`);let d=setInterval(()=>{p.idle&&(clearInterval(d),M())},3e3)};process.on("SIGINT",W),process.on("SIGTERM",W),process.on("SIGHUP",()=>{try{let d=se();if(!d.jira)throw new Error("no Jira credentials in the reloaded config");for(let m of Object.keys(n))delete n[m];Object.assign(n,d),t=new Ae(d.jira),r.clear(),y.info("config reloaded live - new Jira tokens/repos/rules apply from the next poll. (Poll interval and control-plane URL still need a restart.)")}catch(d){y.error(`config reload failed - keeping the running config: ${d instanceof Error?d.message:String(d)}`)}})}_e.command("start").description("Start watching Jira. Runs in the background by default - close this terminal and it keeps going until you run `allwright stop`. Use --foreground to keep it attached (e.g. under systemd).").option("--foreground","run in this terminal instead of detaching to the background").action(async n=>{let e=se();if(n.foreground){bv(e);return}let t=Pn();if(t&&jn(t)){y.info(`already running in the background (pid ${t}). Use \`allwright status\` or \`stop\`.`);return}let r=gs();if(r){y.info(`a runner is already running on this machine (pid ${r}) - most likely the systemd service. One machine runs ONE runner; nothing to do. (Service controls: sudo systemctl status|stop|restart allwright)`);return}let s=Gl(),i=(0,Zt.spawn)(process.execPath,[process.argv[1],"start","--foreground"],{detached:!0,stdio:["ignore",s,s]});i.unref(),Vl(i.pid),y.info(`Runner started in the background (pid ${i.pid}).`),y.info(`Logs: ${ii()}`),y.info("It will keep polling Jira until you run `allwright stop` - closing this terminal is fine.")});_e.command("stop").description("Stop the background runner started by `start`. Graceful by default: it stops taking new work and exits once active runs and deploys finish - safe to use while customers' tickets are running.").option("--force","kill immediately - anything executing is interrupted and marked failed").action(n=>{let e=Pn();if(!e||!jn(e)){y.info("no background runner is running"),e&&dt.default.rmSync(Or(),{force:!0});return}if(n.force){process.kill(e,"SIGKILL"),dt.default.rmSync(Or(),{force:!0}),y.info(`killed (pid ${e}) - any interrupted run will show as failed on the dashboard`);return}process.kill(e,"SIGTERM"),y.info(`stop signal sent (pid ${e}) - it stops polling now and exits once active work finishes (watch \`allwright status\`). Use --force to kill immediately.`)});_e.command("status").description("Check whether the background runner is running").action(()=>{let n=Pn();n&&jn(n)?y.info(`running in the background (pid ${n})`):y.info("not running")});_e.parseAsync().catch(n=>{y.error(n instanceof Error?n.message:String(n)),process.exit(1)});
|
|
867
|
+
_(requested by ${d.requestedBy} via Allwright)_`:"")),y.info(`Compose created ${N}`+(d.requestedBy?` for ${d.requestedBy}`:"")+(d.triggerComment?` with trigger "${d.triggerComment.trim()}"`:"")),w.sendChatCreateTicketResult(d.requestId,{ok:!0,issueKey:N})}catch(g){w.sendChatCreateTicketResult(d.requestId,{ok:!1,issueKey:"",error:g instanceof Error?g.message:String(g)})}},onAuditStart:async d=>{let m=x(d.projectId);if(!m){w.sendAuditStartResult(d.requestId,{ok:!1,error:P(d.projectId)});return}try{y.info(`Audit (${d.role}) starting on ${m.project.repoName}`+(d.scope.kind!=="repo"?` scoped to ${d.scope.kind}:${d.scope.ref}`:""));let g=Fe(n,m.project,"assist");if("error"in g){w.sendAuditStartResult(d.requestId,{ok:!1,error:g.error});return}let C=await Vr({projectId:d.projectId,repoPath:m.repoPath,role:d.role,scope:d.scope,model:d.model,agent:g,jira:s(m.project.repoName)});if(!C.ok){w.sendAuditStartResult(d.requestId,{ok:!1,error:C.error});return}w.sendAuditStartResult(d.requestId,{ok:!0,audit:C.audit})}catch(g){w.sendAuditStartResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onAuditList:async d=>{try{w.sendAuditListResult(d.requestId,{ok:!0,audits:Yu(d.projectId)})}catch(m){w.sendAuditListResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditGet:async d=>{try{let m=ec(d.projectId,d.auditId);if(!m){w.sendAuditGetResult(d.requestId,{ok:!1,error:"audit not found on this runner"});return}w.sendAuditGetResult(d.requestId,{ok:!0,audit:m})}catch(m){w.sendAuditGetResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditReview:async d=>{try{let m=la(d.projectId,d.auditId,{selected:d.selected,ticketed:d.ticketed,verdicts:d.verdicts,verdictBy:d.verdictBy});if(!m){w.sendAuditReviewResult(d.requestId,{ok:!1,error:"audit not found on this runner"});return}let g=x(d.projectId);if(g&&d.verdicts.length){let C=[];for(let N of d.verdicts){if(N.verdict==="valid"||m.lessonsWritten.includes(N.findingId))continue;let G=m.findings.find(V=>V.id===N.findingId);G&&(fa(g.repoPath,m.role,ac(G,N.verdict,N.note,d.verdictBy)),C.push(N.findingId),y.info(`Lesson written (${m.role}): ${N.verdict} - ${G.title.slice(0,60)}`))}C.length&&(m=la(d.projectId,d.auditId,{markLessonsWritten:C})??m)}w.sendAuditReviewResult(d.requestId,{ok:!0,audit:m})}catch(m){w.sendAuditReviewResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onKnowledgeList:async d=>{let m=x(d.projectId);if(!m){w.sendKnowledgeListResult(d.requestId,{ok:!1,error:P(d.projectId)});return}try{w.sendKnowledgeListResult(d.requestId,{ok:!0,files:uc(m.repoPath)})}catch(g){w.sendKnowledgeListResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onKnowledgeSave:async d=>{let m=x(d.projectId);if(!m){w.sendKnowledgeSaveResult(d.requestId,{ok:!1,error:P(d.projectId)});return}try{d.append?fa(m.repoPath,d.role,lc(d.content,d.by),d.level):cc(m.repoPath,d.role,d.level,d.source,d.name,d.content),y.info(`Knowledge ${d.append?"taught":"saved"}: ${d.role}/${d.level}/${d.name}`),w.sendKnowledgeSaveResult(d.requestId,{ok:!0})}catch(g){w.sendKnowledgeSaveResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onEpicList:async d=>{let m=x(d.projectId);if(!m){w.sendEpicListResult(d.requestId,{ok:!1,error:P(d.projectId)});return}try{let g=s(m.project.repoName);if(d.epicKey){let C=await g.epicChildren(d.epicKey);w.sendEpicListResult(d.requestId,{ok:!0,children:C})}else{let C=await g.searchEpics(m.project.jiraProjectKey);w.sendEpicListResult(d.requestId,{ok:!0,epics:C})}}catch(g){w.sendEpicListResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onEpicSuggest:async d=>{let m=x(d.projectId);if(!m){w.sendEpicSuggestResult(d.requestId,{ok:!1,error:P(d.projectId)});return}try{let g=s(m.project.repoName),C=await g.epicChildren(d.epicKey),N=Uu(C);if(!N.length){w.sendEpicSuggestResult(d.requestId,{ok:!1,error:`every child of ${d.epicKey} is already done or in an agent's hands - nothing to sequence`});return}if(N.length===1){w.sendEpicSuggestResult(d.requestId,{ok:!0,issueKey:N[0].key,reason:"It's the only pending ticket left in this epic.",considered:1});return}let G=await Promise.all(N.slice(0,12).map(async oe=>{try{let fe=await g.getIssue(oe.key);return{...oe,description:fe.description}}catch{return{...oe,description:""}}})),V=(await g.getIssue(d.epicKey).catch(()=>null))?.summary??"";y.info(`Epic suggest: weighing ${G.length} pending children of ${d.epicKey}`);let ee=Fe(n,m.project,"assist");if("error"in ee){w.sendEpicSuggestResult(d.requestId,{ok:!1,error:ee.error});return}let z=await ee.adapter.run({repoPath:m.repoPath,prompt:qu(d.epicKey,V,G),timeoutSeconds:150,bin:ee.bin,mode:"read_only",maxTurns:20,sessionId:(0,Bs.randomUUID)(),model:d.model||"claude-sonnet-5",onLog:()=>{}}),L=Fu(z.resultText,G.map(oe=>oe.key));if("error"in L){w.sendEpicSuggestResult(d.requestId,{ok:!1,error:L.error});return}y.info(`Epic suggest: ${d.epicKey} -> do ${L.issueKey} first`),w.sendEpicSuggestResult(d.requestId,{ok:!0,issueKey:L.issueKey,reason:L.reason,considered:G.length})}catch(g){w.sendEpicSuggestResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onTeamCreds:async d=>{try{let m=ye()??n;if(m.github?.token&&!m.github.login)try{let{GitHubClient:C}=await Promise.resolve().then(()=>(at(),sr));m.github.login=await new C(m.github.token).whoami(),ge(m)}catch{}let g=Ou(m,d.emails);w.sendTeamCredsResult(d.requestId,{ok:!0,...g})}catch(m){w.sendTeamCredsResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupStatus:async d=>{try{let m=ye()??n,{buildSetupReport:g}=await Promise.resolve().then(()=>(Wh(),Vh)),C=await g(m,d.repoNames);w.sendSetupStatusResult(d.requestId,{ok:!0,...C})}catch(m){w.sendSetupStatusResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdGenerate:async d=>{try{let m=x(d.projectId);if(!m){w.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=d.kind==="deploy"?"DEPLOY.md":d.kind==="design"?"DESIGN.md":"CLAUDE.md";y.info(`Setup: drafting ${g} for ${m.project.repoName}`);let C="Explore this repository and draft the content of a CLAUDE.md file for its repo root - the memory file AI agents read before working on tickets here. Cover: what the product does (one paragraph), the tech stack, how the code is organized (key directories and what lives in them), exact commands to install dependencies / build / run tests, code conventions worth following, and gotchas a newcomer would trip over. Under 150 lines, factual, no marketing language, nothing you cannot verify from the code. Reply with ONLY the file content - no preamble, no fences around the whole thing.",N='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.',G=`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.`,V=Fe(n,m.project,"assist");if("error"in V){w.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,content:"",error:V.error});return}let z=(await V.adapter.run({repoPath:m.repoPath,prompt:d.kind==="deploy"?N:d.kind==="design"?G:C,timeoutSeconds:240,bin:V.bin,mode:"read_only",maxTurns:40,sessionId:(0,Bs.randomUUID)(),onLog:()=>{}})).resultText.trim();if(!z){w.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:"the agent returned no content - try again"});return}w.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!0,content:z})}catch(m){w.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdSave:async d=>{try{let m=x(d.projectId);if(!m){w.sendSetupClaudeMdSaveResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=d.kind==="deploy"?"DEPLOY.md":d.kind==="design"?"DESIGN.md":"CLAUDE.md",C=await ll({repoPath:m.repoPath,relPath:g,content:d.content,overwrite:d.overwrite,commitMessage:`Add ${g} (agent-drafted, human-approved via Allwright)`});C.ok&&y.info(`Setup: wrote human-approved ${g} to ${m.repoPath}`),w.sendSetupClaudeMdSaveResult(d.requestId,C)}catch(m){w.sendSetupClaudeMdSaveResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRepoDocSave:async d=>{try{let m=x(d.projectId);if(!m){w.sendRepoDocSaveResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=await ll({repoPath:m.repoPath,relPath:d.relPath,content:d.content,overwrite:d.overwrite,commitMessage:`Add ${d.relPath.trim()} (written in Allwright Compose, human-approved)`});g.ok&&y.info(`Saved approved doc ${d.relPath} into ${m.repoPath}`),w.sendRepoDocSaveResult(d.requestId,g)}catch(m){w.sendRepoDocSaveResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditStats:d=>{try{w.sendAuditStatsResult(d.requestId,{ok:!0,byProject:Xu(d.projectIds,d.since)})}catch(m){w.sendAuditStatsResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRunnerUpdate:async d=>{if(!process.env.INVOCATION_ID){w.sendRunnerUpdateResult(d.requestId,{ok:!1,error:"this runner is not running as a systemd service, so it cannot restart itself after updating. On the machine run: allwright update && allwright stop && allwright start"});return}let m=()=>{y.info("Installing allwright@latest");let C=us.default.dirname(process.execPath),N=dt.default.existsSync(us.default.join(C,"npm"))?us.default.join(C,"npm"):"npm";(0,Zt.execFile)(N,["install","-g","allwright@latest"],{timeout:18e4,env:{...process.env,PATH:`${C}:${process.env.PATH??""}`}},(G,V,ee)=>{if(G){w.sendRunnerUpdateResult(d.requestId,{ok:!1,error:`npm install failed: ${(ee||G.message).slice(0,300)} - on the machine run: allwright update && sudo systemctl restart allwright`});return}w.sendRunnerUpdateResult(d.requestId,{ok:!0,note:"updated - restarting now, back in a few seconds"}),y.info("Update installed; exiting so systemd restarts on the new version"),setTimeout(()=>process.exit(0),1500)})};if(p.idle){m();return}if(v){w.sendRunnerUpdateResult(d.requestId,{ok:!0,scheduled:!0,note:"an update is already scheduled and will install once the current work finishes"});return}let g=p.busyCount;w.sendRunnerUpdateResult(d.requestId,{ok:!0,scheduled:!0,note:`scheduled - ${g} run(s)/deploy(s) active right now. Nothing is refused meanwhile; the install runs automatically as soon as this machine goes idle.`}),y.info(`Update scheduled: waiting for ${g} active run(s)/deploy(s) to finish`),v=setInterval(()=>{p.idle&&(clearInterval(v),v=null,m())},5e3)},onTestFix:async d=>{let m=g=>w.sendTestFixResult(d.requestId,{ok:!1,note:g});try{let g=Jr(d.runId);if(!g){m("this runner no longer has that PR on file - it may have been decided already");return}let C=n.repos[g.repoName];if(!C){m(`no local checkout mapped for "${g.repoName}" on this machine`);return}let N=Ie(n,g.repoName);if(!N){m("no GitHub token on this runner for that repo");return}let G=await new Re(N).getPullRequest(g.owner,g.repo,g.prNumber);if(!G){m("that pull request no longer exists on GitHub");return}if(G.merged||G.state==="closed"){m("that pull request is already merged or closed - there is nothing left to fix");return}let V=u.find(oe=>oe.repoName===g.repoName),ee=g.nextDecisionSeq??1e5,z=(oe,fe)=>{w.send({type:"run.log",runId:d.runId,seq:ee++,ts:new Date().toISOString(),level:oe,message:fe}),g.nextDecisionSeq=ee,lt(g)},L=await gd({cfg:n,repoPath:C.path,branch:g.branch,baseBranch:G.baseRef||"main",issueKey:g.issueKey,agentId:V?.defaultAgent||Kt.DEFAULT_AGENT_ID,configDir:g.agentConfigDir,failedTests:d.failedTests,timeoutSeconds:900,onLog:z});L.ok&&L.headSha&&(g.headSha=L.headSha,lt(g),w.send({type:"run.status",runId:d.runId,status:"awaiting_approval",headSha:L.headSha,failedTests:L.remaining??[],...L.testsPassed!==void 0?{testsPassed:L.testsPassed}:{},...L.testsTotal!==void 0?{testsTotal:L.testsTotal}:{},...L.costUsd!==void 0?{costUsd:L.costUsd}:{},...L.inputTokens!==void 0?{inputTokens:L.inputTokens}:{},...L.outputTokens!==void 0?{outputTokens:L.outputTokens}:{}})),ot(C.path,{issueKey:g.issueKey,runId:d.runId,title:L.ok?L.headSha?(L.remaining??[]).length?"dashboard test fix pushed, some commands still failing":"tests fixed from the dashboard":"dashboard test fix: agent changed nothing":"dashboard test fix failed",detail:L.note.slice(0,500)}),w.sendTestFixResult(d.requestId,L)}catch(g){m(g instanceof Error?g.message.slice(0,300):String(g))}},onResolveConflict:async d=>{let m=g=>w.sendResolveConflictResult(d.requestId,{ok:!1,note:g});try{let g=Jr(d.runId);if(!g){m("this runner no longer has that PR on file - it may have been decided already");return}let C=n.repos[g.repoName];if(!C){m(`no local checkout mapped for "${g.repoName}" on this machine`);return}let N=Ie(n,g.repoName);if(!N){m("no GitHub token on this runner for that repo");return}let G=await new Re(N).getPullRequest(g.owner,g.repo,g.prNumber);if(!G){m("that pull request no longer exists on GitHub");return}if(!G.baseRef){m("GitHub did not report the PR's base branch, so there is nothing to merge in");return}let V=u.find(oe=>oe.repoName===g.repoName),ee=g.nextDecisionSeq??1e5,z=(oe,fe)=>{w.send({type:"run.log",runId:d.runId,seq:ee++,ts:new Date().toISOString(),level:oe,message:fe}),g.nextDecisionSeq=ee,lt(g)},L=await pd({cfg:n,repoPath:C.path,branch:g.branch,baseBranch:G.baseRef,issueKey:g.issueKey,agentId:V?.defaultAgent||Kt.DEFAULT_AGENT_ID,configDir:g.agentConfigDir,timeoutSeconds:900,onLog:z});L.ok&&L.headSha&&(g.headSha=L.headSha,g.conflictNotified=!1,lt(g),w.send({type:"run.pr.conflict",runId:d.runId,conflicted:!1}),w.send({type:"run.status",runId:d.runId,status:"awaiting_approval",headSha:L.headSha,...L.costUsd!==void 0?{costUsd:L.costUsd}:{},...L.inputTokens!==void 0?{inputTokens:L.inputTokens}:{},...L.outputTokens!==void 0?{outputTokens:L.outputTokens}:{}})),w.sendResolveConflictResult(d.requestId,L)}catch(g){m(g instanceof Error?g.message.slice(0,300):String(g))}},onAgentProfiles:d=>{try{let m=C=>{try{return dt.default.existsSync(C)&&dt.default.readdirSync(C).length>0}catch{return!1}},g=Object.entries(n.claudeProfiles).map(([C,N])=>({agent:"claude-code",name:C,loggedIn:m(N.configDir)}));w.sendAgentProfilesResult(d.requestId,{ok:!0,profiles:g,defaultLoggedIn:m(us.default.join(cl.default.homedir(),".claude")),agentsWithoutProfiles:Kt.REGISTERED_AGENTS.filter(C=>!C.capabilities.loginProfiles).map(C=>C.id)})}catch(m){w.sendAgentProfilesResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onJiraUsers:async d=>{try{let m=await t.searchUsers(d.query);w.sendJiraUsersResult(d.requestId,{ok:!0,users:m})}catch(m){w.sendJiraUsersResult(d.requestId,{ok:!1,users:[],error:m instanceof Error?m.message:String(m)})}}});b.transport=w,p=new qi(n,s,w);let B=Object.values(Yr()).filter(d=>d.kind==="implement").map(d=>d.repoPath);Zo(Object.values(n.repos).map(d=>d.path),B).catch(()=>{}),w.start(),p.start();let M=()=>{y.info("shutting down"),v&&clearInterval(v),w.stop(),Wl(process.pid),Po(),process.exit(0)},D=!1,W=()=>{if(D){y.warn("second stop signal - exiting NOW; the interrupted run will be marked failed"),M();return}if(D=!0,p.stop(),p.idle){M();return}y.info(`stop requested - no new work will start; waiting for ${p.busyCount} active run(s)/deploy(s) to finish. Send the signal again to kill them immediately.`);let d=setInterval(()=>{p.idle&&(clearInterval(d),M())},3e3)};process.on("SIGINT",W),process.on("SIGTERM",W),process.on("SIGHUP",()=>{try{let d=se();if(!d.jira)throw new Error("no Jira credentials in the reloaded config");for(let m of Object.keys(n))delete n[m];Object.assign(n,d),t=new Ae(d.jira),r.clear(),y.info("config reloaded live - new Jira tokens/repos/rules apply from the next poll. (Poll interval and control-plane URL still need a restart.)")}catch(d){y.error(`config reload failed - keeping the running config: ${d instanceof Error?d.message:String(d)}`)}})}_e.command("start").description("Start watching Jira. Runs in the background by default - close this terminal and it keeps going until you run `allwright stop`. Use --foreground to keep it attached (e.g. under systemd).").option("--foreground","run in this terminal instead of detaching to the background").action(async n=>{let e=se();if(n.foreground){vb(e);return}let t=Pn();if(t&&jn(t)){y.info(`already running in the background (pid ${t}). Use \`allwright status\` or \`stop\`.`);return}let r=gs();if(r){y.info(`a runner is already running on this machine (pid ${r}) - most likely the systemd service. One machine runs ONE runner; nothing to do. (Service controls: sudo systemctl status|stop|restart allwright)`);return}let s=Gl(),i=(0,Zt.spawn)(process.execPath,[process.argv[1],"start","--foreground"],{detached:!0,stdio:["ignore",s,s]});i.unref(),Vl(i.pid),y.info(`Runner started in the background (pid ${i.pid}).`),y.info(`Logs: ${ii()}`),y.info("It will keep polling Jira until you run `allwright stop` - closing this terminal is fine.")});_e.command("stop").description("Stop the background runner started by `start`. Graceful by default: it stops taking new work and exits once active runs and deploys finish - safe to use while customers' tickets are running.").option("--force","kill immediately - anything executing is interrupted and marked failed").action(n=>{let e=Pn();if(!e||!jn(e)){y.info("no background runner is running"),e&&dt.default.rmSync(Or(),{force:!0});return}if(n.force){process.kill(e,"SIGKILL"),dt.default.rmSync(Or(),{force:!0}),y.info(`killed (pid ${e}) - any interrupted run will show as failed on the dashboard`);return}process.kill(e,"SIGTERM"),y.info(`stop signal sent (pid ${e}) - it stops polling now and exits once active work finishes (watch \`allwright status\`). Use --force to kill immediately.`)});_e.command("status").description("Check whether the background runner is running").action(()=>{let n=Pn();n&&jn(n)?y.info(`running in the background (pid ${n})`):y.info("not running")});_e.parseAsync().catch(n=>{y.error(n instanceof Error?n.message:String(n)),process.exit(1)});
|