allwright 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +30 -0
- package/bin/allwright.js +683 -0
- package/bin/ticketpilot-runner.js +683 -0
- package/package.json +28 -0
package/bin/allwright.js
ADDED
|
@@ -0,0 +1,683 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";var cd=Object.create;var ti=Object.defineProperty;var ud=Object.getOwnPropertyDescriptor;var ld=Object.getOwnPropertyNames;var dd=Object.getPrototypeOf,hd=Object.prototype.hasOwnProperty;var ra=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=[n],n}};var Y=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},ri=(r,e)=>{for(var t in e)ti(r,t,{get:e[t],enumerable:!0})},fd=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ld(e))!hd.call(r,s)&&s!==t&&ti(r,s,{get:()=>e[s],enumerable:!(n=ud(e,s))||n.enumerable});return r};var $=(r,e,t)=>(t=r!=null?cd(dd(r)):{},fd(e||!r||!r.__esModule?ti(t,"default",{value:r,enumerable:!0}):t,r));var gn=Y(si=>{var Wn=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},ni=class extends Wn{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};si.CommanderError=Wn;si.InvalidArgumentError=ni});var Jn=Y(oi=>{var{InvalidArgumentError:pd}=gn(),ii=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new pd(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function md(r){let e=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+e+">":"["+e+"]"}oi.Argument=ii;oi.humanReadableArgName=md});var ci=Y(na=>{var{humanReadableArgName:gd}=Jn(),ai=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let t=e.commands.filter(s=>!s._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((s,i)=>s.name().localeCompare(i.name())),t}compareOptions(e,t){let n=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(s=>!s.hidden),n=e._getHelpOption();if(n&&!n.hidden){let s=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!s&&!i?t.push(n):n.long&&!i?t.push(e.createOption(n.long,n.description)):n.short&&!s&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let s=n.options.filter(i=>!i.hidden);t.push(...s)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(n=>gd(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((n,s)=>Math.max(n,t.subcommandTerm(s).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((n,s)=>Math.max(n,t.optionTerm(s).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((n,s)=>Math.max(n,t.optionTerm(s).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((n,s)=>Math.max(n,t.argumentTerm(s).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let n="";for(let s=e.parent;s;s=s.parent)n=s.name()+" "+n;return n+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,t){let n=t.padWidth(e,t),s=t.helpWidth||80,i=2,o=2;function a(x,w){if(w){let j=`${x.padEnd(n+o)}${w}`;return t.wrap(j,s-i,n+o)}return x}function u(x){return x.join(`
|
|
3
|
+
`).replace(/^/gm," ".repeat(i))}let l=[`Usage: ${t.commandUsage(e)}`,""],d=t.commandDescription(e);d.length>0&&(l=l.concat([t.wrap(d,s,0),""]));let p=t.visibleArguments(e).map(x=>a(t.argumentTerm(x),t.argumentDescription(x)));p.length>0&&(l=l.concat(["Arguments:",u(p),""]));let v=t.visibleOptions(e).map(x=>a(t.optionTerm(x),t.optionDescription(x)));if(v.length>0&&(l=l.concat(["Options:",u(v),""])),this.showGlobalOptions){let x=t.visibleGlobalOptions(e).map(w=>a(t.optionTerm(w),t.optionDescription(w)));x.length>0&&(l=l.concat(["Global Options:",u(x),""]))}let S=t.visibleCommands(e).map(x=>a(t.subcommandTerm(x),t.subcommandDescription(x)));return S.length>0&&(l=l.concat(["Commands:",u(S),""])),l.join(`
|
|
4
|
+
`)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,n,s=40){let i=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",o=new RegExp(`[\\n][${i}]+`);if(e.match(o))return e;let a=t-n;if(a<s)return e;let u=e.slice(0,n),l=e.slice(n).replace(`\r
|
|
5
|
+
`,`
|
|
6
|
+
`),d=" ".repeat(n),v="\\s\u200B",S=new RegExp(`
|
|
7
|
+
|.{1,${a-1}}([${v}]|$)|[^${v}]+?([${v}]|$)`,"g"),x=l.match(S)||[];return u+x.map((w,j)=>w===`
|
|
8
|
+
`?"":(j>0?d:"")+w.trimEnd()).join(`
|
|
9
|
+
`)}};na.Help=ai});var hi=Y(di=>{var{InvalidArgumentError:yd}=gn(),ui=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=vd(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new yd(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return _d(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},li=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let s=this.negativeOptions.get(n).presetArg,i=s!==void 0?s:!1;return t.negate===(i===e)}};function _d(r){return r.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function vd(r){let e,t,n=r.split(/[ |,]+/);return n.length>1&&!/^[[<]/.test(n[1])&&(e=n.shift()),t=n.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}di.Option=ui;di.DualOptions=li});var ia=Y(sa=>{function bd(r,e){if(Math.abs(r.length-e.length)>3)return Math.max(r.length,e.length);let t=[];for(let n=0;n<=r.length;n++)t[n]=[n];for(let n=0;n<=e.length;n++)t[0][n]=n;for(let n=1;n<=e.length;n++)for(let s=1;s<=r.length;s++){let i=1;r[s-1]===e[n-1]?i=0:i=1,t[s][n]=Math.min(t[s-1][n]+1,t[s][n-1]+1,t[s-1][n-1]+i),s>1&&n>1&&r[s-1]===e[n-2]&&r[s-2]===e[n-1]&&(t[s][n]=Math.min(t[s][n],t[s-2][n-2]+1))}return t[r.length][e.length]}function wd(r,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=r.startsWith("--");t&&(r=r.slice(2),e=e.map(o=>o.slice(2)));let n=[],s=3,i=.4;return e.forEach(o=>{if(o.length<=1)return;let a=bd(r,o),u=Math.max(r.length,o.length);(u-a)/u>i&&(a<s?(s=a,n=[o]):a===s&&n.push(o))}),n.sort((o,a)=>o.localeCompare(a)),t&&(n=n.map(o=>`--${o}`)),n.length>1?`
|
|
10
|
+
(Did you mean one of ${n.join(", ")}?)`:n.length===1?`
|
|
11
|
+
(Did you mean ${n[0]}?)`:""}sa.suggestSimilar=wd});var la=Y(ua=>{var kd=require("node:events").EventEmitter,fi=require("node:child_process"),Qe=require("node:path"),pi=require("node:fs"),se=require("node:process"),{Argument:Sd,humanReadableArgName:Td}=Jn(),{CommanderError:mi}=gn(),{Help:xd}=ci(),{Option:oa,DualOptions:Cd}=hi(),{suggestSimilar:aa}=ia(),gi=class r extends kd{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=>se.stdout.write(t),writeErr:t=>se.stderr.write(t),getOutHelpWidth:()=>se.stdout.isTTY?se.stdout.columns:void 0,getErrHelpWidth:()=>se.stderr.isTTY?se.stderr.columns:void 0,outputError:(t,n)=>n(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let s=t,i=n;typeof s=="object"&&s!==null&&(i=s,s=null),i=i||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),u=this.createCommand(o);return s&&(u.description(s),u._executableHandler=!0),i.isDefault&&(this._defaultCommandName=u._name),u._hidden=!!(i.noHelp||i.hidden),u._executableFile=i.executableFile||null,a&&u.arguments(a),this._registerCommand(u),u.parent=this,u.copyInheritedSettings(this),s?this:u}createCommand(e){return new r(e)}createHelp(){return Object.assign(new xd,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
12
|
+
- specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new Sd(e,t)}argument(e,t,n,s){let i=this.createArgument(e,t);return typeof n=="function"?i.default(s).argParser(n):i.default(n),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,n,s]=e.match(/([^ ]+) *(.*)/),i=t??"display help for command",o=this.createCommand(n);return o.helpOption(!1),s&&o.arguments(s),i&&o.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
13
|
+
Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new mi(e,t,n)),se.exit(e)}action(e){let t=n=>{let s=this.registeredArguments.length,i=n.slice(0,s);return this._storeOptionsAsProperties?i[s]=this:i[s]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=t,this}createOption(e,t){return new oa(e,t)}_callParseArg(e,t,n,s){try{return e.parseArg(t,n)}catch(i){if(i.code==="commander.invalidArgument"){let o=`${s} ${i.message}`;this.error(o,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
|
|
14
|
+
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=s=>[s.name()].concat(s.aliases()),n=t(e).find(s=>this._findCommand(s));if(n){let s=t(this._findCommand(n)).join("|"),i=t(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let s=(i,o,a)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let u=this.getOptionValue(n);i!==null&&e.parseArg?i=this._callParseArg(e,i,u,o):i!==null&&e.variadic&&(i=e._concatValue(i,u)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(n,i,a)};return this.on("option:"+t,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;s(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+t,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;s(i,o,"env")}),this}_optionEx(e,t,n,s,i){if(typeof t=="object"&&t instanceof oa)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(t,n);if(o.makeOptionMandatory(!!e.mandatory),typeof s=="function")o.default(i).argParser(s);else if(s instanceof RegExp){let a=s;s=(u,l)=>{let d=a.exec(u);return d?d[0]:l},o.default(i).argParser(s)}else o.default(s);return this.addOption(o)}option(e,t,n,s){return this._optionEx({},e,t,n,s)}requiredOption(e,t,n,s){return this._optionEx({mandatory:!0},e,t,n,s)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){se.versions?.electron&&(t.from="electron");let s=se.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(t.from="eval")}e===void 0&&(e=se.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":se.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,t){let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_executeSubCommand(e,t){t=t.slice();let n=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function i(d,p){let v=Qe.resolve(d,p);if(pi.existsSync(v))return v;if(s.includes(Qe.extname(p)))return;let S=s.find(x=>pi.existsSync(`${v}${x}`));if(S)return`${v}${S}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let d;try{d=pi.realpathSync(this._scriptPath)}catch{d=this._scriptPath}a=Qe.resolve(Qe.dirname(d),a)}if(a){let d=i(a,o);if(!d&&!e._executableFile&&this._scriptPath){let p=Qe.basename(this._scriptPath,Qe.extname(this._scriptPath));p!==this._name&&(d=i(a,`${p}-${e._name}`))}o=d||o}n=s.includes(Qe.extname(o));let u;se.platform!=="win32"?n?(t.unshift(o),t=ca(se.execArgv).concat(t),u=fi.spawn(se.argv[0],t,{stdio:"inherit"})):u=fi.spawn(o,t,{stdio:"inherit"}):(t.unshift(o),t=ca(se.execArgv).concat(t),u=fi.spawn(se.execPath,t,{stdio:"inherit"})),u.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(p=>{se.on(p,()=>{u.killed===!1&&u.exitCode===null&&u.kill(p)})});let l=this._exitCallback;u.on("close",d=>{d=d??1,l?l(new mi(d,"commander.executeSubCommandAsync","(close)")):se.exit(d)}),u.on("error",d=>{if(d.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
|
+
- if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
16
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
17
|
+
- ${p}`;throw new Error(v)}else if(d.code==="EACCES")throw new Error(`'${o}' not executable`);if(!l)se.exit(1);else{let p=new mi(1,"commander.executeSubCommandAsync","(error)");p.nestedError=d,l(p)}}),this.runningCommand=u}_dispatchSubcommand(e,t,n){let s=this._findCommand(e);s||this.help({error:!0});let i;return i=this._chainOrCallSubCommandHook(i,s,"preSubcommand"),i=this._chainOrCall(i,()=>{if(s._executableHandler)this._executeSubCommand(s,t.concat(n));else return s._parseCommand(t,n)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(n,s,i)=>{let o=s;if(s!==null&&n.parseArg){let a=`error: command-argument value '${s}' is invalid for argument '${n.name()}'.`;o=this._callParseArg(n,s,i,a)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,s)=>{let i=n.defaultValue;n.variadic?s<this.args.length?(i=this.args.slice(s),n.parseArg&&(i=i.reduce((o,a)=>e(n,a,o),n.defaultValue))):i===void 0&&(i=[]):s<this.args.length&&(i=this.args[s],n.parseArg&&(i=e(n,i,n.defaultValue))),t[s]=i}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,s=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[t]!==void 0).forEach(i=>{i._lifeCycleHooks[t].forEach(o=>{s.push({hookedCommand:i,callback:o})})}),t==="postAction"&&s.reverse(),s.forEach(i=>{n=this._chainOrCall(n,()=>i.callback(i.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let s=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(i=>{s=this._chainOrCall(s,()=>i(this,t))}),s}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){s(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(i,e,t)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(i))s(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(n=>{let s=n.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let s=e.find(i=>n.conflictsWith.includes(i.attributeName()));s&&this._conflictingOption(n,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],s=t,i=e.slice();function o(u){return u.length>1&&u[0]==="-"}let a=null;for(;i.length;){let u=i.shift();if(u==="--"){s===n&&s.push(u),s.push(...i);break}if(a&&!o(u)){this.emit(`option:${a.name()}`,u);continue}if(a=null,o(u)){let l=this._findOption(u);if(l){if(l.required){let d=i.shift();d===void 0&&this.optionMissingArgument(l),this.emit(`option:${l.name()}`,d)}else if(l.optional){let d=null;i.length>0&&!o(i[0])&&(d=i.shift()),this.emit(`option:${l.name()}`,d)}else this.emit(`option:${l.name()}`);a=l.variadic?l:null;continue}}if(u.length>2&&u[0]==="-"&&u[1]!=="-"){let l=this._findOption(`-${u[1]}`);if(l){l.required||l.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${l.name()}`,u.slice(2)):(this.emit(`option:${l.name()}`),i.unshift(`-${u.slice(2)}`));continue}}if(/^--[^=]+=/.test(u)){let l=u.indexOf("="),d=this._findOption(u.slice(0,l));if(d&&(d.required||d.optional)){this.emit(`option:${d.name()}`,u.slice(l+1));continue}}if(o(u)&&(s=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(u)){t.push(u),i.length>0&&n.push(...i);break}else if(this._getHelpCommand()&&u===this._getHelpCommand().name()){t.push(u),i.length>0&&t.push(...i);break}else if(this._defaultCommandName){n.push(u),i.length>0&&n.push(...i);break}}if(this._passThroughOptions){s.push(u),i.length>0&&s.push(...i);break}s.push(u)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let s=this.options[n].attributeName();e[s]=s===this._versionOptionName?this._version:this[s]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
|
|
18
|
+
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
19
|
+
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
20
|
+
`),this.outputHelp({error:!0}));let n=t||{},s=n.exitCode||1,i=n.code||"commander.error";this._exit(s,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in se.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()}`,se.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Cd(this.options),t=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(s=>!t(s)).forEach(s=>{this.setOptionValueWithSource(s,n.implied[s],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let n=o=>{let a=o.attributeName(),u=this.getOptionValue(a),l=this.options.find(p=>p.negate&&a===p.attributeName()),d=this.options.find(p=>!p.negate&&a===p.attributeName());return l&&(l.presetArg===void 0&&u===!1||l.presetArg!==void 0&&u===l.presetArg)?l:d||o},s=o=>{let a=n(o),u=a.attributeName();return this.getOptionValueSource(u)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},i=`error: ${s(e)} cannot be used with ${s(t)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],i=this;do{let o=i.createHelp().visibleOptions(i).filter(a=>a.long).map(a=>a.long);s=s.concat(o),i=i.parent}while(i&&!i._enablePositionalOptions);t=aa(e,s)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(i=>{s.push(i.name()),i.alias()&&s.push(i.alias())}),t=aa(e,s)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:"commander.unknownCommand"})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",n=n||"output the version number";let s=this.createOption(t,n);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
21
|
+
`),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let s=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(n=>Td(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=Qe.basename(e,Qe.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};let t={error:!!e.error},n;return t.error?n=s=>this._outputConfiguration.writeErr(s):n=s=>this._outputConfiguration.writeOut(s),t.write=e.write||n,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let n=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let s=this.helpInformation(n);if(t&&(s=t(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",n))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=se.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
22
|
+
Expecting one of '${n.join("', '")}'`);let s=`${e}Help`;return this.on(s,i=>{let o;typeof t=="function"?o=t({error:i.error,command:i.command}):o=t,o&&i.write(`${o}
|
|
23
|
+
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(s=>t.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function ca(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",s="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?t=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=i[1],/^\d+$/.test(i[3])?s=i[3]:n=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],s=i[4]),t&&s!=="0"?`${t}=${n}:${parseInt(s)+1}`:e})}ua.Command=gi});var pa=Y(Ee=>{var{Argument:da}=Jn(),{Command:yi}=la(),{CommanderError:Ed,InvalidArgumentError:ha}=gn(),{Help:Id}=ci(),{Option:fa}=hi();Ee.program=new yi;Ee.createCommand=r=>new yi(r);Ee.createOption=(r,e)=>new fa(r,e);Ee.createArgument=(r,e)=>new da(r,e);Ee.Command=yi;Ee.Option=fa;Ee.Argument=da;Ee.Help=Id;Ee.CommanderError=Ed;Ee.InvalidArgumentError=ha;Ee.InvalidOptionArgumentError=ha});var kn=Y(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.getParsedType=te.ZodParsedType=te.objectUtil=te.util=void 0;var Ti;(function(r){r.assertEqual=s=>{};function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},r.getValidEnumValues=s=>{let i=r.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),o={};for(let a of i)o[a]=s[a];return r.objectValues(o)},r.objectValues=s=>r.objectKeys(s).map(function(i){return s[i]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},r.find=(s,i)=>{for(let o of s)if(i(o))return o},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}r.joinValues=n,r.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(Ti||(te.util=Ti={}));var Da;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(Da||(te.objectUtil=Da={}));te.ZodParsedType=Ti.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var Vh=r=>{switch(typeof r){case"undefined":return te.ZodParsedType.undefined;case"string":return te.ZodParsedType.string;case"number":return Number.isNaN(r)?te.ZodParsedType.nan:te.ZodParsedType.number;case"boolean":return te.ZodParsedType.boolean;case"function":return te.ZodParsedType.function;case"bigint":return te.ZodParsedType.bigint;case"symbol":return te.ZodParsedType.symbol;case"object":return Array.isArray(r)?te.ZodParsedType.array:r===null?te.ZodParsedType.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?te.ZodParsedType.promise:typeof Map<"u"&&r instanceof Map?te.ZodParsedType.map:typeof Set<"u"&&r instanceof Set?te.ZodParsedType.set:typeof Date<"u"&&r instanceof Date?te.ZodParsedType.date:te.ZodParsedType.object;default:return te.ZodParsedType.unknown}};te.getParsedType=Vh});var us=Y(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.ZodError=Tt.quotelessJson=Tt.ZodIssueCode=void 0;var La=kn();Tt.ZodIssueCode=La.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 Hh=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:");Tt.quotelessJson=Hh;var Sn=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},n={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)n._errors.push(t(o));else{let a=n,u=0;for(;u<o.path.length;){let l=o.path[u];u===o.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(t(o))):a[l]=a[l]||{_errors:[]},a=a[l],u++}}};return s(this),n}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,La.util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},n=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];t[i]=t[i]||[],t[i].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};Tt.ZodError=Sn;Sn.create=r=>new Sn(r)});var Ci=Y(xi=>{"use strict";Object.defineProperty(xi,"__esModule",{value:!0});var fe=us(),Jt=kn(),Gh=(r,e)=>{let t;switch(r.code){case fe.ZodIssueCode.invalid_type:r.received===Jt.ZodParsedType.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case fe.ZodIssueCode.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,Jt.util.jsonStringifyReplacer)}`;break;case fe.ZodIssueCode.unrecognized_keys:t=`Unrecognized key(s) in object: ${Jt.util.joinValues(r.keys,", ")}`;break;case fe.ZodIssueCode.invalid_union:t="Invalid input";break;case fe.ZodIssueCode.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${Jt.util.joinValues(r.options)}`;break;case fe.ZodIssueCode.invalid_enum_value:t=`Invalid enum value. Expected ${Jt.util.joinValues(r.options)}, received '${r.received}'`;break;case fe.ZodIssueCode.invalid_arguments:t="Invalid function arguments";break;case fe.ZodIssueCode.invalid_return_type:t="Invalid function return type";break;case fe.ZodIssueCode.invalid_date:t="Invalid date";break;case fe.ZodIssueCode.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:Jt.util.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case fe.ZodIssueCode.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case fe.ZodIssueCode.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case fe.ZodIssueCode.custom:t="Invalid input";break;case fe.ZodIssueCode.invalid_intersection_types:t="Intersection results could not be merged";break;case fe.ZodIssueCode.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case fe.ZodIssueCode.not_finite:t="Number must be finite";break;default:t=e.defaultError,Jt.util.assertNever(r)}return{message:t}};xi.default=Gh});var ls=Y(xt=>{"use strict";var Wh=xt&&xt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(xt,"__esModule",{value:!0});xt.defaultErrorMap=void 0;xt.setErrorMap=Jh;xt.getErrorMap=Yh;var za=Wh(Ci());xt.defaultErrorMap=za.default;var Ua=za.default;function Jh(r){Ua=r}function Yh(){return Ua}});var Ii=Y(X=>{"use strict";var Xh=X&&X.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(X,"__esModule",{value:!0});X.isAsync=X.isValid=X.isDirty=X.isAborted=X.OK=X.DIRTY=X.INVALID=X.ParseStatus=X.EMPTY_PATH=X.makeIssue=void 0;X.addIssueToContext=tf;var Qh=ls(),qa=Xh(Ci()),ef=r=>{let{data:e,path:t,errorMaps:n,issueData:s}=r,i=[...t,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let a="",u=n.filter(l=>!!l).slice().reverse();for(let l of u)a=l(o,{data:e,defaultError:a}).message;return{...s,path:i,message:a}};X.makeIssue=ef;X.EMPTY_PATH=[];function tf(r,e){let t=(0,Qh.getErrorMap)(),n=(0,X.makeIssue)({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===qa.default?void 0:qa.default].filter(s=>!!s)});r.common.issues.push(n)}var Ei=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let s of t){if(s.status==="aborted")return X.INVALID;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let s of t){let i=await s.key,o=await s.value;n.push({key:i,value:o})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let s of t){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return X.INVALID;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(n[i.value]=o.value)}return{status:e.value,value:n}}};X.ParseStatus=Ei;X.INVALID=Object.freeze({status:"aborted"});var rf=r=>({status:"dirty",value:r});X.DIRTY=rf;var nf=r=>({status:"valid",value:r});X.OK=nf;var sf=r=>r.status==="aborted";X.isAborted=sf;var of=r=>r.status==="dirty";X.isDirty=of;var af=r=>r.status==="valid";X.isValid=af;var cf=r=>typeof Promise<"u"&&r instanceof Promise;X.isAsync=cf});var Fa=Y(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0})});var Ka=Y(ds=>{"use strict";Object.defineProperty(ds,"__esModule",{value:!0});ds.errorUtil=void 0;var Za;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(Za||(ds.errorUtil=Za={}))});var nc=Y(y=>{"use strict";Object.defineProperty(y,"__esModule",{value:!0});y.discriminatedUnion=y.date=y.boolean=y.bigint=y.array=y.any=y.coerce=y.ZodFirstPartyTypeKind=y.late=y.ZodSchema=y.Schema=y.ZodReadonly=y.ZodPipeline=y.ZodBranded=y.BRAND=y.ZodNaN=y.ZodCatch=y.ZodDefault=y.ZodNullable=y.ZodOptional=y.ZodTransformer=y.ZodEffects=y.ZodPromise=y.ZodNativeEnum=y.ZodEnum=y.ZodLiteral=y.ZodLazy=y.ZodFunction=y.ZodSet=y.ZodMap=y.ZodRecord=y.ZodTuple=y.ZodIntersection=y.ZodDiscriminatedUnion=y.ZodUnion=y.ZodObject=y.ZodArray=y.ZodVoid=y.ZodNever=y.ZodUnknown=y.ZodAny=y.ZodNull=y.ZodUndefined=y.ZodSymbol=y.ZodDate=y.ZodBoolean=y.ZodBigInt=y.ZodNumber=y.ZodString=y.ZodType=void 0;y.NEVER=y.void=y.unknown=y.union=y.undefined=y.tuple=y.transformer=y.symbol=y.string=y.strictObject=y.set=y.record=y.promise=y.preprocess=y.pipeline=y.ostring=y.optional=y.onumber=y.oboolean=y.object=y.number=y.nullable=y.null=y.never=y.nativeEnum=y.nan=y.map=y.literal=y.lazy=y.intersection=y.instanceof=y.function=y.enum=y.effect=void 0;y.datetimeRegex=Ja;y.custom=Xa;var C=us(),hs=ls(),O=Ka(),_=Ii(),E=kn(),Pe=class{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Va=(r,e)=>{if((0,_.isValid)(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new C.ZodError(r.common.issues);return this._error=t,this._error}}};function B(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,a)=>{let{message:u}=r;return o.code==="invalid_enum_value"?{message:u??a.defaultError}:typeof a.data>"u"?{message:u??n??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:u??t??a.defaultError}},description:s}}var F=class{get description(){return this._def.description}_getType(e){return(0,E.getParsedType)(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:(0,E.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new _.ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:(0,E.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if((0,_.isAsync)(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,E.getParsedType)(e)},s=this._parseSync({data:e,path:n.path,parent:n});return Va(n,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,E.getParsedType)(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return(0,_.isValid)(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>(0,_.isValid)(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,E.getParsedType)(e)},s=this._parse({data:e,path:n.path,parent:n}),i=await((0,_.isAsync)(s)?s:Promise.resolve(s));return Va(n,i)}refine(e,t){let n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,i)=>{let o=e(s),a=()=>i.addIssue({code:C.ZodIssueCode.custom,...n(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(u=>u?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new ke({schema:this,typeName:L.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 $e.create(this,this._def)}nullable(){return He.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ct.create(this)}promise(){return It.create(this,this._def)}or(e){return nr.create([this,e],this._def)}and(e){return sr.create(this,e,this._def)}transform(e){return new ke({...B(this._def),schema:this,typeName:L.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new ur({...B(this._def),innerType:this,defaultValue:t,typeName:L.ZodDefault})}brand(){return new Tn({typeName:L.ZodBranded,type:this,...B(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new lr({...B(this._def),innerType:this,catchValue:t,typeName:L.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return xn.create(this,e)}readonly(){return dr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};y.ZodType=F;y.Schema=F;y.ZodSchema=F;var uf=/^c[^\s-]{8,}$/i,lf=/^[0-9a-z]+$/,df=/^[0-9A-HJKMNP-TV-Z]{26}$/i,hf=/^[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,ff=/^[a-z0-9_-]{21}$/i,pf=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,mf=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,gf=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,yf="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ai,_f=/^(?:(?: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])$/,vf=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,bf=/^(([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]))$/,wf=/^(([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])$/,kf=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Sf=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ga="((\\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])))",Tf=new RegExp(`^${Ga}$`);function Wa(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function xf(r){return new RegExp(`^${Wa(r)}$`)}function Ja(r){let e=`${Ga}T${Wa(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Cf(r,e){return!!((e==="v4"||!e)&&_f.test(r)||(e==="v6"||!e)&&bf.test(r))}function Ef(r,e){if(!pf.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function If(r,e){return!!((e==="v4"||!e)&&vf.test(r)||(e==="v6"||!e)&&wf.test(r))}var Ct=class r extends F{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==E.ZodParsedType.string){let i=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(i,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.string,received:i.parsedType}),_.INVALID}let n=new _.ParseStatus,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(s=this._getOrReturnCtx(e,s),o?(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")gf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"email",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")Ai||(Ai=new RegExp(yf,"u")),Ai.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"emoji",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")hf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"uuid",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")ff.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"nanoid",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")uf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"cuid",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")lf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"cuid2",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")df.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"ulid",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"url",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"regex",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?Ja(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?Tf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?xf(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?mf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"duration",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?Cf(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"ip",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?Ef(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"jwt",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?If(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"cidr",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?kf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"base64",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?Sf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"base64url",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):E.util.assertNever(i);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:C.ZodIssueCode.invalid_string,...O.errorUtil.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...O.errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...O.errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...O.errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...O.errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...O.errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...O.errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...O.errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...O.errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...O.errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...O.errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...O.errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...O.errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...O.errorUtil.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...O.errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...O.errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...O.errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...O.errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...O.errorUtil.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...O.errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...O.errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...O.errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...O.errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...O.errorUtil.errToObj(t)})}nonempty(e){return this.min(1,O.errorUtil.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};y.ZodString=Ct;Ct.create=r=>new Ct({checks:[],typeName:L.ZodString,coerce:r?.coerce??!1,...B(r)});function Af(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,i=Number.parseInt(r.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var Yt=class r extends F{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)!==E.ZodParsedType.number){let i=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(i,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.number,received:i.parsedType}),_.INVALID}let n,s=new _.ParseStatus;for(let i of this._def.checks)i.kind==="int"?E.util.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Af(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.not_finite,message:i.message}),s.dirty()):E.util.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,O.errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,O.errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,O.errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,O.errorUtil.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:O.errorUtil.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:O.errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:O.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:O.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:O.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:O.errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:O.errorUtil.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:O.errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:O.errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:O.errorUtil.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&E.util.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};y.ZodNumber=Yt;Yt.create=r=>new Yt({checks:[],typeName:L.ZodNumber,coerce:r?.coerce||!1,...B(r)});var Xt=class r extends F{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)!==E.ZodParsedType.bigint)return this._getInvalidInput(e);let n,s=new _.ParseStatus;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):E.util.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.bigint,received:t.parsedType}),_.INVALID}gte(e,t){return this.setLimit("min",e,!0,O.errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,O.errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,O.errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,O.errorUtil.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:O.errorUtil.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:O.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:O.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:O.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:O.errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:O.errorUtil.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};y.ZodBigInt=Xt;Xt.create=r=>new Xt({checks:[],typeName:L.ZodBigInt,coerce:r?.coerce??!1,...B(r)});var Qt=class extends F{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==E.ZodParsedType.boolean){let n=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.boolean,received:n.parsedType}),_.INVALID}return(0,_.OK)(e.data)}};y.ZodBoolean=Qt;Qt.create=r=>new Qt({typeName:L.ZodBoolean,coerce:r?.coerce||!1,...B(r)});var er=class r extends F{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==E.ZodParsedType.date){let i=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(i,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.date,received:i.parsedType}),_.INVALID}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(i,{code:C.ZodIssueCode.invalid_date}),_.INVALID}let n=new _.ParseStatus,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):E.util.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:O.errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:O.errorUtil.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};y.ZodDate=er;er.create=r=>new er({checks:[],coerce:r?.coerce||!1,typeName:L.ZodDate,...B(r)});var qr=class extends F{_parse(e){if(this._getType(e)!==E.ZodParsedType.symbol){let n=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.symbol,received:n.parsedType}),_.INVALID}return(0,_.OK)(e.data)}};y.ZodSymbol=qr;qr.create=r=>new qr({typeName:L.ZodSymbol,...B(r)});var tr=class extends F{_parse(e){if(this._getType(e)!==E.ZodParsedType.undefined){let n=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.undefined,received:n.parsedType}),_.INVALID}return(0,_.OK)(e.data)}};y.ZodUndefined=tr;tr.create=r=>new tr({typeName:L.ZodUndefined,...B(r)});var rr=class extends F{_parse(e){if(this._getType(e)!==E.ZodParsedType.null){let n=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.null,received:n.parsedType}),_.INVALID}return(0,_.OK)(e.data)}};y.ZodNull=rr;rr.create=r=>new rr({typeName:L.ZodNull,...B(r)});var Et=class extends F{constructor(){super(...arguments),this._any=!0}_parse(e){return(0,_.OK)(e.data)}};y.ZodAny=Et;Et.create=r=>new Et({typeName:L.ZodAny,...B(r)});var at=class extends F{constructor(){super(...arguments),this._unknown=!0}_parse(e){return(0,_.OK)(e.data)}};y.ZodUnknown=at;at.create=r=>new at({typeName:L.ZodUnknown,...B(r)});var Le=class extends F{_parse(e){let t=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.never,received:t.parsedType}),_.INVALID}};y.ZodNever=Le;Le.create=r=>new Le({typeName:L.ZodNever,...B(r)});var Br=class extends F{_parse(e){if(this._getType(e)!==E.ZodParsedType.undefined){let n=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.void,received:n.parsedType}),_.INVALID}return(0,_.OK)(e.data)}};y.ZodVoid=Br;Br.create=r=>new Br({typeName:L.ZodVoid,...B(r)});var ct=class r extends F{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==E.ZodParsedType.array)return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.array,received:t.parsedType}),_.INVALID;if(s.exactLength!==null){let o=t.data.length>s.exactLength.value,a=t.data.length<s.exactLength.value;(o||a)&&((0,_.addIssueToContext)(t,{code:o?C.ZodIssueCode.too_big:C.ZodIssueCode.too_small,minimum:a?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&((0,_.addIssueToContext)(t,{code:C.ZodIssueCode.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&((0,_.addIssueToContext)(t,{code:C.ZodIssueCode.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>s.type._parseAsync(new Pe(t,o,t.path,a)))).then(o=>_.ParseStatus.mergeArray(n,o));let i=[...t.data].map((o,a)=>s.type._parseSync(new Pe(t,o,t.path,a)));return _.ParseStatus.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:O.errorUtil.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:O.errorUtil.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:O.errorUtil.toString(t)}})}nonempty(e){return this.min(1,e)}};y.ZodArray=ct;ct.create=(r,e)=>new ct({type:r,minLength:null,maxLength:null,exactLength:null,typeName:L.ZodArray,...B(e)});function Ur(r){if(r instanceof _e){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=$e.create(Ur(n))}return new _e({...r._def,shape:()=>e})}else return r instanceof ct?new ct({...r._def,type:Ur(r.element)}):r instanceof $e?$e.create(Ur(r.unwrap())):r instanceof He?He.create(Ur(r.unwrap())):r instanceof Ve?Ve.create(r.items.map(e=>Ur(e))):r}var _e=class r extends F{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=E.util.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==E.ZodParsedType.object){let l=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(l,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.object,received:l.parsedType}),_.INVALID}let{status:n,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof Le&&this._def.unknownKeys==="strip"))for(let l in s.data)o.includes(l)||a.push(l);let u=[];for(let l of o){let d=i[l],p=s.data[l];u.push({key:{status:"valid",value:l},value:d._parse(new Pe(s,p,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof Le){let l=this._def.unknownKeys;if(l==="passthrough")for(let d of a)u.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(l==="strict")a.length>0&&((0,_.addIssueToContext)(s,{code:C.ZodIssueCode.unrecognized_keys,keys:a}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let d of a){let p=s.data[d];u.push({key:{status:"valid",value:d},value:l._parse(new Pe(s,p,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let l=[];for(let d of u){let p=await d.key,v=await d.value;l.push({key:p,value:v,alwaysSet:d.alwaysSet})}return l}).then(l=>_.ParseStatus.mergeObjectSync(n,l)):_.ParseStatus.mergeObjectSync(n,u)}get shape(){return this._def.shape()}strict(e){return O.errorUtil.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let s=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:O.errorUtil.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:L.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let n of E.util.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let n of E.util.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return Ur(this)}partial(e){let t={};for(let n of E.util.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let n of E.util.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof $e;)i=i._def.innerType;t[n]=i}return new r({...this._def,shape:()=>t})}keyof(){return Ya(E.util.objectKeys(this.shape))}};y.ZodObject=_e;_e.create=(r,e)=>new _e({shape:()=>r,unknownKeys:"strip",catchall:Le.create(),typeName:L.ZodObject,...B(e)});_e.strictCreate=(r,e)=>new _e({shape:()=>r,unknownKeys:"strict",catchall:Le.create(),typeName:L.ZodObject,...B(e)});_e.lazycreate=(r,e)=>new _e({shape:r,unknownKeys:"strip",catchall:Le.create(),typeName:L.ZodObject,...B(e)});var nr=class extends F{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function s(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return t.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(a=>new C.ZodError(a.ctx.common.issues));return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_union,unionErrors:o}),_.INVALID}if(t.common.async)return Promise.all(n.map(async i=>{let o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let u of n){let l={...t,common:{...t.common,issues:[]},parent:null},d=u._parseSync({data:t.data,path:t.path,parent:l});if(d.status==="valid")return d;d.status==="dirty"&&!i&&(i={result:d,ctx:l}),l.common.issues.length&&o.push(l.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let a=o.map(u=>new C.ZodError(u));return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_union,unionErrors:a}),_.INVALID}}get options(){return this._def.options}};y.ZodUnion=nr;nr.create=(r,e)=>new nr({options:r,typeName:L.ZodUnion,...B(e)});var ot=r=>r instanceof ir?ot(r.schema):r instanceof ke?ot(r.innerType()):r instanceof or?[r.value]:r instanceof ar?r.options:r instanceof cr?E.util.objectValues(r.enum):r instanceof ur?ot(r._def.innerType):r instanceof tr?[void 0]:r instanceof rr?[null]:r instanceof $e?[void 0,...ot(r.unwrap())]:r instanceof He?[null,...ot(r.unwrap())]:r instanceof Tn||r instanceof dr?ot(r.unwrap()):r instanceof lr?ot(r._def.innerType):[],fs=class r extends F{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==E.ZodParsedType.object)return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.object,received:t.parsedType}),_.INVALID;let n=this.discriminator,s=t.data[n],i=this.optionsMap.get(s);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):((0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),_.INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let s=new Map;for(let i of t){let o=ot(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of o){if(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,i)}}return new r({typeName:L.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...B(n)})}};y.ZodDiscriminatedUnion=fs;function Ri(r,e){let t=(0,E.getParsedType)(r),n=(0,E.getParsedType)(e);if(r===e)return{valid:!0,data:r};if(t===E.ZodParsedType.object&&n===E.ZodParsedType.object){let s=E.util.objectKeys(e),i=E.util.objectKeys(r).filter(a=>s.indexOf(a)!==-1),o={...r,...e};for(let a of i){let u=Ri(r[a],e[a]);if(!u.valid)return{valid:!1};o[a]=u.data}return{valid:!0,data:o}}else if(t===E.ZodParsedType.array&&n===E.ZodParsedType.array){if(r.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<r.length;i++){let o=r[i],a=e[i],u=Ri(o,a);if(!u.valid)return{valid:!1};s.push(u.data)}return{valid:!0,data:s}}else return t===E.ZodParsedType.date&&n===E.ZodParsedType.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var sr=class extends F{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=(i,o)=>{if((0,_.isAborted)(i)||(0,_.isAborted)(o))return _.INVALID;let a=Ri(i.value,o.value);return a.valid?(((0,_.isDirty)(i)||(0,_.isDirty)(o))&&t.dirty(),{status:t.value,value:a.data}):((0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_intersection_types}),_.INVALID)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};y.ZodIntersection=sr;sr.create=(r,e,t)=>new sr({left:r,right:e,typeName:L.ZodIntersection,...B(t)});var Ve=class r extends F{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==E.ZodParsedType.array)return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.array,received:n.parsedType}),_.INVALID;if(n.data.length<this._def.items.length)return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),_.INVALID;!this._def.rest&&n.data.length>this._def.items.length&&((0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...n.data].map((o,a)=>{let u=this._def.items[a]||this._def.rest;return u?u._parse(new Pe(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(i).then(o=>_.ParseStatus.mergeArray(t,o)):_.ParseStatus.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};y.ZodTuple=Ve;Ve.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ve({items:r,typeName:L.ZodTuple,rest:null,...B(e)})};var ps=class r extends F{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==E.ZodParsedType.object)return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.object,received:n.parsedType}),_.INVALID;let s=[],i=this._def.keyType,o=this._def.valueType;for(let a in n.data)s.push({key:i._parse(new Pe(n,a,n.path,a)),value:o._parse(new Pe(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?_.ParseStatus.mergeObjectAsync(t,s):_.ParseStatus.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof F?new r({keyType:e,valueType:t,typeName:L.ZodRecord,...B(n)}):new r({keyType:Ct.create(),valueType:e,typeName:L.ZodRecord,...B(t)})}};y.ZodRecord=ps;var Fr=class extends F{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==E.ZodParsedType.map)return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.map,received:n.parsedType}),_.INVALID;let s=this._def.keyType,i=this._def.valueType,o=[...n.data.entries()].map(([a,u],l)=>({key:s._parse(new Pe(n,a,n.path,[l,"key"])),value:i._parse(new Pe(n,u,n.path,[l,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let u of o){let l=await u.key,d=await u.value;if(l.status==="aborted"||d.status==="aborted")return _.INVALID;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),a.set(l.value,d.value)}return{status:t.value,value:a}})}else{let a=new Map;for(let u of o){let l=u.key,d=u.value;if(l.status==="aborted"||d.status==="aborted")return _.INVALID;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),a.set(l.value,d.value)}return{status:t.value,value:a}}}};y.ZodMap=Fr;Fr.create=(r,e,t)=>new Fr({valueType:e,keyType:r,typeName:L.ZodMap,...B(t)});var Zr=class r extends F{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==E.ZodParsedType.set)return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.set,received:n.parsedType}),_.INVALID;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&((0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&((0,_.addIssueToContext)(n,{code:C.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 l=new Set;for(let d of u){if(d.status==="aborted")return _.INVALID;d.status==="dirty"&&t.dirty(),l.add(d.value)}return{status:t.value,value:l}}let a=[...n.data.values()].map((u,l)=>i._parse(new Pe(n,u,n.path,l)));return n.common.async?Promise.all(a).then(u=>o(u)):o(a)}min(e,t){return new r({...this._def,minSize:{value:e,message:O.errorUtil.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:O.errorUtil.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};y.ZodSet=Zr;Zr.create=(r,e)=>new Zr({valueType:r,minSize:null,maxSize:null,typeName:L.ZodSet,...B(e)});var ms=class r extends F{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==E.ZodParsedType.function)return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.function,received:t.parsedType}),_.INVALID;function n(a,u){return(0,_.makeIssue)({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,(0,hs.getErrorMap)(),hs.defaultErrorMap].filter(l=>!!l),issueData:{code:C.ZodIssueCode.invalid_arguments,argumentsError:u}})}function s(a,u){return(0,_.makeIssue)({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,(0,hs.getErrorMap)(),hs.defaultErrorMap].filter(l=>!!l),issueData:{code:C.ZodIssueCode.invalid_return_type,returnTypeError:u}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof It){let a=this;return(0,_.OK)(async function(...u){let l=new C.ZodError([]),d=await a._def.args.parseAsync(u,i).catch(S=>{throw l.addIssue(n(u,S)),l}),p=await Reflect.apply(o,this,d);return await a._def.returns._def.type.parseAsync(p,i).catch(S=>{throw l.addIssue(s(p,S)),l})})}else{let a=this;return(0,_.OK)(function(...u){let l=a._def.args.safeParse(u,i);if(!l.success)throw new C.ZodError([n(u,l.error)]);let d=Reflect.apply(o,this,l.data),p=a._def.returns.safeParse(d,i);if(!p.success)throw new C.ZodError([s(d,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:Ve.create(e).rest(at.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||Ve.create([]).rest(at.create()),returns:t||at.create(),typeName:L.ZodFunction,...B(n)})}};y.ZodFunction=ms;var ir=class extends F{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};y.ZodLazy=ir;ir.create=(r,e)=>new ir({getter:r,typeName:L.ZodLazy,...B(e)});var or=class extends F{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(t,{received:t.data,code:C.ZodIssueCode.invalid_literal,expected:this._def.value}),_.INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}};y.ZodLiteral=or;or.create=(r,e)=>new or({value:r,typeName:L.ZodLiteral,...B(e)});function Ya(r,e){return new ar({values:r,typeName:L.ZodEnum,...B(e)})}var ar=class r extends F{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return(0,_.addIssueToContext)(t,{expected:E.util.joinValues(n),received:t.parsedType,code:C.ZodIssueCode.invalid_type}),_.INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return(0,_.addIssueToContext)(t,{received:t.data,code:C.ZodIssueCode.invalid_enum_value,options:n}),_.INVALID}return(0,_.OK)(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};y.ZodEnum=ar;ar.create=Ya;var cr=class extends F{_parse(e){let t=E.util.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==E.ZodParsedType.string&&n.parsedType!==E.ZodParsedType.number){let s=E.util.objectValues(t);return(0,_.addIssueToContext)(n,{expected:E.util.joinValues(s),received:n.parsedType,code:C.ZodIssueCode.invalid_type}),_.INVALID}if(this._cache||(this._cache=new Set(E.util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=E.util.objectValues(t);return(0,_.addIssueToContext)(n,{received:n.data,code:C.ZodIssueCode.invalid_enum_value,options:s}),_.INVALID}return(0,_.OK)(e.data)}get enum(){return this._def.values}};y.ZodNativeEnum=cr;cr.create=(r,e)=>new cr({values:r,typeName:L.ZodNativeEnum,...B(e)});var It=class extends F{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==E.ZodParsedType.promise&&t.common.async===!1)return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.promise,received:t.parsedType}),_.INVALID;let n=t.parsedType===E.ZodParsedType.promise?t.data:Promise.resolve(t.data);return(0,_.OK)(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};y.ZodPromise=It;It.create=(r,e)=>new It({type:r,typeName:L.ZodPromise,...B(e)});var ke=class extends F{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===L.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{(0,_.addIssueToContext)(n,o),o.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(n.data,i);if(n.common.async)return Promise.resolve(o).then(async a=>{if(t.value==="aborted")return _.INVALID;let u=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return u.status==="aborted"?_.INVALID:u.status==="dirty"||t.value==="dirty"?(0,_.DIRTY)(u.value):u});{if(t.value==="aborted")return _.INVALID;let a=this._def.schema._parseSync({data:o,path:n.path,parent:n});return a.status==="aborted"?_.INVALID:a.status==="dirty"||t.value==="dirty"?(0,_.DIRTY)(a.value):a}}if(s.type==="refinement"){let o=a=>{let u=s.refinement(a,i);if(n.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?_.INVALID:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?_.INVALID:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.value,value:a.value}))))}if(s.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!(0,_.isValid)(o))return _.INVALID;let a=s.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>(0,_.isValid)(o)?Promise.resolve(s.transform(o.value,i)).then(a=>({status:t.value,value:a})):_.INVALID);E.util.assertNever(s)}};y.ZodEffects=ke;y.ZodTransformer=ke;ke.create=(r,e,t)=>new ke({schema:r,typeName:L.ZodEffects,effect:e,...B(t)});ke.createWithPreprocess=(r,e,t)=>new ke({schema:e,effect:{type:"preprocess",transform:r},typeName:L.ZodEffects,...B(t)});var $e=class extends F{_parse(e){return this._getType(e)===E.ZodParsedType.undefined?(0,_.OK)(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};y.ZodOptional=$e;$e.create=(r,e)=>new $e({innerType:r,typeName:L.ZodOptional,...B(e)});var He=class extends F{_parse(e){return this._getType(e)===E.ZodParsedType.null?(0,_.OK)(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};y.ZodNullable=He;He.create=(r,e)=>new He({innerType:r,typeName:L.ZodNullable,...B(e)});var ur=class extends F{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===E.ZodParsedType.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};y.ZodDefault=ur;ur.create=(r,e)=>new ur({innerType:r,typeName:L.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...B(e)});var lr=class extends F{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return(0,_.isAsync)(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new C.ZodError(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new C.ZodError(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};y.ZodCatch=lr;lr.create=(r,e)=>new lr({innerType:r,typeName:L.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...B(e)});var Kr=class extends F{_parse(e){if(this._getType(e)!==E.ZodParsedType.nan){let n=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.nan,received:n.parsedType}),_.INVALID}return{status:"valid",value:e.data}}};y.ZodNaN=Kr;Kr.create=r=>new Kr({typeName:L.ZodNaN,...B(r)});y.BRAND=Symbol("zod_brand");var Tn=class extends F{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}};y.ZodBranded=Tn;var xn=class r extends F{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?_.INVALID:i.status==="dirty"?(t.dirty(),(0,_.DIRTY)(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?_.INVALID:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:L.ZodPipeline})}};y.ZodPipeline=xn;var dr=class extends F{_parse(e){let t=this._def.innerType._parse(e),n=s=>((0,_.isValid)(s)&&(s.value=Object.freeze(s.value)),s);return(0,_.isAsync)(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}};y.ZodReadonly=dr;dr.create=(r,e)=>new dr({innerType:r,typeName:L.ZodReadonly,...B(e)});function Ha(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function Xa(r,e={},t){return r?Et.create().superRefine((n,s)=>{let i=r(n);if(i instanceof Promise)return i.then(o=>{if(!o){let a=Ha(e,n),u=a.fatal??t??!0;s.addIssue({code:"custom",...a,fatal:u})}});if(!i){let o=Ha(e,n),a=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:a})}}):Et.create()}y.late={object:_e.lazycreate};var L;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(L||(y.ZodFirstPartyTypeKind=L={}));var Rf=(r,e={message:`Input not instance of ${r.name}`})=>Xa(t=>t instanceof r,e);y.instanceof=Rf;var Qa=Ct.create;y.string=Qa;var ec=Yt.create;y.number=ec;var $f=Kr.create;y.nan=$f;var Pf=Xt.create;y.bigint=Pf;var tc=Qt.create;y.boolean=tc;var jf=er.create;y.date=jf;var Of=qr.create;y.symbol=Of;var Nf=tr.create;y.undefined=Nf;var Mf=rr.create;y.null=Mf;var Df=Et.create;y.any=Df;var Lf=at.create;y.unknown=Lf;var zf=Le.create;y.never=zf;var Uf=Br.create;y.void=Uf;var qf=ct.create;y.array=qf;var Bf=_e.create;y.object=Bf;var Ff=_e.strictCreate;y.strictObject=Ff;var Zf=nr.create;y.union=Zf;var Kf=fs.create;y.discriminatedUnion=Kf;var Vf=sr.create;y.intersection=Vf;var Hf=Ve.create;y.tuple=Hf;var Gf=ps.create;y.record=Gf;var Wf=Fr.create;y.map=Wf;var Jf=Zr.create;y.set=Jf;var Yf=ms.create;y.function=Yf;var Xf=ir.create;y.lazy=Xf;var Qf=or.create;y.literal=Qf;var ep=ar.create;y.enum=ep;var tp=cr.create;y.nativeEnum=tp;var rp=It.create;y.promise=rp;var rc=ke.create;y.effect=rc;y.transformer=rc;var np=$e.create;y.optional=np;var sp=He.create;y.nullable=sp;var ip=ke.createWithPreprocess;y.preprocess=ip;var op=xn.create;y.pipeline=op;var ap=()=>Qa().optional();y.ostring=ap;var cp=()=>ec().optional();y.onumber=cp;var up=()=>tc().optional();y.oboolean=up;y.coerce={string:(r=>Ct.create({...r,coerce:!0})),number:(r=>Yt.create({...r,coerce:!0})),boolean:(r=>Qt.create({...r,coerce:!0})),bigint:(r=>Xt.create({...r,coerce:!0})),date:(r=>er.create({...r,coerce:!0}))};y.NEVER=_.INVALID});var $i=Y(je=>{"use strict";var lp=je&&je.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),Vr=je&&je.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&lp(e,r,t)};Object.defineProperty(je,"__esModule",{value:!0});Vr(ls(),je);Vr(Ii(),je);Vr(Fa(),je);Vr(kn(),je);Vr(nc(),je);Vr(us(),je)});var oc=Y(ve=>{"use strict";var sc=ve&&ve.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),dp=ve&&ve.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),hp=ve&&ve.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&sc(e,r,t);return dp(e,r),e},fp=ve&&ve.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&sc(e,r,t)};Object.defineProperty(ve,"__esModule",{value:!0});ve.z=void 0;var ic=hp($i());ve.z=ic;fp($i(),ve);ve.default=ic});var Se=Y(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.EpicListResultMsg=h.EpicChild=h.EpicListMsg=h.BoardTriggerResultMsg=h.BoardTriggerMsg=h.BoardFetchResultMsg=h.BoardFetchMsg=h.ChatLoadResultMsg=h.ChatLoadMsg=h.ChatListResultMsg=h.ChatListMsg=h.ChatStreamMsg=h.JiraUsersResultMsg=h.DeployClaimResultMsg=h.DeployClaimMsg=h.RuleDiagnoseResultMsg=h.ProjectTestResultMsg=h.RunStatusMsg=h.RunLogMsg=h.RunClaimMsg=h.HeartbeatMsg=h.HelloMsg=h.RuleConfig=h.ProjectConfig=h.ActionConfig=h.DeployAction=h.EnvironmentConfig=h.PromotionMode=h.DeployStep=h.RespondAction=h.ImplementAction=h.PlanOnlyAction=h.TriggerConfig=h.StatusChangedTrigger=h.CommentKeywordTrigger=h.LabelAddedTrigger=h.ActionType=h.TriggerType=h.ACTIVE_RUN_STATUSES=h.RunStatus=h.needsInputMarkerIn=h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=h.NEEDS_INPUT_COMMENT_MARKER=h.NEEDS_INPUT_LABEL=h.NEEDS_INPUT_MARKER=h.BRANCH_DEPLOY_ISSUE_KEY=h.REQUIRED_AGENT_CAPABILITIES=h.DEFAULT_AGENT_ID=h.REGISTERED_AGENTS=h.PROTOCOL_VERSION=void 0;h.TECHNICAL_PLAN_PROMPT_TEMPLATE=h.MEMORY_UPDATE_PROMPT=h.DEFAULT_IMPLEMENT_PROMPT_TEMPLATE=h.DEFAULT_PLAN_PROMPT_TEMPLATE=h.EnrollResponse=h.EnrollRequest=h.ServerToRunnerMsg=h.JiraUsersMsg=h.DeploySuggestMsg=h.DeployStartMsg=h.RunRetryPushMsg=h.RunRejectedMsg=h.RunApprovedMsg=h.RunCancelMsg=h.RuleDiagnoseMsg=h.ProjectTestMsg=h.RunClaimResultMsg=h.ConfigMsg=h.HelloAckMsg=h.RunnerToServerMsg=h.DeploySuggestResultMsg=h.EnvPreflightResultMsg=h.EnvPreflightMsg=h.ChatCreateTicketResultMsg=h.ChatCreateTicketMsg=h.ChatTurnResultMsg=h.ChatTurnMsg=h.ChatFile=h.TeamCredsResultMsg=h.TeamCredsMsg=h.KnowledgeSaveResultMsg=h.KnowledgeSaveMsg=h.KnowledgeListResultMsg=h.KnowledgeFile=h.KnowledgeListMsg=h.AuditReviewResultMsg=h.AuditReviewMsg=h.AuditGetResultMsg=h.AuditGetMsg=h.AuditListResultMsg=h.AuditListMsg=h.AuditStartResultMsg=h.AuditStartMsg=h.AuditRecord=h.AuditFinding=h.AuditScope=h.AuditSeverity=h.AuditRole=h.EpicSuggestResultMsg=h.EpicSuggestMsg=void 0;h.DEFAULT_DEPLOY_SUGGEST_PROMPT_TEMPLATE=h.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE=h.PROMPT_PRESETS=h.DEFAULT_RESPOND_PROMPT_TEMPLATE=h.BUGFIX_IMPLEMENT_PROMPT_TEMPLATE=h.BUG_INVESTIGATION_PROMPT_TEMPLATE=void 0;h.missingAgentCapabilities=pp;h.parseRunnerMsg=gp;h.parseServerMsg=yp;var c=oc();h.PROTOCOL_VERSION="1.21";h.REGISTERED_AGENTS=[{id:"claude-code",displayName:"Claude Code",capabilities:{readOnlyJail:!0,editNoShellJail:!0,sessionResume:!0,costReporting:!0,modelSelection:!0,loginProfiles:!0},suggestedModels:["claude-fable-5","claude-opus-5","claude-sonnet-5","claude-haiku-4-5-20251001"],experimental:!1},{id:"codex",displayName:"OpenAI Codex CLI (experimental)",capabilities:{readOnlyJail:!0,editNoShellJail:!1,sessionResume:!1,costReporting:!1,modelSelection:!0,loginProfiles:!1},suggestedModels:[],experimental:!0}];h.DEFAULT_AGENT_ID="claude-code";h.REQUIRED_AGENT_CAPABILITIES={plan_only:["readOnlyJail","sessionResume"],respond:["readOnlyJail"],implement:["editNoShellJail","sessionResume"],deploy:[]};function pp(r,e){let t=h.REGISTERED_AGENTS.find(n=>n.id===r);return t?(h.REQUIRED_AGENT_CAPABILITIES[e]??[]).filter(n=>!t.capabilities[n]):null}h.BRANCH_DEPLOY_ISSUE_KEY="(branch deploy)";h.NEEDS_INPUT_MARKER="NEEDS-INPUT";h.NEEDS_INPUT_LABEL="agent-needs-input";h.NEEDS_INPUT_COMMENT_MARKER="Allwright needs your input";h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=["TicketPilot needs your input"];var mp=r=>r.includes(h.NEEDS_INPUT_COMMENT_MARKER)||h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS.some(e=>r.includes(e));h.needsInputMarkerIn=mp;h.RunStatus=c.z.enum(["queued","running","posting","awaiting_approval","needs_input","succeeded","failed","timed_out"]);h.ACTIVE_RUN_STATUSES=["queued","running","posting","awaiting_approval"];h.TriggerType=c.z.enum(["label_added","comment_keyword","status_changed"]);h.ActionType=c.z.enum(["plan_only","implement","respond","deploy"]);h.LabelAddedTrigger=c.z.object({type:c.z.literal("label_added"),label:c.z.string().min(1),doneLabel:c.z.string().min(1).default("agent-planned"),failedLabel:c.z.string().min(1).default("agent-failed")});h.CommentKeywordTrigger=c.z.object({type:c.z.literal("comment_keyword"),keyword:c.z.string().min(1),doneLabel:c.z.string().min(1).default("agent-implemented"),failedLabel:c.z.string().min(1).default("agent-failed")});h.StatusChangedTrigger=c.z.object({type:c.z.literal("status_changed"),status:c.z.string().min(1),doneLabel:c.z.string().min(1).default("agent-deployed"),failedLabel:c.z.string().min(1).default("agent-failed")});h.TriggerConfig=c.z.discriminatedUnion("type",[h.LabelAddedTrigger,h.CommentKeywordTrigger,h.StatusChangedTrigger]);h.PlanOnlyAction=c.z.object({type:c.z.literal("plan_only"),promptTemplate:c.z.string().min(1),timeoutSeconds:c.z.number().int().positive().max(3600).default(900),agent:c.z.string().default(h.DEFAULT_AGENT_ID),model:c.z.string().default("")});h.ImplementAction=c.z.object({type:c.z.literal("implement"),promptTemplate:c.z.string().min(1),timeoutSeconds:c.z.number().int().positive().max(7200).default(1800),maxTurns:c.z.number().int().positive().max(500).default(120),requireApproval:c.z.boolean().default(!0),branchTemplate:c.z.string().min(1).default("agent/{{issueKey}}").refine(r=>r.includes("{{issueKey}}"),{message:"branchTemplate must contain {{issueKey}}"}),baseBranch:c.z.string().min(1).default("main"),jiraTransition:c.z.string().optional(),jiraTransitionOnStart:c.z.string().optional(),jiraTransitionOnMerge:c.z.string().optional(),agent:c.z.string().default(h.DEFAULT_AGENT_ID),model:c.z.string().default(""),updateMemory:c.z.boolean().default(!1)});h.RespondAction=c.z.object({type:c.z.literal("respond"),promptTemplate:c.z.string().min(1),timeoutSeconds:c.z.number().int().positive().max(3600).default(600),agent:c.z.string().default(h.DEFAULT_AGENT_ID),model:c.z.string().default("")});h.DeployStep=c.z.object({name:c.z.string().min(1).max(120),run:c.z.string().min(1).max(4e3),continueOnError:c.z.boolean().default(!1)});h.PromotionMode=c.z.enum(["deploy_only","merge_and_deploy"]);h.EnvironmentConfig=c.z.object({id:c.z.string(),projectId:c.z.string(),name:c.z.string(),rank:c.z.number().int().nonnegative(),auditBeforeDeploy:c.z.enum(["","security","testing"]).default(""),branch:c.z.string().default(""),useDedicatedCheckout:c.z.boolean().default(!1),promotionMode:h.PromotionMode.default("deploy_only"),ticketBranchTemplate:c.z.string().default("agent/{{issueKey}}"),steps:c.z.array(h.DeployStep).default([]),workdir:c.z.string().default(""),timeoutSeconds:c.z.number().int().positive().max(21600).default(1800),requiredSecrets:c.z.array(c.z.string()).default([]),requireApproval:c.z.boolean().default(!1),requireSyncCheck:c.z.boolean().default(!1),previousEnvBranch:c.z.string().optional(),deployFromColumn:c.z.string().default(""),deployToColumn:c.z.string().default("")});h.DeployAction=c.z.object({type:c.z.literal("deploy"),envSelection:c.z.enum(["fixed","from_comment"]).default("from_comment"),environmentId:c.z.string().optional(),requireStatus:c.z.string().optional()});h.ActionConfig=c.z.discriminatedUnion("type",[h.PlanOnlyAction,h.ImplementAction,h.RespondAction,h.DeployAction]);h.ProjectConfig=c.z.object({id:c.z.string(),name:c.z.string(),jiraProjectKey:c.z.string(),repoName:c.z.string(),componentRoutes:c.z.array(c.z.object({component:c.z.string().min(1),repoName:c.z.string().min(1)})).default([])});h.RuleConfig=c.z.object({id:c.z.string(),projectId:c.z.string(),name:c.z.string(),enabled:c.z.boolean(),trigger:h.TriggerConfig,action:h.ActionConfig});h.HelloMsg=c.z.object({type:c.z.literal("hello"),protocolVersion:c.z.string(),runnerVersion:c.z.string(),platform:c.z.string(),justBooted:c.z.boolean().optional()});h.HeartbeatMsg=c.z.object({type:c.z.literal("heartbeat"),ts:c.z.string()});h.RunClaimMsg=c.z.object({type:c.z.literal("run.claim"),requestId:c.z.string(),ruleId:c.z.string(),issueKey:c.z.string(),issueSummary:c.z.string().default(""),triggerFingerprint:c.z.string(),dedupKey:c.z.string().optional(),triggeredByAccountId:c.z.string().optional()});h.RunLogMsg=c.z.object({type:c.z.literal("run.log"),runId:c.z.string(),seq:c.z.number().int().nonnegative(),ts:c.z.string(),level:c.z.enum(["info","warn","error","agent"]),message:c.z.string().max(16384)});h.RunStatusMsg=c.z.object({type:c.z.literal("run.status"),runId:c.z.string(),status:h.RunStatus,error:c.z.string().optional(),errorKind:c.z.enum(["guard"]).optional(),costUsd:c.z.number().nonnegative().optional(),inputTokens:c.z.number().int().nonnegative().optional(),outputTokens:c.z.number().int().nonnegative().optional(),resultSummary:c.z.string().max(2e3).optional(),billingMode:c.z.enum(["subscription","api","unknown"]).optional(),model:c.z.string().max(200).optional(),prUrl:c.z.string().optional(),headSha:c.z.string().optional(),deployedRef:c.z.string().optional(),retryAvailable:c.z.boolean().optional()});h.ProjectTestResultMsg=c.z.object({type:c.z.literal("project.test.result"),requestId:c.z.string(),ok:c.z.boolean(),checks:c.z.array(c.z.object({name:c.z.string(),ok:c.z.boolean(),detail:c.z.string()}))});h.RuleDiagnoseResultMsg=c.z.object({type:c.z.literal("rule.diagnose.result"),requestId:c.z.string(),checks:c.z.array(c.z.object({name:c.z.string(),ok:c.z.boolean(),detail:c.z.string()})),matchedCount:c.z.number().int().nonnegative(),excludedCount:c.z.number().int().nonnegative(),excludedSample:c.z.array(c.z.string()).max(5)});h.DeployClaimMsg=c.z.object({type:c.z.literal("deploy.claim"),requestId:c.z.string(),projectId:c.z.string(),ruleId:c.z.string(),issueKey:c.z.string(),issueSummary:c.z.string().default(""),environmentName:c.z.string(),requestedByAccountId:c.z.string().optional(),requestedByDisplayName:c.z.string().default(""),dedupKey:c.z.string(),triggerFingerprint:c.z.string()});h.DeployClaimResultMsg=c.z.object({type:c.z.literal("deploy.claim.result"),requestId:c.z.string(),accepted:c.z.boolean(),runId:c.z.string().optional(),environment:h.EnvironmentConfig.optional(),reason:c.z.string().optional(),code:c.z.enum(["ok","duplicate","unknown_environment","not_permitted","unlinked_jira_account","promotion_order","jira_disabled","rule_disabled","cap"]).optional()});h.JiraUsersResultMsg=c.z.object({type:c.z.literal("jira.users.result"),requestId:c.z.string(),ok:c.z.boolean(),users:c.z.array(c.z.object({accountId:c.z.string(),displayName:c.z.string(),email:c.z.string().default(""),active:c.z.boolean().default(!0)})).default([]),error:c.z.string().optional()});h.ChatStreamMsg=c.z.object({type:c.z.literal("chat.stream"),requestId:c.z.string(),seq:c.z.number().int().nonnegative(),text:c.z.string().max(8e3)});h.ChatListMsg=c.z.object({type:c.z.literal("chat.list"),requestId:c.z.string(),projectId:c.z.string()});h.ChatListResultMsg=c.z.object({type:c.z.literal("chat.list.result"),requestId:c.z.string(),sessions:c.z.array(c.z.object({sessionId:c.z.string(),title:c.z.string().default(""),updatedAt:c.z.string().default(""),messageCount:c.z.number().int().nonnegative().default(0)})).default([])});h.ChatLoadMsg=c.z.object({type:c.z.literal("chat.load"),requestId:c.z.string(),sessionId:c.z.string()});h.ChatLoadResultMsg=c.z.object({type:c.z.literal("chat.load.result"),requestId:c.z.string(),ok:c.z.boolean(),projectId:c.z.string().default(""),messages:c.z.array(c.z.object({role:c.z.enum(["user","agent"]),text:c.z.string()})).default([]),error:c.z.string().optional()});h.BoardFetchMsg=c.z.object({type:c.z.literal("board.fetch"),requestId:c.z.string(),projectId:c.z.string()});h.BoardFetchResultMsg=c.z.object({type:c.z.literal("board.fetch.result"),requestId:c.z.string(),ok:c.z.boolean(),browseBaseUrl:c.z.string().default(""),columns:c.z.array(c.z.object({name:c.z.string(),issues:c.z.array(c.z.object({key:c.z.string(),summary:c.z.string(),labels:c.z.array(c.z.string()).default([])})).default([])})).default([]),error:c.z.string().optional()});h.BoardTriggerMsg=c.z.object({type:c.z.literal("board.trigger"),requestId:c.z.string(),projectId:c.z.string(),issueKey:c.z.string(),comment:c.z.string().max(2e3).default(""),removeLabel:c.z.string().default(""),requestedBy:c.z.string().default(""),requestedByEmail:c.z.string().default(""),reimplement:c.z.boolean().default(!1)});h.BoardTriggerResultMsg=c.z.object({type:c.z.literal("board.trigger.result"),requestId:c.z.string(),ok:c.z.boolean(),error:c.z.string().optional()});h.EpicListMsg=c.z.object({type:c.z.literal("epic.list"),requestId:c.z.string(),projectId:c.z.string(),epicKey:c.z.string().default("")});h.EpicChild=c.z.object({key:c.z.string(),summary:c.z.string(),status:c.z.string(),statusCategory:c.z.string(),labels:c.z.array(c.z.string()).default([])});h.EpicListResultMsg=c.z.object({type:c.z.literal("epic.list.result"),requestId:c.z.string(),ok:c.z.boolean(),error:c.z.string().optional(),epics:c.z.array(c.z.object({key:c.z.string(),summary:c.z.string(),status:c.z.string()})).default([]),children:c.z.array(h.EpicChild).default([])});h.EpicSuggestMsg=c.z.object({type:c.z.literal("epic.suggest"),requestId:c.z.string(),projectId:c.z.string(),epicKey:c.z.string().min(1),model:c.z.string().default("")});h.EpicSuggestResultMsg=c.z.object({type:c.z.literal("epic.suggest.result"),requestId:c.z.string(),ok:c.z.boolean(),error:c.z.string().optional(),issueKey:c.z.string().default(""),reason:c.z.string().default(""),considered:c.z.number().int().default(0)});h.AuditRole=c.z.enum(["security","testing","architecture"]);h.AuditSeverity=c.z.enum(["critical","high","medium","low","info"]);h.AuditScope=c.z.object({kind:c.z.enum(["repo","ticket","branch"]).default("repo"),ref:c.z.string().default("")});h.AuditFinding=c.z.object({id:c.z.string().min(1),title:c.z.string().min(1),ruleId:c.z.string().max(20).default(""),severity:h.AuditSeverity,area:c.z.string().default(""),evidence:c.z.array(c.z.object({file:c.z.string().min(1),line:c.z.number().int().positive().optional(),note:c.z.string().default("")})).min(1),fix:c.z.string().default("")});h.AuditRecord=c.z.object({id:c.z.string(),role:h.AuditRole,createdAt:c.z.string(),model:c.z.string().default(""),summary:c.z.string().default(""),packNames:c.z.array(c.z.string()).default([]),findings:c.z.array(h.AuditFinding).default([]),costUsd:c.z.number().default(0),review:c.z.object({selected:c.z.array(c.z.string()),updatedAt:c.z.string()}).optional(),verdicts:c.z.record(c.z.object({verdict:c.z.enum(["valid","false-positive","wont-fix"]),note:c.z.string().default(""),by:c.z.string().default(""),at:c.z.string().default("")})).default({}),lessonsWritten:c.z.array(c.z.string()).default([]),ticketed:c.z.record(c.z.string()).default({}),scope:h.AuditScope.default({kind:"repo",ref:""}),testRun:c.z.array(c.z.object({command:c.z.string(),exitCode:c.z.number().int(),durationMs:c.z.number().int().default(0),tail:c.z.string().default("")})).optional()});h.AuditStartMsg=c.z.object({type:c.z.literal("audit.start"),requestId:c.z.string(),projectId:c.z.string(),role:h.AuditRole,model:c.z.string().default(""),scope:h.AuditScope.default({kind:"repo",ref:""})});h.AuditStartResultMsg=c.z.object({type:c.z.literal("audit.start.result"),requestId:c.z.string(),ok:c.z.boolean(),error:c.z.string().optional(),audit:h.AuditRecord.optional()});h.AuditListMsg=c.z.object({type:c.z.literal("audit.list"),requestId:c.z.string(),projectId:c.z.string()});h.AuditListResultMsg=c.z.object({type:c.z.literal("audit.list.result"),requestId:c.z.string(),ok:c.z.boolean(),error:c.z.string().optional(),audits:c.z.array(c.z.object({id:c.z.string(),role:h.AuditRole,createdAt:c.z.string(),findingCount:c.z.number().int(),bySeverity:c.z.record(c.z.number().int()).default({})})).default([])});h.AuditGetMsg=c.z.object({type:c.z.literal("audit.get"),requestId:c.z.string(),projectId:c.z.string(),auditId:c.z.string()});h.AuditGetResultMsg=c.z.object({type:c.z.literal("audit.get.result"),requestId:c.z.string(),ok:c.z.boolean(),error:c.z.string().optional(),audit:h.AuditRecord.optional()});h.AuditReviewMsg=c.z.object({type:c.z.literal("audit.review"),requestId:c.z.string(),projectId:c.z.string(),auditId:c.z.string(),selected:c.z.array(c.z.string()).optional(),ticketed:c.z.array(c.z.object({findingId:c.z.string(),issueKey:c.z.string()})).default([]),verdicts:c.z.array(c.z.object({findingId:c.z.string(),verdict:c.z.enum(["valid","false-positive","wont-fix"]),note:c.z.string().max(2e3).default("")})).default([]),verdictBy:c.z.string().default("")});h.AuditReviewResultMsg=c.z.object({type:c.z.literal("audit.review.result"),requestId:c.z.string(),ok:c.z.boolean(),error:c.z.string().optional(),audit:h.AuditRecord.optional()});h.KnowledgeListMsg=c.z.object({type:c.z.literal("knowledge.list"),requestId:c.z.string(),projectId:c.z.string()});h.KnowledgeFile=c.z.object({role:h.AuditRole,level:c.z.enum(["global","org","project"]),source:c.z.enum(["pack","lessons"]),name:c.z.string(),content:c.z.string(),editable:c.z.boolean().default(!1)});h.KnowledgeListResultMsg=c.z.object({type:c.z.literal("knowledge.list.result"),requestId:c.z.string(),ok:c.z.boolean(),error:c.z.string().optional(),files:c.z.array(h.KnowledgeFile).default([])});h.KnowledgeSaveMsg=c.z.object({type:c.z.literal("knowledge.save"),requestId:c.z.string(),projectId:c.z.string(),role:h.AuditRole,level:c.z.enum(["org","project"]),source:c.z.enum(["pack","lessons"]),name:c.z.string().min(1).max(100),content:c.z.string().max(6e4),append:c.z.boolean().default(!1),by:c.z.string().default("")});h.KnowledgeSaveResultMsg=c.z.object({type:c.z.literal("knowledge.save.result"),requestId:c.z.string(),ok:c.z.boolean(),error:c.z.string().optional()});h.TeamCredsMsg=c.z.object({type:c.z.literal("team.creds"),requestId:c.z.string(),emails:c.z.array(c.z.string()).max(200)});h.TeamCredsResultMsg=c.z.object({type:c.z.literal("team.creds.result"),requestId:c.z.string(),ok:c.z.boolean(),error:c.z.string().optional(),githubShared:c.z.boolean().default(!1),sharedGithubLogin:c.z.string().default(""),entries:c.z.array(c.z.object({email:c.z.string(),jira:c.z.enum(["own","runner-account","missing"]),jiraAs:c.z.string().default(""),github:c.z.enum(["own","shared","missing"]),githubAs:c.z.string().default("")})).default([])});h.ChatFile=c.z.object({name:c.z.string().min(1).max(255),contentBase64:c.z.string().min(1).max(6e6)});h.ChatTurnMsg=c.z.object({type:c.z.literal("chat.turn"),requestId:c.z.string(),projectId:c.z.string(),sessionId:c.z.string().optional(),message:c.z.string().min(1).max(2e4),userName:c.z.string().default(""),model:c.z.string().default(""),files:c.z.array(h.ChatFile).max(8).default([])});h.ChatTurnResultMsg=c.z.object({type:c.z.literal("chat.turn.result"),requestId:c.z.string(),ok:c.z.boolean(),sessionId:c.z.string().default(""),reply:c.z.string().default(""),error:c.z.string().optional()});h.ChatCreateTicketMsg=c.z.object({type:c.z.literal("chat.create.ticket"),requestId:c.z.string(),projectId:c.z.string(),summary:c.z.string().min(1).max(250),description:c.z.string().default(""),triggerComment:c.z.string().default(""),requestedBy:c.z.string().default(""),requestedByEmail:c.z.string().default(""),asEpic:c.z.boolean().default(!1),children:c.z.array(c.z.object({summary:c.z.string().min(1),description:c.z.string().default("")})).max(20).default([]),files:c.z.array(h.ChatFile).max(8).default([])});h.ChatCreateTicketResultMsg=c.z.object({type:c.z.literal("chat.create.ticket.result"),requestId:c.z.string(),ok:c.z.boolean(),issueKey:c.z.string().default(""),error:c.z.string().optional(),childKeys:c.z.array(c.z.string()).default([])});h.EnvPreflightMsg=c.z.object({type:c.z.literal("env.preflight"),requestId:c.z.string(),projectId:c.z.string(),environmentName:c.z.string().default(""),steps:c.z.array(h.DeployStep).default([]),requiredSecrets:c.z.array(c.z.string()).default([]),workdir:c.z.string().default(""),branch:c.z.string().default("")});h.EnvPreflightResultMsg=c.z.object({type:c.z.literal("env.preflight.result"),requestId:c.z.string(),ok:c.z.boolean(),checks:c.z.array(c.z.object({name:c.z.string(),ok:c.z.boolean(),detail:c.z.string().default("")})).default([])});h.DeploySuggestResultMsg=c.z.object({type:c.z.literal("deploy.suggest.result"),requestId:c.z.string(),ok:c.z.boolean(),steps:c.z.array(h.DeployStep).default([]),requiredSecrets:c.z.array(c.z.string()).default([]),notes:c.z.string().default(""),error:c.z.string().optional()});h.RunnerToServerMsg=c.z.discriminatedUnion("type",[h.HelloMsg,h.HeartbeatMsg,h.RunClaimMsg,h.RunLogMsg,h.RunStatusMsg,h.ProjectTestResultMsg,h.RuleDiagnoseResultMsg,h.DeployClaimMsg,h.DeploySuggestResultMsg,h.EnvPreflightResultMsg,h.ChatTurnResultMsg,h.ChatStreamMsg,h.ChatCreateTicketResultMsg,h.ChatListResultMsg,h.ChatLoadResultMsg,h.BoardFetchResultMsg,h.BoardTriggerResultMsg,h.TeamCredsResultMsg,h.AuditStartResultMsg,h.AuditListResultMsg,h.AuditGetResultMsg,h.AuditReviewResultMsg,h.KnowledgeListResultMsg,h.KnowledgeSaveResultMsg,h.EpicListResultMsg,h.EpicSuggestResultMsg,h.JiraUsersResultMsg]);h.HelloAckMsg=c.z.object({type:c.z.literal("hello.ack"),runnerId:c.z.string(),runnerName:c.z.string(),serverTime:c.z.string()});h.ConfigMsg=c.z.object({type:c.z.literal("config"),projects:c.z.array(h.ProjectConfig),rules:c.z.array(h.RuleConfig),environments:c.z.array(h.EnvironmentConfig).default([]),pollingPaused:c.z.boolean().default(!1)});h.RunClaimResultMsg=c.z.object({type:c.z.literal("run.claim.result"),requestId:c.z.string(),accepted:c.z.boolean(),runId:c.z.string().optional(),reason:c.z.string().optional(),claudeProfile:c.z.string().optional(),actorEmail:c.z.string().optional()});h.ProjectTestMsg=c.z.object({type:c.z.literal("project.test"),requestId:c.z.string(),projectId:c.z.string()});h.RuleDiagnoseMsg=c.z.object({type:c.z.literal("rule.diagnose"),requestId:c.z.string(),ruleId:c.z.string()});h.RunCancelMsg=c.z.object({type:c.z.literal("run.cancel"),runId:c.z.string()});h.RunApprovedMsg=c.z.object({type:c.z.literal("run.approved"),runId:c.z.string(),headSha:c.z.string().optional()});h.RunRejectedMsg=c.z.object({type:c.z.literal("run.rejected"),runId:c.z.string()});h.RunRetryPushMsg=c.z.object({type:c.z.literal("run.retryPush"),runId:c.z.string()});h.DeployStartMsg=c.z.object({type:c.z.literal("deploy.start"),runId:c.z.string(),projectId:c.z.string(),issueKey:c.z.string(),issueSummary:c.z.string().default(""),environment:h.EnvironmentConfig,requestedBy:c.z.string().default(""),attempt:c.z.number().int().positive().default(1)});h.DeploySuggestMsg=c.z.object({type:c.z.literal("deploy.suggest"),requestId:c.z.string(),projectId:c.z.string(),environmentName:c.z.string(),notes:c.z.string().default(""),timeoutSeconds:c.z.number().int().positive().max(1800).default(300)});h.JiraUsersMsg=c.z.object({type:c.z.literal("jira.users"),requestId:c.z.string(),query:c.z.string().default("")});h.ServerToRunnerMsg=c.z.discriminatedUnion("type",[h.HelloAckMsg,h.ConfigMsg,h.RunClaimResultMsg,h.ProjectTestMsg,h.RuleDiagnoseMsg,h.RunCancelMsg,h.RunApprovedMsg,h.RunRejectedMsg,h.RunRetryPushMsg,h.DeployClaimResultMsg,h.DeployStartMsg,h.DeploySuggestMsg,h.EnvPreflightMsg,h.ChatTurnMsg,h.ChatCreateTicketMsg,h.ChatListMsg,h.ChatLoadMsg,h.BoardFetchMsg,h.BoardTriggerMsg,h.TeamCredsMsg,h.AuditStartMsg,h.AuditListMsg,h.AuditGetMsg,h.AuditReviewMsg,h.KnowledgeListMsg,h.KnowledgeSaveMsg,h.EpicListMsg,h.EpicSuggestMsg,h.JiraUsersMsg]);h.EnrollRequest=c.z.object({enrollToken:c.z.string().min(10),name:c.z.string().min(1).max(100),platform:c.z.string(),runnerVersion:c.z.string()});h.EnrollResponse=c.z.object({runnerId:c.z.string(),runnerToken:c.z.string(),controlPlaneWsUrl:c.z.string()});function gp(r){return h.RunnerToServerMsg.parse(r)}function yp(r){return h.ServerToRunnerMsg.parse(r)}h.DEFAULT_PLAN_PROMPT_TEMPLATE=`You are a senior engineer asked to assess a Jira ticket. You have read-only access to the repository \u2014 do not attempt to modify anything.
|
|
24
|
+
|
|
25
|
+
Ticket {{issueKey}}: {{summary}}
|
|
26
|
+
|
|
27
|
+
Description:
|
|
28
|
+
{{description}}
|
|
29
|
+
|
|
30
|
+
Comments:
|
|
31
|
+
{{comments}}
|
|
32
|
+
|
|
33
|
+
The comments are in chronological order and may supersede the description: when they disagree, follow the newest decision made in the comments, and say so in your answer.
|
|
34
|
+
|
|
35
|
+
Explore the repository as needed, then write your answer.
|
|
36
|
+
|
|
37
|
+
YOUR ANSWER WILL BE POSTED AS A JIRA COMMENT, AND THE PERSON READING IT IS USUALLY NOT A PROGRAMMER. Write for them:
|
|
38
|
+
- Plain, everyday language. No jargon, no function names, no code snippets. Mention a file name only if the reader genuinely needs it.
|
|
39
|
+
- Short. As long as needed, no longer \u2014 a few sentences for a small ticket, at most ~200 words for a big one.
|
|
40
|
+
- Cover, in this order: what will be done (in product terms \u2014 what the user of the software will notice), roughly how big the job is (small / medium / large), and any assumption you had to make, stated simply.
|
|
41
|
+
- Do not describe your exploration process or list implementation steps \u2014 the developer doing the work will figure those out from the code.
|
|
42
|
+
|
|
43
|
+
IF THE TICKET IS TOO AMBIGUOUS to assess honestly \u2014 you cannot tell what is being asked, or two reasonable readings lead to very different work \u2014 do NOT guess. Instead make your ENTIRE final message start with the line:
|
|
44
|
+
${h.NEEDS_INPUT_MARKER}
|
|
45
|
+
followed by at most 3 numbered questions, in the same plain language, that the ticket author can answer without reading code. They will be posted as a comment on the ticket, and you will be resumed \u2014 with this exact conversation, not a fresh one \u2014 as soon as someone replies. Minor ambiguity is NOT a reason to ask \u2014 prefer a stated assumption; ask only when you are truly blocked.`;h.DEFAULT_IMPLEMENT_PROMPT_TEMPLATE=`You are a senior engineer implementing a Jira ticket in this repository. You can read the code and edit/create files. You cannot run commands, so be careful and conservative: follow the existing code style, keep the change minimal, and do not refactor unrelated code.
|
|
46
|
+
|
|
47
|
+
Ticket {{issueKey}}: {{summary}}
|
|
48
|
+
|
|
49
|
+
Description:
|
|
50
|
+
{{description}}
|
|
51
|
+
|
|
52
|
+
Comments:
|
|
53
|
+
{{comments}}
|
|
54
|
+
|
|
55
|
+
The comments are in chronological order and may supersede the description: when they disagree, follow the newest decision made in the comments, and say so in your answer.
|
|
56
|
+
|
|
57
|
+
Explore the repository, then implement the change.
|
|
58
|
+
|
|
59
|
+
DELETING FILES: you cannot delete a file directly. If the ticket requires removing files, create a file named .ticketpilot-delete at the repository root containing one repo-relative path per line \u2014 those files are deleted automatically just before your work is committed (CI/workflow paths are refused, and the manifest itself is never committed). Mention the deletions in your summary.
|
|
60
|
+
|
|
61
|
+
BEFORE editing anything: if the ticket is too ambiguous to implement \u2014 you cannot tell what is being asked, or two reasonable readings lead to very different code \u2014 do NOT guess and do NOT edit any file. Instead make your ENTIRE final message start with the line:
|
|
62
|
+
${h.NEEDS_INPUT_MARKER}
|
|
63
|
+
followed by at most 3 numbered questions in plain, non-technical language that the ticket author can answer without reading code. They will be posted as a comment on the ticket, and you will be resumed \u2014 with this exact conversation, not a fresh one \u2014 as soon as someone replies. Minor ambiguity is NOT a reason to ask \u2014 prefer a stated assumption; ask only when you are truly blocked.
|
|
64
|
+
|
|
65
|
+
When you are done, END your final message with a section titled "## Summary of changes" describing:
|
|
66
|
+
1. What you changed and why, file by file.
|
|
67
|
+
2. Anything you could NOT verify because you cannot run tests or commands.
|
|
68
|
+
3. Anything ambiguous in the ticket and the assumption you made.
|
|
69
|
+
|
|
70
|
+
That summary will become the pull request description a human reviews \u2014 write it for them.`;h.MEMORY_UPDATE_PROMPT=`
|
|
71
|
+
|
|
72
|
+
ALSO: after the implementation is complete, update the CLAUDE.md file at the repository root (create it if it does not exist). Record only durable knowledge about this codebase that would help someone working on a FUTURE ticket: where key modules live, non-obvious conventions, tricky couplings, gotchas you hit while working. Keep it short and general \u2014 do NOT log what this ticket changed, and do not repeat what the file already says. If nothing durable was learned, leave the file unchanged.`;h.TECHNICAL_PLAN_PROMPT_TEMPLATE=`You are a senior engineer asked to produce an implementation plan for a Jira ticket. You have read-only access to the repository \u2014 do not attempt to modify anything.
|
|
73
|
+
|
|
74
|
+
Ticket {{issueKey}}: {{summary}}
|
|
75
|
+
|
|
76
|
+
Description:
|
|
77
|
+
{{description}}
|
|
78
|
+
|
|
79
|
+
Comments:
|
|
80
|
+
{{comments}}
|
|
81
|
+
|
|
82
|
+
The comments are in chronological order and may supersede the description: when they disagree, follow the newest decision made in the comments, and say so in your answer.
|
|
83
|
+
|
|
84
|
+
Explore the repository as needed, then write a concise implementation plan with:
|
|
85
|
+
1. A one-paragraph summary of the approach.
|
|
86
|
+
2. The files you expect to change and why.
|
|
87
|
+
3. Step-by-step changes, in order.
|
|
88
|
+
4. Risks, open questions, and anything the ticket leaves ambiguous.
|
|
89
|
+
5. A rough size estimate (S/M/L).
|
|
90
|
+
|
|
91
|
+
Write the plan in Markdown. It will be posted as a comment on the ticket for a developer to review \u2014 be specific to THIS codebase, not generic.
|
|
92
|
+
|
|
93
|
+
IF THE TICKET IS TOO AMBIGUOUS to plan honestly, do NOT guess. Instead make your ENTIRE final message start with the line:
|
|
94
|
+
${h.NEEDS_INPUT_MARKER}
|
|
95
|
+
followed by at most 3 numbered questions the ticket author can answer. They will be posted as a comment on the ticket, and you will be resumed \u2014 with this exact conversation, not a fresh one \u2014 as soon as someone replies. Minor ambiguity is NOT a reason to ask \u2014 prefer a stated assumption; ask only when you are truly blocked.`;h.BUG_INVESTIGATION_PROMPT_TEMPLATE=`You are a senior engineer investigating a bug reported in a Jira ticket. You have read-only access to the repository \u2014 do not attempt to modify anything.
|
|
96
|
+
|
|
97
|
+
Ticket {{issueKey}}: {{summary}}
|
|
98
|
+
|
|
99
|
+
Description:
|
|
100
|
+
{{description}}
|
|
101
|
+
|
|
102
|
+
Comments:
|
|
103
|
+
{{comments}}
|
|
104
|
+
|
|
105
|
+
The comments are in chronological order and may supersede the description: when they disagree, follow the newest decision made in the comments, and say so in your answer.
|
|
106
|
+
|
|
107
|
+
Trace the reported behavior through the code, then write, in Markdown:
|
|
108
|
+
1. The bug, restated in one sentence.
|
|
109
|
+
2. The most likely root cause \u2014 name the specific file(s) and logic responsible, and say how confident you are.
|
|
110
|
+
3. If several causes are plausible, list them in order of likelihood.
|
|
111
|
+
4. The fix you would make, and any regression risk around it.
|
|
112
|
+
|
|
113
|
+
The reader is a developer. Do not pad \u2014 a short, confident answer beats a long, hedged one.
|
|
114
|
+
|
|
115
|
+
IF YOU CANNOT investigate meaningfully (the ticket does not say what happened, or how to see it), make your ENTIRE final message start with the line:
|
|
116
|
+
${h.NEEDS_INPUT_MARKER}
|
|
117
|
+
followed by at most 3 numbered questions (steps to reproduce, expected vs actual behavior). They will be posted on the ticket, and you will be resumed \u2014 with this exact conversation, not a fresh one \u2014 as soon as someone replies.`;h.BUGFIX_IMPLEMENT_PROMPT_TEMPLATE=`You are a senior engineer fixing a bug reported in a Jira ticket. You can read the code and edit/create files. You cannot run commands, so be careful and conservative.
|
|
118
|
+
|
|
119
|
+
Ticket {{issueKey}}: {{summary}}
|
|
120
|
+
|
|
121
|
+
Description:
|
|
122
|
+
{{description}}
|
|
123
|
+
|
|
124
|
+
Comments:
|
|
125
|
+
{{comments}}
|
|
126
|
+
|
|
127
|
+
The comments are in chronological order and may supersede the description: when they disagree, follow the newest decision made in the comments, and say so in your answer.
|
|
128
|
+
|
|
129
|
+
Find the root cause, then make the SMALLEST change that fixes it. Do not refactor, do not fix unrelated issues you notice, do not change formatting beyond the fix.
|
|
130
|
+
|
|
131
|
+
DELETING FILES: you cannot delete a file directly. If the fix requires removing a file, create a file named .ticketpilot-delete at the repository root containing one repo-relative path per line \u2014 those files are deleted automatically just before your work is committed (CI/workflow paths are refused, and the manifest itself is never committed). Mention the deletions in your summary.
|
|
132
|
+
|
|
133
|
+
BEFORE editing anything: if you cannot tell what the bug is, or cannot locate a plausible cause, do NOT guess and do NOT edit any file. Instead make your ENTIRE final message start with the line:
|
|
134
|
+
${h.NEEDS_INPUT_MARKER}
|
|
135
|
+
followed by at most 3 numbered questions (steps to reproduce, expected vs actual behavior). They will be posted on the ticket, and you will be resumed \u2014 with this exact conversation, not a fresh one \u2014 as soon as someone replies.
|
|
136
|
+
|
|
137
|
+
When you are done, END your final message with a section titled "## Summary of changes" describing:
|
|
138
|
+
1. The root cause.
|
|
139
|
+
2. The fix, file by file.
|
|
140
|
+
3. Regression risk, and what you could not verify (you cannot run tests).
|
|
141
|
+
|
|
142
|
+
That summary will become the pull request description a human reviews \u2014 write it for them.`;h.DEFAULT_RESPOND_PROMPT_TEMPLATE=`You are the engineering assistant for this repository, answering a question asked in a Jira ticket comment. You have read-only access to the code \u2014 explore it as needed to answer accurately.
|
|
143
|
+
|
|
144
|
+
Ticket {{issueKey}}: {{summary}}
|
|
145
|
+
|
|
146
|
+
Description:
|
|
147
|
+
{{description}}
|
|
148
|
+
|
|
149
|
+
Comments:
|
|
150
|
+
{{comments}}
|
|
151
|
+
|
|
152
|
+
The comments are in chronological order and may supersede the description: when they disagree, follow the newest decision made in the comments, and say so in your answer.
|
|
153
|
+
|
|
154
|
+
The question you are answering, asked by {{questionAuthor}}:
|
|
155
|
+
{{question}}
|
|
156
|
+
|
|
157
|
+
Write your answer as a Jira comment addressed to {{questionAuthor}}. Match their technical level \u2014 if they sound non-technical, answer in plain language with no jargon or code. Be direct, and only as long as the answer needs. If the code contradicts an assumption in the question, say so plainly. If you cannot answer from the ticket and the code alone, say exactly what information you would need \u2014 your reply IS the conversation, so just ask.`;h.PROMPT_PRESETS=[{id:"plan-simple",name:"Simple plan \u2014 plain language",action:"plan_only",whenToUse:"Default. The Jira comment is read by non-technical people: short, no jargon, describes the work in product terms.",template:h.DEFAULT_PLAN_PROMPT_TEMPLATE},{id:"plan-technical",name:"Technical plan \u2014 for developers",action:"plan_only",whenToUse:"The readers are developers: files to change, ordered steps, risks, and a size estimate.",template:h.TECHNICAL_PLAN_PROMPT_TEMPLATE},{id:"plan-bug",name:"Bug investigation",action:"plan_only",whenToUse:"The ticket reports a bug: trace the root cause in the code and propose the fix \u2014 without changing anything.",template:h.BUG_INVESTIGATION_PROMPT_TEMPLATE},{id:"impl-standard",name:"Standard implement",action:"implement",whenToUse:"Default. Careful, minimal implementation that follows the existing code style.",template:h.DEFAULT_IMPLEMENT_PROMPT_TEMPLATE},{id:"impl-bugfix",name:"Bug fix \u2014 smallest change",action:"implement",whenToUse:"The ticket is a bug: find the root cause and make the smallest possible fix, nothing else.",template:h.BUGFIX_IMPLEMENT_PROMPT_TEMPLATE},{id:"respond-default",name:"Answer a question",action:"respond",whenToUse:"Default for reply rules. Reads the code and answers the comment at the asker's technical level.",template:h.DEFAULT_RESPOND_PROMPT_TEMPLATE}];h.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE=`You are a release engineer. This repository ships a deploy document written by its operators \u2014 it is the ground truth for how "{{envName}}" is deployed. Your ONLY job is to translate that document into executable steps.
|
|
158
|
+
|
|
159
|
+
The document ({{docPath}}):
|
|
160
|
+
---
|
|
161
|
+
{{docContent}}
|
|
162
|
+
---
|
|
163
|
+
|
|
164
|
+
What the operator told us about this environment:
|
|
165
|
+
{{notes}}
|
|
166
|
+
|
|
167
|
+
{{machineContext}}
|
|
168
|
+
|
|
169
|
+
Reply with a single fenced \`\`\`json block and nothing else, in this shape:
|
|
170
|
+
|
|
171
|
+
{
|
|
172
|
+
"steps": [
|
|
173
|
+
{ "name": "Install dependencies", "run": "pnpm install --frozen-lockfile" },
|
|
174
|
+
{ "name": "Build", "run": "pnpm build" }
|
|
175
|
+
],
|
|
176
|
+
"requiredSecrets": ["SSH_HOST", "SSH_KEY_PATH"],
|
|
177
|
+
"notes": "Anything the human must check or fill in before saving."
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
Output rules: emit the fenced block and nothing else. Use exactly the key names above. Keep each "name" under 100 characters; explanations go in "notes".
|
|
181
|
+
|
|
182
|
+
Rules for the steps:
|
|
183
|
+
- Translate ONLY what the document says. Do NOT invent commands, hosts, paths or tooling the document does not mention \u2014 if the document is missing something a deploy obviously needs, say so in "notes" instead of guessing.
|
|
184
|
+
- If the document describes several environments, extract the "{{envName}}" parts; if it doesn't distinguish, say so in "notes".
|
|
185
|
+
- Each "run" is one bash command line, executed in the repo checkout on the machine the runner is installed on.
|
|
186
|
+
- Reference secrets as environment variables ($DEPLOY_HOST), never literal values, and list every variable you use in "requiredSecrets".
|
|
187
|
+
- Prefer commands that are safe to re-run; a deploy may be retried.`;h.DEFAULT_DEPLOY_SUGGEST_PROMPT_TEMPLATE=`You are a release engineer. Inspect this repository read-only and propose the shell steps needed to deploy it to the "{{envName}}" environment.
|
|
188
|
+
|
|
189
|
+
What the operator told us about this environment:
|
|
190
|
+
{{notes}}
|
|
191
|
+
|
|
192
|
+
{{machineContext}}
|
|
193
|
+
|
|
194
|
+
Ground your answer in what is ACTUALLY in this repo: package manager and scripts in package.json / Makefile / Dockerfile / docker-compose.yml, CI workflows, existing deploy or release scripts, framework conventions, and any deployment docs. Do not invent tooling the repo does not use \u2014 and do not reference tools the machine context above says are missing.
|
|
195
|
+
|
|
196
|
+
Reply with a single fenced \`\`\`json block and nothing else, in this shape:
|
|
197
|
+
|
|
198
|
+
{
|
|
199
|
+
"steps": [
|
|
200
|
+
{ "name": "Install dependencies", "run": "pnpm install --frozen-lockfile" },
|
|
201
|
+
{ "name": "Build", "run": "pnpm build" }
|
|
202
|
+
],
|
|
203
|
+
"requiredSecrets": ["SSH_HOST", "SSH_KEY_PATH"],
|
|
204
|
+
"notes": "Anything the human must check or fill in before saving."
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
Output rules, which matter as much as the content: emit the fenced block and nothing else \u2014 no preamble, no commentary after it. Use exactly the key names above ("steps", "run", "name", "requiredSecrets", "notes"). Keep each "name" under 100 characters and put any explanation in "notes" instead.
|
|
208
|
+
|
|
209
|
+
Rules for the steps:
|
|
210
|
+
- Each "run" is one bash command line, executed in the repo checkout on the machine the runner is installed on.
|
|
211
|
+
- Reference secrets as environment variables ($DEPLOY_HOST), never literal values, and list every variable you use in "requiredSecrets".
|
|
212
|
+
- Prefer commands that are safe to re-run; a deploy may be retried.
|
|
213
|
+
- Order matters: install, build, test (if cheap), then release.
|
|
214
|
+
- If you genuinely cannot tell how this repo is deployed, return an empty "steps" array and explain what is missing in "notes".`});var _c={};ri(_c,{DELETE_MANIFEST_FILE:()=>Hr,MAX_CHANGED_FILES:()=>ys,MAX_CHANGED_LINES:()=>_s,applyDeleteManifest:()=>Pi,branchForIssue:()=>Ui,branchSha:()=>ws,branchesDiffer:()=>Zi,checkDiffSafety:()=>Di,commitAll:()=>bs,deleteStaleBranch:()=>Ni,diffAgainstDefault:()=>ks,envCheckoutPath:()=>yc,envCheckoutsRoot:()=>gc,fetchBase:()=>Gr,headSha:()=>En,mergeTicketBranch:()=>Bi,originUrl:()=>fr,parseOwnerRepo:()=>pr,prepareEnvCheckout:()=>qi,pruneWorktrees:()=>zi,pushBranch:()=>Li,pushEnvBranch:()=>Fi,pushWipBranch:()=>ji,removeWorktree:()=>Wr,statusSnapshot:()=>Oi,worktreeAdd:()=>Mi,worktreeFingerprint:()=>vs,worktreesRoot:()=>Cn});async function Z(r,e,t={}){try{let{stdout:n}=await hc("git",["-C",r,...e],{timeout:t.timeoutMs??12e4,maxBuffer:16777216,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});return n}catch(n){let s=n;throw new Error(`git ${e[0]} failed: ${(s.stderr||s.message||"").trim().slice(0,500)}`)}}async function Pi(r){let e={deleted:[],refused:[]},t=re.default.join(r,Hr);if(!ue.default.existsSync(t))return e;let n=re.default.resolve(r),s=ue.default.readFileSync(t,"utf8").split(`
|
|
215
|
+
`).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#"));for(let i of s.slice(0,200)){if(re.default.isAbsolute(i)){e.refused.push(`${i} \u2014 absolute paths are not allowed`);continue}let o=re.default.resolve(n,i);if(o!==n&&!o.startsWith(n+re.default.sep)){e.refused.push(`${i} \u2014 escapes the worktree`);continue}let a=re.default.relative(n,o).split(re.default.sep).join("/");if(a===Hr)continue;if(mc.some(l=>l.test(a))){e.refused.push(`${i} \u2014 protected path (CI/hook files are never touched)`);continue}let u;try{u=ue.default.lstatSync(o)}catch{e.refused.push(`${i} \u2014 no such file`);continue}if(u.isDirectory()){e.refused.push(`${i} \u2014 is a directory (list the files inside it instead)`);continue}try{ue.default.rmSync(o),e.deleted.push(a)}catch(l){e.refused.push(`${i} \u2014 ${l instanceof Error?l.message:"delete failed"}`)}}return ue.default.rmSync(t,{force:!0}),e}async function ji(r,e){await Z(r,["push","--force","origin",`HEAD:refs/heads/${e}`],{timeoutMs:3e5})}async function vs(r){let e=await Z(r,["status","--porcelain"]),t=await Z(r,["diff","--numstat"]),n=e.split(`
|
|
216
|
+
`).filter(s=>s.startsWith("??")).map(s=>s.slice(3).trim()).slice(0,500).map(s=>{try{let i=ue.default.statSync(re.default.join(r,s));return`${s}:${i.size}:${i.mtimeMs}`}catch{return s}}).join(`
|
|
217
|
+
`);return`${e}
|
|
218
|
+
--
|
|
219
|
+
${t}
|
|
220
|
+
--
|
|
221
|
+
${n}`}async function Oi(r){let e=(await Z(r,["rev-parse","--abbrev-ref","HEAD"])).trim(),t=(await Z(r,["log","--oneline","-1"])).trim(),n=(await Z(r,["status","--porcelain"])).trim(),s=n?n.split(`
|
|
222
|
+
`):[],i=s.slice(0,15).join(`
|
|
223
|
+
`),o=s.length>15?`
|
|
224
|
+
(\u2026 ${s.length-15} more)`:"";return`branch ${e} @ ${t}
|
|
225
|
+
working tree: ${s.length?`
|
|
226
|
+
${i}${o}`:"clean"}`}function Cn(){let r=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(ue.default.existsSync(re.default.join(hr.default.homedir(),".cache","ticketpilot"))?re.default.join(hr.default.homedir(),".cache","ticketpilot"):re.default.join(hr.default.homedir(),".cache","allwright"));return re.default.join(r,"worktrees")}async function Gr(r,e){try{await Z(r,["fetch","origin",e])}catch(t){throw new Error(`could not fetch base branch "${e}" from origin \u2014 check the rule's base branch and that this machine can reach the remote (${t instanceof Error?t.message:t})`)}}async function Ni(r,e){try{let t=await Z(r,["worktree","list","--porcelain"]),n=Cn(),s=null;for(let i of t.split(`
|
|
227
|
+
`))i.startsWith("worktree ")&&(s=i.slice(9).trim()),i===`branch refs/heads/${e}`&&s&&s.startsWith(n)&&await Z(r,["worktree","remove","--force",s]);await Z(r,["worktree","prune"])}catch{}try{await Z(r,["branch","-D",e])}catch{}}async function Mi(r,e,t,n){ue.default.mkdirSync(re.default.dirname(e),{recursive:!0,mode:448}),await Z(r,["worktree","add","-b",t,e,`origin/${n}`])}async function bs(r,e){if(await Z(r,["add","-A"]),!(await Z(r,["status","--porcelain"])).trim())throw new Error("Claude wrote no changes \u2014 nothing to commit");await Z(r,["-c",`user.name=${fc}`,"-c",`user.email=${pc}`,"commit","-m",e])}async function Di(r,e){let n=(await Z(r,["diff","--name-only",`origin/${e}...HEAD`])).split(`
|
|
228
|
+
`).filter(Boolean),s=n.filter(l=>mc.some(d=>d.test(l))),i=await Z(r,["diff","--shortstat",`origin/${e}...HEAD`]),o=Number(/(\d+) insertion/.exec(i)?.[1]??0),a=Number(/(\d+) deletion/.exec(i)?.[1]??0);return{ok:s.length===0&&n.length<=ys&&o+a<=_s,files:n.length,insertions:o,deletions:a,forbidden:s}}async function Li(r,e){await Z(r,["fetch","--prune","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],{timeoutMs:12e4}).catch(()=>Z(r,["update-ref","-d",`refs/remotes/origin/${e}`]).catch(()=>{})),await Z(r,["push","--force-with-lease","-u","origin",e],{timeoutMs:3e5})}async function En(r){return(await Z(r,["rev-parse","HEAD"])).trim()}async function ws(r,e){try{return(await Z(r,["rev-parse","--verify",`refs/heads/${e}`])).trim()}catch{return null}}async function Wr(r,e){try{await Z(r,["worktree","remove","--force",e])}catch{ue.default.rmSync(e,{recursive:!0,force:!0})}}async function zi(r,e=[]){let t=new Set(e.map(s=>re.default.basename(re.default.resolve(s))).filter(s=>s.length>0)),n=Cn();if(ue.default.existsSync(n))for(let s of ue.default.readdirSync(n))t.has(s)||ue.default.rmSync(re.default.join(n,s),{recursive:!0,force:!0});for(let s of r)try{await Z(s,["worktree","prune"])}catch{}}async function Ui(r,e){return await Z(r,["fetch","origin","--prune"]).catch(()=>{}),(await Z(r,["branch","-r","--list",`*${e}*`])).split(`
|
|
229
|
+
`).map(s=>s.trim()).filter(s=>s&&!s.includes("->"))[0]??null}async function ks(r,e,t=6e4){let s=(await Z(r,["symbolic-ref","refs/remotes/origin/HEAD"]).catch(()=>"")).trim().replace("refs/remotes/","")||"origin/main",i=await Z(r,["diff","--stat",`${s}...${e}`]),o=await Z(r,["diff",`${s}...${e}`]);return{base:s,stat:i.slice(0,4e3),diff:o.slice(0,t)}}function gc(){let r=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(ue.default.existsSync(re.default.join(hr.default.homedir(),".cache","ticketpilot"))?re.default.join(hr.default.homedir(),".cache","ticketpilot"):re.default.join(hr.default.homedir(),".cache","allwright"));return re.default.join(r,"env-checkouts")}function uc(r){return r.replace(/[^\w.-]+/g,"_")}function yc(r,e){return re.default.join(gc(),uc(r),uc(e))}async function qi(r){let e=yc(r.repoName,r.envName);return await Z(r.repoPath,["fetch","origin",r.branch],{timeoutMs:3e5}),ue.default.existsSync(re.default.join(e,".git"))?await Z(e,["fetch","origin",r.branch],{timeoutMs:3e5}):(ue.default.rmSync(e,{recursive:!0,force:!0}),ue.default.mkdirSync(re.default.dirname(e),{recursive:!0,mode:448}),await Z(r.repoPath,["worktree","prune"]).catch(()=>{}),await Z(r.repoPath,["worktree","add","--detach",e,`origin/${r.branch}`])),r.attached?await Z(e,["checkout","-B",r.branch,`origin/${r.branch}`]):await Z(e,["checkout","--force","--detach",`origin/${r.branch}`]),e}async function Bi(r,e,t){try{await Z(r,["fetch","origin",e],{timeoutMs:3e5})}catch{return{ok:!1,reason:`branch "${e}" does not exist on origin \u2014 nothing to promote. Check the environment's ticket branch template against the branch your implement rule creates.`}}try{return await Z(r,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyMerged:!0}}catch{}try{return await Z(r,["-c",`user.name=${fc}`,"-c",`user.email=${pc}`,"merge","--no-ff","-m",t,`origin/${e}`]),{ok:!0}}catch(n){return await Z(r,["merge","--abort"]).catch(()=>{}),{ok:!1,reason:`could not merge "${e}" into the environment branch \u2014 ${n instanceof Error?n.message:n}. Resolve it manually and deploy again.`}}}async function Fi(r,e){try{await Z(r,["push","origin",e],{timeoutMs:3e5})}catch(t){throw new Error(`could not push "${e}" \u2014 ${t instanceof Error?t.message:t}. Someone may have pushed to it since this deploy started; retry.`)}}async function Zi(r,e,t){try{return await hc("git",["-C",r,"diff","--quiet",e,t,"--"],{timeout:12e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),!1}catch(n){let s=n;if(s.code===1)return!0;throw new Error(`git diff failed comparing ${e}..${t}: ${(s.stderr||s.message||"").trim().slice(0,500)}`)}}async function fr(r){return(await Z(r,["config","--get","remote.origin.url"])).trim()}function pr(r){let e=/^git@github\.com(?:-[\w.-]+)?:([^/]+)\/(.+?)(\.git)?$/.exec(r)??/^https:\/\/github\.com\/([^/]+)\/(.+?)(\.git)?\/?$/.exec(r)??/^ssh:\/\/git@github\.com(?:-[\w.-]+)?\/([^/]+)\/(.+?)(\.git)?$/.exec(r);return e?{owner:e[1],repo:e[2]}:null}var ue,hr,re,lc,dc,hc,fc,pc,ys,_s,mc,Hr,mr=ra(()=>{"use strict";ue=$(require("node:fs"),1),hr=$(require("node:os"),1),re=$(require("node:path"),1),lc=require("node:child_process"),dc=require("node:util"),hc=(0,dc.promisify)(lc.execFile),fc="Allwright Agent",pc="agent@ticketpilot.local",ys=200,_s=2e4,mc=[/^\.github\/workflows\//,/^\.git\b/,/(^|\/)\.githooks\//];Hr=".ticketpilot-delete"});var Qr={};ri(Qr,{GitHubClient:()=>Oe});var Op,Oe,ut=ra(()=>{"use strict";Op=process.env.TICKETPILOT_GITHUB_API??"https://api.github.com",Oe=class{constructor(e){this.token=e}token;async request(e,t,n){let s=await fetch(`${Op}${t}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"allwright",...n!==void 0?{"Content-Type":"application/json"}:{}},body:n===void 0?void 0:JSON.stringify(n)}),i=await s.text(),o=null;try{o=i?JSON.parse(i):null}catch{}if(s.status===401)throw new Error("GitHub rejected the token (401) \u2014 expired or revoked? Run `allwright github set-token`");if(!s.ok&&s.status!==422){let a=o?.message??i.slice(0,300);throw new Error(`GitHub ${e} ${t} -> ${s.status}: ${a}`)}return{status:s.status,data:o}}async whoami(){let{data:e}=await this.request("GET","/user");return e.login}async createPullRequest(e,t,n){let{status:s,data:i}=await this.request("POST",`/repos/${e}/${t}/pulls`,n);if(s===422){let{data:o}=await this.request("GET",`/repos/${e}/${t}/pulls?head=${encodeURIComponent(`${e}:${n.head}`)}&state=open`);if(o?.length){let a=o[0];return{number:a.number,url:a.html_url,state:a.state,merged:a.merged??!1,headSha:a.head.sha,mergeableState:null}}throw new Error(`GitHub refused the PR (422): ${i?.message??"validation failed"}`)}return{number:i.number,url:i.html_url,state:i.state,merged:i.merged??!1,headSha:i.head.sha,mergeableState:null}}async getReviews(e,t,n){let{data:s}=await this.request("GET",`/repos/${e}/${t}/pulls/${n}/reviews?per_page=100`);return(s??[]).map(i=>({state:i.state??"",commitId:i.commit_id??"",user:i.user?.login??"",submittedAt:i.submitted_at??""}))}async getPullRequest(e,t,n){try{let{data:s}=await this.request("GET",`/repos/${e}/${t}/pulls/${n}`);return{number:s.number,url:s.html_url,state:s.state,merged:s.merged,headSha:s.head.sha,mergeableState:s.mergeable_state??null}}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return null;throw s}}async closePullRequest(e,t,n){await this.request("PATCH",`/repos/${e}/${t}/pulls/${n}`,{state:"closed"})}async deleteBranch(e,t,n){try{await this.request("DELETE",`/repos/${e}/${t}/git/refs/heads/${encodeURIComponent(n)}`)}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return;throw s}}}});var ht=Y((Cv,el)=>{"use strict";var Xu=["nodebuffer","arraybuffer","fragments"],Qu=typeof Blob<"u";Qu&&Xu.push("blob");el.exports={BINARY_TYPES:Xu,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Qu,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var zn=Y((Ev,zs)=>{"use strict";var{EMPTY_BUFFER:vm}=ht(),To=Buffer[Symbol.species];function bm(r,e){if(r.length===0)return vm;if(r.length===1)return r[0];let t=Buffer.allocUnsafe(e),n=0;for(let s=0;s<r.length;s++){let i=r[s];t.set(i,n),n+=i.length}return n<e?new To(t.buffer,t.byteOffset,n):t}function tl(r,e,t,n,s){for(let i=0;i<s;i++)t[n+i]=r[i]^e[i&3]}function rl(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function wm(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function xo(r){if(xo.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new To(r):ArrayBuffer.isView(r)?e=new To(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),xo.readOnly=!1),e}zs.exports={concat:bm,mask:tl,toArrayBuffer:wm,toBuffer:xo,unmask:rl};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=require("bufferutil");zs.exports.mask=function(e,t,n,s,i){i<48?tl(e,t,n,s,i):r.mask(e,t,n,s,i)},zs.exports.unmask=function(e,t){e.length<32?rl(e,t):r.unmask(e,t)}}catch{}});var il=Y((Iv,sl)=>{"use strict";var nl=Symbol("kDone"),Co=Symbol("kRun"),Eo=class{constructor(e){this[nl]=()=>{this.pending--,this[Co]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Co]()}[Co](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[nl])}}};sl.exports=Eo});var an=Y((Av,ul)=>{"use strict";var Un=require("zlib"),ol=zn(),km=il(),{kStatusCode:al}=ht(),Sm=Buffer[Symbol.species],Tm=Buffer.from([0,0,255,255]),qs=Symbol("permessage-deflate"),ft=Symbol("total-length"),sn=Symbol("callback"),$t=Symbol("buffers"),on=Symbol("error"),Us,Io=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,!Us){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Us=new km(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[sn];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,n=e.find(s=>!(t.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>s.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(n=>{let s=t[n];if(s.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(s=s[0],n==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else if(n==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else throw new Error(`Unknown parameter "${n}"`);t[n]=s})}),e}decompress(e,t,n){Us.add(s=>{this._decompress(e,t,(i,o)=>{s(),n(i,o)})})}compress(e,t,n){Us.add(s=>{this._compress(e,t,(i,o)=>{s(),n(i,o)})})}_decompress(e,t,n){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Un.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Un.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[qs]=this,this._inflate[ft]=0,this._inflate[$t]=[],this._inflate.on("error",Cm),this._inflate.on("data",cl)}this._inflate[sn]=n,this._inflate.write(e),t&&this._inflate.write(Tm),this._inflate.flush(()=>{let i=this._inflate[on];if(i){this._inflate.close(),this._inflate=null,n(i);return}let o=ol.concat(this._inflate[$t],this._inflate[ft]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[ft]=0,this._inflate[$t]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),n(null,o)})}_compress(e,t,n){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Un.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Un.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[ft]=0,this._deflate[$t]=[],this._deflate.on("data",xm)}this._deflate[sn]=n,this._deflate.write(e),this._deflate.flush(Un.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=ol.concat(this._deflate[$t],this._deflate[ft]);t&&(i=new Sm(i.buffer,i.byteOffset,i.length-4)),this._deflate[sn]=null,this._deflate[ft]=0,this._deflate[$t]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),n(null,i)})}};ul.exports=Io;function xm(r){this[$t].push(r),this[ft]+=r.length}function cl(r){if(this[ft]+=r.length,this[qs]._maxPayload<1||this[ft]<=this[qs]._maxPayload){this[$t].push(r);return}this[on]=new RangeError("Max payload size exceeded"),this[on].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[on][al]=1009,this.removeListener("data",cl),this.reset()}function Cm(r){if(this[qs]._inflate=null,this[on]){this[sn](this[on]);return}r[al]=1007,this[sn](r)}});var cn=Y((Rv,Bs)=>{"use strict";var{isUtf8:ll}=require("buffer"),{hasBlob:Em}=ht(),Im=[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 Am(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function Ao(r){let e=r.length,t=0;for(;t<e;)if((r[t]&128)===0)t++;else if((r[t]&224)===192){if(t+1===e||(r[t+1]&192)!==128||(r[t]&254)===192)return!1;t+=2}else if((r[t]&240)===224){if(t+2>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||r[t]===224&&(r[t+1]&224)===128||r[t]===237&&(r[t+1]&224)===160)return!1;t+=3}else if((r[t]&248)===240){if(t+3>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||(r[t+3]&192)!==128||r[t]===240&&(r[t+1]&240)===128||r[t]===244&&r[t+1]>143||r[t]>244)return!1;t+=4}else return!1;return!0}function Rm(r){return Em&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}Bs.exports={isBlob:Rm,isValidStatusCode:Am,isValidUTF8:Ao,tokenChars:Im};if(ll)Bs.exports.isValidUTF8=function(r){return r.length<24?Ao(r):ll(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=require("utf-8-validate");Bs.exports.isValidUTF8=function(e){return e.length<32?Ao(e):r(e)}}catch{}});var Oo=Y(($v,yl)=>{"use strict";var{Writable:$m}=require("stream"),dl=an(),{BINARY_TYPES:Pm,EMPTY_BUFFER:hl,kStatusCode:jm,kWebSocket:Om}=ht(),{concat:Ro,toArrayBuffer:Nm,unmask:Mm}=zn(),{isValidStatusCode:Dm,isValidUTF8:fl}=cn(),Fs=Buffer[Symbol.species],Ne=0,pl=1,ml=2,gl=3,$o=4,Po=5,Zs=6,jo=class extends $m{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Pm[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[Om]=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=Ne}_write(e,t,n){if(this._opcode===8&&this._state==Ne)return n();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){n(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new Fs(n.buffer,n.byteOffset+e,n.length-e),new Fs(n.buffer,n.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],s=t.length-e;e>=n.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),s),this._buffers[0]=new Fs(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case Ne:this.getInfo(e);break;case pl:this.getPayloadLength16(e);break;case ml:this.getPayloadLength64(e);break;case gl:this.getMask();break;case $o:this.getData(e);break;case Po:case Zs:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((t[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let n=(t[0]&64)===64;if(n&&!this._extensions[dl.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=pl:this._payloadLength===127?this._state=ml:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=n*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=gl:this._state=$o}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=$o}getData(e){let t=hl;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&&Mm(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let n=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(n);return}if(this._compressed){this._state=Po,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[dl.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===Ne&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=Ne;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=Ro(n,t):this._binaryType==="arraybuffer"?s=Nm(Ro(n,t)):this._binaryType==="blob"?s=new Blob(n):s=n,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=Ne):(this._state=Zs,setImmediate(()=>{this.emit("message",s,!0),this._state=Ne,this.startLoop(e)}))}else{let s=Ro(n,t);if(!this._skipUTF8Validation&&!fl(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Po||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=Ne):(this._state=Zs,setImmediate(()=>{this.emit("message",s,!1),this._state=Ne,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,hl),this.end();else{let n=e.readUInt16BE(0);if(!Dm(n)){let i=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new Fs(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!fl(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(i);return}this._loop=!1,this.emit("conclude",n,s),this.end()}this._state=Ne;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Ne):(this._state=Zs,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Ne,this.startLoop(t)}))}createError(e,t,n,s,i){this._loop=!1,this._errored=!0;let o=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[jm]=s,o}};yl.exports=jo});var Do=Y((jv,bl)=>{"use strict";var{Duplex:Pv}=require("stream"),{randomFillSync:Lm}=require("crypto"),{types:{isUint8Array:zm}}=require("util"),_l=an(),{EMPTY_BUFFER:Um,kWebSocket:qm,NOOP:Bm}=ht(),{isBlob:un,isValidStatusCode:Fm}=cn(),{mask:vl,toBuffer:Sr}=zn(),Me=Symbol("kByteLength"),Zm=Buffer.alloc(4),Ks=8*1024,Tr,ln=Ks,Be=0,Km=1,Vm=2,No=class r{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Be,this.onerror=Bm,this[qm]=void 0}static frame(e,t){let n,s=!1,i=2,o=!1;t.mask&&(n=t.maskBuffer||Zm,t.generateMask?t.generateMask(n):(ln===Ks&&(Tr===void 0&&(Tr=Buffer.alloc(Ks)),Lm(Tr,0,Ks),ln=0),n[0]=Tr[ln++],n[1]=Tr[ln++],n[2]=Tr[ln++],n[3]=Tr[ln++]),o=(n[0]|n[1]|n[2]|n[3])===0,i=6);let a;typeof e=="string"?(!t.mask||o)&&t[Me]!==void 0?a=t[Me]:(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 l=Buffer.allocUnsafe(s?a+i:i);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=u,u===126?l.writeUInt16BE(a,2):u===127&&(l[2]=l[3]=0,l.writeUIntBE(a,4,6)),t.mask?(l[1]|=128,l[i-4]=n[0],l[i-3]=n[1],l[i-2]=n[2],l[i-1]=n[3],o?[l,e]:s?(vl(e,n,l,i,a),[l]):(vl(e,n,e,0,a),[l,e])):[l,e]}close(e,t,n,s){let i;if(e===void 0)i=Um;else{if(typeof e!="number"||!Fm(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(zm(t))i.set(t,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[Me]:i.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Be?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(r.frame(i,o),s)}ping(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):un(e)?(s=e.size,i=!1):(e=Sr(e),s=e.length,i=Sr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Me]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};un(e)?this._state!==Be?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==Be?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(r.frame(e,o),n)}pong(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):un(e)?(s=e.size,i=!1):(e=Sr(e),s=e.length,i=Sr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Me]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};un(e)?this._state!==Be?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==Be?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(r.frame(e,o),n)}send(e,t,n){let s=this._extensions[_l.extensionName],i=t.binary?2:1,o=t.compress,a,u;typeof e=="string"?(a=Buffer.byteLength(e),u=!1):un(e)?(a=e.size,u=!1):(e=Sr(e),a=e.length,u=Sr.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 l={[Me]:a,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:u,rsv1:o};un(e)?this._state!==Be?this.enqueue([this.getBlobData,e,this._compress,l,n]):this.getBlobData(e,this._compress,l,n):this._state!==Be?this.enqueue([this.dispatch,e,this._compress,l,n]):this.dispatch(e,this._compress,l,n)}getBlobData(e,t,n,s){this._bufferedBytes+=n[Me],this._state=Vm,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Mo,this,a,s);return}this._bufferedBytes-=n[Me];let o=Sr(i);t?this.dispatch(o,t,n,s):(this._state=Be,this.sendFrame(r.frame(o,n),s),this.dequeue())}).catch(i=>{process.nextTick(Hm,this,i,s)})}dispatch(e,t,n,s){if(!t){this.sendFrame(r.frame(e,n),s);return}let i=this._extensions[_l.extensionName];this._bufferedBytes+=n[Me],this._state=Km,i.compress(e,n.fin,(o,a)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");Mo(this,u,s);return}this._bufferedBytes-=n[Me],this._state=Be,n.readOnly=!1,this.sendFrame(r.frame(a,n),s),this.dequeue()})}dequeue(){for(;this._state===Be&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Me],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Me],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)}};bl.exports=No;function Mo(r,e,t){typeof t=="function"&&t(e);for(let n=0;n<r._queue.length;n++){let s=r._queue[n],i=s[s.length-1];typeof i=="function"&&i(e)}}function Hm(r,e,t){Mo(r,e,t),r.onerror(e)}});var Al=Y((Ov,Il)=>{"use strict";var{kForOnEventAttribute:qn,kListener:Lo}=ht(),wl=Symbol("kCode"),kl=Symbol("kData"),Sl=Symbol("kError"),Tl=Symbol("kMessage"),xl=Symbol("kReason"),dn=Symbol("kTarget"),Cl=Symbol("kType"),El=Symbol("kWasClean"),pt=class{constructor(e){this[dn]=null,this[Cl]=e}get target(){return this[dn]}get type(){return this[Cl]}};Object.defineProperty(pt.prototype,"target",{enumerable:!0});Object.defineProperty(pt.prototype,"type",{enumerable:!0});var xr=class extends pt{constructor(e,t={}){super(e),this[wl]=t.code===void 0?0:t.code,this[xl]=t.reason===void 0?"":t.reason,this[El]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[wl]}get reason(){return this[xl]}get wasClean(){return this[El]}};Object.defineProperty(xr.prototype,"code",{enumerable:!0});Object.defineProperty(xr.prototype,"reason",{enumerable:!0});Object.defineProperty(xr.prototype,"wasClean",{enumerable:!0});var hn=class extends pt{constructor(e,t={}){super(e),this[Sl]=t.error===void 0?null:t.error,this[Tl]=t.message===void 0?"":t.message}get error(){return this[Sl]}get message(){return this[Tl]}};Object.defineProperty(hn.prototype,"error",{enumerable:!0});Object.defineProperty(hn.prototype,"message",{enumerable:!0});var Bn=class extends pt{constructor(e,t={}){super(e),this[kl]=t.data===void 0?null:t.data}get data(){return this[kl]}};Object.defineProperty(Bn.prototype,"data",{enumerable:!0});var Gm={addEventListener(r,e,t={}){for(let s of this.listeners(r))if(!t[qn]&&s[Lo]===e&&!s[qn])return;let n;if(r==="message")n=function(i,o){let a=new Bn("message",{data:o?i:i.toString()});a[dn]=this,Vs(e,this,a)};else if(r==="close")n=function(i,o){let a=new xr("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[dn]=this,Vs(e,this,a)};else if(r==="error")n=function(i){let o=new hn("error",{error:i,message:i.message});o[dn]=this,Vs(e,this,o)};else if(r==="open")n=function(){let i=new pt("open");i[dn]=this,Vs(e,this,i)};else return;n[qn]=!!t[qn],n[Lo]=e,t.once?this.once(r,n):this.on(r,n)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[Lo]===e&&!t[qn]){this.removeListener(r,t);break}}};Il.exports={CloseEvent:xr,ErrorEvent:hn,Event:pt,EventTarget:Gm,MessageEvent:Bn};function Vs(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var Hs=Y((Nv,Rl)=>{"use strict";var{tokenChars:Fn}=cn();function Ye(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function Wm(r){let e=Object.create(null),t=Object.create(null),n=!1,s=!1,i=!1,o,a,u=-1,l=-1,d=-1,p=0;for(;p<r.length;p++)if(l=r.charCodeAt(p),o===void 0)if(d===-1&&Fn[l]===1)u===-1&&(u=p);else if(p!==0&&(l===32||l===9))d===-1&&u!==-1&&(d=p);else if(l===59||l===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1&&(d=p);let S=r.slice(u,d);l===44?(Ye(e,S,t),t=Object.create(null)):o=S,u=d=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(a===void 0)if(d===-1&&Fn[l]===1)u===-1&&(u=p);else if(l===32||l===9)d===-1&&u!==-1&&(d=p);else if(l===59||l===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1&&(d=p),Ye(t,r.slice(u,d),!0),l===44&&(Ye(e,o,t),t=Object.create(null),o=void 0),u=d=-1}else if(l===61&&u!==-1&&d===-1)a=r.slice(u,p),u=d=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(s){if(Fn[l]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:n||(n=!0),s=!1}else if(i)if(Fn[l]===1)u===-1&&(u=p);else if(l===34&&u!==-1)i=!1,d=p;else if(l===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(l===34&&r.charCodeAt(p-1)===61)i=!0;else if(d===-1&&Fn[l]===1)u===-1&&(u=p);else if(u!==-1&&(l===32||l===9))d===-1&&(d=p);else if(l===59||l===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1&&(d=p);let S=r.slice(u,d);n&&(S=S.replace(/\\/g,""),n=!1),Ye(t,a,S),l===44&&(Ye(e,o,t),t=Object.create(null),o=void 0),a=void 0,u=d=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(u===-1||i||l===32||l===9)throw new SyntaxError("Unexpected end of input");d===-1&&(d=p);let v=r.slice(u,d);return o===void 0?Ye(e,v,t):(a===void 0?Ye(t,v,!0):n?Ye(t,a,v.replace(/\\/g,"")):Ye(t,a,v),Ye(e,o,t)),e}function Jm(r){return Object.keys(r).map(e=>{let t=r[e];return Array.isArray(t)||(t=[t]),t.map(n=>[e].concat(Object.keys(n).map(s=>{let i=n[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Rl.exports={format:Jm,parse:Wm}});var Ys=Y((Lv,Bl)=>{"use strict";var Ym=require("events"),Xm=require("https"),Qm=require("http"),jl=require("net"),eg=require("tls"),{randomBytes:tg,createHash:rg}=require("crypto"),{Duplex:Mv,Readable:Dv}=require("stream"),{URL:zo}=require("url"),Pt=an(),ng=Oo(),sg=Do(),{isBlob:ig}=cn(),{BINARY_TYPES:$l,CLOSE_TIMEOUT:og,EMPTY_BUFFER:Gs,GUID:ag,kForOnEventAttribute:Uo,kListener:cg,kStatusCode:ug,kWebSocket:oe,NOOP:Ol}=ht(),{EventTarget:{addEventListener:lg,removeEventListener:dg}}=Al(),{format:hg,parse:fg}=Hs(),{toBuffer:pg}=zn(),Nl=Symbol("kAborted"),qo=[8,13],mt=["CONNECTING","OPEN","CLOSING","CLOSED"],mg=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ne=class r extends Ym{constructor(e,t,n){super(),this._binaryType=$l[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Gs,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=r.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(n=t,t=[]):t=[t]),Ml(this,e,t,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){$l.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,n){let s=new ng({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:n.maxBufferedChunks,maxFragments:n.maxFragments,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),i=new sg(e,this._extensions,n.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[oe]=this,i[oe]=this,e[oe]=this,s.on("conclude",_g),s.on("drain",vg),s.on("error",bg),s.on("message",wg),s.on("ping",kg),s.on("pong",Sg),i.onerror=Tg,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",zl),e.on("data",Js),e.on("end",Ul),e.on("error",ql),this._readyState=r.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Pt.extensionName]&&this._extensions[Pt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){xe(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===r.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=r.CLOSING,this._sender.close(e,t,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Ll(this)}}pause(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Bo(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Gs,t,n)}pong(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Bo(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Gs,t,n)}resume(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(n=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Bo(this,e,n);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Pt.extensionName]||(s.compress=!1),this._sender.send(e||Gs,s,n)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){xe(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(ne,"CONNECTING",{enumerable:!0,value:mt.indexOf("CONNECTING")});Object.defineProperty(ne.prototype,"CONNECTING",{enumerable:!0,value:mt.indexOf("CONNECTING")});Object.defineProperty(ne,"OPEN",{enumerable:!0,value:mt.indexOf("OPEN")});Object.defineProperty(ne.prototype,"OPEN",{enumerable:!0,value:mt.indexOf("OPEN")});Object.defineProperty(ne,"CLOSING",{enumerable:!0,value:mt.indexOf("CLOSING")});Object.defineProperty(ne.prototype,"CLOSING",{enumerable:!0,value:mt.indexOf("CLOSING")});Object.defineProperty(ne,"CLOSED",{enumerable:!0,value:mt.indexOf("CLOSED")});Object.defineProperty(ne.prototype,"CLOSED",{enumerable:!0,value:mt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(ne.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(ne.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[Uo])return e[cg];return null},set(e){for(let t of this.listeners(r))if(t[Uo]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[Uo]:!0})}})});ne.prototype.addEventListener=lg;ne.prototype.removeEventListener=dg;Bl.exports=ne;function Ml(r,e,t,n){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:og,protocolVersion:qo[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(r._autoPong=s.autoPong,r._closeTimeout=s.closeTimeout,!qo.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${qo.join(", ")})`);let i;if(e instanceof zo)i=e;else try{i=new zo(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),r._url=i.href;let o=i.protocol==="wss:",a=i.protocol==="ws+unix:",u;if(i.protocol!=="ws:"&&!o&&!a?u=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?u="The URL's pathname is empty":i.hash&&(u="The URL contains a fragment identifier"),u){let w=new SyntaxError(u);if(r._redirects===0)throw w;Ws(r,w);return}let l=o?443:80,d=tg(16).toString("base64"),p=o?Xm.request:Qm.request,v=new Set,S;if(s.createConnection=s.createConnection||(o?yg:gg),s.defaultPort=s.defaultPort||l,s.port=i.port||l,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(S=new Pt({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=hg({[Pt.extensionName]:S.offer()})),t.length){for(let w of t){if(typeof w!="string"||!mg.test(w)||v.has(w))throw new SyntaxError("An invalid or duplicated subprotocol was specified");v.add(w)}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 w=s.path.split(":");s.socketPath=w[0],s.path=w[1]}let x;if(s.followRedirects){if(r._redirects===0){r._originalIpc=a,r._originalSecure=o,r._originalHostOrSocketPath=a?s.socketPath:i.host;let w=n&&n.headers;if(n={...n,headers:{}},w)for(let[j,U]of Object.entries(w))n.headers[j.toLowerCase()]=U}else if(r.listenerCount("redirect")===0){let w=a?r._originalIpc?s.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:i.host===r._originalHostOrSocketPath;(!w||r._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,w||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),x=r._req=p(s),r._redirects&&r.emit("redirect",r.url,x)}else x=r._req=p(s);s.timeout&&x.on("timeout",()=>{xe(r,x,"Opening handshake has timed out")}),x.on("error",w=>{x===null||x[Nl]||(x=r._req=null,Ws(r,w))}),x.on("response",w=>{let j=w.headers.location,U=w.statusCode;if(j&&s.followRedirects&&U>=300&&U<400){if(++r._redirects>s.maxRedirects){xe(r,x,"Maximum redirects exceeded");return}x.abort();let f;try{f=new zo(j,e)}catch{let b=new SyntaxError(`Invalid URL: ${j}`);Ws(r,b);return}Ml(r,f,t,n)}else r.emit("unexpected-response",x,w)||xe(r,x,`Unexpected server response: ${w.statusCode}`)}),x.on("upgrade",(w,j,U)=>{if(r.emit("upgrade",w),r.readyState!==ne.CONNECTING)return;x=r._req=null;let f=w.headers.upgrade;if(f===void 0||f.toLowerCase()!=="websocket"){xe(r,j,"Invalid Upgrade header");return}let g=rg("sha1").update(d+ag).digest("base64");if(w.headers["sec-websocket-accept"]!==g){xe(r,j,"Invalid Sec-WebSocket-Accept header");return}let b=w.headers["sec-websocket-protocol"],I;if(b!==void 0?v.size?v.has(b)||(I="Server sent an invalid subprotocol"):I="Server sent a subprotocol but none was requested":v.size&&(I="Server sent no subprotocol"),I){xe(r,j,I);return}b&&(r._protocol=b);let N=w.headers["sec-websocket-extensions"];if(N!==void 0){if(!S){xe(r,j,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let V;try{V=fg(N)}catch{xe(r,j,"Invalid Sec-WebSocket-Extensions header");return}let W=Object.keys(V);if(W.length!==1||W[0]!==Pt.extensionName){xe(r,j,"Server indicated an extension that was not requested");return}try{S.accept(V[Pt.extensionName])}catch{xe(r,j,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[Pt.extensionName]=S}r.setSocket(j,U,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(x,r):x.end()}function Ws(r,e){r._readyState=ne.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function gg(r){return r.path=r.socketPath,jl.connect(r)}function yg(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=jl.isIP(r.host)?"":r.host),eg.connect(r)}function xe(r,e,t){r._readyState=ne.CLOSING;let n=new Error(t);Error.captureStackTrace(n,xe),e.setHeader?(e[Nl]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Ws,r,n)):(e.destroy(n),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function Bo(r,e,t){if(e){let n=ig(e)?e.size:pg(e).length;r._socket?r._sender._bufferedBytes+=n:r._bufferedAmount+=n}if(t){let n=new Error(`WebSocket is not open: readyState ${r.readyState} (${mt[r.readyState]})`);process.nextTick(t,n)}}function _g(r,e){let t=this[oe];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[oe]!==void 0&&(t._socket.removeListener("data",Js),process.nextTick(Dl,t._socket),r===1005?t.close():t.close(r,e))}function vg(){let r=this[oe];r.isPaused||r._socket.resume()}function bg(r){let e=this[oe];e._socket[oe]!==void 0&&(e._socket.removeListener("data",Js),process.nextTick(Dl,e._socket),e.close(r[ug])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function Pl(){this[oe].emitClose()}function wg(r,e){this[oe].emit("message",r,e)}function kg(r){let e=this[oe];e._autoPong&&e.pong(r,!this._isServer,Ol),e.emit("ping",r)}function Sg(r){this[oe].emit("pong",r)}function Dl(r){r.resume()}function Tg(r){let e=this[oe];e.readyState!==ne.CLOSED&&(e.readyState===ne.OPEN&&(e._readyState=ne.CLOSING,Ll(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function Ll(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),r._closeTimeout)}function zl(){let r=this[oe];if(this.removeListener("close",zl),this.removeListener("data",Js),this.removeListener("end",Ul),r._readyState=ne.CLOSING,!this._readableState.endEmitted&&!r._closeFrameReceived&&!r._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);r._receiver.write(e)}r._receiver.end(),this[oe]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",Pl),r._receiver.on("finish",Pl))}function Js(r){this[oe]._receiver.write(r)||this.pause()}function Ul(){let r=this[oe];r._readyState=ne.CLOSING,r._receiver.end(),this.end()}function ql(){let r=this[oe];this.removeListener("error",ql),this.on("error",Ol),r&&(r._readyState=ne.CLOSING,this.destroy())}});var Vl=Y((Uv,Kl)=>{"use strict";var zv=Ys(),{Duplex:xg}=require("stream");function Fl(r){r.emit("close")}function Cg(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Zl(r){this.removeListener("error",Zl),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function Eg(r,e){let t=!0,n=new xg({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(i,o){let a=!o&&n._readableState.objectMode?i.toString():i;n.push(a)||r.pause()}),r.once("error",function(i){n.destroyed||(t=!1,n.destroy(i))}),r.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(s,i){if(r.readyState===r.CLOSED){i(s),process.nextTick(Fl,n);return}let o=!1;r.once("error",function(u){o=!0,i(u)}),r.once("close",function(){o||i(s),process.nextTick(Fl,n)}),t&&r.terminate()},n._final=function(s){if(r.readyState===r.CONNECTING){r.once("open",function(){n._final(s)});return}r._socket!==null&&(r._socket._writableState.finished?(s(),n._readableState.endEmitted&&n.destroy()):(r._socket.once("finish",function(){s()}),r.close()))},n._read=function(){r.isPaused&&r.resume()},n._write=function(s,i,o){if(r.readyState===r.CONNECTING){r.once("open",function(){n._write(s,i,o)});return}r.send(s,o)},n.on("end",Cg),n.on("error",Zl),n}Kl.exports=Eg});var Fo=Y((qv,Hl)=>{"use strict";var{tokenChars:Ig}=cn();function Ag(r){let e=new Set,t=-1,n=-1,s=0;for(s;s<r.length;s++){let o=r.charCodeAt(s);if(n===-1&&Ig[o]===1)t===-1&&(t=s);else if(s!==0&&(o===32||o===9))n===-1&&t!==-1&&(n=s);else if(o===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${s}`);n===-1&&(n=s);let a=r.slice(t,n);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),t=n=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(t===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let i=r.slice(t,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}Hl.exports={parse:Ag}});var ed=Y((Fv,Ql)=>{"use strict";var Rg=require("events"),Xs=require("http"),{Duplex:Bv}=require("stream"),{createHash:$g}=require("crypto"),Gl=Hs(),Cr=an(),Pg=Fo(),jg=Ys(),{CLOSE_TIMEOUT:Og,GUID:Ng,kWebSocket:Mg}=ht(),Dg=/^[+/0-9A-Za-z]{22}==$/,Wl=0,Jl=1,Xl=2,Zo=class extends Rg{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:Og,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:jg,...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=Xs.createServer((n,s)=>{let i=Xs.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=Lg(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Wl}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===Xl){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Zn,this);return}if(e&&this.once("close",e),this._state!==Jl)if(this._state=Jl,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(Zn,this):process.nextTick(Zn,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{Zn(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,s){t.on("error",Yl);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Er(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Er(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!Dg.test(i)){Er(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Er(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Kn(t,400);return}let u=e.headers["sec-websocket-protocol"],l=new Set;if(u!==void 0)try{l=Pg.parse(u)}catch{Er(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let d=e.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&d!==void 0){let v=new Cr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let S=Gl.parse(d);S[Cr.extensionName]&&(v.accept(S[Cr.extensionName]),p[Cr.extensionName]=v)}catch{Er(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let v={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(v,(S,x,w,j)=>{if(!S)return Kn(t,x||401,w,j);this.completeUpgrade(p,i,l,e,t,n,s)});return}if(!this.options.verifyClient(v))return Kn(t,401)}this.completeUpgrade(p,i,l,e,t,n,s)}completeUpgrade(e,t,n,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[Mg])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Wl)return Kn(i,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${$g("sha1").update(t+Ng).digest("base64")}`],d=new this.options.WebSocket(null,void 0,this.options);if(n.size){let p=this.options.handleProtocols?this.options.handleProtocols(n,s):n.values().next().value;p&&(l.push(`Sec-WebSocket-Protocol: ${p}`),d._protocol=p)}if(e[Cr.extensionName]){let p=e[Cr.extensionName].params,v=Gl.format({[Cr.extensionName]:[p]});l.push(`Sec-WebSocket-Extensions: ${v}`),d._extensions=e}this.emit("headers",l,s),i.write(l.concat(`\r
|
|
230
|
+
`).join(`\r
|
|
231
|
+
`)),i.removeListener("error",Yl),d.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(d),d.on("close",()=>{this.clients.delete(d),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Zn,this)})),a(d,s)}};Ql.exports=Zo;function Lg(r,e){for(let t of Object.keys(e))r.on(t,e[t]);return function(){for(let n of Object.keys(e))r.removeListener(n,e[n])}}function Zn(r){r._state=Xl,r.emit("close")}function Yl(){this.destroy()}function Kn(r,e,t,n){t=t||Xs.STATUS_CODES[e],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...n},r.once("finish",r.destroy),r.end(`HTTP/1.1 ${e} ${Xs.STATUS_CODES[e]}\r
|
|
232
|
+
`+Object.keys(n).map(s=>`${s}: ${n[s]}`).join(`\r
|
|
233
|
+
`)+`\r
|
|
234
|
+
\r
|
|
235
|
+
`+t)}function Er(r,e,t,n,s,i){if(r.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,Er),r.emit("wsClientError",o,t,e)}else Kn(t,n,s,i)}});var pn=$(require("node:fs"),1),id=$(require("node:os"),1),od=$(require("node:path"),1),Hn=require("node:child_process"),Wo=require("node:crypto"),Ir=$(require("node:readline/promises"),1);var ma=$(pa(),1),{program:oy,createCommand:ay,createArgument:cy,createOption:uy,CommanderError:ly,InvalidArgumentError:dy,InvalidOptionArgumentError:hy,Command:ga,Argument:fy,Option:py,Help:my}=ma.default;var st=$(require("node:fs"),1),rs=$(require("node:os"),1),ns=$(require("node:path"),1);var k={};ri(k,{BRAND:()=>eh,DIRTY:()=>jt,EMPTY_PATH:()=>Pd,INVALID:()=>M,NEVER:()=>Lh,OK:()=>de,ParseStatus:()=>ce,Schema:()=>K,ZodAny:()=>vt,ZodArray:()=>nt,ZodBigInt:()=>Nt,ZodBoolean:()=>Mt,ZodBranded:()=>_n,ZodCatch:()=>Ht,ZodDate:()=>Dt,ZodDefault:()=>Vt,ZodDiscriminatedUnion:()=>Qn,ZodEffects:()=>Re,ZodEnum:()=>Zt,ZodError:()=>ge,ZodFirstPartyTypeKind:()=>D,ZodFunction:()=>ts,ZodIntersection:()=>qt,ZodIssueCode:()=>T,ZodLazy:()=>Bt,ZodLiteral:()=>Ft,ZodMap:()=>Or,ZodNaN:()=>Mr,ZodNativeEnum:()=>Kt,ZodNever:()=>De,ZodNull:()=>zt,ZodNullable:()=>Ke,ZodNumber:()=>Ot,ZodObject:()=>ye,ZodOptional:()=>Ie,ZodParsedType:()=>R,ZodPipeline:()=>vn,ZodPromise:()=>bt,ZodReadonly:()=>Gt,ZodRecord:()=>es,ZodSchema:()=>K,ZodSet:()=>Nr,ZodString:()=>_t,ZodSymbol:()=>Pr,ZodTransformer:()=>Re,ZodTuple:()=>Ze,ZodType:()=>K,ZodUndefined:()=>Lt,ZodUnion:()=>Ut,ZodUnknown:()=>rt,ZodVoid:()=>jr,addIssueToContext:()=>A,any:()=>uh,array:()=>fh,bigint:()=>sh,boolean:()=>Ea,coerce:()=>Dh,custom:()=>Ta,date:()=>ih,datetimeRegex:()=>ka,defaultErrorMap:()=>et,discriminatedUnion:()=>yh,effect:()=>Ah,enum:()=>Ch,function:()=>Sh,getErrorMap:()=>Ar,getParsedType:()=>Fe,instanceof:()=>rh,intersection:()=>_h,isAborted:()=>Yn,isAsync:()=>Rr,isDirty:()=>Xn,isValid:()=>yt,late:()=>th,lazy:()=>Th,literal:()=>xh,makeIssue:()=>yn,map:()=>wh,nan:()=>nh,nativeEnum:()=>Eh,never:()=>dh,null:()=>ch,nullable:()=>$h,number:()=>Ca,object:()=>ph,objectUtil:()=>_i,oboolean:()=>Mh,onumber:()=>Nh,optional:()=>Rh,ostring:()=>Oh,pipeline:()=>jh,preprocess:()=>Ph,promise:()=>Ih,quotelessJson:()=>Ad,record:()=>bh,set:()=>kh,setErrorMap:()=>$d,strictObject:()=>mh,string:()=>xa,symbol:()=>oh,transformer:()=>Ah,tuple:()=>vh,undefined:()=>ah,union:()=>gh,unknown:()=>lh,util:()=>G,void:()=>hh});var G;(function(r){r.assertEqual=s=>{};function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},r.getValidEnumValues=s=>{let i=r.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),o={};for(let a of i)o[a]=s[a];return r.objectValues(o)},r.objectValues=s=>r.objectKeys(s).map(function(i){return s[i]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},r.find=(s,i)=>{for(let o of s)if(i(o))return o},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}r.joinValues=n,r.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(G||(G={}));var _i;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(_i||(_i={}));var R=G.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Fe=r=>{switch(typeof r){case"undefined":return R.undefined;case"string":return R.string;case"number":return Number.isNaN(r)?R.nan:R.number;case"boolean":return R.boolean;case"function":return R.function;case"bigint":return R.bigint;case"symbol":return R.symbol;case"object":return Array.isArray(r)?R.array:r===null?R.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?R.promise:typeof Map<"u"&&r instanceof Map?R.map:typeof Set<"u"&&r instanceof Set?R.set:typeof Date<"u"&&r instanceof Date?R.date:R.object;default:return R.unknown}};var T=G.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"]),Ad=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),ge=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},n={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)n._errors.push(t(o));else{let a=n,u=0;for(;u<o.path.length;){let l=o.path[u];u===o.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(t(o))):a[l]=a[l]||{_errors:[]},a=a[l],u++}}};return s(this),n}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,G.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},n=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];t[i]=t[i]||[],t[i].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};ge.create=r=>new ge(r);var Rd=(r,e)=>{let t;switch(r.code){case T.invalid_type:r.received===R.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case T.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,G.jsonStringifyReplacer)}`;break;case T.unrecognized_keys:t=`Unrecognized key(s) in object: ${G.joinValues(r.keys,", ")}`;break;case T.invalid_union:t="Invalid input";break;case T.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${G.joinValues(r.options)}`;break;case T.invalid_enum_value:t=`Invalid enum value. Expected ${G.joinValues(r.options)}, received '${r.received}'`;break;case T.invalid_arguments:t="Invalid function arguments";break;case T.invalid_return_type:t="Invalid function return type";break;case T.invalid_date:t="Invalid date";break;case T.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:G.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case T.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case T.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case T.custom:t="Invalid input";break;case T.invalid_intersection_types:t="Intersection results could not be merged";break;case T.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case T.not_finite:t="Number must be finite";break;default:t=e.defaultError,G.assertNever(r)}return{message:t}},et=Rd;var ya=et;function $d(r){ya=r}function Ar(){return ya}var yn=r=>{let{data:e,path:t,errorMaps:n,issueData:s}=r,i=[...t,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let a="",u=n.filter(l=>!!l).slice().reverse();for(let l of u)a=l(o,{data:e,defaultError:a}).message;return{...s,path:i,message:a}},Pd=[];function A(r,e){let t=Ar(),n=yn({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===et?void 0:et].filter(s=>!!s)});r.common.issues.push(n)}var ce=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let s of t){if(s.status==="aborted")return M;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let s of t){let i=await s.key,o=await s.value;n.push({key:i,value:o})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let s of t){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return M;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(n[i.value]=o.value)}return{status:e.value,value:n}}},M=Object.freeze({status:"aborted"}),jt=r=>({status:"dirty",value:r}),de=r=>({status:"valid",value:r}),Yn=r=>r.status==="aborted",Xn=r=>r.status==="dirty",yt=r=>r.status==="valid",Rr=r=>typeof Promise<"u"&&r instanceof Promise;var P;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(P||(P={}));var Ae=class{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},_a=(r,e)=>{if(yt(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new ge(r.common.issues);return this._error=t,this._error}}};function q(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,a)=>{let{message:u}=r;return o.code==="invalid_enum_value"?{message:u??a.defaultError}:typeof a.data>"u"?{message:u??n??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:u??t??a.defaultError}},description:s}}var K=class{get description(){return this._def.description}_getType(e){return Fe(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Fe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ce,ctx:{common:e.parent.common,data:e.data,parsedType:Fe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Rr(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Fe(e)},s=this._parseSync({data:e,path:n.path,parent:n});return _a(n,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Fe(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return yt(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>yt(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Fe(e)},s=this._parse({data:e,path:n.path,parent:n}),i=await(Rr(s)?s:Promise.resolve(s));return _a(n,i)}refine(e,t){let n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,i)=>{let o=e(s),a=()=>i.addIssue({code:T.custom,...n(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(u=>u?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new Re({schema:this,typeName:D.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return Ie.create(this,this._def)}nullable(){return Ke.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return nt.create(this)}promise(){return bt.create(this,this._def)}or(e){return Ut.create([this,e],this._def)}and(e){return qt.create(this,e,this._def)}transform(e){return new Re({...q(this._def),schema:this,typeName:D.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Vt({...q(this._def),innerType:this,defaultValue:t,typeName:D.ZodDefault})}brand(){return new _n({typeName:D.ZodBranded,type:this,...q(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Ht({...q(this._def),innerType:this,catchValue:t,typeName:D.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return vn.create(this,e)}readonly(){return Gt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},jd=/^c[^\s-]{8,}$/i,Od=/^[0-9a-z]+$/,Nd=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Md=/^[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,Dd=/^[a-z0-9_-]{21}$/i,Ld=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,zd=/^[-+]?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)?)??$/,Ud=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,qd="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",vi,Bd=/^(?:(?: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])$/,Fd=/^(?:(?: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])$/,Zd=/^(([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]))$/,Kd=/^(([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])$/,Vd=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Hd=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ba="((\\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])))",Gd=new RegExp(`^${ba}$`);function wa(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Wd(r){return new RegExp(`^${wa(r)}$`)}function ka(r){let e=`${ba}T${wa(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Jd(r,e){return!!((e==="v4"||!e)&&Bd.test(r)||(e==="v6"||!e)&&Zd.test(r))}function Yd(r,e){if(!Ld.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function Xd(r,e){return!!((e==="v4"||!e)&&Fd.test(r)||(e==="v6"||!e)&&Kd.test(r))}var _t=class r extends K{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==R.string){let i=this._getOrReturnCtx(e);return A(i,{code:T.invalid_type,expected:R.string,received:i.parsedType}),M}let n=new ce,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),A(s,{code:T.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),A(s,{code:T.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(s=this._getOrReturnCtx(e,s),o?A(s,{code:T.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&A(s,{code:T.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")Ud.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"email",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")vi||(vi=new RegExp(qd,"u")),vi.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"emoji",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")Md.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"uuid",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")Dd.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"nanoid",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")jd.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"cuid",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")Od.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"cuid2",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")Nd.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"ulid",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),A(s,{validation:"url",code:T.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"regex",code:T.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),A(s,{code:T.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),A(s,{code:T.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),A(s,{code:T.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?ka(i).test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{code:T.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?Gd.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{code:T.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?Wd(i).test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{code:T.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?zd.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"duration",code:T.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?Jd(e.data,i.version)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"ip",code:T.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?Yd(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"jwt",code:T.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?Xd(e.data,i.version)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"cidr",code:T.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?Vd.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"base64",code:T.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?Hd.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"base64url",code:T.invalid_string,message:i.message}),n.dirty()):G.assertNever(i);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:T.invalid_string,...P.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...P.errToObj(e)})}url(e){return this._addCheck({kind:"url",...P.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...P.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...P.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...P.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...P.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...P.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...P.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...P.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...P.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...P.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...P.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...P.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,...P.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,...P.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...P.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...P.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...P.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...P.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...P.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...P.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...P.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...P.errToObj(t)})}nonempty(e){return this.min(1,P.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};_t.create=r=>new _t({checks:[],typeName:D.ZodString,coerce:r?.coerce??!1,...q(r)});function Qd(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,i=Number.parseInt(r.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var Ot=class r extends K{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)!==R.number){let i=this._getOrReturnCtx(e);return A(i,{code:T.invalid_type,expected:R.number,received:i.parsedType}),M}let n,s=new ce;for(let i of this._def.checks)i.kind==="int"?G.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),A(n,{code:T.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Qd(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),A(n,{code:T.not_finite,message:i.message}),s.dirty()):G.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,P.toString(t))}gt(e,t){return this.setLimit("min",e,!1,P.toString(t))}lte(e,t){return this.setLimit("max",e,!0,P.toString(t))}lt(e,t){return this.setLimit("max",e,!1,P.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:P.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:P.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:P.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:P.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:P.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:P.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:P.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:P.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:P.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:P.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"&&G.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};Ot.create=r=>new Ot({checks:[],typeName:D.ZodNumber,coerce:r?.coerce||!1,...q(r)});var Nt=class r extends K{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)!==R.bigint)return this._getInvalidInput(e);let n,s=new ce;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):G.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return A(t,{code:T.invalid_type,expected:R.bigint,received:t.parsedType}),M}gte(e,t){return this.setLimit("min",e,!0,P.toString(t))}gt(e,t){return this.setLimit("min",e,!1,P.toString(t))}lte(e,t){return this.setLimit("max",e,!0,P.toString(t))}lt(e,t){return this.setLimit("max",e,!1,P.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:P.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:P.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:P.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:P.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:P.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:P.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}};Nt.create=r=>new Nt({checks:[],typeName:D.ZodBigInt,coerce:r?.coerce??!1,...q(r)});var Mt=class extends K{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==R.boolean){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:R.boolean,received:n.parsedType}),M}return de(e.data)}};Mt.create=r=>new Mt({typeName:D.ZodBoolean,coerce:r?.coerce||!1,...q(r)});var Dt=class r extends K{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==R.date){let i=this._getOrReturnCtx(e);return A(i,{code:T.invalid_type,expected:R.date,received:i.parsedType}),M}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return A(i,{code:T.invalid_date}),M}let n=new ce,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),A(s,{code:T.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),A(s,{code:T.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):G.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:P.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:P.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}};Dt.create=r=>new Dt({checks:[],coerce:r?.coerce||!1,typeName:D.ZodDate,...q(r)});var Pr=class extends K{_parse(e){if(this._getType(e)!==R.symbol){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:R.symbol,received:n.parsedType}),M}return de(e.data)}};Pr.create=r=>new Pr({typeName:D.ZodSymbol,...q(r)});var Lt=class extends K{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:R.undefined,received:n.parsedType}),M}return de(e.data)}};Lt.create=r=>new Lt({typeName:D.ZodUndefined,...q(r)});var zt=class extends K{_parse(e){if(this._getType(e)!==R.null){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:R.null,received:n.parsedType}),M}return de(e.data)}};zt.create=r=>new zt({typeName:D.ZodNull,...q(r)});var vt=class extends K{constructor(){super(...arguments),this._any=!0}_parse(e){return de(e.data)}};vt.create=r=>new vt({typeName:D.ZodAny,...q(r)});var rt=class extends K{constructor(){super(...arguments),this._unknown=!0}_parse(e){return de(e.data)}};rt.create=r=>new rt({typeName:D.ZodUnknown,...q(r)});var De=class extends K{_parse(e){let t=this._getOrReturnCtx(e);return A(t,{code:T.invalid_type,expected:R.never,received:t.parsedType}),M}};De.create=r=>new De({typeName:D.ZodNever,...q(r)});var jr=class extends K{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:R.void,received:n.parsedType}),M}return de(e.data)}};jr.create=r=>new jr({typeName:D.ZodVoid,...q(r)});var nt=class r extends K{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==R.array)return A(t,{code:T.invalid_type,expected:R.array,received:t.parsedType}),M;if(s.exactLength!==null){let o=t.data.length>s.exactLength.value,a=t.data.length<s.exactLength.value;(o||a)&&(A(t,{code:o?T.too_big:T.too_small,minimum:a?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(A(t,{code:T.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(A(t,{code:T.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>s.type._parseAsync(new Ae(t,o,t.path,a)))).then(o=>ce.mergeArray(n,o));let i=[...t.data].map((o,a)=>s.type._parseSync(new Ae(t,o,t.path,a)));return ce.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:P.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:P.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:P.toString(t)}})}nonempty(e){return this.min(1,e)}};nt.create=(r,e)=>new nt({type:r,minLength:null,maxLength:null,exactLength:null,typeName:D.ZodArray,...q(e)});function $r(r){if(r instanceof ye){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=Ie.create($r(n))}return new ye({...r._def,shape:()=>e})}else return r instanceof nt?new nt({...r._def,type:$r(r.element)}):r instanceof Ie?Ie.create($r(r.unwrap())):r instanceof Ke?Ke.create($r(r.unwrap())):r instanceof Ze?Ze.create(r.items.map(e=>$r(e))):r}var ye=class r extends K{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=G.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==R.object){let l=this._getOrReturnCtx(e);return A(l,{code:T.invalid_type,expected:R.object,received:l.parsedType}),M}let{status:n,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof De&&this._def.unknownKeys==="strip"))for(let l in s.data)o.includes(l)||a.push(l);let u=[];for(let l of o){let d=i[l],p=s.data[l];u.push({key:{status:"valid",value:l},value:d._parse(new Ae(s,p,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof De){let l=this._def.unknownKeys;if(l==="passthrough")for(let d of a)u.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(l==="strict")a.length>0&&(A(s,{code:T.unrecognized_keys,keys:a}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let d of a){let p=s.data[d];u.push({key:{status:"valid",value:d},value:l._parse(new Ae(s,p,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let l=[];for(let d of u){let p=await d.key,v=await d.value;l.push({key:p,value:v,alwaysSet:d.alwaysSet})}return l}).then(l=>ce.mergeObjectSync(n,l)):ce.mergeObjectSync(n,u)}get shape(){return this._def.shape()}strict(e){return P.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let s=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:P.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:D.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let n of G.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let n of G.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return $r(this)}partial(e){let t={};for(let n of G.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let n of G.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof Ie;)i=i._def.innerType;t[n]=i}return new r({...this._def,shape:()=>t})}keyof(){return Sa(G.objectKeys(this.shape))}};ye.create=(r,e)=>new ye({shape:()=>r,unknownKeys:"strip",catchall:De.create(),typeName:D.ZodObject,...q(e)});ye.strictCreate=(r,e)=>new ye({shape:()=>r,unknownKeys:"strict",catchall:De.create(),typeName:D.ZodObject,...q(e)});ye.lazycreate=(r,e)=>new ye({shape:r,unknownKeys:"strip",catchall:De.create(),typeName:D.ZodObject,...q(e)});var Ut=class extends K{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function s(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return t.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(a=>new ge(a.ctx.common.issues));return A(t,{code:T.invalid_union,unionErrors:o}),M}if(t.common.async)return Promise.all(n.map(async i=>{let o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let u of n){let l={...t,common:{...t.common,issues:[]},parent:null},d=u._parseSync({data:t.data,path:t.path,parent:l});if(d.status==="valid")return d;d.status==="dirty"&&!i&&(i={result:d,ctx:l}),l.common.issues.length&&o.push(l.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let a=o.map(u=>new ge(u));return A(t,{code:T.invalid_union,unionErrors:a}),M}}get options(){return this._def.options}};Ut.create=(r,e)=>new Ut({options:r,typeName:D.ZodUnion,...q(e)});var tt=r=>r instanceof Bt?tt(r.schema):r instanceof Re?tt(r.innerType()):r instanceof Ft?[r.value]:r instanceof Zt?r.options:r instanceof Kt?G.objectValues(r.enum):r instanceof Vt?tt(r._def.innerType):r instanceof Lt?[void 0]:r instanceof zt?[null]:r instanceof Ie?[void 0,...tt(r.unwrap())]:r instanceof Ke?[null,...tt(r.unwrap())]:r instanceof _n||r instanceof Gt?tt(r.unwrap()):r instanceof Ht?tt(r._def.innerType):[],Qn=class r extends K{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==R.object)return A(t,{code:T.invalid_type,expected:R.object,received:t.parsedType}),M;let n=this.discriminator,s=t.data[n],i=this.optionsMap.get(s);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(A(t,{code:T.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),M)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let s=new Map;for(let i of t){let o=tt(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of o){if(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,i)}}return new r({typeName:D.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...q(n)})}};function bi(r,e){let t=Fe(r),n=Fe(e);if(r===e)return{valid:!0,data:r};if(t===R.object&&n===R.object){let s=G.objectKeys(e),i=G.objectKeys(r).filter(a=>s.indexOf(a)!==-1),o={...r,...e};for(let a of i){let u=bi(r[a],e[a]);if(!u.valid)return{valid:!1};o[a]=u.data}return{valid:!0,data:o}}else if(t===R.array&&n===R.array){if(r.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<r.length;i++){let o=r[i],a=e[i],u=bi(o,a);if(!u.valid)return{valid:!1};s.push(u.data)}return{valid:!0,data:s}}else return t===R.date&&n===R.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var qt=class extends K{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=(i,o)=>{if(Yn(i)||Yn(o))return M;let a=bi(i.value,o.value);return a.valid?((Xn(i)||Xn(o))&&t.dirty(),{status:t.value,value:a.data}):(A(n,{code:T.invalid_intersection_types}),M)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};qt.create=(r,e,t)=>new qt({left:r,right:e,typeName:D.ZodIntersection,...q(t)});var Ze=class r extends K{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.array)return A(n,{code:T.invalid_type,expected:R.array,received:n.parsedType}),M;if(n.data.length<this._def.items.length)return A(n,{code:T.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),M;!this._def.rest&&n.data.length>this._def.items.length&&(A(n,{code:T.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...n.data].map((o,a)=>{let u=this._def.items[a]||this._def.rest;return u?u._parse(new Ae(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(i).then(o=>ce.mergeArray(t,o)):ce.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};Ze.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ze({items:r,typeName:D.ZodTuple,rest:null,...q(e)})};var es=class r extends K{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.object)return A(n,{code:T.invalid_type,expected:R.object,received:n.parsedType}),M;let s=[],i=this._def.keyType,o=this._def.valueType;for(let a in n.data)s.push({key:i._parse(new Ae(n,a,n.path,a)),value:o._parse(new Ae(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?ce.mergeObjectAsync(t,s):ce.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof K?new r({keyType:e,valueType:t,typeName:D.ZodRecord,...q(n)}):new r({keyType:_t.create(),valueType:e,typeName:D.ZodRecord,...q(t)})}},Or=class extends K{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.map)return A(n,{code:T.invalid_type,expected:R.map,received:n.parsedType}),M;let s=this._def.keyType,i=this._def.valueType,o=[...n.data.entries()].map(([a,u],l)=>({key:s._parse(new Ae(n,a,n.path,[l,"key"])),value:i._parse(new Ae(n,u,n.path,[l,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let u of o){let l=await u.key,d=await u.value;if(l.status==="aborted"||d.status==="aborted")return M;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),a.set(l.value,d.value)}return{status:t.value,value:a}})}else{let a=new Map;for(let u of o){let l=u.key,d=u.value;if(l.status==="aborted"||d.status==="aborted")return M;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),a.set(l.value,d.value)}return{status:t.value,value:a}}}};Or.create=(r,e,t)=>new Or({valueType:e,keyType:r,typeName:D.ZodMap,...q(t)});var Nr=class r extends K{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.set)return A(n,{code:T.invalid_type,expected:R.set,received:n.parsedType}),M;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(A(n,{code:T.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(A(n,{code:T.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let i=this._def.valueType;function o(u){let l=new Set;for(let d of u){if(d.status==="aborted")return M;d.status==="dirty"&&t.dirty(),l.add(d.value)}return{status:t.value,value:l}}let a=[...n.data.values()].map((u,l)=>i._parse(new Ae(n,u,n.path,l)));return n.common.async?Promise.all(a).then(u=>o(u)):o(a)}min(e,t){return new r({...this._def,minSize:{value:e,message:P.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:P.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Nr.create=(r,e)=>new Nr({valueType:r,minSize:null,maxSize:null,typeName:D.ZodSet,...q(e)});var ts=class r extends K{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==R.function)return A(t,{code:T.invalid_type,expected:R.function,received:t.parsedType}),M;function n(a,u){return yn({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Ar(),et].filter(l=>!!l),issueData:{code:T.invalid_arguments,argumentsError:u}})}function s(a,u){return yn({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Ar(),et].filter(l=>!!l),issueData:{code:T.invalid_return_type,returnTypeError:u}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof bt){let a=this;return de(async function(...u){let l=new ge([]),d=await a._def.args.parseAsync(u,i).catch(S=>{throw l.addIssue(n(u,S)),l}),p=await Reflect.apply(o,this,d);return await a._def.returns._def.type.parseAsync(p,i).catch(S=>{throw l.addIssue(s(p,S)),l})})}else{let a=this;return de(function(...u){let l=a._def.args.safeParse(u,i);if(!l.success)throw new ge([n(u,l.error)]);let d=Reflect.apply(o,this,l.data),p=a._def.returns.safeParse(d,i);if(!p.success)throw new ge([s(d,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:Ze.create(e).rest(rt.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||Ze.create([]).rest(rt.create()),returns:t||rt.create(),typeName:D.ZodFunction,...q(n)})}},Bt=class extends K{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})}};Bt.create=(r,e)=>new Bt({getter:r,typeName:D.ZodLazy,...q(e)});var Ft=class extends K{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return A(t,{received:t.data,code:T.invalid_literal,expected:this._def.value}),M}return{status:"valid",value:e.data}}get value(){return this._def.value}};Ft.create=(r,e)=>new Ft({value:r,typeName:D.ZodLiteral,...q(e)});function Sa(r,e){return new Zt({values:r,typeName:D.ZodEnum,...q(e)})}var Zt=class r extends K{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return A(t,{expected:G.joinValues(n),received:t.parsedType,code:T.invalid_type}),M}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return A(t,{received:t.data,code:T.invalid_enum_value,options:n}),M}return de(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};Zt.create=Sa;var Kt=class extends K{_parse(e){let t=G.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==R.string&&n.parsedType!==R.number){let s=G.objectValues(t);return A(n,{expected:G.joinValues(s),received:n.parsedType,code:T.invalid_type}),M}if(this._cache||(this._cache=new Set(G.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=G.objectValues(t);return A(n,{received:n.data,code:T.invalid_enum_value,options:s}),M}return de(e.data)}get enum(){return this._def.values}};Kt.create=(r,e)=>new Kt({values:r,typeName:D.ZodNativeEnum,...q(e)});var bt=class extends K{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==R.promise&&t.common.async===!1)return A(t,{code:T.invalid_type,expected:R.promise,received:t.parsedType}),M;let n=t.parsedType===R.promise?t.data:Promise.resolve(t.data);return de(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};bt.create=(r,e)=>new bt({type:r,typeName:D.ZodPromise,...q(e)});var Re=class extends K{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===D.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{A(n,o),o.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(n.data,i);if(n.common.async)return Promise.resolve(o).then(async a=>{if(t.value==="aborted")return M;let u=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return u.status==="aborted"?M:u.status==="dirty"?jt(u.value):t.value==="dirty"?jt(u.value):u});{if(t.value==="aborted")return M;let a=this._def.schema._parseSync({data:o,path:n.path,parent:n});return a.status==="aborted"?M:a.status==="dirty"?jt(a.value):t.value==="dirty"?jt(a.value):a}}if(s.type==="refinement"){let o=a=>{let u=s.refinement(a,i);if(n.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?M:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?M:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.value,value:a.value}))))}if(s.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!yt(o))return M;let a=s.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>yt(o)?Promise.resolve(s.transform(o.value,i)).then(a=>({status:t.value,value:a})):M);G.assertNever(s)}};Re.create=(r,e,t)=>new Re({schema:r,typeName:D.ZodEffects,effect:e,...q(t)});Re.createWithPreprocess=(r,e,t)=>new Re({schema:e,effect:{type:"preprocess",transform:r},typeName:D.ZodEffects,...q(t)});var Ie=class extends K{_parse(e){return this._getType(e)===R.undefined?de(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ie.create=(r,e)=>new Ie({innerType:r,typeName:D.ZodOptional,...q(e)});var Ke=class extends K{_parse(e){return this._getType(e)===R.null?de(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ke.create=(r,e)=>new Ke({innerType:r,typeName:D.ZodNullable,...q(e)});var Vt=class extends K{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===R.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Vt.create=(r,e)=>new Vt({innerType:r,typeName:D.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...q(e)});var Ht=class extends K{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Rr(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ge(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ge(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Ht.create=(r,e)=>new Ht({innerType:r,typeName:D.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...q(e)});var Mr=class extends K{_parse(e){if(this._getType(e)!==R.nan){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:R.nan,received:n.parsedType}),M}return{status:"valid",value:e.data}}};Mr.create=r=>new Mr({typeName:D.ZodNaN,...q(r)});var eh=Symbol("zod_brand"),_n=class extends K{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},vn=class r extends K{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?M:i.status==="dirty"?(t.dirty(),jt(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?M:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:D.ZodPipeline})}},Gt=class extends K{_parse(e){let t=this._def.innerType._parse(e),n=s=>(yt(s)&&(s.value=Object.freeze(s.value)),s);return Rr(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}};Gt.create=(r,e)=>new Gt({innerType:r,typeName:D.ZodReadonly,...q(e)});function va(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function Ta(r,e={},t){return r?vt.create().superRefine((n,s)=>{let i=r(n);if(i instanceof Promise)return i.then(o=>{if(!o){let a=va(e,n),u=a.fatal??t??!0;s.addIssue({code:"custom",...a,fatal:u})}});if(!i){let o=va(e,n),a=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:a})}}):vt.create()}var th={object:ye.lazycreate},D;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(D||(D={}));var rh=(r,e={message:`Input not instance of ${r.name}`})=>Ta(t=>t instanceof r,e),xa=_t.create,Ca=Ot.create,nh=Mr.create,sh=Nt.create,Ea=Mt.create,ih=Dt.create,oh=Pr.create,ah=Lt.create,ch=zt.create,uh=vt.create,lh=rt.create,dh=De.create,hh=jr.create,fh=nt.create,ph=ye.create,mh=ye.strictCreate,gh=Ut.create,yh=Qn.create,_h=qt.create,vh=Ze.create,bh=es.create,wh=Or.create,kh=Nr.create,Sh=ts.create,Th=Bt.create,xh=Ft.create,Ch=Zt.create,Eh=Kt.create,Ih=bt.create,Ah=Re.create,Rh=Ie.create,$h=Ke.create,Ph=Re.createWithPreprocess,jh=vn.create,Oh=()=>xa().optional(),Nh=()=>Ca().optional(),Mh=()=>Ea().optional(),Dh={string:(r=>_t.create({...r,coerce:!0})),number:(r=>Ot.create({...r,coerce:!0})),boolean:(r=>Mt.create({...r,coerce:!0})),bigint:(r=>Nt.create({...r,coerce:!0})),date:(r=>Dt.create({...r,coerce:!0}))};var Lh=M;var Ia=k.object({baseUrl:k.string().url(),email:k.string().email(),apiToken:k.string().min(1)}),wi=k.object({controlPlaneUrl:k.string().url(),runnerId:k.string().optional(),runnerToken:k.string().optional(),runnerName:k.string().default(rs.default.hostname()),jira:Ia.optional(),repos:k.record(k.object({path:k.string(),jira:Ia.optional(),github:k.object({token:k.string().min(1),login:k.string().optional()}).optional()})).default({}),github:k.object({token:k.string().min(1),login:k.string().optional()}).optional(),githubUsers:k.record(k.object({token:k.string().min(1),login:k.string().optional()})).default({}),deploy:k.object({enabled:k.boolean().default(!1)}).default({enabled:!1}),environments:k.record(k.object({secrets:k.record(k.string()).default({})})).default({}),claudeProfiles:k.record(k.object({configDir:k.string()})).default({}),claudeBin:k.string().default("claude"),agents:k.record(k.object({bin:k.string()})).default({}),jiraUsers:k.record(k.object({email:k.string().email(),apiToken:k.string().min(1)})).default({}),auditSchedules:k.array(k.object({repoName:k.string(),role:k.enum(["security","testing"]),intervalHours:k.number().int().min(6).max(720)})).default([]),pollIntervalSeconds:k.number().int().min(10).max(600).default(30)});function ee(){let r=process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR;if(r)return r;let e=ns.default.join(rs.default.homedir(),".config","allwright"),t=ns.default.join(rs.default.homedir(),".config","ticketpilot");return!st.default.existsSync(e)&&st.default.existsSync(t)?t:e}function wt(){return ns.default.join(ee(),"runner.json")}function he(){let r=wt();if(!st.default.existsSync(r))return null;let e=JSON.parse(st.default.readFileSync(r,"utf8"));return wi.parse(e)}function ie(r){let e=ee();st.default.mkdirSync(e,{recursive:!0,mode:448});let t=wt(),n=t+".tmp";st.default.writeFileSync(n,JSON.stringify(r,null,2)+`
|
|
236
|
+
`,{mode:384}),st.default.renameSync(n,t),st.default.chmodSync(t,384)}function ss(r,e){return`${r}:${e}`}function Wt(r,e,t){return r.environments[ss(e,t)]?.secrets??{}}function Q(){let r=he();if(!r)throw new Error(`No runner config found at ${wt()}. Run \`allwright init\` first.`);return r}var is=require("node:child_process"),we=$(require("node:fs"),1),os=$(require("node:path"),1);var zh=new Set(["runner.log","runner.pid"]);function Uh(r){return we.default.readdirSync(r).filter(e=>!zh.has(e)&&!/\.bak-\d+$/.test(e)).sort()}function Aa(r){let e=ee();if(!we.default.existsSync(e))throw new Error(`nothing to export \u2014 ${e} does not exist`);let t=Uh(e);if(!t.length)throw new Error(`nothing to export \u2014 ${e} is empty`);let n=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),s=os.default.resolve(r||`ticketpilot-backup-${n}.tgz`);return we.default.writeFileSync(s,"",{mode:384}),(0,is.execFileSync)("tar",["-czf",s,"-C",e,...t]),we.default.chmodSync(s,384),{file:s,entries:t}}function Ra(r){let e=os.default.resolve(r);if(!we.default.existsSync(e))throw new Error(`backup file not found: ${e}`);let t=(0,is.execFileSync)("tar",["-tzf",e],{encoding:"utf8"}).split(`
|
|
237
|
+
`).filter(Boolean);for(let i of t)if(i.startsWith("/")||i.split("/").includes(".."))throw new Error(`refusing to import \u2014 unsafe path in archive: ${i}`);let n=ee(),s;we.default.existsSync(n)&&we.default.readdirSync(n).length&&(s=`${n}.bak-${Date.now()}`,we.default.renameSync(n,s)),we.default.mkdirSync(n,{recursive:!0,mode:448}),(0,is.execFileSync)("tar",["-xzf",e,"-C",n]);for(let i of we.default.readdirSync(n)){let o=os.default.join(n,i);we.default.statSync(o).isFile()&&we.default.chmodSync(o,384)}return{restored:t.map(i=>i.replace(/\/$/,"")).sort(),previousDir:s}}var Dr=$(require("node:fs"),1),kt=$(require("node:path"),1),as=".ticketpilot-attachments",qh=15*1024*1024,Bh=50*1024*1024,$a=20;function Pa(r,e){let t=kt.default.basename(r).replace(/[^\w.\- ()]/g,"_").replace(/^\.+/,"").slice(-100)||"file",n=t,s=1;for(;e.has(n);)n=`${s++}-${t}`;return e.add(n),n}async function Lr(r,e,t,n){if(!e.length)return"";let s=kt.default.join(t,as);Dr.default.mkdirSync(s,{recursive:!0});let i=new Set,o=[],a=0;for(let u of e){if(o.length>=$a){n("warn",`attachment cap reached (${$a} files) \u2014 skipping the rest`);break}if(u.size>qh){n("warn",`skipping attachment "${u.filename}" \u2014 ${Kh(u.size)} MB exceeds the 15 MB limit`);continue}if(a+u.size>Bh){n("warn",`attachment size budget reached \u2014 skipping "${u.filename}" and the rest`);break}try{let l=await r.downloadAttachment(u.contentUrl),d=Pa(u.filename,i);Dr.default.writeFileSync(kt.default.join(s,d),l),a+=l.length,o.push(`- ${as}/${d} (${u.mimeType||"unknown type"}, ${ki(l.length)} KB)`),n("info",`Downloaded attachment "${u.filename}" (${ki(l.length)} KB)`)}catch(l){n("warn",`could not download attachment "${u.filename}": ${l instanceof Error?l.message:l}`)}}return o.length?`
|
|
238
|
+
|
|
239
|
+
Files attached to the Jira ticket, downloaded locally for this run. They are reference material and NOT part of the repository \u2014 never commit, copy, or edit them:
|
|
240
|
+
${o.join(`
|
|
241
|
+
`)}
|
|
242
|
+
Read them with the Read tool when relevant; images (screenshots) can be viewed directly.`:(St(t),"")}function St(r){Dr.default.rmSync(kt.default.join(r,as),{recursive:!0,force:!0})}var Fh=4*1024*1024,Zh=16*1024*1024;function ja(r,e,t){let n=kt.default.join(r,as,`chat-${e.replace(/[^\w-]/g,"")}`);if(!t.length)return{section:"",dir:n};Dr.default.mkdirSync(n,{recursive:!0});let s=new Set,i=[],o=0,a=kt.default.relative(r,n);for(let l of t){let d=Buffer.from(l.contentBase64,"base64");if(d.length>Fh||o+d.length>Zh){i.push(`- (skipped "${l.name}" \u2014 over the upload size budget)`);continue}let p=Pa(l.name,s);Dr.default.writeFileSync(kt.default.join(n,p),d),o+=d.length,i.push(`- ${a}/${p} (${ki(d.length)} KB)`)}return{section:`
|
|
243
|
+
|
|
244
|
+
The user attached file(s) with this message, staged locally for you. They are reference material and NOT part of the repository \u2014 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:
|
|
245
|
+
${i.join(`
|
|
246
|
+
`)}
|
|
247
|
+
Read them with the Read tool; images can be viewed directly.`,dir:n}}var ki=r=>Math.max(1,Math.round(r/1024)),Kh=r=>Math.round(r/(1024*1024)*10)/10;var it=$(require("node:fs"),1),Si=$(require("node:path"),1);function bn(){return Si.default.join(ee(),"runner.pid")}function cs(){return Si.default.join(ee(),"runner.log")}function Oa(){it.default.mkdirSync(ee(),{recursive:!0,mode:448});let r=it.default.openSync(cs(),"a",384);try{it.default.chmodSync(cs(),384)}catch{}return r}function zr(){let r=bn();if(!it.default.existsSync(r))return null;let e=Number(it.default.readFileSync(r,"utf8").trim());return Number.isFinite(e)&&e>0?e:null}function wn(r){try{return process.kill(r,0),!0}catch{return!1}}function Na(r){it.default.mkdirSync(ee(),{recursive:!0,mode:448}),it.default.writeFileSync(bn(),String(r),{mode:384})}function Ma(r){zr()===r&&it.default.rmSync(bn(),{force:!0})}var ac=$(Se(),1);async function cc(r,e){let t=await fetch(new URL("/api/runners/enroll",r.controlPlaneUrl),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enrollToken:e,name:r.runnerName,platform:`${process.platform}/${process.arch}`,runnerVersion:gs})});if(!t.ok){let i=await t.text().catch(()=>"");throw new Error(`enrollment failed (${t.status}): ${i.slice(0,300)}`)}let n=ac.EnrollResponse.parse(await t.json()),s={...r,runnerId:n.runnerId,runnerToken:n.runnerToken};return ie(s),s}var gs="1.1.0";mr();var bc="Posted automatically by Allwright",_p=["Posted automatically by TicketPilot"],Ge=r=>r.includes(bc)||_p.some(e=>r.includes(e));var ze=class{constructor(e){this.auth=e}auth;headers(){return{Authorization:`Basic ${Buffer.from(`${this.auth.email}:${this.auth.apiToken}`).toString("base64")}`,Accept:"application/json","Content-Type":"application/json"}}async request(e,t,n){let s=new URL(t,this.auth.baseUrl).toString(),i=await fetch(s,{method:e,headers:this.headers(),body:n===void 0?void 0:JSON.stringify(n)});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`Jira ${e} ${t} -> ${i.status}: ${o.slice(0,500)}`)}if(i.status!==204)return await i.json()}async myself(){return this.request("GET","/rest/api/3/myself")}async searchUsers(e,t=20){let n=await this.userSearch(e,t);return n.length||!e.includes("@")?n:this.userSearch(e.slice(0,e.indexOf("@")),t)}async userSearch(e,t){return e.trim()?(await this.request("GET",`/rest/api/3/user/search?query=${encodeURIComponent(e)}&maxResults=${t}`)??[]).filter(s=>s.accountId&&(s.accountType??"atlassian")==="atlassian").map(s=>({accountId:s.accountId,displayName:s.displayName??"(no name)",email:s.emailAddress??"",active:s.active??!0})):[]}async search(e,t=20){return((await this.request("POST","/rest/api/3/search/jql",{jql:e,maxResults:t,fields:["summary","components"]})).issues??[]).map(s=>({key:s.key,summary:s.fields?.summary??"",components:(s.fields?.components??[]).map(i=>i.name??"").filter(Boolean)}))}async projectStatuses(e){let t=await this.request("GET",`/rest/api/3/project/${encodeURIComponent(e)}/statuses`),n=new Map;for(let i of t??[])for(let o of i.statuses??[])o.name&&!n.has(o.name)&&n.set(o.name,o.statusCategory?.key??"indeterminate");let s=i=>i==="new"?0:i==="done"?2:1;return[...n.entries()].sort((i,o)=>s(i[1])-s(o[1])).map(([i])=>i)}async searchEpics(e,t=20){return((await this.request("POST","/rest/api/3/search/jql",{jql:`project = "${e}" AND issuetype = Epic AND statusCategory != Done ORDER BY created DESC`,maxResults:t,fields:["summary","status"]})).issues??[]).map(s=>({key:s.key,summary:s.fields?.summary??"",status:s.fields?.status?.name??""}))}async epicChildren(e,t=50){return((await this.request("POST","/rest/api/3/search/jql",{jql:`parent = "${e}" ORDER BY created ASC`,maxResults:t,fields:["summary","status","labels"]})).issues??[]).map(s=>({key:s.key,summary:s.fields?.summary??"",status:s.fields?.status?.name??"",statusCategory:s.fields?.status?.statusCategory?.key??"indeterminate",labels:s.fields?.labels??[]}))}async searchBoard(e,t=100){return((await this.request("POST","/rest/api/3/search/jql",{jql:e,maxResults:t,fields:["summary","status","labels"]})).issues??[]).map(s=>({key:s.key,summary:s.fields?.summary??"",status:s.fields?.status?.name??"(no status)",statusId:s.fields?.status?.id??"",labels:s.fields?.labels??[]}))}async boardColumns(e){try{let n=(await this.request("GET",`/rest/agile/1.0/board?projectKeyOrId=${encodeURIComponent(e)}`)).values?.[0]?.id;if(!n)return null;let i=((await this.request("GET",`/rest/agile/1.0/board/${n}/configuration`)).columnConfig?.columns??[]).filter(o=>(o.statuses??[]).length>0&&o.name).map(o=>({name:o.name,statusIds:(o.statuses??[]).map(a=>a.id??"").filter(Boolean)}));return i.length?i:null}catch{return null}}async getIssue(e){let t=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}?fields=summary,description,labels,comment,status,attachment`),n;try{n=await this.listAllComments(e)}catch{n=t.fields.comment?.comments??[]}let s=n.map(o=>({id:o.id??"",author:o.author?.displayName??"unknown",authorAccountId:o.author?.accountId??null,created:o.created,body:vc(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:vc(t.fields.description),labels:t.fields.labels??[],status:t.fields.status?.name??"",comments:s,attachments:i}}async listAllComments(e){let t=await this.fetchCommentPage(e,0),n=t.total??t.comments.length;if(n<=t.comments.length)return t.comments;let s=Math.max(0,n-200),i=s===0?[...t.comments]:[];for(;i.length<Math.min(n,200);){let o=await this.fetchCommentPage(e,s+i.length);if(!o.comments.length)break;i.push(...o.comments)}return i.slice(-200)}async fetchCommentPage(e,t){let n=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}/comment?startAt=${t}&maxResults=100`);return{comments:n.comments??[],total:n.total}}async downloadAttachment(e){let t=await fetch(e,{headers:this.headers()});if(!t.ok)throw new Error(`attachment download failed: ${t.status}`);return Buffer.from(await t.arrayBuffer())}async lastEnteredStatus(e,t){let n=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}?expand=changelog&fields=status`),s=t.toLowerCase(),i=null;for(let o of n.changelog?.histories??[])(o.items??[]).some(u=>(u.field==="status"||u.fieldId==="status")&&(u.toString??"").toLowerCase()===s)&&(!i||new Date(o.created)>new Date(i.at))&&(i={at:o.created,author:o.author?.displayName??"unknown",authorAccountId:o.author?.accountId??null});return i}async createIssue(e,t,n,s="Task",i){return{key:(await this.request("POST","/rest/api/3/issue",{fields:{project:{key:e},issuetype:{name:s},summary:t.slice(0,250),description:Ki(n),...i?{parent:{key:i}}:{}}})).key}}async addAttachments(e,t){if(!t.length)return;let n=new FormData;for(let a of t)n.append("file",new Blob([new Uint8Array(a.content)]),a.name.slice(0,255));let s=new URL(`/rest/api/3/issue/${encodeURIComponent(e)}/attachments`,this.auth.baseUrl).toString(),i=Buffer.from(`${this.auth.email}:${this.auth.apiToken}`).toString("base64"),o=await fetch(s,{method:"POST",headers:{Authorization:`Basic ${i}`,Accept:"application/json","X-Atlassian-Token":"no-check"},body:n});if(!o.ok)throw new Error(`Jira attachment upload failed: HTTP ${o.status}`)}async addTriggerComment(e,t){await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/comment`,{body:Ki(t)})}async addComment(e,t){let n=`${t}
|
|
248
|
+
|
|
249
|
+
---
|
|
250
|
+
_${bc} \u2014 never treated as a trigger._`;await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/comment`,{body:Ki(n)})}async editLabels(e,t){let n=[...(t.add??[]).map(s=>({add:s})),...(t.remove??[]).map(s=>({remove:s}))];await this.request("PUT",`/rest/api/3/issue/${encodeURIComponent(e)}`,{update:{labels:n}})}async getTransitions(e){return((await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}/transitions`)).transitions??[]).map(n=>({id:n.id,name:n.name}))}async transition(e,t){await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/transitions`,{transition:{id:t}})}async transitionByName(e,t){let s=(await this.getTransitions(e)).find(i=>i.name.toLowerCase()===t.toLowerCase());return s?(await this.transition(e,s.id),!0):!1}};function vc(r){if(!r)return"";let e=[],t=n=>{n.text&&e.push(n.text),n.type==="hardBreak"&&e.push(`
|
|
251
|
+
`);for(let s of n.content??[])t(s);n.type&&["paragraph","heading","listItem","codeBlock","blockquote"].includes(n.type)&&e.push(`
|
|
252
|
+
`)};return t(r),e.join("").replace(/\n{3,}/g,`
|
|
253
|
+
|
|
254
|
+
`).trim()}function Ki(r){let e=r.replace(/\r\n/g,`
|
|
255
|
+
`).split(`
|
|
256
|
+
`),t=[],n=0,s=i=>{let o=[],a=/(\*\*[^*]+\*\*|`[^`]+`)/g,u=0,l;for(;(l=a.exec(i))!==null;){l.index>u&&o.push({type:"text",text:i.slice(u,l.index)});let d=l[0];d.startsWith("**")?o.push({type:"text",text:d.slice(2,-2),marks:[{type:"strong"}]}):o.push({type:"text",text:d.slice(1,-1),marks:[{type:"code"}]}),u=l.index+d.length}return u<i.length&&o.push({type:"text",text:i.slice(u)}),o.length?o:[{type:"text",text:" "}]};for(;n<e.length;){let i=e[n];if(i.trim()===""){n++;continue}let o=i.match(/^```(\w*)\s*$/);if(o){let p=[];for(n++;n<e.length&&!/^```\s*$/.test(e[n]);)p.push(e[n]),n++;n++,t.push({type:"codeBlock",attrs:o[1]?{language:o[1]}:{},content:[{type:"text",text:p.join(`
|
|
257
|
+
`)||" "}]});continue}let a=i.match(/^(#{1,6})\s+(.*)$/);if(a){t.push({type:"heading",attrs:{level:a[1].length},content:s(a[2])}),n++;continue}if(i.match(/^\s*[-*]\s+(.*)$/)){let p=[];for(;n<e.length;){let v=e[n].match(/^\s*[-*]\s+(.*)$/);if(!v)break;p.push({type:"listItem",content:[{type:"paragraph",content:s(v[1])}]}),n++}t.push({type:"bulletList",content:p});continue}if(i.match(/^\s*\d+[.)]\s+(.*)$/)){let p=[];for(;n<e.length;){let v=e[n].match(/^\s*\d+[.)]\s+(.*)$/);if(!v)break;p.push({type:"listItem",content:[{type:"paragraph",content:s(v[1])}]}),n++}t.push({type:"orderedList",content:p});continue}let d=[i];for(n++;n<e.length&&e[n].trim()!==""&&!/^(#{1,6}\s|```|\s*[-*]\s|\s*\d+[.)]\s)/.test(e[n]);)d.push(e[n]),n++;t.push({type:"paragraph",content:s(d.join(" "))})}return{type:"doc",version:1,content:t}}function wc(r,e,t){let n=r.repos[e]?.jira??r.jira;if(!n)return{kind:"legacy"};let s=t.trim().toLowerCase();if(!s)return{kind:"legacy"};if(s===n.email.toLowerCase())return{kind:"self"};let i=r.jiraUsers[s];return i?{kind:"user",creds:{baseUrl:n.baseUrl,email:i.email,apiToken:i.apiToken}}:{kind:"missing",error:`Jira actions from Allwright post under YOUR OWN Atlassian identity, and no Jira credential is set up for ${s} on the runner yet. Ask your admin to run this on the runner machine:
|
|
258
|
+
|
|
259
|
+
allwright jira user-add ${s}
|
|
260
|
+
|
|
261
|
+
It prompts for your Atlassian email and an API token (create one at id.atlassian.com -> Security -> API tokens). Takes effect immediately \u2014 then just retry this action.`}}function Ss(r,e,t){let n=(t??"").trim().toLowerCase(),s=n?r.githubUsers[n]?.token:void 0;if(s)return{token:s,source:"user"};let i=r.repos[e]?.github?.token;return i?{token:i,source:"repo"}:r.github?.token?{token:r.github.token,source:"global"}:null}function At(r,e){return r.repos[e]?.github?.token??r.github?.token??null}function kc(r,e){let t=[r.jira,...Object.values(r.repos).map(a=>a.jira)].filter(a=>!!a),n=new Set(t.map(a=>a.email.toLowerCase())),s=!!r.github?.token||Object.values(r.repos).some(a=>a.github?.token),i=r.github?.login??Object.values(r.repos).find(a=>a.github?.login)?.github?.login??"",o=e.map(a=>{let u=a.trim().toLowerCase(),l=r.jiraUsers[u]?"own":n.has(u)?"runner-account":"missing",d=l==="own"?r.jiraUsers[u].email:l==="runner-account"?u:"",p=r.githubUsers[u]?"own":s?"shared":"missing",v=p==="own"?r.githubUsers[u].login??"":p==="shared"?i:"";return{email:u,jira:l,jiraAs:d,github:p,githubAs:v}});return{githubShared:s,sharedGithubLogin:i,entries:o}}var In=require("node:child_process"),Jr=$(require("node:fs"),1),Vi=$(require("node:os"),1),Hi=$(require("node:path"),1),Ts="allwright",Sc=`/etc/systemd/system/${Ts}.service`,vp="ticketpilot-runner";function Gi(){let r=process.env.SUDO_USER&&process.env.SUDO_USER!=="root"?process.env.SUDO_USER:"",e=r||Vi.default.userInfo().username,t=r?Hi.default.join("/home",r):Vi.default.homedir();return{nodePath:process.execPath,scriptPath:Jr.default.realpathSync(process.argv[1]),user:e,home:t}}function Wi(r){let e=Hi.default.dirname(r.nodePath);return`[Unit]
|
|
262
|
+
Description=Allwright runner
|
|
263
|
+
After=network-online.target
|
|
264
|
+
|
|
265
|
+
[Service]
|
|
266
|
+
Type=simple
|
|
267
|
+
User=${r.user}
|
|
268
|
+
Environment=HOME=${r.home}
|
|
269
|
+
Environment=PATH=${e}:/usr/local/bin:/usr/bin:/bin
|
|
270
|
+
ExecStart=${r.nodePath} ${r.scriptPath} start --foreground
|
|
271
|
+
Restart=always
|
|
272
|
+
RestartSec=5
|
|
273
|
+
|
|
274
|
+
[Install]
|
|
275
|
+
WantedBy=multi-user.target
|
|
276
|
+
`}function Tc(){return process.platform==="linux"&&Jr.default.existsSync("/run/systemd/system")}function xc(r){if(!Tc())throw new Error(process.platform==="win32"?"Windows service install isn't built in yet \u2014 use NSSM: nssm install allwright <node> <this script> start --foreground":"no systemd on this machine \u2014 run `allwright start` (background mode) instead");let e=Gi(),t=Wi(e);if(typeof process.getuid=="function"&&process.getuid()!==0){r.info("Root is needed to write the unit. Re-run as:"),r.info(' sudo env "PATH=$PATH" allwright service install'),r.info("(the env PATH part matters when node is installed via nvm \u2014 plain sudo can't find it)"),r.info(""),r.info(`This is exactly what it will write to ${Sc}:`),r.info(`
|
|
277
|
+
`+t);return}Jr.default.writeFileSync(Sc,t),(0,In.execFileSync)("systemctl",["daemon-reload"]),(0,In.execFileSync)("systemctl",["enable","--now",Ts]),r.info(`Installed and started (runs as ${e.user}, survives reboots).`),r.info(`Watch it: journalctl -u ${Ts} -f`),r.info("Status: allwright service status")}function Cc(r){if(!Tc())throw new Error("no systemd on this machine");if(typeof process.getuid=="function"&&process.getuid()!==0)throw new Error("root is needed \u2014 run: sudo allwright service uninstall");for(let e of[Ts,vp]){try{(0,In.execFileSync)("systemctl",["disable","--now",e])}catch{}let t=`/etc/systemd/system/${e}.service`;Jr.default.existsSync(t)&&Jr.default.rmSync(t)}(0,In.execFileSync)("systemctl",["daemon-reload"]),r.info("Service removed. The runner config and credentials were not touched.")}var Ec=$(Se(),1);function Ic(r){return r.filter(e=>e.statusCategory!=="done"&&!e.labels.includes("agent-implemented")&&!e.labels.includes(Ec.NEEDS_INPUT_LABEL))}function Ac(r,e,t){let n=t.map(s=>{let i=(s.description??"").trim().slice(0,600);return`- ${s.key} [${s.status}] ${s.summary}${i?`
|
|
278
|
+
${i.replace(/\n+/g," ")}`:""}`}).join(`
|
|
279
|
+
`);return`You are looking at this repository to help sequence work on the Jira epic ${r} ("${e}"). These child tickets are still pending:
|
|
280
|
+
|
|
281
|
+
${n}
|
|
282
|
+
|
|
283
|
+
Pick the ONE ticket that should be implemented FIRST. Weigh, in this order: (1) dependencies \u2014 does another ticket build on it? Foundations (schema, APIs, shared components) come before things that consume them; (2) risk \u2014 unknowns worth surfacing early; (3) user value. Use the code you can read to judge what already exists.
|
|
284
|
+
|
|
285
|
+
Answer with ONLY a fenced json block, nothing after it:
|
|
286
|
+
\`\`\`json
|
|
287
|
+
{"issueKey": "<one of the keys above>", "reason": "<2-3 sentences: why this one first, and what it unblocks>"}
|
|
288
|
+
\`\`\``}function Rc(r,e){let n=r.match(/```(?:json)?\s*(\{[\s\S]*?\})\s*```/)?.[1]??r.match(/\{[\s\S]*"issueKey"[\s\S]*?\}/)?.[0];if(!n)return{error:"the agent's answer contained no JSON recommendation"};try{let s=JSON.parse(n),i=typeof s.issueKey=="string"?s.issueKey.trim():"",o=typeof s.reason=="string"?s.reason.trim():"";return e.includes(i)?{issueKey:i,reason:o||"(no reasoning given)"}:{error:`the agent recommended "${i}", which is not a pending child of this epic`}}catch{return{error:"the agent's JSON recommendation did not parse"}}}var no=require("node:crypto"),ou=$(require("node:fs"),1);var Ji=$(require("node:fs"),1),$c=$(require("node:os"),1),xs=$(require("node:path"),1),Pc=require("node:child_process"),jc=$(require("node:readline"),1),Oc=$(Se(),1),bp={read_only:["Read(./**)","Glob(./**)","Grep(./**)"],edit_no_shell:["Read(./**)","Glob(./**)","Grep(./**)","Edit(./**)","Write(./**)"]};function wp(r){if(process.env.ANTHROPIC_API_KEY)return"API key";let e=r??xs.default.join($c.default.homedir(),".claude");try{if(Ji.default.existsSync(xs.default.join(e,".credentials.json"))||Ji.default.existsSync(xs.default.join(e,"credentials.json")))return"subscription"}catch{}return"unknown"}async function kp(r){let e=["-p","--output-format","stream-json","--verbose","--allowedTools",bp[r.mode].join(","),"--max-turns",String(r.maxTurns??60),...r.model?["--model",r.model]:[],...r.resume?["--resume",r.sessionId]:["--session-id",r.sessionId]],t=wp(r.configDir);return t!=="unknown"&&r.onLog("info",t==="subscription"?"Billing: Claude subscription \u2014 costs shown are notional list prices, not money charged":"Billing: Anthropic API key \u2014 costs shown are actual metered spend"),new Promise(n=>{let s=(0,Pc.spawn)(r.bin,e,{cwd:r.repoPath,env:r.configDir?{...process.env,CLAUDE_CONFIG_DIR:r.configDir}:process.env,stdio:["pipe","pipe","pipe"]}),i={ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,billingMode:t==="subscription"?"subscription":t==="API key"?"api":"unknown"},o=!1,a=()=>{o||(o=!0,clearTimeout(u),n(i))},u=setTimeout(()=>{i.timedOut=!0,i.error=`run exceeded ${r.timeoutSeconds}s wall-clock limit`,r.onLog("error",i.error),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),5e3).unref()},r.timeoutSeconds*1e3);s.stdin.write(r.prompt),s.stdin.end(),jc.default.createInterface({input:s.stdout}).on("line",p=>{if(!p.trim())return;let v;try{v=JSON.parse(p)}catch{r.onLog("agent",p.slice(0,1e3));return}if(v.type==="system"&&v.subtype==="init")i.model=typeof v.model=="string"?v.model:void 0,r.onLog("info",`Claude Code session started (model: ${v.model??"default"})`);else if(v.type==="assistant"){for(let S of v.message?.content??[])if(S.type==="text"&&S.text?.trim())r.onLog("agent",S.text.trim().slice(0,4e3));else if(S.type==="tool_use"){let x=JSON.stringify(S.input??{}).slice(0,300);r.onLog("info",`tool ${S.name} ${x}`)}}else v.type==="result"&&(i.costUsd=Number(v.total_cost_usd??0),i.inputTokens=Number(v.usage?.input_tokens??0),i.outputTokens=Number(v.usage?.output_tokens??0),v.subtype==="success"&&!v.is_error?(i.ok=!0,i.resultText=String(v.result??"")):v.subtype==="error_max_turns"?(i.turnLimitHit=!0,i.error=`hit the ${r.maxTurns??60}-turn limit before finishing`):(i.error=String(v.result??v.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 \u2014 the run will work again once the limit window resets. Original error: ${i.error.slice(0,400)}`)))});let d="";s.stderr.on("data",p=>{d=(d+p.toString()).slice(-2e3)}),s.on("error",p=>{i.error=`failed to start ${r.bin}: ${p.message}`,r.onLog("error",i.error),a()}),s.on("close",p=>{!i.ok&&!i.error&&(i.error=i.timedOut?i.error:`claude exited with code ${p}${d?`: ${d.slice(-500)}`:""}`),a()})})}var Ue={id:"claude-code",displayName:"Claude Code",capabilities:Oc.REGISTERED_AGENTS.find(r=>r.id==="claude-code").capabilities,run:kp};var Cs=$(Se(),1),Sp={security:"You are a security auditor. You can READ this repository; you can never run or change anything. Audit it against the knowledge packs below and report real, exploitable-here problems \u2014 not checklist theatre.",testing:"You are a test-coverage auditor. You can READ this repository (code and tests); you can never run anything. Find what is untested and fragile against the knowledge packs below \u2014 gaps that would actually bite this product, not generic coverage philosophy.",architecture:"You are a software architecture auditor. You can READ this repository; you can never run or change anything. Judge whether it is structurally HEALTHY for what it is trying to be, against the knowledge packs below \u2014 real structural pain for this team, not textbook purity."};function Mc(r,e,t,n={}){let s=e.map(u=>`### Pack: ${u.name}
|
|
289
|
+
|
|
290
|
+
${u.content}`).join(`
|
|
291
|
+
|
|
292
|
+
`),i=t.trim()?`
|
|
293
|
+
|
|
294
|
+
### Lessons from THIS project (read first \u2014 human-confirmed corrections; never re-raise what these mark as accepted/false-positive)
|
|
295
|
+
|
|
296
|
+
${t}`:"",o=n.scopeNote?`
|
|
297
|
+
|
|
298
|
+
### SCOPE \u2014 audit ONLY this
|
|
299
|
+
|
|
300
|
+
${n.scopeNote}
|
|
301
|
+
|
|
302
|
+
Read whatever surrounding code you need for context, but every finding must be about the scope above.`:"",a=n.testResults?`
|
|
303
|
+
|
|
304
|
+
### Real test-run results (executed by the runner from TEST.md \u2014 you cannot run anything yourself)
|
|
305
|
+
|
|
306
|
+
${n.testResults}
|
|
307
|
+
|
|
308
|
+
Fold what these results show \u2014 failures, flaky exits, suspiciously green suites \u2014 into your findings with the rest of the audit.`:"";return`${Sp[r]}
|
|
309
|
+
|
|
310
|
+
Knowledge below is LAYERED: global (product) -> org (this company) -> project (this repo). More specific levels OVERRIDE general ones; entries referencing a rule id (SEC-001 style) modify or disable that rule.
|
|
311
|
+
|
|
312
|
+
${s}${i}${o}${a}
|
|
313
|
+
|
|
314
|
+
Explore the repository first \u2014 entry points, routes, storage, tests \u2014 then audit. Finish with EXACTLY one fenced json block (nothing after it):
|
|
315
|
+
\`\`\`json
|
|
316
|
+
{"summary": "<3-5 sentences: overall posture, the theme of what you found>",
|
|
317
|
+
"findings": [{"id": "<stable-kebab-slug>", "title": "<one line>", "ruleId": "<the pack rule id this violates, e.g. SEC-013 \u2014 "" only if genuinely no rule covers it>",
|
|
318
|
+
"severity": "critical|high|medium|low|info", "area": "<short group, e.g. auth>",
|
|
319
|
+
"evidence": [{"file": "<repo-relative path>", "line": <number, omit if n/a>, "note": "<what is there>"}],
|
|
320
|
+
"fix": "<2-4 sentences: concrete fix, specific to this code>"}]}
|
|
321
|
+
\`\`\`
|
|
322
|
+
Rules: every finding needs at least one evidence file you actually read \u2014 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 Dc(r){let t=r.match(/```(?:json)?\s*(\{[\s\S]*\})\s*```(?![\s\S]*```)/)?.[1]??r.match(/\{[\s\S]*"findings"[\s\S]*\}/)?.[0];if(!t)return{error:"the agent's report contained no JSON block"};let n;try{n=JSON.parse(t)}catch{return{error:"the agent's JSON report did not parse"}}if(!Array.isArray(n.findings))return{error:"the report has no findings array"};let s=[],i=0,o=new Set;for(let a of n.findings.slice(0,25)){let u=Tp(a),l=u?Cs.AuditFinding.safeParse(u):null;if(!l?.success){i++;continue}let d=l.data.id;for(;o.has(d);)d=`${d}-2`;o.add(d),s.push({...l.data,id:d})}return{summary:typeof n.summary=="string"?n.summary.trim().slice(0,2e3):"",findings:s,dropped:i}}function Tp(r){if(typeof r!="object"||r===null)return null;let e=r,t=typeof e.severity=="string"?e.severity.toLowerCase():"",n=Array.isArray(e.evidence)?e.evidence.filter(i=>typeof i=="object"&&i!==null).map(i=>({file:typeof i.file=="string"?i.file:"",...Nc(i.line)?{line:Nc(i.line)}:{},note:typeof i.note=="string"?i.note:""})).filter(i=>i.file):[],s=typeof e.ruleId=="string"?e.ruleId.trim().toUpperCase():"";return{id:xp(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:Cs.AuditSeverity.options.includes(t)?t:void 0,area:typeof e.area=="string"?e.area.slice(0,60):"",evidence:n,fix:typeof e.fix=="string"?e.fix.slice(0,2e3):""}}function Nc(r){let e=typeof r=="number"?r:typeof r=="string"?parseInt(r,10):NaN;return Number.isInteger(e)&&e>0?e:void 0}function xp(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"finding"}var An=$(require("node:fs"),1),Yi=$(require("node:path"),1),Lc=$(Se(),1);var Cp=20;function zc(){return Yi.default.join(ee(),"audits.json")}function Rn(){try{return{byProject:JSON.parse(An.default.readFileSync(zc(),"utf8")).byProject??{}}}catch{return{byProject:{}}}}function Uc(r){let e=zc();An.default.mkdirSync(Yi.default.dirname(e),{recursive:!0,mode:448});let t=e+".tmp";An.default.writeFileSync(t,JSON.stringify(r,null,2),{mode:384}),An.default.renameSync(t,e)}function qc(r,e){let t=Rn(),n=t.byProject[r]??[];n.unshift(Lc.AuditRecord.parse(e)),t.byProject[r]=n.slice(0,Cp),Uc(t)}function Bc(r){return(Rn().byProject[r]??[]).map(e=>{let t={};for(let n of e.findings)t[n.severity]=(t[n.severity]??0)+1;return{id:e.id,role:e.role,createdAt:e.createdAt,findingCount:e.findings.length,bySeverity:t}})}function Xi(r,e,t){let n=Rn(),i=(n.byProject[r]??[]).find(a=>a.id===e);if(!i)return null;i.ticketed??={},i.verdicts??={},i.lessonsWritten??=[];let o=new Set(i.findings.map(a=>a.id));t.selected&&(i.review={selected:t.selected.filter(a=>o.has(a)),updatedAt:new Date().toISOString()});for(let a of t.ticketed??[])o.has(a.findingId)&&(i.ticketed={...i.ticketed,[a.findingId]:a.issueKey});for(let a of t.verdicts??[])o.has(a.findingId)&&(i.verdicts={...i.verdicts,[a.findingId]:{verdict:a.verdict,note:a.note,by:t.verdictBy??"",at:new Date().toISOString()}});for(let a of t.markLessonsWritten??[])o.has(a)&&!i.lessonsWritten.includes(a)&&i.lessonsWritten.push(a);return Uc(n),i}function Fc(r,e){return(Rn().byProject[r]??[]).find(s=>s.role===e&&(s.scope?.kind??"repo")==="repo")?.createdAt??null}function Zc(r,e){return(Rn().byProject[r]??[]).find(t=>t.id===e)??null}mr();var pe=$(require("node:fs"),1),We=$(require("node:path"),1),Vc=$(Se(),1);var Ep=`# Security baseline \u2014 what to check in any repo
|
|
323
|
+
|
|
324
|
+
Every rule has a stable id. Findings must cite the id they violate.
|
|
325
|
+
|
|
326
|
+
## Secrets & configuration
|
|
327
|
+
- **SEC-001** Credentials, API keys, tokens or private keys committed anywhere
|
|
328
|
+
(including leftovers: .env.example with real values, dumps, backups).
|
|
329
|
+
- **SEC-002** Secrets logged, echoed into error messages, or sent to third
|
|
330
|
+
parties.
|
|
331
|
+
- **SEC-003** Debug flags / verbose modes that would ship enabled.
|
|
332
|
+
|
|
333
|
+
## Injection surfaces
|
|
334
|
+
- **SEC-010** SQL built by string concatenation instead of parameters.
|
|
335
|
+
- **SEC-011** Shell commands assembled from user input.
|
|
336
|
+
- **SEC-012** HTML rendered from user input without escaping (XSS);
|
|
337
|
+
dangerouslySetInnerHTML and template-injection equivalents.
|
|
338
|
+
- **SEC-013** Path traversal: user input joined into filesystem paths without
|
|
339
|
+
normalization checks.
|
|
340
|
+
|
|
341
|
+
## AuthN / AuthZ
|
|
342
|
+
- **SEC-020** Routes or handlers missing an authentication check that their
|
|
343
|
+
siblings have.
|
|
344
|
+
- **SEC-021** Authorization done in the UI only \u2014 server trusts the client's
|
|
345
|
+
claim of role or ownership (IDOR: records fetched/updated by id without an
|
|
346
|
+
owner check).
|
|
347
|
+
- **SEC-022** Password handling: plaintext or weak hashing, tokens that never
|
|
348
|
+
expire, session fixation.
|
|
349
|
+
|
|
350
|
+
## Data exposure
|
|
351
|
+
- **SEC-030** Endpoints returning more fields than the UI needs (emails,
|
|
352
|
+
tokens, internal ids) \u2014 especially list endpoints.
|
|
353
|
+
- **SEC-031** Uploads/static folders publicly reachable; user files served
|
|
354
|
+
without access control.
|
|
355
|
+
- **SEC-032** Missing rate limits on login/OTP/expensive endpoints.
|
|
356
|
+
|
|
357
|
+
## Dependencies & platform
|
|
358
|
+
- **SEC-040** Obviously outdated or abandoned dependencies with
|
|
359
|
+
known-vulnerable majors.
|
|
360
|
+
- **SEC-041** CORS wide open with credentials; cookies missing
|
|
361
|
+
HttpOnly/Secure/SameSite.
|
|
362
|
+
- **SEC-042** TLS/redirect handling that downgrades to http.
|
|
363
|
+
|
|
364
|
+
Prioritize by real exploitability in THIS codebase, not by rule order.
|
|
365
|
+
`,Ip=`# Test gaps \u2014 what to check in any repo
|
|
366
|
+
|
|
367
|
+
Every rule has a stable id. Findings must cite the id they violate.
|
|
368
|
+
|
|
369
|
+
## Critical paths
|
|
370
|
+
- **TEST-001** A core product flow (from CLAUDE.md, routes, or entry points)
|
|
371
|
+
with no meaningful test covering it.
|
|
372
|
+
- **TEST-002** Money, auth, permissions or data-deletion paths without tests \u2014
|
|
373
|
+
these deserve coverage even when everything else is bare.
|
|
374
|
+
|
|
375
|
+
## Gap patterns
|
|
376
|
+
- **TEST-010** Modules with complex branching and zero test files touching
|
|
377
|
+
them.
|
|
378
|
+
- **TEST-011** Error paths: code that catches/raises but only the happy path
|
|
379
|
+
is tested.
|
|
380
|
+
- **TEST-012** Boundary values untested: empty lists, zero/negative amounts,
|
|
381
|
+
unicode, max lengths.
|
|
382
|
+
- **TEST-013** Concurrency-sensitive code (queues, locks, dedup keys) with no
|
|
383
|
+
test at all.
|
|
384
|
+
|
|
385
|
+
## Test quality smells (flag only when clear)
|
|
386
|
+
- **TEST-020** Tests with no assertions, or asserting only "no exception".
|
|
387
|
+
- **TEST-021** Heavy mocking that re-implements the unit under test (tests
|
|
388
|
+
the mock).
|
|
389
|
+
- **TEST-022** Snapshot/golden tests covering logic that deserves behavioral
|
|
390
|
+
assertions.
|
|
391
|
+
- **TEST-023** Time/order-dependent tests (sleeps, Date.now, shared state) \u2014
|
|
392
|
+
flaky suspects.
|
|
393
|
+
|
|
394
|
+
Report the GAP and why it is risky here, not generic coverage philosophy.
|
|
395
|
+
`,Ap=`# GDPR readiness \u2014 data-protection audit for repos with EU exposure
|
|
396
|
+
|
|
397
|
+
FIRST decide exposure: if this product clearly has no EU users, no personal
|
|
398
|
+
data, or is a purely static/internal tool, say so in ONE summary sentence and
|
|
399
|
+
skip deep GDPR analysis \u2014 do not manufacture findings. Otherwise audit the
|
|
400
|
+
rules below. Cite the rule id AND map the area to the closest GDPR article
|
|
401
|
+
(e.g. area "gdpr-art-17"). Evidence rules stay absolute.
|
|
402
|
+
|
|
403
|
+
## Personal-data inventory (Art. 5, 30)
|
|
404
|
+
- **GDPR-001** Personal data collected but never used (minimization), or
|
|
405
|
+
entering through forms/APIs/imports with no record of where it lands.
|
|
406
|
+
- **GDPR-002** Personal data in logs, analytics events, error reporters, or
|
|
407
|
+
backups.
|
|
408
|
+
|
|
409
|
+
## Lawful basis & consent (Art. 6, 7; ePrivacy)
|
|
410
|
+
- **GDPR-010** Cookies/trackers/pixels set BEFORE consent; banners that load
|
|
411
|
+
vendors regardless of the answer; withdrawal harder than consent.
|
|
412
|
+
- **GDPR-011** Marketing default-opt-ins; pre-ticked boxes.
|
|
413
|
+
|
|
414
|
+
## Data-subject rights (Art. 15\u201321)
|
|
415
|
+
- **GDPR-020** No code path to export a person's data (access/portability).
|
|
416
|
+
- **GDPR-021** No code path to delete/anonymize a person; hard-deletes that
|
|
417
|
+
miss related tables, backups, or third-party copies.
|
|
418
|
+
- **GDPR-022** Stored personal data that cannot actually be corrected.
|
|
419
|
+
|
|
420
|
+
## Retention & deletion (Art. 5(1)(e), 17)
|
|
421
|
+
- **GDPR-030** Data with no TTL/cleanup anywhere: sessions, logs with PII,
|
|
422
|
+
soft-deleted rows kept forever, orphaned uploads.
|
|
423
|
+
|
|
424
|
+
## Security of processing (Art. 32)
|
|
425
|
+
- **GDPR-040** Personal data unencrypted in transit/storage where it
|
|
426
|
+
reasonably should be; PII endpoints without authz; PII in URLs.
|
|
427
|
+
|
|
428
|
+
## Processors & transfers (Art. 28, 44\u201349)
|
|
429
|
+
- **GDPR-050** Third-party services receiving personal data (analytics,
|
|
430
|
+
email, cloud) \u2014 list what the CODE sends; flag transfers with no EU
|
|
431
|
+
region/SCC signal in configuration.
|
|
432
|
+
|
|
433
|
+
## Breach readiness (Art. 33\u201334)
|
|
434
|
+
- **GDPR-060** Not enough logging/audit trail to even DETECT and scope a
|
|
435
|
+
personal-data breach.
|
|
436
|
+
|
|
437
|
+
Severity: many users' data exposed or a missing legal-basis mechanism is
|
|
438
|
+
high/critical; hygiene and documentation gaps are medium/low.
|
|
439
|
+
`,Rp=`# Architecture health \u2014 is this repository structurally sound?
|
|
440
|
+
|
|
441
|
+
Every rule has a stable id. Findings must cite the id they violate. Judge
|
|
442
|
+
against what THIS codebase is trying to be (a static site does not need
|
|
443
|
+
hexagonal layers) \u2014 flag structure that hurts THIS team, not textbook
|
|
444
|
+
deviations.
|
|
445
|
+
|
|
446
|
+
## Dependencies & boundaries
|
|
447
|
+
- **ARCH-001** Circular dependencies between modules/packages.
|
|
448
|
+
- **ARCH-002** Missing service/domain layer: business logic living in
|
|
449
|
+
controllers/handlers/UI components.
|
|
450
|
+
- **ARCH-003** Layering violations: lower layers importing upward (db layer
|
|
451
|
+
importing HTTP concerns, domain importing framework).
|
|
452
|
+
- **ARCH-004** Shared mutable state or god-objects passed everywhere instead
|
|
453
|
+
of explicit interfaces.
|
|
454
|
+
|
|
455
|
+
## Size & duplication
|
|
456
|
+
- **ARCH-010** God classes/files: one unit owning many unrelated
|
|
457
|
+
responsibilities (watch for 1000+ line hubs everything imports).
|
|
458
|
+
- **ARCH-011** Duplicate implementations of the same concept (two repositories
|
|
459
|
+
for one entity, copy-pasted business rules that will drift).
|
|
460
|
+
- **ARCH-012** Dead code: modules/exports nothing references anymore.
|
|
461
|
+
|
|
462
|
+
## Structure & conventions
|
|
463
|
+
- **ARCH-020** Folder structure that fights the architecture (by-type folders
|
|
464
|
+
hiding feature boundaries, or vice versa \u2014 inconsistency is the flag).
|
|
465
|
+
- **ARCH-021** Naming that lies: modules whose name no longer matches what
|
|
466
|
+
they do.
|
|
467
|
+
- **ARCH-022** Configuration scattered/hard-coded instead of centralized.
|
|
468
|
+
|
|
469
|
+
## Runtime shape
|
|
470
|
+
- **ARCH-030** Missing caching where the code repeatedly recomputes/refetches
|
|
471
|
+
obviously cacheable data on hot paths.
|
|
472
|
+
- **ARCH-031** N+1 query patterns / chatty IO in loops.
|
|
473
|
+
- **ARCH-032** No seams for testing: singletons/hard-wired dependencies that
|
|
474
|
+
make units untestable in isolation.
|
|
475
|
+
|
|
476
|
+
Summarize with an overall verdict: is this repository HEALTHY for its
|
|
477
|
+
purpose, and what are the 2-3 structural moves with the best payoff?
|
|
478
|
+
`,Kc={security:[{name:"baseline.md",content:Ep},{name:"gdpr.md",content:Ap}],testing:[{name:"test-gaps.md",content:Ip}],architecture:[{name:"architecture-health.md",content:Rp}]},$p=["You are auditing code you can READ but never run or change.","You are auditing test coverage by READING code and tests","\\`area\\`"];function Qi(r){return We.default.join(ee(),"knowledge",r)}function Hc(r,e){return We.default.join(r,".ticketpilot","knowledge",`${e}.md`)}function eo(r,e){return We.default.join(r,".ticketpilot","lessons",`${e}.md`)}function Gc(r,e){let t=[],n=Qi(r),s=[];if(pe.default.existsSync(n)){for(let u of pe.default.readdirSync(n)){if(!u.endsWith(".md"))continue;let l=We.default.join(n,u),d=pe.default.readFileSync(l,"utf8");if($p.some(p=>d.includes(p))&&Kc[r].map(v=>v.name).includes(u)&&!d.includes("SEC-0")&&!d.includes("TEST-0")&&!d.includes("GDPR-0")){pe.default.rmSync(l);continue}s.push(u)}s.sort()}let i=new Set(s);for(let u of Kc[r])i.has(u.name)||t.push({level:"global",source:"pack",name:u.name,content:u.content,editable:!1});for(let u of s)t.push({level:"org",source:"pack",name:u,content:pe.default.readFileSync(We.default.join(n,u),"utf8").slice(0,3e4),editable:!0});let o=Hc(e,r);pe.default.existsSync(o)&&t.push({level:"project",source:"pack",name:`${r}.md`,content:pe.default.readFileSync(o,"utf8").slice(0,3e4),editable:!0});let a=eo(e,r);return pe.default.existsSync(a)&&t.push({level:"project",source:"lessons",name:`${r}.md`,content:pe.default.readFileSync(a,"utf8").slice(0,2e4),editable:!0}),t}function Wc(r,e){let t=Gc(r,e);return{packs:t.filter(n=>n.source==="pack").map(n=>({name:`${n.level}/${n.name}`,content:n.content})),lessons:t.find(n=>n.source==="lessons")?.content??"",layers:t}}function to(r,e,t,n="project"){let s=n==="org"?We.default.join(Qi(e),"org-lessons.md"):eo(r,e);pe.default.mkdirSync(We.default.dirname(s),{recursive:!0});let i=pe.default.existsSync(s)?"":`# ${e} lessons (${n} level)
|
|
479
|
+
|
|
480
|
+
Human-confirmed corrections and rules. Every ${e} audit reads this FIRST. Reference rule ids (SEC-001 style) when overriding a rule.
|
|
481
|
+
|
|
482
|
+
`;pe.default.appendFileSync(s,i+t.trimEnd()+`
|
|
483
|
+
|
|
484
|
+
`)}function Jc(r,e,t,n){let s=new Date().toISOString().slice(0,10),i=r.evidence[0]?` (${r.evidence[0].file}${r.evidence[0].line?`:${r.evidence[0].line}`:""})`:"",o=r.ruleId?` \xB7 rule ${r.ruleId}`:"";return`## ${s} \xB7 ${e}${o} \xB7 ${r.title}${i}
|
|
485
|
+
Finding \`${r.id}\` [${r.severity}] was marked **${e}**`+(n?` by ${n}`:"")+`.${t?` Reason: ${t}`:""}
|
|
486
|
+
`+(e==="false-positive"?"Do not raise this class of finding here again unless the code meaningfully changes.":"Known and accepted \u2014 do not re-raise; mention only if its risk materially grows.")}function Yc(r,e){return`## ${new Date().toISOString().slice(0,10)} \xB7 taught${e?` by ${e}`:""}
|
|
487
|
+
${r.trim()}`}function Xc(r){let e=[];for(let t of Vc.AuditRole.options)for(let n of Gc(t,r))e.push({role:t,...n});return e}function Qc(r,e,t,n,s,i){if(!/^[a-zA-Z0-9._-]+\.md$/.test(s))throw new Error("file name must be a simple .md name");let o=t==="org"?We.default.join(Qi(e),s):n==="lessons"?eo(r,e):Hc(r,e);pe.default.mkdirSync(We.default.dirname(o),{recursive:!0}),pe.default.writeFileSync(o,i,{mode:t==="org"?384:420})}var ro=()=>new Date().toISOString(),m={info:r=>console.log(`${ro()} [info] ${r}`),warn:r=>console.warn(`${ro()} [warn] ${r}`),error:r=>console.error(`${ro()} [error] ${r}`)};var eu=require("node:child_process"),tu=$(require("node:fs"),1),ru=$(require("node:path"),1);function nu(r){for(let e of["TEST.md","TESTING.md","docs/TEST.md"]){let t=ru.default.join(r,e);if(tu.default.existsSync(t))return t}return null}function su(r){let e=[];for(let t of r.matchAll(/```(?:bash|sh|shell)?\s*\n([\s\S]*?)```/g))for(let n of t[1].split(`
|
|
488
|
+
`)){let s=n.trim();!s||s.startsWith("#")||e.push(s)}return e.slice(0,10)}async function iu(r,e,t={}){let n=[],s=t.perCommandTimeoutMs??6e5;for(let i of e){t.onProgress?.(`running: ${i}`);let o=Date.now(),a=await new Promise(u=>{let l=(0,eu.spawn)("bash",["-lc",i],{cwd:r,env:{...process.env,CI:"1",FORCE_COLOR:"0"}}),d="",p=S=>{d+=S.toString(),d.length>2e5&&(d=d.slice(-1e5))};l.stdout.on("data",p),l.stderr.on("data",p);let v=setTimeout(()=>{l.kill("SIGKILL"),d+=`
|
|
489
|
+
[killed: timed out]`},s);l.on("close",S=>{clearTimeout(v),u({command:i,exitCode:S??-1,durationMs:Date.now()-o,tail:d.slice(-4e3)})}),l.on("error",S=>{clearTimeout(v),u({command:i,exitCode:-1,durationMs:Date.now()-o,tail:String(S)})})});t.onProgress?.(`exit ${a.exitCode} in ${Math.round(a.durationMs/1e3)}s: ${i}`),n.push(a)}return n}async function Yr(r){let{packs:e,lessons:t}=Wc(r.role,r.repoPath);if(!e.length)return{ok:!1,error:`no knowledge packs found for the ${r.role} role \u2014 add markdown files under ~/.config/ticketpilot/knowledge/${r.role}/ on the runner`};let n="";if(r.scope.kind==="ticket"&&r.scope.ref){let d=r.scope.ref,p="";try{let S=await r.jira.getIssue(d);p=`Ticket ${d}: ${S.summary}
|
|
490
|
+
|
|
491
|
+
${S.description}`.slice(0,4e3)}catch{p=`Ticket ${d} (could not fetch its text from Jira).`}let v=await Ui(r.repoPath,d).catch(()=>null);if(v){let{base:S,stat:x,diff:w}=await ks(r.repoPath,v).catch(()=>({base:"",stat:"",diff:""}));n=`${p}
|
|
492
|
+
|
|
493
|
+
Its implementation branch \`${v}\` vs \`${S}\`:
|
|
494
|
+
\`\`\`
|
|
495
|
+
${x}\`\`\`
|
|
496
|
+
\`\`\`diff
|
|
497
|
+
${w}
|
|
498
|
+
\`\`\``}else n=`${p}
|
|
499
|
+
|
|
500
|
+
No implementation branch found for ${d} \u2014 audit the parts of the codebase this ticket touches or would touch.`}else if(r.scope.kind==="branch"&&r.scope.ref){let{base:d,stat:p,diff:v}=await ks(r.repoPath,r.scope.ref);n=`The diff of \`${r.scope.ref}\` vs \`${d}\`:
|
|
501
|
+
\`\`\`
|
|
502
|
+
${p}\`\`\`
|
|
503
|
+
\`\`\`diff
|
|
504
|
+
${v}
|
|
505
|
+
\`\`\``}let s,i;if(r.role==="testing"){let d=nu(r.repoPath),p=d?su(ou.default.readFileSync(d,"utf8")):[];p.length&&(m.info(`Audit (testing): executing ${p.length} TEST.md command(s)`),i=await iu(r.repoPath,p,{onProgress:v=>m.info(`[test-run] ${v}`)}),s=i.map(v=>`$ ${v.command}
|
|
506
|
+
(exit ${v.exitCode}, ${Math.round(v.durationMs/1e3)}s)
|
|
507
|
+
${v.tail.slice(-2e3)}`).join(`
|
|
508
|
+
|
|
509
|
+
---
|
|
510
|
+
|
|
511
|
+
`))}let o=r.model||"claude-fable-5",a=await Ue.run({repoPath:r.repoPath,prompt:Mc(r.role,e,t,{scopeNote:n,testResults:s}),timeoutSeconds:480,bin:r.claudeBin,mode:"read_only",maxTurns:120,sessionId:(0,no.randomUUID)(),model:o,onLog:(d,p)=>{d==="agent"&&m.info(`[audit:${r.role}] ${p.slice(0,160)}`)}}),u=Dc(a.resultText);if("error"in u)return{ok:!1,error:u.error};let l={id:(0,no.randomUUID)(),role:r.role,createdAt:new Date().toISOString(),model:a.model||o,summary:u.summary,packNames:e.map(d=>d.name),findings:u.findings,costUsd:a.costUsd??0,ticketed:{},verdicts:{},lessonsWritten:[],scope:r.scope,...i?{testRun:i}:{}};return qc(r.projectId,l),m.info(`Audit (${r.role}${r.scope.kind!=="repo"?` \xB7 ${r.scope.kind}:${r.scope.ref}`:""}) done: ${u.findings.length} finding(s)`+(u.dropped?`, ${u.dropped} dropped for missing evidence`:"")),{ok:!0,audit:l}}var wr=$(Se(),1);var yu=$(require("node:path"),1),Ps=require("node:crypto"),Te=$(Se(),1);var $n=$(Se(),1);var au=require("node:child_process"),cu=$(require("node:readline"),1),uu=$(Se(),1);async function Pp(r){if(r.mode!=="read_only")return{ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,error:"the codex adapter only supports read-only runs \u2014 its write sandbox cannot exclude shell, and Allwright never weakens a guarantee silently"};if(r.resume)return{ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,error:"the codex adapter cannot resume sessions"};let e=["exec","--json","--sandbox","read-only","--skip-git-repo-check","--cd",r.repoPath,...r.model?["--model",r.model]:[],"-"];return new Promise(t=>{let n=(0,au.spawn)(r.bin,e,{cwd:r.repoPath,env:process.env,stdio:["pipe","pipe","pipe"]}),s={ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0},i="",o=!1,a=()=>{o||(o=!0,clearTimeout(u),t(s))},u=setTimeout(()=>{s.timedOut=!0,s.error=`run exceeded ${r.timeoutSeconds}s wall-clock limit`,r.onLog("error",s.error),n.kill("SIGTERM"),setTimeout(()=>n.kill("SIGKILL"),5e3).unref()},r.timeoutSeconds*1e3);n.stdin.write(r.prompt),n.stdin.end(),cu.default.createInterface({input:n.stdout}).on("line",p=>{if(!p.trim())return;let v;try{v=JSON.parse(p)}catch{r.onLog("agent",p.slice(0,1e3));return}let S=v.item??v.msg??v,x=S?.type??v.type,w=S?.text??S?.message??"";x==="agent_message"&&typeof w=="string"&&w.trim()?(i=w,r.onLog("agent",w.trim().slice(0,4e3))):x==="command_execution"||x==="exec_command_begin"?r.onLog("info",`tool ${String(S?.command??"").slice(0,300)}`):x==="error"&&typeof w=="string"&&w&&r.onLog("error",w.slice(0,1e3))});let d="";n.stderr.on("data",p=>{d=(d+p.toString()).slice(-2e3)}),n.on("error",p=>{s.error=`failed to start ${r.bin}: ${p.message} \u2014 is the Codex CLI installed and logged in?`,r.onLog("error",s.error),a()}),n.on("close",p=>{p===0&&i.trim()?(s.ok=!0,s.resultText=i):s.error||(s.error=`codex exited with code ${p}`+(i?"":" and produced no answer")+(d?`: ${d.slice(-500)}`:"")),a()})})}var so={id:"codex",displayName:"OpenAI Codex CLI (experimental)",capabilities:uu.REGISTERED_AGENTS.find(r=>r.id==="codex").capabilities,run:Pp};var jp={[Ue.id]:Ue,[so.id]:so};function gr(r){return jp[r||$n.DEFAULT_AGENT_ID]??null}function Xr(r,e){return!e||e===Ue.id?r.claudeBin:r.agents[e]?.bin??e}function Es(r,e){let t=gr(r);if(!t)return`no agent adapter named "${r}" on this runner \u2014 update the runner, or set the rule's agent to "${$n.DEFAULT_AGENT_ID}"`;let n=(0,$n.missingAgentCapabilities)(t.id,e);return n&&n.length?`agent "${t.displayName}" cannot run ${e} rules: it cannot guarantee ${n.join(", ")}. Allwright refuses rather than weakening the isolation silently.`:null}function Rt(r,e){return r.replace(/\{\{(\w+)\}\}/g,(t,n)=>n in e?e[n]:t)}ut();mr();var me=$(require("node:fs"),1),en=$(require("node:path"),1);var Np=k.object({runId:k.string(),issueKey:k.string(),repoName:k.string(),owner:k.string(),repo:k.string(),prNumber:k.number().int(),prUrl:k.string(),branch:k.string(),headSha:k.string(),doneLabel:k.string(),failedLabel:k.string(),jiraTransition:k.string().optional(),changesRequestedNotified:k.boolean().optional(),conflictNotified:k.boolean().optional()}),Mp=k.record(Np),Dp=k.object({runId:k.string(),issueKey:k.string(),issueSummary:k.string().default(""),projectId:k.string(),repoName:k.string(),environmentName:k.string(),requestedBy:k.string().default(""),createdAt:k.string()}),Lp=k.record(Dp),zp=k.object({runId:k.string(),issueKey:k.string(),kind:k.enum(["plan","implement"]),repoPath:k.string(),sessionId:k.string(),doneLabel:k.string(),failedLabel:k.string(),timeoutSeconds:k.number(),createdAt:k.string(),questionsPostedAt:k.string(),rounds:k.number().int().default(1),nextLogSeq:k.number().int().nonnegative().default(0),baseRepoPath:k.string().optional(),repoName:k.string().optional(),branch:k.string().optional(),baseBranch:k.string().optional(),jiraTransition:k.string().optional(),jiraTransitionOnMerge:k.string().optional(),requireApproval:k.boolean().optional(),maxTurns:k.number().int().optional(),issueSummary:k.string().default(""),claudeConfigDir:k.string().optional(),agent:k.string().optional(),model:k.string().optional(),actorEmail:k.string().optional()}),Up=k.object({runId:k.string(),issueKey:k.string(),issueSummary:k.string().default(""),repoName:k.string(),baseRepoPath:k.string(),branch:k.string(),baseBranch:k.string(),headSha:k.string(),requireApproval:k.boolean(),doneLabel:k.string(),failedLabel:k.string(),jiraTransition:k.string().optional(),jiraTransitionOnMerge:k.string().optional(),actorEmail:k.string().optional(),resultSummary:k.string().default(""),costUsd:k.number().default(0),nextLogSeq:k.number().int().default(1e5),createdAt:k.string()}),qp=k.record(Up),Bp=k.object({runId:k.string(),issueKey:k.string(),repoName:k.string(),owner:k.string(),repo:k.string(),prNumber:k.number().int(),prUrl:k.string(),jiraTransitionOnMerge:k.string().default(""),createdAt:k.string()}),Fp=k.record(Bp),Zp=k.record(zp);function lu(){return en.default.join(ee(),"pending-runs.json")}function io(){return en.default.join(ee(),"pending-deploys.json")}function oo(){return en.default.join(ee(),"pending-inputs.json")}function ao(){return en.default.join(ee(),"merge-watch.json")}function co(){return en.default.join(ee(),"pending-pushes.json")}function uo(){let r=co();if(!me.default.existsSync(r))return{};try{return qp.parse(JSON.parse(me.default.readFileSync(r,"utf8")))}catch{return{}}}function lo(r){let e=uo();e[r.runId]=r,lt(co(),e)}function Is(r){return uo()[r]??null}function ho(r){let e=uo();r in e&&(delete e[r],lt(co(),e))}function As(){let r=ao();if(!me.default.existsSync(r))return{};try{return Fp.parse(JSON.parse(me.default.readFileSync(r,"utf8")))}catch{return{}}}function du(r){let e=As();e[r.runId]=r,lt(ao(),e)}function Pn(r){let e=As();r in e&&(delete e[r],lt(ao(),e))}function jn(){let r=lu();if(!me.default.existsSync(r))return{};try{return Mp.parse(JSON.parse(me.default.readFileSync(r,"utf8")))}catch{return{}}}function lt(r,e){me.default.mkdirSync(ee(),{recursive:!0,mode:448});let t=r+".tmp";me.default.writeFileSync(t,JSON.stringify(e,null,2)+`
|
|
512
|
+
`,{mode:384}),me.default.renameSync(t,r),me.default.chmodSync(r,384)}function hu(r){lt(lu(),r)}function tn(r){let e=jn();e[r.runId]=r,hu(e)}function fo(r){return jn()[r]??null}function yr(r){let e=jn();r in e&&(delete e[r],hu(e))}function po(){let r=io();if(!me.default.existsSync(r))return{};try{return Lp.parse(JSON.parse(me.default.readFileSync(r,"utf8")))}catch{return{}}}function fu(r){let e=po();e[r.runId]=r,lt(io(),e)}function Rs(r){return po()[r]??null}function $s(r){let e=po();r in e&&(delete e[r],lt(io(),e))}function rn(){let r=oo();if(!me.default.existsSync(r))return{};try{return Zp.parse(JSON.parse(me.default.readFileSync(r,"utf8")))}catch{return{}}}function pu(r){let e=rn();e[r.runId]=r,lt(oo(),e)}function Je(r){let e=rn();r in e&&(delete e[r],lt(oo(),e))}var _u=5,mu=2,Kp=8,gu=2,Vp="You stopped because the session hit its turn limit \u2014 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 Nn(r,e,t,n){let s=Date.now(),i="";n&&(i=await n().catch(()=>""));let o=await r.run(e),a=0,u="",l=n?Kp:mu;for(;!o.ok&&o.turnLimitHit&&r.capabilities.sessionResume;){if(a>=l){u=`resume cap (${l}) reached`;break}if(n&&a>=mu){let p=await n().catch(()=>""),v=p!==""&&p!==i;if(i=p,!v){u="the last resume produced no new work";break}if(Date.now()-s>e.timeoutSeconds*gu*1e3){u=`wall-clock budget (${gu}x the rule's timeout) exhausted`;break}}a++,t("info",`Turn limit hit mid-work \u2014 auto-resuming the same session (resume ${a}, cap ${l})`);let d=await r.run({...e,prompt:Vp,resume:!0});d.costUsd+=o.costUsd,d.inputTokens+=o.inputTokens,d.outputTokens+=o.outputTokens,o=d}return!o.ok&&o.turnLimitHit&&r.capabilities.sessionResume&&(o.error=`${o.error??"hit the turn limit"} \u2014 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}function _r(r,e,t=0){let n=t;return{emit:(o,a)=>{e.send({type:"run.log",runId:r,seq:n++,ts:new Date().toISOString(),level:o,message:a}),o!=="agent"&&m.info(`[run ${r}] ${a}`)},setStatus:(o,a={})=>{e.send({type:"run.status",runId:r,status:o,...a})},nextSeq:()=>n}}async function mo(r){return r.rule.action.type==="implement"?Wp(r):r.rule.action.type==="respond"?Gp(r):Hp(r)}async function Hp(r){let{emit:e,setStatus:t,nextSeq:n}=_r(r.runId,r.transport),{trigger:s}=r.rule,i=r.rule.action;if(i.type!=="plan_only")return;let o=Es(i.agent,i.type);if(o){e("error",o),await nn(r,o),t("failed",{error:o});return}let a=(0,Ps.randomUUID)();try{t("running"),e("info",`Run started for ${r.issueKey} (rule "${r.rule.name}", plan-only)`),e("info",`Fetching ${r.issueKey} from Jira`);let u=await r.jira.getIssue(r.issueKey),l=Rt(i.promptTemplate,{issueKey:u.key,summary:u.summary,description:u.description||"(no description)",comments:Dn(u.comments)})+await Lr(r.jira,u.attachments,r.repoPath,e);e("info",`Starting Claude Code in ${r.repoPath} \u2014 read-only tools, path-jailed to the repo, timeout ${i.timeoutSeconds}s`);let d=await Nn(gr(i.agent),{repoPath:r.repoPath,prompt:l,timeoutSeconds:i.timeoutSeconds,bin:Xr(r.cfg,i.agent),configDir:r.claudeConfigDir,mode:"read_only",model:i.model||void 0,sessionId:a,onLog:(S,x)=>e(S,x)},e),p={costUsd:d.costUsd,inputTokens:d.inputTokens,outputTokens:d.outputTokens,billingMode:d.billingMode,model:d.model};if(!d.ok||!d.resultText.trim()){let S=d.error??"Claude Code produced no output";e("error",`Run failed: ${S}`),await nn(r,S),t(d.timedOut?"timed_out":"failed",{error:S,...p});return}let v=js(d.resultText);if(v){await Os({kind:"plan",runId:r.runId,issueKey:r.issueKey,repoPath:r.repoPath,sessionId:a,doneLabel:s.doneLabel,failedLabel:s.failedLabel,timeoutSeconds:i.timeoutSeconds,jira:r.jira,nextLogSeq:n(),rounds:1,claudeConfigDir:r.claudeConfigDir,agent:i.agent,model:i.model},v,e,t,p);return}await bu({runId:r.runId,issueKey:r.issueKey,doneLabel:s.doneLabel,jira:r.jira,resultText:d.resultText,costFields:p,emit:e,setStatus:t})}catch(u){let l=u instanceof Error?u.message:String(u);e("error",`Run failed: ${l}`),await nn(r,l),t("failed",{error:l})}finally{St(r.repoPath)}}async function vu(r,e,t,n){let{emit:s,setStatus:i,nextSeq:o}=_r(r.runId,n.transport,r.nextLogSeq);try{i("running"),s("info",`Reply received on ${r.issueKey} \u2014 continuing run \`${r.runId}\``);let a=$u(e)+await Lr(n.jiraFor(r.repoName??""),t,r.repoPath,s),u=await Nn(gr(r.agent),{repoPath:r.repoPath,prompt:a,timeoutSeconds:r.timeoutSeconds,bin:Xr(n.cfg,r.agent??""),configDir:r.claudeConfigDir,mode:"read_only",model:r.model||void 0,sessionId:r.sessionId,resume:!0,onLog:(p,v)=>s(p,v)},s),l={costUsd:u.costUsd,inputTokens:u.inputTokens,outputTokens:u.outputTokens,billingMode:u.billingMode,model:u.model};if(!u.ok||!u.resultText.trim()){let p=u.error??"Claude Code produced no output";s("error",`Run failed: ${p}`),await dt(n.jiraFor(r.repoName??""),r.issueKey,r.runId,r.failedLabel,p),Je(r.runId),i(u.timedOut?"timed_out":"failed",{error:p,...l});return}let d=js(u.resultText);if(d){if(r.rounds>=_u){await Pu(n.jiraFor(r.repoName??""),r,s,i,l);return}await Os({kind:"plan",runId:r.runId,issueKey:r.issueKey,repoPath:r.repoPath,sessionId:r.sessionId,doneLabel:r.doneLabel,failedLabel:r.failedLabel,timeoutSeconds:r.timeoutSeconds,jira:n.jiraFor(r.repoName??""),nextLogSeq:o(),rounds:r.rounds+1,createdAt:r.createdAt,claudeConfigDir:r.claudeConfigDir,actorEmail:r.actorEmail,agent:r.agent,model:r.model},d,s,i,l);return}await bu({runId:r.runId,issueKey:r.issueKey,doneLabel:r.doneLabel,jira:n.jiraFor(r.repoName??""),resultText:u.resultText,costFields:l,emit:s,setStatus:i}),Je(r.runId)}catch(a){let u=a instanceof Error?a.message:String(a);s("error",`Run failed: ${u}`),await dt(n.jiraFor(r.repoName??""),r.issueKey,r.runId,r.failedLabel,u),Je(r.runId),i("failed",{error:u})}finally{St(r.repoPath)}}async function bu(r){let{runId:e,issueKey:t,doneLabel:n,jira:s,resultText:i,costFields:o,emit:a,setStatus:u}=r;u("posting",o),a("info",`Posting plan to ${t} (${i.length} chars)`);let l=`
|
|
513
|
+
|
|
514
|
+
---
|
|
515
|
+
_Allwright plan-only run \`${e}\` \xB7 cost $${o.costUsd.toFixed(4)} \xB7 no code was written._`;await s.addComment(t,i+l),await s.editLabels(t,{add:[n],remove:[Te.NEEDS_INPUT_LABEL]}),a("info",`Labeled ${t} with "${n}"`),u("succeeded",{...o,resultSummary:On(i)}),a("info",`Run succeeded \xB7 $${o.costUsd.toFixed(4)}`)}async function Gp(r){let{emit:e,setStatus:t}=_r(r.runId,r.transport),n=r.rule.action;if(n.type!=="respond")return;let s=Es(n.agent,n.type);if(s){e("error",s),await r.jira.addComment(r.issueKey,`**Allwright could not answer this question.**
|
|
516
|
+
|
|
517
|
+
${s}`).catch(()=>{}),t("failed",{error:s});return}try{t("running"),e("info",`Run started for ${r.issueKey} (rule "${r.rule.name}", respond`+(r.question?`, question from ${r.question.author}`:"")+")"),e("info",`Fetching ${r.issueKey} from Jira`);let i=await r.jira.getIssue(r.issueKey),o=Rt(n.promptTemplate,{issueKey:i.key,summary:i.summary,description:i.description||"(no description)",comments:Dn(i.comments),question:r.question?.body??"(see the latest comment on the ticket)",questionAuthor:r.question?.author??"the commenter"})+await Lr(r.jira,i.attachments,r.repoPath,e);e("info",`Starting Claude Code in ${r.repoPath} \u2014 read-only tools, path-jailed, timeout ${n.timeoutSeconds}s`);let a=await Nn(gr(n.agent),{repoPath:r.repoPath,prompt:o,timeoutSeconds:n.timeoutSeconds,bin:Xr(r.cfg,n.agent),configDir:r.claudeConfigDir,mode:"read_only",model:n.model||void 0,sessionId:(0,Ps.randomUUID)(),onLog:(l,d)=>e(l,d)},e),u={costUsd:a.costUsd,inputTokens:a.inputTokens,outputTokens:a.outputTokens,billingMode:a.billingMode,model:a.model};if(!a.ok||!a.resultText.trim()){let l=a.error??"Claude Code produced no answer";e("error",`Run failed: ${l}`),await r.jira.addComment(r.issueKey,`**Allwright could not answer this question.**
|
|
518
|
+
|
|
519
|
+
Error: ${l.slice(0,800)}
|
|
520
|
+
|
|
521
|
+
Ask again in a new comment to retry. (run \`${r.runId}\`)`).catch(d=>m.error(`could not post answer failure to ${r.issueKey}: ${d}`)),t(a.timedOut?"timed_out":"failed",{error:l,...u});return}t("posting",u),e("info",`Posting answer to ${r.issueKey} (${a.resultText.length} chars)`),await r.jira.addComment(r.issueKey,a.resultText),t("succeeded",{...u,resultSummary:On(a.resultText)}),e("info",`Run succeeded \xB7 $${a.costUsd.toFixed(4)}`)}catch(i){let o=i instanceof Error?i.message:String(i);e("error",`Run failed: ${o}`),t("failed",{error:o})}finally{St(r.repoPath)}}async function wu(r,e,t,n){let s=`${e}-wip`;try{return St(r),await bs(r,`WIP: turn limit exhausted (Allwright run ${t})`),await ji(r,s),n("info",`Partial work preserved on branch "${s}"`),s}catch(i){return n("warn",`could not preserve partial work: ${i instanceof Error?i.message:i}`),null}}function ku(r){return`
|
|
522
|
+
|
|
523
|
+
Partial work from this run is saved on branch \`${r}\` \u2014 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 Wp(r){let{emit:e,setStatus:t,nextSeq:n}=_r(r.runId,r.transport),{trigger:s}=r.rule,i=r.rule.action;if(i.type!=="implement")return;let o=Es(i.agent,i.type);if(o){e("error",o),await nn(r,o),t("failed",{error:o});return}let a=yu.default.join(Cn(),r.runId),u=Rt(i.branchTemplate,{issueKey:r.issueKey}),l=(0,Ps.randomUUID)(),d=!1,p=!1;try{if(!Ss(he()??r.cfg,r.project.repoName,r.actorEmail))throw new Error("no GitHub token applies to this repo \u2014 run `allwright github set-token` (runner-wide) or `github set <repoName>` (this repo only)");if(u===i.baseBranch)throw new Error(`rendered branch "${u}" equals the base branch \u2014 refusing (check the rule's branch template)`);if(t("running"),e("info",`Run started for ${r.issueKey} (rule "${r.rule.name}", implement)`),i.jiraTransitionOnStart)try{await r.jira.transitionByName(r.issueKey,i.jiraTransitionOnStart)?e("info",`Jira transition "${i.jiraTransitionOnStart}" applied at run start`):e("warn",`no transition named "${i.jiraTransitionOnStart}" is available from this ticket's current status \u2014 continuing anyway`)}catch(f){e("warn",`Jira start transition failed: ${f instanceof Error?f.message:f} \u2014 continuing anyway`)}let v=await fr(r.repoPath);if(e("info",`Repo origin: ${v}`),!pr(v))throw new Error(`origin "${v}" is not a GitHub remote \u2014 implement mode supports GitHub only`);e("info",`Fetching ${r.issueKey} from Jira`);let S=await r.jira.getIssue(r.issueKey);e("info",`Preparing worktree on branch "${u}" from origin/${i.baseBranch}`),await Gr(r.repoPath,i.baseBranch),await Ni(r.repoPath,u),await Mi(r.repoPath,a,u,i.baseBranch),d=!0;let x=Rt(i.promptTemplate,{issueKey:S.key,summary:S.summary,description:S.description||"(no description)",comments:Dn(S.comments)})+await Lr(r.jira,S.attachments,a,e)+(i.updateMemory?Te.MEMORY_UPDATE_PROMPT:"");e("info",`Starting Claude Code in the worktree \u2014 edit tools enabled, path-jailed, no shell, timeout ${i.timeoutSeconds}s`);let w=await Nn(gr(i.agent),{repoPath:a,prompt:x,timeoutSeconds:i.timeoutSeconds,bin:Xr(r.cfg,i.agent),configDir:r.claudeConfigDir,mode:"edit_no_shell",model:i.model||void 0,maxTurns:i.maxTurns,sessionId:l,onLog:(f,g)=>e(f,g)},e,()=>vs(a)),j={costUsd:w.costUsd,inputTokens:w.inputTokens,outputTokens:w.outputTokens,billingMode:w.billingMode,model:w.model};if(!w.ok){let f=w.error??"Claude Code failed";e("error",`Run failed: ${f}`);let g=f;if(w.turnLimitHit){let b=await wu(a,u,r.runId,e);b&&(g+=ku(b))}await nn(r,g),t(w.timedOut?"timed_out":"failed",{error:f,...j});return}let U=js(w.resultText);if(U){p=!0,await Os({kind:"implement",runId:r.runId,issueKey:r.issueKey,repoPath:a,sessionId:l,doneLabel:s.doneLabel,failedLabel:s.failedLabel,timeoutSeconds:i.timeoutSeconds,jira:r.jira,nextLogSeq:n(),rounds:1,claudeConfigDir:r.claudeConfigDir,agent:i.agent,model:i.model,actorEmail:r.actorEmail,baseRepoPath:r.repoPath,repoName:r.project.repoName,branch:u,baseBranch:i.baseBranch,jiraTransition:i.jiraTransition,jiraTransitionOnMerge:i.jiraTransitionOnMerge,requireApproval:i.requireApproval,maxTurns:i.maxTurns,issueSummary:S.summary},U,e,t,j);return}St(a),await Tu({runId:r.runId,issueKey:r.issueKey,issueSummary:S.summary,worktreePath:a,baseRepoPath:r.repoPath,branch:u,baseBranch:i.baseBranch,jiraTransition:i.jiraTransition,jiraTransitionOnMerge:i.jiraTransitionOnMerge,requireApproval:i.requireApproval,doneLabel:s.doneLabel,failedLabel:s.failedLabel,repoName:r.project.repoName,jira:r.jira,cfg:r.cfg,actorEmail:r.actorEmail,resultText:w.resultText,costFields:j,emit:e,setStatus:t})}catch(v){let S=v instanceof Error?v.message:String(v);e("error",`Run failed: ${S}`),await nn(r,S),t("failed",{error:S})}finally{d&&!p&&await Wr(r.repoPath,a).catch(()=>{})}}async function Su(r,e,t,n){let{emit:s,setStatus:i,nextSeq:o}=_r(r.runId,n.transport,r.nextLogSeq),a=r.repoPath,u=!1;try{if(!Ss(he()??n.cfg,r.repoName??"",r.actorEmail))throw new Error("no GitHub token applies to this repo \u2014 run `allwright github set-token` (runner-wide) or `github set <repoName>` (this repo only)");i("running"),s("info",`Reply received on ${r.issueKey} \u2014 continuing run \`${r.runId}\``);let l=$u(e)+await Lr(n.jiraFor(r.repoName??""),t,a,s),d=await Nn(gr(r.agent),{repoPath:a,prompt:l,timeoutSeconds:r.timeoutSeconds,bin:Xr(n.cfg,r.agent??""),configDir:r.claudeConfigDir,mode:"edit_no_shell",model:r.model||void 0,maxTurns:r.maxTurns??120,sessionId:r.sessionId,resume:!0,onLog:(S,x)=>s(S,x)},s,()=>vs(a)),p={costUsd:d.costUsd,inputTokens:d.inputTokens,outputTokens:d.outputTokens,billingMode:d.billingMode,model:d.model};if(!d.ok){let S=d.error??"Claude Code failed";s("error",`Run failed: ${S}`);let x=S;if(d.turnLimitHit&&r.branch){let w=await wu(a,r.branch,r.runId,s);w&&(x+=ku(w))}await dt(n.jiraFor(r.repoName??""),r.issueKey,r.runId,r.failedLabel,x),Je(r.runId),i(d.timedOut?"timed_out":"failed",{error:S,...p});return}let v=js(d.resultText);if(v){if(r.rounds>=_u){await Pu(n.jiraFor(r.repoName??""),r,s,i,p);return}u=!0,await Os({kind:"implement",runId:r.runId,issueKey:r.issueKey,repoPath:a,sessionId:r.sessionId,doneLabel:r.doneLabel,failedLabel:r.failedLabel,timeoutSeconds:r.timeoutSeconds,jira:n.jiraFor(r.repoName??""),nextLogSeq:o(),rounds:r.rounds+1,createdAt:r.createdAt,claudeConfigDir:r.claudeConfigDir,actorEmail:r.actorEmail,agent:r.agent,model:r.model,baseRepoPath:r.baseRepoPath,repoName:r.repoName,branch:r.branch,baseBranch:r.baseBranch,jiraTransition:r.jiraTransition,jiraTransitionOnMerge:r.jiraTransitionOnMerge,requireApproval:r.requireApproval,maxTurns:r.maxTurns,issueSummary:r.issueSummary},v,s,i,p);return}St(a),await Tu({runId:r.runId,issueKey:r.issueKey,issueSummary:r.issueSummary,worktreePath:a,baseRepoPath:r.baseRepoPath??a,branch:r.branch,baseBranch:r.baseBranch,jiraTransition:r.jiraTransition,requireApproval:r.requireApproval??!0,doneLabel:r.doneLabel,failedLabel:r.failedLabel,repoName:r.repoName,jira:n.jiraFor(r.repoName??""),cfg:n.cfg,actorEmail:r.actorEmail,resultText:d.resultText,costFields:p,emit:s,setStatus:i}),Je(r.runId)}catch(l){let d=l instanceof Error?l.message:String(l);s("error",`Run failed: ${d}`),await dt(n.jiraFor(r.repoName??""),r.issueKey,r.runId,r.failedLabel,d),Je(r.runId),i("failed",{error:d})}finally{u||await Wr(r.baseRepoPath??a,a).catch(()=>{})}}async function Tu(r){let{runId:e,issueKey:t,issueSummary:n,worktreePath:s,baseRepoPath:i,branch:o,baseBranch:a,jiraTransition:u,jiraTransitionOnMerge:l,requireApproval:d,doneLabel:p,failedLabel:v,repoName:S,jira:x,cfg:w,actorEmail:j,resultText:U,costFields:f,emit:g,setStatus:b}=r,I=await Pi(s);I.deleted.length&&g("info",`Deleted ${I.deleted.length} file(s) listed in ${Hr}: `+I.deleted.slice(0,10).join(", ")+(I.deleted.length>10?", \u2026":""));for(let H of I.refused)g("warn",`${Hr} entry refused: ${H}`);g("info","Committing changes"),await bs(s,`${t}: ${n}
|
|
524
|
+
|
|
525
|
+
Allwright run ${e}`);let N=await Di(s,a);if(!N.ok){let H=N.forbidden.length?`refusing to push: changes touch protected paths (${N.forbidden.slice(0,5).join(", ")}) \u2014 CI/workflow files can exfiltrate repo secrets and are never pushed by the agent`:`refusing to push: change is too large (${N.files} files, ${N.insertions+N.deletions} lines; limits ${ys}/${_s})`;g("error",H),await dt(x,t,e,v,H),b("failed",{error:H,...f});return}g("info",`Diff: ${N.files} file(s), +${N.insertions}/-${N.deletions}`);let V=await fr(s),W=pr(V);if(!W){let H=`origin "${V}" is not a GitHub remote \u2014 implement mode supports GitHub only`;g("error",H),await dt(x,t,e,v,H),b("failed",{error:H,...f});return}let J=await En(s),z=Jp(U);try{await xu({gitDir:s,ownerRepo:W,runId:e,issueKey:t,issueSummary:n,branch:o,baseBranch:a,jiraTransition:u,jiraTransitionOnMerge:l,requireApproval:d,doneLabel:p,failedLabel:v,repoName:S,jira:x,cfg:w,actorEmail:j,summary:z,cost:f,emit:g,setStatus:b})}catch(H){let be=H instanceof Error?H.message:String(H);lo({runId:e,issueKey:t,issueSummary:n,repoName:S,baseRepoPath:i,branch:o,baseBranch:a,headSha:J,requireApproval:d,doneLabel:p,failedLabel:v,jiraTransition:u,jiraTransitionOnMerge:l,actorEmail:j,resultSummary:z,costUsd:f.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),g("error",`Run failed: ${be}`),g("info",`The commit itself survived on the runner (branch ${o}) \u2014 fix the cause, then use "Retry push" on this run's dashboard page.`),await dt(x,t,e,v,`${be}
|
|
526
|
+
|
|
527
|
+
The agent's commit survived on the runner \u2014 "Retry push" on the dashboard's run page re-pushes it without a new agent run.`),b("failed",{error:be,retryAvailable:!0,...f})}}async function xu(r){let{gitDir:e,ownerRepo:t,runId:n,issueKey:s,issueSummary:i,branch:o,baseBranch:a,jiraTransition:u,jiraTransitionOnMerge:l,requireApproval:d,doneLabel:p,failedLabel:v,repoName:S,jira:x,cfg:w,actorEmail:j,summary:U,cost:f,emit:g,setStatus:b}=r;g("info",`Pushing ${o} to origin`),await Li(e,o);let I=await ws(e,o),N=`${U}
|
|
528
|
+
|
|
529
|
+
---
|
|
530
|
+
Jira: ${new URL(`/browse/${s}`,w.jira?.baseUrl??"").toString()}
|
|
531
|
+
_Allwright implement run \`${n}\` \xB7 cost $${f.costUsd.toFixed(4)}. The agent could not run tests \u2014 review accordingly._`;g("info","Opening pull request");let V=Ss(he()??w,S,j);V.source==="user"&&g("info",`PR will be authored with ${j}'s own GitHub token`);let J=await new Oe(V.token).createPullRequest(t.owner,t.repo,{title:`${s}: ${i}`.slice(0,250),head:o,base:a,body:N});g("info",`PR ready: ${J.url}`),du({runId:n,issueKey:s,repoName:S,owner:t.owner,repo:t.repo,prNumber:J.number,prUrl:J.url,jiraTransitionOnMerge:l??"",createdAt:new Date().toISOString()}),b("posting",f);let z={runId:n,issueKey:s,repoName:S,owner:t.owner,repo:t.repo,prNumber:J.number,prUrl:J.url,branch:o,headSha:I,doneLabel:p,failedLabel:v,jiraTransition:u};d?(tn(z),await x.addComment(s,`**Allwright opened a pull request for review.**
|
|
532
|
+
|
|
533
|
+
PR: ${J.url}
|
|
534
|
+
|
|
535
|
+
Approve the PR on GitHub OR on the Allwright dashboard \u2014 either completes the run. Rejecting on the dashboard closes the PR and deletes the branch. (run \`${n}\`)`),b("awaiting_approval",{...f,prUrl:J.url,headSha:I,resultSummary:On(U),retryAvailable:!1}),g("info",`Awaiting approval on the dashboard \xB7 $${f.costUsd.toFixed(4)}`)):(await Cu({jira:x,issueKey:s},z,g),b("succeeded",{...f,prUrl:J.url,headSha:I,resultSummary:On(U),retryAvailable:!1}),g("info",`Run succeeded \xB7 ${J.url} \xB7 $${f.costUsd.toFixed(4)}`))}async function Cu(r,e,t){let n=null;if(e.jiraTransition)try{await r.jira.transitionByName(e.issueKey,e.jiraTransition)?t("info",`Jira transition "${e.jiraTransition}" applied`):(n=`no transition named "${e.jiraTransition}" is available from this ticket's current status \u2014 the PR is fine, but move the ticket manually`,t("warn",n))}catch(s){n=`Jira transition failed: ${s instanceof Error?s.message:s}`,t("warn",n)}return await r.jira.addComment(e.issueKey,`**Allwright: implementation complete.**
|
|
536
|
+
|
|
537
|
+
PR: ${e.prUrl}`+(n?`
|
|
538
|
+
|
|
539
|
+
Note: ${n}`:"")+`
|
|
540
|
+
|
|
541
|
+
(run \`${e.runId}\`)`),await r.jira.editLabels(e.issueKey,{add:[e.doneLabel],remove:[Te.NEEDS_INPUT_LABEL]}),n}async function Mn(r,e,t){let n=fo(e);if(!n){m.warn(`run.approved for ${e}: no pending entry (already processed?) \u2014 ignoring`);return}let{emit:s,setStatus:i}=Au(r,e);try{let o=At(he()??r.cfg,n.repoName);if(!o)throw new Error("GitHub token missing on this runner");let a=new Oe(o);s("info",`Approval received for ${n.issueKey} \u2014 verifying PR state`);let u=await a.getPullRequest(n.owner,n.repo,n.prNumber);if(!u)throw new Error(`PR #${n.prNumber} no longer exists on GitHub`);if(u.state==="closed"&&!u.merged)throw new Error(`PR #${n.prNumber} was closed on GitHub without merging`);let l=t??n.headSha;if(u.state==="open"&&u.headSha!==l){let d=`PR #${n.prNumber} changed since review started (${l.slice(0,7)} \u2192 ${u.headSha.slice(0,7)}) \u2014 approval not applied. Re-review the PR and approve again.`;s("warn",d),await r.jiraFor(n.repoName??"").addComment(n.issueKey,`**Allwright:** ${d}`),i("awaiting_approval",{prUrl:n.prUrl,headSha:u.headSha,resultSummary:d});return}await Cu({jira:r.jiraFor(n.repoName??""),issueKey:n.issueKey},n,s),i("succeeded",{prUrl:n.prUrl}),s("info","Run completed after approval"),yr(e)}catch(o){let a=o instanceof Error?o.message:String(o);s("error",`Approval handling failed: ${a}`),await Ru(r,n,a),i("failed",{error:a}),yr(e)}}async function Eu(r,e){let t=fo(e);if(!t){m.warn(`run.rejected for ${e}: no pending entry (already processed?) \u2014 ignoring`);return}let{emit:n,setStatus:s}=Au(r,e);try{let i=At(he()??r.cfg,t.repoName);if(!i)throw new Error("GitHub token missing on this runner");let o=new Oe(i);n("info",`Rejection received for ${t.issueKey} \u2014 closing PR #${t.prNumber}`);let a=await o.getPullRequest(t.owner,t.repo,t.prNumber);a&&a.state==="open"&&await o.closePullRequest(t.owner,t.repo,t.prNumber),a?.merged||await o.deleteBranch(t.owner,t.repo,t.branch),await r.jiraFor(t.repoName??"").addComment(t.issueKey,`**Allwright: changes rejected.**
|
|
542
|
+
|
|
543
|
+
The pull request was closed and the branch deleted. This ticket is labeled \`${t.failedLabel}\`; remove the label to try again. (run \`${t.runId}\`)`),await r.jiraFor(t.repoName??"").editLabels(t.issueKey,{add:[t.failedLabel]}),s("failed",{error:"rejected by user"}),n("info","PR closed, branch deleted, ticket labeled"),yr(e)}catch(i){let o=i instanceof Error?i.message:String(i);n("error",`Rejection handling failed: ${o}`),await Ru(r,t,o),s("failed",{error:o}),yr(e)}}async function Iu(r,e){let t=Is(e);if(!t){m.warn(`run.retryPush for ${e}: no retry record (already pushed, or invalidated?)`);let{emit:o,setStatus:a}=_r(e,r.transport,1e5);o("error","Retry push requested, but this runner holds no retry record for the run \u2014 it was already used or never saved. Re-run the ticket instead."),a("failed",{retryAvailable:!1});return}let{emit:n,setStatus:s,nextSeq:i}=_r(e,r.transport,t.nextLogSeq);try{let o=await ws(t.baseRepoPath,t.branch);if(o!==t.headSha){n("error",`Retry push aborted: branch ${t.branch} no longer holds the commit this run produced (expected ${t.headSha.slice(0,7)}, ${o?`found ${o.slice(0,7)}`:"the branch is gone"}) \u2014 a newer run has likely reused the branch. Re-run the ticket instead.`),ho(e),s("failed",{retryAvailable:!1});return}let a=await fr(t.baseRepoPath),u=pr(a);if(!u)throw new Error(`origin "${a}" is not a GitHub remote`);n("info",`Retry push for ${t.issueKey}: branch ${t.branch} at ${t.headSha.slice(0,7)}`);let l=r.jiraFor(t.repoName);await xu({gitDir:t.baseRepoPath,ownerRepo:u,runId:t.runId,issueKey:t.issueKey,issueSummary:t.issueSummary,branch:t.branch,baseBranch:t.baseBranch,jiraTransition:t.jiraTransition,jiraTransitionOnMerge:t.jiraTransitionOnMerge,requireApproval:t.requireApproval,doneLabel:t.doneLabel,failedLabel:t.failedLabel,repoName:t.repoName,jira:l,cfg:he()??r.cfg,actorEmail:t.actorEmail,summary:t.resultSummary,cost:{costUsd:t.costUsd},emit:n,setStatus:s}),ho(e),await l.editLabels(t.issueKey,{remove:[t.failedLabel]}).catch(()=>{})}catch(o){let a=o instanceof Error?o.message:String(o);n("error",`Retry push failed: ${a}`),lo({...t,nextLogSeq:i()}),s("failed",{error:a,retryAvailable:!0})}}function Au(r,e){let t=1e5;return{emit:(i,o)=>{r.transport.send({type:"run.log",runId:e,seq:t++,ts:new Date().toISOString(),level:i,message:o}),i!=="agent"&&m.info(`[run ${e}] ${o}`)},setStatus:(i,o={})=>{r.transport.send({type:"run.status",runId:e,status:i,...o})}}}async function Ru(r,e,t){try{await r.jiraFor(e.repoName??"").addComment(e.issueKey,`**Allwright could not complete the approval decision.**
|
|
544
|
+
|
|
545
|
+
Error: ${t.slice(0,800)}
|
|
546
|
+
|
|
547
|
+
PR: ${e.prUrl}
|
|
548
|
+
(run \`${e.runId}\`)`),await r.jiraFor(e.repoName??"").editLabels(e.issueKey,{add:[e.failedLabel]})}catch(n){m.error(`could not post decision failure to ${e.issueKey}: ${n}`)}}function Dn(r){if(!r.length)return"(no comments)";let e=6e4,t=r.map(i=>`${i.author} (${i.created}):
|
|
549
|
+
${i.body}`),n=[],s=0;for(let i=t.length-1;i>=0;i--){if(s+=t[i].length+6,s>e){n.unshift(`(\u2026 ${i+1} earlier comment(s) omitted for length \u2026)`);break}n.unshift(t[i])}return n.join(`
|
|
550
|
+
---
|
|
551
|
+
`)}function $u(r){return`The ticket author replied:
|
|
552
|
+
|
|
553
|
+
${r}
|
|
554
|
+
|
|
555
|
+
Continue from where you left off now that you have this information. If you are still missing what you need, ask again the same way as before (the ${Te.NEEDS_INPUT_MARKER} marker).`}function js(r){let e=r.trim(),t=e.split(`
|
|
556
|
+
`,1)[0].trim(),n=o=>o.replace(/[^a-z]/gi,"").toUpperCase();if(n(t)!==n(Te.NEEDS_INPUT_MARKER))return null;let s=e.indexOf(`
|
|
557
|
+
`);return s<0?null:e.slice(s+1).trim()||null}async function Os(r,e,t,n,s){t("info",`Claude needs more information \u2014 posting questions to ${r.issueKey}`),await r.jira.addComment(r.issueKey,`**${Te.NEEDS_INPUT_COMMENT_MARKER} before it can continue.**
|
|
558
|
+
|
|
559
|
+
${e}
|
|
560
|
+
|
|
561
|
+
Reply with your answers in a comment on this ticket \u2014 this run will pick up right where it left off, automatically, once you do. (run \`${r.runId}\`)`);let i=new Date().toISOString();await r.jira.editLabels(r.issueKey,{add:[Te.NEEDS_INPUT_LABEL]}),pu({runId:r.runId,issueKey:r.issueKey,kind:r.kind,repoPath:r.repoPath,sessionId:r.sessionId,doneLabel:r.doneLabel,failedLabel:r.failedLabel,timeoutSeconds:r.timeoutSeconds,createdAt:r.createdAt??i,questionsPostedAt:i,rounds:r.rounds,nextLogSeq:r.nextLogSeq,baseRepoPath:r.baseRepoPath,repoName:r.repoName,branch:r.branch,baseBranch:r.baseBranch,jiraTransition:r.jiraTransition,jiraTransitionOnMerge:r.jiraTransitionOnMerge,requireApproval:r.requireApproval,maxTurns:r.maxTurns,issueSummary:r.issueSummary??"",claudeConfigDir:r.claudeConfigDir,agent:r.agent,model:r.model,actorEmail:r.actorEmail}),n("needs_input",{...s,resultSummary:On(e)}),t("info",`Waiting for a reply on ${r.issueKey} (label "${Te.NEEDS_INPUT_LABEL}")`)}async function Pu(r,e,t,n,s){let i=`Claude asked for clarification ${e.rounds} times without reaching a result \u2014 giving up. Answer more completely and re-trigger manually if you want another attempt.`;t("error",i),await dt(r,e.issueKey,e.runId,e.failedLabel,i),Je(e.runId),n("failed",{error:i,...s})}async function nn(r,e){await dt(r.jira,r.issueKey,r.runId,r.rule.trigger.failedLabel,e)}async function dt(r,e,t,n,s){try{await r.addComment(e,`**Allwright run failed.**
|
|
562
|
+
|
|
563
|
+
Error: ${s.slice(0,800)}
|
|
564
|
+
|
|
565
|
+
This ticket has been labeled \`${n}\` and will not be retried automatically. To retry, fix the cause and remove the \`${n}\` label. (run \`${t}\`)`),await r.editLabels(e,{add:[n],remove:[Te.NEEDS_INPUT_LABEL]})}catch(i){m.error(`could not post failure comment to ${e}: ${i}`)}}function Jp(r){let e=/##\s*Summary of changes\s*\n([\s\S]*)$/i.exec(r);return(e?e[1]:r).trim().slice(0,8e3)||"(no summary provided)"}function On(r){for(let e of r.split(`
|
|
566
|
+
`)){let t=e.replace(/^#+\s*/,"").trim();if(t.length>10)return t.slice(0,200)}return r.slice(0,200)}var Ln=$(require("node:fs"),1),vr=$(require("node:path"),1),Ns=require("node:child_process"),yo=$(require("node:readline"),1),Lu=require("node:crypto"),br=$(Se(),1);mr();ut();var ju=4e3,Yp=4e3;function _o(r){let e=0;return{emit:(s,i)=>{r.transport.send({type:"run.log",runId:r.runId,seq:e++,ts:new Date().toISOString(),level:s,message:i.slice(0,Yp)}),s!=="agent"&&m.info(`[deploy ${r.runId}] ${i}`)},setStatus:(s,i={})=>{r.transport.send({type:"run.status",runId:r.runId,status:s,...i})}}}async function Ms(r){let{emit:e,setStatus:t}=_o(r),n=r.environment;try{let s=Xp(r);if(s){e("error",s),await qe(r,`**Allwright could not deploy to \`${n.name}\`.**
|
|
567
|
+
|
|
568
|
+
${s}`),t("failed",{error:s});return}if(n.requireApproval){fu({runId:r.runId,issueKey:r.issueKey,issueSummary:r.issueSummary,projectId:r.project.id,repoName:r.project.repoName,environmentName:n.name,requestedBy:r.requestedBy,createdAt:new Date().toISOString()}),e("info",`Deploy to "${n.name}" is waiting for approval on the dashboard \u2014 no step has run yet`),await qe(r,`**Allwright: deploy to \`${n.name}\` needs approval.**
|
|
569
|
+
|
|
570
|
+
${r.requestedBy?`Requested by ${r.requestedBy}. `:""}Nothing has been executed yet. Approve it on the Allwright dashboard to run the ${n.steps.length} deploy step(s), or reject to cancel. (run \`${r.runId}\`)`),t("awaiting_approval",{resultSummary:`Awaiting approval to deploy ${r.issueKey} to ${n.name}`});return}await zu(r,e,t)}catch(s){let i=s instanceof Error?s.message:String(s);e("error",`Deploy failed: ${i}`),await qe(r,`**Allwright deploy to \`${n.name}\` failed.**
|
|
571
|
+
|
|
572
|
+
${i.slice(0,800)}
|
|
573
|
+
|
|
574
|
+
(run \`${r.runId}\`)`),t("failed",{error:i})}}function Xp(r){let e=r.environment;if(!r.cfg.deploy.enabled)return"deployments are turned off on this runner. Deploy steps are shell commands, so they stay disabled until someone with access to this machine runs `allwright deploy enable`.";if(!e.steps.length)return`environment "${e.name}" has no deploy steps configured \u2014 add them in the dashboard first`;if(e.promotionMode==="merge_and_deploy"&&!e.branch)return`environment "${e.name}" is set to merge-and-deploy but has no branch configured`;if(e.useDedicatedCheckout&&!e.branch)return`environment "${e.name}" wants a dedicated checkout but has no branch configured`;let t=Wt(r.cfg,r.project.repoName,e.name),n=e.requiredSecrets.filter(s=>!t[s]&&!process.env[s]);return n.length?`missing deploy secret(s) on this runner: ${n.join(", ")}. Set them with: allwright env set "${r.project.repoName}" "${e.name}" ${n[0]}=...`:null}async function zu(r,e,t){let n=r.environment,s=Wt(r.cfg,r.project.repoName,n.name),i=nm(Object.values(s)),o=Date.now();if(t("running"),e("info",`Deploying ${r.issueKey} to "${n.name}"`+(r.requestedBy?` (requested by ${r.requestedBy})`:"")+` \u2014 ${n.steps.length} step(s), ${n.timeoutSeconds}s budget`),n.auditBeforeDeploy){e("info",`Pre-deploy ${n.auditBeforeDeploy} audit starting (advisory \u2014 will not block)`);try{let j=await Yr({projectId:r.project.id,repoPath:r.repoPath,role:n.auditBeforeDeploy,scope:{kind:"repo",ref:""},model:"",claudeBin:r.cfg.claudeBin,jira:r.jira});if(!j.ok)e("warn",`Pre-deploy audit could not run: ${j.error} \u2014 deploying anyway (advisory)`);else if(!j.audit.findings.length)e("info","Pre-deploy audit: no findings \u2713");else{let U={};for(let f of j.audit.findings)U[f.severity]=(U[f.severity]??0)+1;e("warn",`Pre-deploy audit: ${j.audit.findings.length} finding(s) (`+Object.entries(U).map(([f,g])=>`${g} ${f}`).join(", ")+") \u2014 full report on the Audits page. Deploying anyway (advisory).");for(let f of j.audit.findings.slice(0,5))e("warn",` [${f.severity}] ${f.title} \u2014 ${f.evidence[0]?.file??""}`)}}catch(j){e("warn",`Pre-deploy audit crashed: ${j instanceof Error?j.message:String(j)} \u2014 deploying anyway`)}}if(n.requireSyncCheck){if(!n.previousEnvBranch||!n.branch){let U=n.branch?`"${n.name}" requires a branch sync check, but no earlier stage in the pipeline has a branch to compare against. Check the pipeline order on the Environments page (was "${n.name}" moved to the top?), or turn the check off.`:`"${n.name}" requires a branch sync check but has no branch set \u2014 set it, or turn the check off`;e("error",U),await qe(r,`**Allwright refused to deploy to \`${n.name}\`.**
|
|
575
|
+
|
|
576
|
+
${U}
|
|
577
|
+
|
|
578
|
+
(run \`${r.runId}\`)`),t("failed",{error:U,errorKind:"guard"});return}let j=await em(r,e);if(j){await qe(r,j.comment),t("failed",{error:j.error,...j.guard?{errorKind:"guard"}:{}});return}}let a=r.repoPath;if(n.useDedicatedCheckout||n.promotionMode==="merge_and_deploy"?(e("info",`Preparing ${n.name} checkout at origin/${n.branch}`),a=await qi({repoPath:r.repoPath,repoName:r.project.repoName,envName:n.name,branch:n.branch,attached:n.promotionMode==="merge_and_deploy"})):e("info",`No dedicated checkout for "${n.name}" \u2014 running the steps in the mapped checkout as it is`),n.promotionMode==="merge_and_deploy"){let j=Rt(n.ticketBranchTemplate,{issueKey:r.issueKey});e("info",`Merging "${j}" into "${n.branch}"`);let U=await Bi(a,j,`Deploy ${r.issueKey} to ${n.name}
|
|
579
|
+
|
|
580
|
+
Allwright run ${r.runId}`);if(!U.ok){e("error",U.reason??"merge failed"),await qe(r,`**Allwright deploy to \`${n.name}\` failed before running anything.**
|
|
581
|
+
|
|
582
|
+
${U.reason}`),t("failed",{error:U.reason});return}U.alreadyMerged?e("info",`"${j}" is already in "${n.branch}" \u2014 nothing to merge`):(e("info",`Pushing "${n.branch}" to origin`),await Fi(a,n.branch))}let l=await En(a).catch(()=>"");l&&e("info",`Deploying commit ${l.slice(0,10)}`);let d=tm(a,n.workdir),p={...process.env,...s,ALLWRIGHT_ENVIRONMENT:n.name,ALLWRIGHT_ISSUE_KEY:r.issueKey,ALLWRIGHT_RUN_ID:r.runId,ALLWRIGHT_DEPLOY_REF:l,ALLWRIGHT_BRANCH:n.branch,TICKETPILOT_ENVIRONMENT:n.name,TICKETPILOT_ISSUE_KEY:r.issueKey,TICKETPILOT_RUN_ID:r.runId,TICKETPILOT_DEPLOY_REF:l,TICKETPILOT_BRANCH:n.branch},v=0,S=n.timeoutSeconds*1e3;for(let[j,U]of n.steps.entries()){let f=S-(Date.now()-o);if(f<=0){let b=`deploy exceeded its ${n.timeoutSeconds}s budget before step ${j+1}`;e("error",b),await qe(r,`**Allwright deploy to \`${n.name}\` timed out.**
|
|
583
|
+
|
|
584
|
+
${b}`),t("timed_out",{error:b,deployedRef:l});return}e("info",`\u25B6 step ${j+1}/${n.steps.length}: ${U.name}`);let g=await rm({command:U.run,cwd:d,env:p,timeoutMs:f,onLine:(b,I)=>{v++,v===ju&&e("warn","(output truncated \u2014 deploy log limit reached)"),!(v>=ju)&&e(b,i(I))}});if(g.timedOut){let b=`step "${U.name}" hit the ${n.timeoutSeconds}s deploy budget and was killed`;e("error",b),await qe(r,`**Allwright deploy to \`${n.name}\` timed out.**
|
|
585
|
+
|
|
586
|
+
${b}`),t("timed_out",{error:b,deployedRef:l});return}if(g.code!==0){if(U.continueOnError){e("warn",`step "${U.name}" exited ${g.code} \u2014 continuing (marked continue-on-error)`);continue}let b="";try{b=i(await Oi(a))}catch{}let I=`step ${j+1} "${U.name}" failed with exit code ${g.code}`+(g.tail?`: ${i(g.tail)}`:"")+(b?`
|
|
587
|
+
|
|
588
|
+
Checkout at failure:
|
|
589
|
+
${b}`:"");e("error",I),await qe(r,`**Allwright deploy to \`${n.name}\` failed.**
|
|
590
|
+
|
|
591
|
+
Step ${j+1} \`${U.name}\` exited ${g.code}.
|
|
592
|
+
|
|
593
|
+
`+(g.tail?`\`\`\`
|
|
594
|
+
${i(g.tail).slice(0,1200)}
|
|
595
|
+
\`\`\`
|
|
596
|
+
|
|
597
|
+
`:"")+(b?`Checkout at failure:
|
|
598
|
+
\`\`\`
|
|
599
|
+
${b.slice(0,800)}
|
|
600
|
+
\`\`\`
|
|
601
|
+
|
|
602
|
+
`:"")+`Nothing after it ran. Full log is on the Allwright dashboard. (run \`${r.runId}\`)`),t("failed",{error:I.slice(0,1600),deployedRef:l});return}e("info",`\u2713 step ${j+1}/${n.steps.length}: ${U.name}`)}t("posting");let x=Math.round((Date.now()-o)/1e3);r.issueKey!==br.BRANCH_DEPLOY_ISSUE_KEY&&await qe(r,`**Allwright deployed \`${r.issueKey}\` to \`${n.name}\`.**
|
|
603
|
+
|
|
604
|
+
`+(l?`Commit: \`${l.slice(0,10)}\`${n.branch?` on \`${n.branch}\``:""}
|
|
605
|
+
`:"")+`${n.steps.length} step(s) in ${x}s.`+(r.requestedBy?` Requested by ${r.requestedBy}.`:"")+`
|
|
606
|
+
|
|
607
|
+
(run \`${r.runId}\`)`);let w=await Qp(r,e,l);t("succeeded",{resultSummary:`Deployed to ${n.name}${l?` at ${l.slice(0,10)}`:""} in ${x}s`+(w!==null?` \xB7 ${w} ticket(s) moved to "${n.deployToColumn}"`:""),deployedRef:l}),e("info",`Deploy to "${n.name}" succeeded in ${x}s`)}async function Qp(r,e,t){let n=r.environment;if(!n.deployFromColumn||!n.deployToColumn)return null;let s=new Date().toISOString().slice(0,10),i;try{i=await r.jira.search(`project = "${r.project.jiraProjectKey}" AND status = "${n.deployFromColumn}" ORDER BY updated ASC`,50)}catch(a){return e("warn",`deploy succeeded, but listing tickets in "${n.deployFromColumn}" failed: ${a instanceof Error?a.message:a} \u2014 move them by hand`),null}if(!i.length)return e("info",`No tickets in "${n.deployFromColumn}" to move`),0;e("info",`Moving ${i.length} ticket(s) from "${n.deployFromColumn}" to "${n.deployToColumn}"`);let o=0;for(let a of i)try{if(await r.jira.addComment(a.key,`**Allwright: deployed to \`${n.name}\` on ${s}.**
|
|
608
|
+
|
|
609
|
+
`+(t?`Commit: \`${t.slice(0,10)}\`${n.branch?` on \`${n.branch}\``:""}
|
|
610
|
+
`:"")+(r.requestedBy?`Requested by ${r.requestedBy}. `:"")+`(run \`${r.runId}\`)`),!await r.jira.transitionByName(a.key,n.deployToColumn)){e("warn",`${a.key}: no workflow transition to "${n.deployToColumn}" from its current status \u2014 left in place`),await r.jira.addComment(a.key,`**Allwright could not move this ticket to \`${n.deployToColumn}\`** \u2014 no such transition from its current status. The deploy itself succeeded; move it by hand. (run \`${r.runId}\`)`).catch(()=>{});continue}o++,e("info",`\u2713 ${a.key} \u2192 "${n.deployToColumn}"`)}catch(u){e("warn",`${a.key}: sweep failed (${u instanceof Error?u.message:u}) \u2014 left in "${n.deployFromColumn}"`)}return e("info",`Moved ${o}/${i.length} ticket(s) to "${n.deployToColumn}"`),o}async function em(r,e){let t=r.environment,n=t.previousEnvBranch,s=(a,u=!1)=>({error:a,guard:u,comment:`**Allwright could not deploy \`${r.issueKey}\` to \`${t.name}\`.**
|
|
611
|
+
|
|
612
|
+
${a}
|
|
613
|
+
|
|
614
|
+
(run \`${r.runId}\`)`});e("info",`Checking "${t.branch}" is in sync with "${n}" before deploying`);try{await Gr(r.repoPath,n),await Gr(r.repoPath,t.branch)}catch(a){return s(`sync check could not fetch branches: ${a instanceof Error?a.message:String(a)}`)}let i;try{i=await Zi(r.repoPath,`origin/${n}`,`origin/${t.branch}`)}catch(a){return s(`sync check failed: ${a instanceof Error?a.message:String(a)}`)}if(!i)return e("info",`"${t.branch}" already matches "${n}" \u2014 continuing`),null;e("warn",`"${t.branch}" and "${n}" have diverged \u2014 opening a PR instead of deploying`);let o=At(he()??r.cfg,r.project.repoName);if(!o)return s(`"${t.branch}" and "${n}" have diverged, and no GitHub token applies to this repo to open a PR. Run \`allwright github set-token\`, or merge them manually, then retry the deploy.`,!0);try{let a=await fr(r.repoPath),u=pr(a);if(!u)throw new Error(`could not parse a GitHub owner/repo from origin "${a}"`);let d=await new Oe(o).createPullRequest(u.owner,u.repo,{title:`Sync ${t.name} (${t.branch}) with ${n}`,head:n,base:t.branch,body:`Allwright opened this automatically while trying to deploy \`${r.issueKey}\` to \`${t.name}\`: \`${t.branch}\` doesn't have everything that's on \`${n}\` yet, so deploying now would ship different code than what was validated there. Merge this PR, then retry the deploy.
|
|
615
|
+
|
|
616
|
+
(run \`${r.runId}\`)`});return s(`"${t.branch}" is not in sync with "${n}" \u2014 opened ${d.url} to catch it up. Merge that, then retry the deploy.`,!0)}catch(a){return s(`could not open a sync PR: ${a instanceof Error?a.message:String(a)}`)}}function tm(r,e){if(!e.trim())return r;let t=vr.default.resolve(r,e),n=vr.default.relative(r,t);if(n.startsWith("..")||vr.default.isAbsolute(n))throw new Error(`working directory "${e}" is outside the repository checkout`);return t}function rm(r){return new Promise(e=>{let t=(0,Ns.spawn)("bash",["-lc",r.command],{cwd:r.cwd,env:r.env,detached:!0,stdio:["ignore","pipe","pipe"]}),n=[],s=l=>{n.push(l),n.length>20&&n.shift()},i=!1,o=!1,a=l=>{i||(i=!0,clearTimeout(u),e({code:l,timedOut:o,tail:n.join(`
|
|
617
|
+
`)}))},u=setTimeout(()=>{o=!0,Ou(t.pid,"SIGTERM"),setTimeout(()=>Ou(t.pid,"SIGKILL"),1e4).unref()},r.timeoutMs);yo.default.createInterface({input:t.stdout}).on("line",l=>{s(l),r.onLine("info",l)}),yo.default.createInterface({input:t.stderr}).on("line",l=>{s(l),r.onLine("warn",l)}),t.on("error",l=>{s(`failed to start: ${l.message}`),a(127)}),t.on("close",l=>a(l??1))})}function Ou(r,e){if(r)try{process.kill(-r,e)}catch{try{process.kill(r,e)}catch{}}}function nm(r){let e=r.filter(t=>t&&t.length>=6).sort((t,n)=>n.length-t.length);return e.length?t=>{let n=t;for(let s of e)n=n.split(s).join("***");return n}:t=>t}async function qe(r,e){if(r.issueKey!==br.BRANCH_DEPLOY_ISSUE_KEY)try{await r.jira.addComment(r.issueKey,e)}catch(t){m.error(`could not post deploy comment to ${r.issueKey}: ${t}`)}}function vo(r){return Rs(r)!==null}async function Uu(r,e){let t=Rs(e);if(!t)return;let{emit:n,setStatus:s}=_o({runId:e,transport:r.transport}),i=r.lookup(t.projectId,t.environmentName);if(!i){let a=`approved, but environment "${t.environmentName}" is no longer in this runner's config (deleted or renamed?) \u2014 nothing was deployed`;n("error",a),s("failed",{error:a}),$s(e);return}$s(e);let o={runId:e,project:i.project,environment:i.environment,issueKey:t.issueKey,issueSummary:t.issueSummary,repoPath:i.repoPath,cfg:r.cfg,jira:r.jiraFor(i.project.repoName),transport:r.transport,requestedBy:t.requestedBy};n("info",`Approved \u2014 running the ${i.environment.steps.length} deploy step(s) now`);try{await zu(o,n,s)}catch(a){let u=a instanceof Error?a.message:String(a);n("error",`Deploy failed: ${u}`),await qe(o,`**Allwright deploy failed.**
|
|
618
|
+
|
|
619
|
+
${u.slice(0,800)}`),s("failed",{error:u})}}async function qu(r,e){let t=Rs(e);if(!t)return;let{emit:n,setStatus:s}=_o({runId:e,transport:r.transport});$s(e),n("info",`Deploy to "${t.environmentName}" was rejected \u2014 nothing ran`);let i=r.lookup(t.projectId,t.environmentName);try{await r.jiraFor(i?.project.repoName??"").addComment(t.issueKey,`**Allwright: deploy to \`${t.environmentName}\` was rejected.**
|
|
620
|
+
|
|
621
|
+
No deploy step was executed. (run \`${e}\`)`)}catch(o){m.error(`could not post rejection comment to ${t.issueKey}: ${o}`)}s("failed",{error:"deploy rejected by a reviewer"})}var sm=k.object({steps:k.array(br.DeployStep).max(50).default([]),requiredSecrets:k.array(k.string()).max(50).default([]),notes:k.string().default("")}),im=[".ticketpilot/deploy.md","DEPLOY.md","DEPLOYMENT.md","docs/DEPLOY.md","docs/deploy.md","docs/deployment.md"],Nu=24e3;function bo(r){for(let e of im){let t=vr.default.join(r,e);try{if(!Ln.default.existsSync(t))continue;let n=Ln.default.readFileSync(t,"utf8");if(!n.trim())continue;return{path:e,content:n.length>Nu?n.slice(0,Nu)+`
|
|
622
|
+
|
|
623
|
+
[\u2026document truncated\u2026]`:n}}catch{continue}}return null}var Mu=["docker","docker-compose","pm2","systemctl","node","pnpm","npm","yarn","make","python3","pip","rsync","ssh","caddy","nginx"];function Bu(r){return Fu("bash",["-lc",`command -v ${JSON.stringify(r)}`]).trim().length>0}function Fu(r,e){try{let t=(0,Ns.spawnSync)(r,e,{encoding:"utf8",timeout:5e3});return t.status===0?t.stdout??"":""}catch{return""}}function om(r,e,t){let n=Mu.filter(o=>Bu(o)),s=Mu.filter(o=>!n.includes(o)),i=Object.keys(Wt(r,e,t));return`About the machine these steps will run on (gathered by the runner, trust it):
|
|
624
|
+
- available tools: ${n.join(", ")||"(none of the common ones)"}
|
|
625
|
+
- NOT installed: ${s.join(", ")||"(none missing)"}
|
|
626
|
+
- secrets already stored for this environment (names only): ${i.join(", ")||"(none yet)"}`}async function Zu(r){let e=[];if(e.push(Ln.default.existsSync(r.repoPath)?{name:"repo-path",ok:!0,detail:r.repoPath}:{name:"repo-path",ok:!1,detail:`checkout missing: ${r.repoPath}`}),e.push({name:"deploys-enabled",ok:r.cfg.deploy.enabled,detail:r.cfg.deploy.enabled?"enabled on this runner":"disabled \u2014 run: allwright deploy enable (then restart the runner)"}),r.workdir){let a=vr.default.isAbsolute(r.workdir)?r.workdir:vr.default.join(r.repoPath,r.workdir);e.push(Ln.default.existsSync(a)?{name:"workdir",ok:!0,detail:a}:{name:"workdir",ok:!1,detail:`does not exist: ${a}`})}if(r.branch){let a=Fu("git",["-C",r.repoPath,"ls-remote","--heads","origin",r.branch]);e.push(a.trim()?{name:"branch",ok:!0,detail:`origin/${r.branch} exists`}:{name:"branch",ok:!1,detail:`origin has no branch "${r.branch}" (or the remote is unreachable)`})}let t=Wt(r.cfg,r.repoName,r.environmentName),n=new Set(r.requiredSecrets);for(let a of r.steps)for(let u of a.run.matchAll(/\$\{?([A-Z][A-Z0-9_]{2,})\}?/g))n.add(u[1]);let s=[...n].filter(a=>!t[a]&&!process.env[a]);e.push({name:"secrets",ok:s.length===0,detail:s.length?`missing: ${s.join(", ")} \u2014 set with: allwright env set "${r.repoName}" "${r.environmentName}" ${s[0]}=...`:`${n.size} present`});let i=new Set;for(let a of r.steps)for(let u of a.run.split(/&&|\|\||;|\|/)){let l=u.trim().split(/\s+/),d=l.shift();for(;d&&(/^[A-Za-z_][A-Za-z0-9_]*=/.test(d)||d==="sudo"||d==="env"||d==="nohup");)d=l.shift();!d||d.startsWith("$")||d.startsWith("#")||d.startsWith("(")||i.add(d)}let o=[...i].filter(a=>!Bu(a));return e.push({name:"binaries",ok:o.length===0,detail:o.length?`not found on this machine: ${o.join(", ")}`:`${i.size} found: ${[...i].slice(0,12).join(", ")}`}),{ok:e.every(a=>a.ok),checks:e}}async function Ku(r){let e=bo(r.repoPath);if(!e)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:'this repo has no deploy document. Create DEPLOY.md at the repo root (or .ticketpilot/deploy.md) describing how this project actually deploys \u2014 the same commands you run by hand. "Ask Claude for steps" translates that document; it does not guess.'};let t=om(r.cfg,r.repoName,r.environmentName),n=Rt(br.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE,{envName:r.environmentName,docPath:e.path,docContent:e.content,notes:r.notes.trim()||"(nothing specified)",machineContext:t}),s=await Ue.run({repoPath:r.repoPath,prompt:n,timeoutSeconds:r.timeoutSeconds,bin:r.cfg.claudeBin,mode:"read_only",maxTurns:30,sessionId:(0,Lu.randomUUID)(),onLog:()=>{}});if(!s.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:s.error??"Claude Code produced no output"};let i=am(s.resultText);return i?{ok:!0,...i}:(m.warn(`deploy step suggestion could not be parsed. Claude's raw answer follows:
|
|
627
|
+
`+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 am(r){for(let e of cm(r)){let t;try{t=JSON.parse(e)}catch{continue}let n=sm.safeParse(um(t));if(n.success&&n.data.steps.length||n.success&&n.data.notes.trim())return n.data}return null}function cm(r){let e=[];for(let s of r.matchAll(/```[a-zA-Z0-9_-]*[ \t]*\r?\n([\s\S]*?)```/g))s[1].trim()&&e.push(s[1]);let t=r.indexOf("{"),n=r.lastIndexOf("}");return t>=0&&n>t&&e.push(r.slice(t,n+1)),e}function um(r){if(!r||typeof r!="object")return r;let e=r,n=(Array.isArray(r)?r:Array.isArray(e.steps)?e.steps:Array.isArray(e.deploy_steps)?e.deploy_steps:Array.isArray(e.deploySteps)?e.deploySteps:[]).map((o,a)=>{if(typeof o=="string")return o.trim()?{name:Du(o,a),run:o.trim()}:null;if(!o||typeof o!="object")return null;let u=o,l=go(u.run,u.command,u.cmd,u.script,u.shell);return l?{name:(go(u.name,u.title,u.description)??Du(l,a)).slice(0,120),run:l,continueOnError:u.continueOnError===!0||u.continue_on_error===!0}:null}).filter(Boolean),s=e.requiredSecrets??e.required_secrets??e.secrets,i=Array.isArray(s)?s.filter(o=>typeof o=="string"):s&&typeof s=="object"?Object.keys(s):[];return{steps:n.slice(0,50),requiredSecrets:i.slice(0,50),notes:go(e.notes,e.note,e.explanation)??""}}function go(...r){for(let e of r)if(typeof e=="string"&&e.trim())return e.trim()}function Du(r,e){return(r.split(`
|
|
628
|
+
`)[0].trim()||`Step ${e+1}`).slice(0,120)}mr();ut();function wo(r,e){if(!r.componentRoutes.length)return{project:r};let t=e.filter(Boolean);if(!t.length)return{error:`no Jira component set \u2014 project "${r.name}" routes by component (${r.componentRoutes.map(i=>i.component).join(", ")}); set one on the ticket`};let n=r.componentRoutes.filter(i=>t.includes(i.component));if(!n.length)return{error:`component(s) [${t.join(", ")}] not mapped \u2014 known: `+r.componentRoutes.map(i=>`${i.component}\u2192${i.repoName}`).join(", ")};let s=new Set(n.map(i=>i.repoName));return s.size>1?{error:`components map to DIFFERENT repos (${[...s].join(", ")}) \u2014 ambiguous, refusing`}:{project:{...r,repoName:n[0].repoName}}}var Vu=24*3600*1e3,Ds=14,lm=Ds*24*3600*1e3,dm=new Set(["to","on","this","the","a","an","env","environment","please","now","it"]),Ls=class{constructor(e,t,n){this.cfg=e;this.jiraFor=t;this.transport=n}cfg;jiraFor;transport;projects=[];rules=[];environments=[];inFlight=new Set;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),m.warn(`Component routing refused \u2014 ${t}`))}resolveClaudeProfile(e,t){if(!t)return;let n=this.cfg.claudeProfiles[t]?.configDir;return!n&&e&&(this.transport.send({type:"run.log",runId:e,seq:99e3,ts:new Date().toISOString(),level:"warn",message:`Claude profile "${t}" is not set up on this runner (allwright claude login "${t}") \u2014 using the runner's own login instead.`}),m.warn(`run ${e}: claude profile "${t}" missing locally \u2014 using default login`)),n}setConfig(e,t,n=!1,s=[]){this.projects=e,this.rules=t,this.environments=s;let i=t.filter(o=>o.enabled).length;m.info(`config synced: ${e.length} project(s), ${t.length} rule(s) (${i} enabled), ${s.length} environment(s)`),n!==this.paused&&(m.info(n?"polling paused from the dashboard":"polling resumed from the dashboard"),this.paused=n)}start(){let e=this.cfg.pollIntervalSeconds*1e3;this.timer=setInterval(()=>{this.tick()},e),this.tick(),m.info(`polling Jira every ${this.cfg.pollIntervalSeconds}s`)}stop(){this.timer&&clearInterval(this.timer)}lastScheduleCheck=0;auditInFlight=!1;async runScheduledAudits(){if(!(!this.cfg.auditSchedules.length||this.auditInFlight)&&!(Date.now()-this.lastScheduleCheck<15*6e4)){this.lastScheduleCheck=Date.now();for(let e of this.cfg.auditSchedules){let t=this.projects.find(s=>s.repoName===e.repoName);if(!t)continue;let n=Fc(t.id,e.role);if(!(n&&Date.now()-new Date(n).getTime()<e.intervalHours*36e5)){this.auditInFlight=!0;try{m.info(`Scheduled ${e.role} audit of ${e.repoName} starting (every ${e.intervalHours}h)`);let s=await Yr({projectId:t.id,repoPath:this.cfg.repos[e.repoName]?.path??"",role:e.role,scope:{kind:"repo",ref:""},model:"",claudeBin:this.cfg.claudeBin,jira:this.jiraFor(e.repoName)});if(s.ok){let i=s.audit.findings.length;m.info(`Scheduled audit done: ${i} finding(s) \u2014 drift visible on the Audits page`)}else m.warn(`Scheduled audit failed: ${s.error}`)}catch(s){m.warn(`Scheduled audit crashed: ${s instanceof Error?s.message:String(s)}`)}finally{this.auditInFlight=!1}break}}}}async tick(){if(!(this.ticking||this.paused||!this.transport.connected)){this.ticking=!0;try{await this.runScheduledAudits(),await this.sweepMergedPRs(),await this.sweepGitHubApprovals();let e=new Set;for(let t of this.rules){if(!t.enabled)continue;let n=this.projects.find(i=>i.id===t.projectId);if(!n)continue;let s=this.cfg.repos[n.repoName];if(!s){m.warn(`rule "${t.name}": no local path for repo "${n.repoName}" \u2014 run: allwright repo add "${n.repoName}" /path/to/checkout`);continue}t.action.type==="deploy"?await this.pollDeployRule(t,n,s.path):t.action.type==="respond"?await this.pollRespondRule(t,n,s.path):(e.has(n.id)||(e.add(n.id),await this.sweepNeedsInput(n)),t.trigger.type==="comment_keyword"&&await this.sweepRevisions(t,n),await this.pollRule(t,n,s.path))}}catch(e){m.warn(`poll tick failed: ${e instanceof Error?e.message:e}`)}finally{this.ticking=!1}}}async sweepGitHubApprovals(){let e=Object.values(jn());if(!e.length)return;let t=he()??this.cfg,n=new Map,s=i=>{let o=At(t,i);if(!o)return null;let a=n.get(o);return a||n.set(o,a=new Oe(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,l;try{[u,l]=await Promise.all([o.getReviews(i.owner,i.repo,i.prNumber),o.getPullRequest(i.owner,i.repo,i.prNumber)])}catch(S){m.warn(`review check failed for ${i.owner}/${i.repo}#${i.prNumber}: ${S instanceof Error?S.message:S}`);continue}if(!l)continue;let d={cfg:this.cfg,jiraFor:this.jiraFor,transport:this.transport};if(l.merged){m.info(`PR #${i.prNumber} for ${i.issueKey} was merged on GitHub \u2014 completing the run`),this.inFlight.add(a);try{await Mn(d,i.runId,l.headSha)}finally{this.inFlight.delete(a)}continue}if(l.state==="closed"){m.info(`PR #${i.prNumber} for ${i.issueKey} was closed unmerged on GitHub \u2014 failing the run`);let S=this.jiraFor(i.repoName),x=`PR #${i.prNumber} was closed on GitHub without merging`;await S.addComment(i.issueKey,`**Allwright: the pull request for this ticket was closed on GitHub without merging.**
|
|
629
|
+
|
|
630
|
+
PR: ${i.prUrl}
|
|
631
|
+
|
|
632
|
+
The run is marked failed. Remove the \`${i.failedLabel}\` label (or hit Retry on the Allwright board) to implement again. (run \`${i.runId}\`)`).catch(()=>{}),await S.editLabels(i.issueKey,{add:[i.failedLabel]}).catch(()=>{}),this.transport.send({type:"run.status",runId:i.runId,status:"failed",error:x}),yr(i.runId);continue}l.mergeableState==="dirty"?i.conflictNotified||(await this.jiraFor(i.repoName).addComment(i.issueKey,`**Allwright: the pull request for this ticket has merge conflicts.** The base branch moved after this change was built, so GitHub cannot merge it as-is.
|
|
633
|
+
|
|
634
|
+
PR: ${i.prUrl}
|
|
635
|
+
|
|
636
|
+
To fix: Reject this run on the Allwright dashboard (that closes the conflicted PR), then post the implement trigger comment again \u2014 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,tn(i),m.info(`merge conflicts on PR #${i.prNumber} for ${i.issueKey} \u2014 ticket notified`)):i.conflictNotified&&l.mergeableState!==null&&l.mergeableState!=="unknown"&&(i.conflictNotified=!1,tn(i));let p=u.filter(S=>S.state==="APPROVED"||S.state==="CHANGES_REQUESTED").sort((S,x)=>S.submittedAt.localeCompare(x.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}).
|
|
637
|
+
|
|
638
|
+
PR: ${i.prUrl}
|
|
639
|
+
|
|
640
|
+
Reply to the review on GitHub, or reject the run on the Allwright dashboard and re-trigger with new instructions. (run \`${i.runId}\`)`).catch(()=>{}),tn({...i,changesRequestedNotified:!0}),m.info(`changes requested on PR #${i.prNumber} for ${i.issueKey} \u2014 ticket notified`));continue}if(v.commitId===l.headSha){m.info(`PR #${i.prNumber} for ${i.issueKey} approved on GitHub by ${v.user} \u2014 completing the run`),this.inFlight.add(a);try{await Mn(d,i.runId,v.commitId)}catch(S){m.warn(`github-approval completion failed for ${i.runId}: ${S instanceof Error?S.message:S}`)}finally{this.inFlight.delete(a)}}}}}async sweepMergedPRs(){let e=Object.values(As());if(!e.length)return;let t=he()??this.cfg,n=new Map,s=a=>{let u=At(t,a);if(!u)return null;let l=n.get(u);return l||n.set(u,l=new Oe(u)),l},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){m.warn(`merge watch for ${a.issueKey} PR #${a.prNumber} is over 30 days old \u2014 dropping`),Pn(a.runId);continue}let l;try{l=await u.getPullRequest(a.owner,a.repo,a.prNumber)}catch(v){m.warn(`merge check failed for ${a.owner}/${a.repo}#${a.prNumber}: ${v instanceof Error?v.message:v}`);continue}if(!l){Pn(a.runId);continue}if(l.state==="open")continue;if(!l.merged){Pn(a.runId);continue}let d=this.jiraFor(a.repoName),p="";if(a.jiraTransitionOnMerge)try{p=await d.transitionByName(a.issueKey,a.jiraTransitionOnMerge)?`
|
|
641
|
+
|
|
642
|
+
Ticket moved to **${a.jiraTransitionOnMerge}**.`:`
|
|
643
|
+
|
|
644
|
+
Note: no transition named "${a.jiraTransitionOnMerge}" is available from this ticket's current status \u2014 move it manually.`}catch(v){p=`
|
|
645
|
+
|
|
646
|
+
Note: the "${a.jiraTransitionOnMerge}" transition failed: ${v instanceof Error?v.message:v}`}try{await d.addComment(a.issueKey,`**Allwright: the pull request for this ticket was merged.**
|
|
647
|
+
|
|
648
|
+
PR: ${a.prUrl} (merged at \`${l.headSha.slice(0,10)}\`)${p}
|
|
649
|
+
|
|
650
|
+
(run \`${a.runId}\`)`)}catch(v){m.warn(`could not post merge comment to ${a.issueKey}: ${v instanceof Error?v.message:v}`);continue}m.info(`PR #${a.prNumber} for ${a.issueKey} merged \u2014 ticket updated`),Pn(a.runId)}}async sweepNeedsInput(e){let t;try{t=await this.jiraOf(e).search(`project = "${e.jiraProjectKey}" AND labels = "${wr.NEEDS_INPUT_LABEL}"`,10)}catch(s){m.warn(`needs-input sweep failed for ${e.jiraProjectKey}: ${s instanceof Error?s.message:s}`);return}if(!t.length)return;let n=rn();for(let s of t){let i=Object.values(n).filter(a=>a.issueKey===s.key);if(!i.length){await this.jiraOf(e).editLabels(s.key,{remove:[wr.NEEDS_INPUT_LABEL]}).catch(()=>{}),m.warn(`${s.key}: needs-input label with no local pending record \u2014 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()>lm){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(x){m.warn(`needs-input check failed for ${s.key}: ${x instanceof Error?x.message:x}`);continue}let l=new Date(a.questionsPostedAt).getTime(),d=o.comments.filter(x=>!Ge(x.body)&&new Date(x.created).getTime()>l);if(!d.length)continue;let p=Dn(d),v=o.attachments;this.inFlight.add(u),m.info(`reply received on ${s.key} \u2014 resuming run ${a.runId}`),await this.jiraOf(e).editLabels(s.key,{remove:[wr.NEEDS_INPUT_LABEL]}).catch(x=>{m.warn(`could not remove needs-input label on ${s.key}: ${x}`)});let S={jiraFor:this.jiraFor,transport:this.transport,cfg:this.cfg};a.kind==="implement"?this.enqueueForRepo(a.baseRepoPath??a.repoPath,async()=>{try{await Su(a,p,v,S)}finally{this.inFlight.delete(u)}}):this.enqueueForRepo(a.repoPath,async()=>{try{await vu(a,p,v,S)}finally{this.inFlight.delete(u)}})}}}async abandonStaleInput(e,t){m.warn(`${e.issueKey}: needs-input unanswered for over ${Ds}d \u2014 abandoning run ${e.runId}`);try{await this.jiraOf(t).addComment(e.issueKey,`**Allwright gave up waiting for an answer.**
|
|
651
|
+
|
|
652
|
+
No reply arrived within ${Ds} 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:[wr.NEEDS_INPUT_LABEL]})}catch(n){m.warn(`could not post staleness notice for ${e.issueKey}: ${n}`)}e.kind==="implement"&&await Wr(e.baseRepoPath??e.repoPath,e.repoPath).catch(()=>{}),Je(e.runId),this.transport.send({type:"run.status",runId:e.runId,status:"failed",error:`no reply within ${Ds} days`})}async pollRule(e,t,n){let s=e.trigger.type==="label_added"?await this.matchLabelTrigger(e,t):await this.matchCommentTrigger(e,t);for(let i of s){let o=`${e.id}:${i.issueKey}`;if(this.inFlight.has(o))continue;let a=wo(t,i.components??[]);if("error"in a){this.warnRoutingOnce(`${e.id}:${i.issueKey}`,`${i.issueKey}: ${a.error}`);continue}let u=a.project,l=u.repoName===t.repoName?n:this.cfg.repos[u.repoName]?.path;if(!l){this.warnRoutingOnce(`${e.id}:${i.issueKey}:path`,`${i.issueKey}: routed to repo "${u.repoName}" but it has no local checkout \u2014 run: allwright repo add "${u.repoName}" /path/to/checkout`);continue}let d=await this.transport.claimRun({ruleId:e.id,issueKey:i.issueKey,issueSummary:i.summary,triggerFingerprint:i.fingerprint,triggeredByAccountId:i.triggeredByAccountId});if(!d.accepted||!d.runId){d.reason!=="duplicate"&&m.warn(`claim rejected for ${i.issueKey}: ${d.reason??"unknown"}`);continue}this.inFlight.add(o),m.info(`claimed run ${d.runId} for ${i.issueKey}`+(u.repoName!==t.repoName?` (routed \u2192 ${u.repoName})`:"")+(d.claudeProfile?` (claude profile "${d.claudeProfile}")`:""));let p=this.resolveClaudeProfile(d.runId,d.claudeProfile);this.enqueueForRepo(l,async()=>{try{await mo({runId:d.runId,rule:e,project:u,issueKey:i.issueKey,repoPath:l,cfg:this.cfg,jira:this.jiraOf(u),transport:this.transport,claudeConfigDir:p,actorEmail:d.actorEmail})}finally{this.inFlight.delete(o)}})}}async pollRespondRule(e,t,n){let s=e.trigger;if(s.type!=="comment_keyword"||e.action.type!=="respond")return;let i=await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=s.keyword.toLowerCase(),a=Date.now()-Vu;for(let u of i){let l=await this.jiraOf(t).getIssue(u.key);for(let d of l.comments){if(!d.body.toLowerCase().includes(o)||Ge(d.body)||new Date(d.created).getTime()<a||!d.id)continue;let p=`respond:${d.id}`;if(this.inFlight.has(p))continue;let v=wo(t,u.components??[]);if("error"in v){this.warnRoutingOnce(`${e.id}:${u.key}`,`${u.key}: ${v.error}`);continue}let S=v.project,x=S.repoName===t.repoName?n:this.cfg.repos[S.repoName]?.path;if(!x){this.warnRoutingOnce(`${e.id}:${u.key}:path`,`${u.key}: routed to repo "${S.repoName}" but it has no local checkout \u2014 run: allwright repo add "${S.repoName}" /path/to/checkout`);continue}let w=await this.transport.claimRun({ruleId:e.id,issueKey:u.key,issueSummary:u.summary,triggerFingerprint:`question by ${d.author} at ${d.created}`,dedupKey:`respond:comment:${d.id}`,triggeredByAccountId:d.authorAccountId??void 0});if(!w.accepted||!w.runId){w.reason!=="duplicate"&&m.warn(`respond claim rejected for ${u.key}: ${w.reason??"unknown"}`);continue}this.inFlight.add(p),m.info(`claimed respond run ${w.runId}: ${u.key} (comment ${d.id})`+(S.repoName!==t.repoName?` (routed \u2192 ${S.repoName})`:"")+(w.claudeProfile?` (claude profile "${w.claudeProfile}")`:""));let j={author:d.author,body:d.body},U=this.resolveClaudeProfile(w.runId,w.claudeProfile);this.enqueueForRepo(x,async()=>{try{await mo({runId:w.runId,rule:e,project:S,issueKey:u.key,repoPath:x,cfg:this.cfg,jira:this.jiraOf(S),transport:this.transport,question:j,claudeConfigDir:U,actorEmail:w.actorEmail})}finally{this.inFlight.delete(p)}})}}}async sweepRevisions(e,t){let n=e.trigger;if(n.type!=="comment_keyword")return;let s;try{s=await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND labels = "${n.doneLabel}" AND updated >= "-2d"`,10)}catch(o){m.warn(`revision sweep failed for ${t.jiraProjectKey}: ${o instanceof Error?o.message:o}`);return}let i=n.keyword.toLowerCase();for(let o of s)try{let a=await this.jiraOf(t).getIssue(o.key),u=null;for(let d of a.comments)Ge(d.body)&&(u=Math.max(u??0,new Date(d.created).getTime()));if(u===null||!a.comments.some(d=>!Ge(d.body)&&d.body.toLowerCase().includes(i)&&new Date(d.created).getTime()>u))continue;await this.jiraOf(t).editLabels(o.key,{remove:[n.doneLabel]}),m.info(`revision requested on ${o.key} (new "${n.keyword}" after completion) \u2014 done label removed, rule will re-fire`)}catch(a){m.warn(`revision check failed for ${o.key}: ${a instanceof Error?a.message:a}`)}}async pollDeployRule(e,t,n){if(e.action.type!=="deploy")return;let s=e.trigger.type==="status_changed"?await this.matchStatusDeploys(e,t):await this.matchCommentDeploys(e,t);for(let i of s){let o=`deploy:${i.dedupKey}`;if(this.inFlight.has(o))continue;let a=await this.transport.claimDeploy({projectId:t.id,ruleId:e.id,issueKey:i.issueKey,issueSummary:i.summary,environmentName:i.environmentName,requestedByAccountId:i.requestedByAccountId,requestedByDisplayName:i.requestedByDisplayName,dedupKey:i.dedupKey,triggerFingerprint:i.fingerprint});if(!a.accepted||!a.runId||!a.environment){if(a.code==="duplicate")continue;a.reason&&a.runId?(await this.jiraOf(t).addComment(i.issueKey,`**Allwright did not deploy this ticket.**
|
|
653
|
+
|
|
654
|
+
${a.reason}`+(i.requestedByAccountId?`
|
|
655
|
+
|
|
656
|
+
Jira account id: \`${i.requestedByAccountId}\``:"")+`
|
|
657
|
+
|
|
658
|
+
(run \`${a.runId}\`)`).catch(l=>m.warn(`could not post refusal to ${i.issueKey}: ${l}`)),m.warn(`deploy refused for ${i.issueKey}: ${a.reason}`)):a.reason&&m.warn(`deploy claim rejected for ${i.issueKey}: ${a.reason}`);continue}let u=a.environment;this.inFlight.add(o),m.info(`claimed deploy ${a.runId}: ${i.issueKey} \u2192 ${u.name}`),this.enqueue(this.envQueues,u.id,async()=>{try{await Ms({runId:a.runId,project:t,environment:u,issueKey:i.issueKey,issueSummary:i.summary,repoPath:n,cfg:this.cfg,jira:this.jiraOf(t),transport:this.transport,requestedBy:i.requestedByDisplayName})}finally{this.inFlight.delete(o)}})}}async matchCommentDeploys(e,t){let n=e.trigger,s=e.action;if(n.type!=="comment_keyword"||s.type!=="deploy")return[];let i=await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=n.keyword.toLowerCase(),a=Date.now()-Vu,u=this.environments.filter(p=>p.projectId===t.id).map(p=>p.name),l=this.fixedEnvironmentName(s.environmentId),d=[];for(let p of i){let v=await this.jiraOf(t).getIssue(p.key);if(!(s.requireStatus&&v.status.toLowerCase()!==s.requireStatus.toLowerCase()))for(let S of v.comments){if(!S.body.toLowerCase().includes(o)||Ge(S.body)||new Date(S.created).getTime()<a||!S.id)continue;let x=s.envSelection==="fixed"?l:hm(S.body,n.keyword,u);d.push({issueKey:p.key,summary:p.summary,environmentName:x,requestedByAccountId:S.authorAccountId??void 0,requestedByDisplayName:S.author,dedupKey:`deploy:comment:${S.id}`,fingerprint:`comment "${n.keyword}" by ${S.author} at ${S.created}`+(x?` \u2192 ${x}`:"")})}}return d}async matchStatusDeploys(e,t){let n=e.trigger,s=e.action;if(n.type!=="status_changed"||s.type!=="deploy")return[];let i=await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND status = "${n.status}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=this.fixedEnvironmentName(s.environmentId),a=[];for(let u of i){let l=await this.jiraOf(t).lastEnteredStatus(u.key,n.status);l&&a.push({issueKey:u.key,summary:u.summary,environmentName:o,requestedByAccountId:l.authorAccountId??void 0,requestedByDisplayName:l.author,dedupKey:`deploy:status:${e.id}:${u.key}:${l.at}`,fingerprint:`moved to "${n.status}" by ${l.author} at ${l.at}`})}return a}fixedEnvironmentName(e){return e?this.environments.find(t=>t.id===e)?.name??"":""}async matchLabelTrigger(e,t){let n=e.trigger;if(n.type!=="label_added")return[];let s=`project = "${t.jiraProjectKey}" AND labels = "${n.label}" AND labels not in ("${n.doneLabel}", "${n.failedLabel}", "${wr.NEEDS_INPUT_LABEL}") ORDER BY updated ASC`;return(await this.jiraOf(t).search(s,10)).map(o=>({issueKey:o.key,summary:o.summary,components:o.components,fingerprint:`label "${n.label}" matched at ${new Date().toISOString()}`}))}async matchCommentTrigger(e,t){let n=e.trigger;if(n.type!=="comment_keyword")return[];let s=`project = "${t.jiraProjectKey}" AND updated >= "-2d" AND (labels IS EMPTY OR labels not in ("${n.doneLabel}", "${n.failedLabel}", "${wr.NEEDS_INPUT_LABEL}")) ORDER BY updated DESC`,i=await this.jiraOf(t).search(s,10),o=n.keyword.toLowerCase(),a=[];for(let u of i){let d=(await this.jiraOf(t).getIssue(u.key)).comments.find(p=>p.body.toLowerCase().includes(o)&&!Ge(p.body));d&&a.push({issueKey:u.key,components:u.components,summary:u.summary,fingerprint:`comment keyword "${n.keyword}" by ${d.author} at ${d.created}`,triggeredByAccountId:d.authorAccountId??void 0})}return a}async diagnoseRule(e,t){let n=e.trigger;if(e.action.type==="deploy"){let u=n.type==="status_changed"?await this.matchStatusDeploys(e,t):await this.matchCommentDeploys(e,t),l=u.filter(d=>d.environmentName);return{matchedCount:l.length,excludedCount:u.length-l.length,excludedSample:u.filter(d=>!d.environmentName).slice(0,5).map(d=>d.issueKey)}}if(n.type==="status_changed")return{matchedCount:(await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND status = "${n.status}"`,50)).length,excludedCount:0,excludedSample:[]};if(n.type==="label_added"){let[u,l]=await Promise.all([this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND labels = "${n.label}" AND labels not in ("${n.doneLabel}", "${n.failedLabel}")`,50),this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND labels = "${n.label}" AND labels in ("${n.doneLabel}", "${n.failedLabel}")`,50)]);return{matchedCount:u.length,excludedCount:l.length,excludedSample:l.slice(0,5).map(d=>d.key)}}let s=n.keyword.toLowerCase(),[i,o]=await Promise.all([this.matchCommentTrigger(e,t),this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND updated >= "-2d" AND labels in ("${n.doneLabel}", "${n.failedLabel}")`,50)]),a=[];for(let u of o)(await this.jiraOf(t).getIssue(u.key)).comments.some(d=>d.body.toLowerCase().includes(s))&&a.push(u.key);return{matchedCount:i.length,excludedCount:a.length,excludedSample:a.slice(0,5)}}enqueueForRepo(e,t){this.enqueue(this.repoQueues,e,t)}runOnRepoQueue(e,t){this.enqueue(this.repoQueues,e,t)}runOnEnvironmentQueue(e,t){this.enqueue(this.envQueues,e,t)}enqueue(e,t,n){let i=(e.get(t)??Promise.resolve()).then(n).catch(o=>{m.error(`run crashed: ${o instanceof Error?o.stack:o}`)});e.set(t,i)}};function hm(r,e,t){let n=r.toLowerCase().indexOf(e.toLowerCase());if(n<0)return"";let i=r.slice(n+e.length).split(/[^\w.-]+/).filter(Boolean);for(let o of i){let a=t.find(u=>u.toLowerCase()===o.toLowerCase());if(a)return a}for(let o of i)if(!dm.has(o.toLowerCase()))return o;return""}var kr=$(require("node:fs"),1),Gu=$(require("node:path"),1);var fm=k.object({role:k.enum(["user","agent"]),text:k.string()}),pm=k.object({sessionId:k.string(),projectId:k.string(),title:k.string().default(""),updatedAt:k.string(),messages:k.array(fm).default([])}),mm=k.record(pm),gm=10,ym=200,Hu=2e4;function Wu(){return Gu.default.join(ee(),"chat-sessions.json")}function ko(){let r=Wu();if(!kr.default.existsSync(r))return{};try{return mm.parse(JSON.parse(kr.default.readFileSync(r,"utf8")))}catch{return{}}}function _m(r){kr.default.mkdirSync(ee(),{recursive:!0,mode:448});let e=Wu(),t=e+".tmp";kr.default.writeFileSync(t,JSON.stringify(r,null,2)+`
|
|
659
|
+
`,{mode:384}),kr.default.renameSync(t,e),kr.default.chmodSync(e,384)}function Ju(r,e,t,n){let s=ko(),o=s[e]??{sessionId:e,projectId:r,title:t.slice(0,80),updatedAt:new Date().toISOString(),messages:[]};o.messages.push({role:"user",text:t.slice(0,Hu)},{role:"agent",text:n.slice(0,Hu)}),o.messages=o.messages.slice(-ym),o.updatedAt=new Date().toISOString(),s[e]=o;let a=Object.values(s).filter(u=>u.projectId===o.projectId).sort((u,l)=>l.updatedAt.localeCompare(u.updatedAt));for(let u of a.slice(gm))delete s[u.sessionId];_m(s)}function Yu(r){return Object.values(ko()).filter(e=>e.projectId===r).sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt)).map(e=>({sessionId:e.sessionId,title:e.title,updatedAt:e.updatedAt,messageCount:e.messages.length}))}function So(r){return ko()[r]??null}var zg=$(Vl(),1),Ug=$(Hs(),1),qg=$(an(),1),Bg=$(Oo(),1),Fg=$(Do(),1),Zg=$(Fo(),1),td=$(Ys(),1),Kg=$(ed(),1);var Ko=td.default;var Ho=$(require("node:crypto"),1),Xe=$(Se(),1);function Vg(r){let e=r&&typeof r=="object"&&"name"in r?String(r.name):null;return e?`"${e}"`:"(unnamed)"}function Vo(r,e,t,n){r.push(`dropped ${e} ${t} \u2014 this runner is out of date and does not understand it yet (${n}). Update the runner (npm install -g @ticketpilot/runner) to pick it up.`)}function Hg(r){if(!r||typeof r!="object"||r.type!=="config")return null;let e=r,t=[],n=[];for(let a of Array.isArray(e.projects)?e.projects:[]){let u=Xe.ProjectConfig.safeParse(a);u.success?n.push(u.data):Vo(t,"project","",u.error.issues[0]?.message??"invalid shape")}let s=[];for(let a of Array.isArray(e.rules)?e.rules:[]){let u=Xe.RuleConfig.safeParse(a);u.success?s.push(u.data):Vo(t,"rule",Vg(a),u.error.issues[0]?.message??"invalid shape")}let i=[];for(let a of Array.isArray(e.environments)?e.environments:[]){let u=Xe.EnvironmentConfig.safeParse(a);u.success?i.push(u.data):Vo(t,"environment","",u.error.issues[0]?.message??"invalid shape")}return{msg:{type:"config",projects:n,rules:s,environments:i,pollingPaused:typeof e.pollingPaused=="boolean"?e.pollingPaused:!1},warnings:t}}var Gg=2e4,Wg=6e4,Jg=5e3,Qs=class{constructor(e,t,n,s){this.wsUrl=e;this.runnerToken=t;this.meta=n;this.events=s}wsUrl;runnerToken;meta;events;ws=null;queue=[];pending=new Map;backoffMs=1e3;heartbeat=null;closed=!1;bootAnnounced=!1;start(){this.closed=!1,this.connect()}stop(){this.closed=!0,this.heartbeat&&clearInterval(this.heartbeat),this.ws?.close()}get connected(){return this.ws?.readyState===Ko.OPEN}connect(){if(this.closed)return;m.info(`connecting to control plane at ${this.wsUrl}`);let e=new Ko(this.wsUrl,{headers:{authorization:`Bearer ${this.runnerToken}`}});this.ws=e,e.on("open",()=>{this.backoffMs=1e3,this.sendNow({type:"hello",protocolVersion:Xe.PROTOCOL_VERSION,runnerVersion:this.meta.runnerVersion,platform:`${process.platform}/${process.arch} node${process.versions.node}`,justBooted:!this.bootAnnounced});let t=this.queue.splice(0,this.queue.length);for(let n of t)this.sendNow(n);this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=setInterval(()=>{this.send({type:"heartbeat",ts:new Date().toISOString()})},Gg)}),e.on("message",t=>{let n;try{n=JSON.parse(t.toString())}catch(i){m.warn(`ignoring malformed server message (bad JSON): ${i}`);return}let s;try{s=(0,Xe.parseServerMsg)(n)}catch(i){let o=Hg(n);if(!o){m.warn(`ignoring malformed server message: ${i}`);return}for(let a of o.warnings)m.warn(a);m.warn(`config push had ${o.warnings.length} ${o.warnings.length===1?"entry":"entries"} this runner doesn't understand \u2014 applied everything else instead of dropping the whole config`),s=o.msg}this.handle(s)}),e.on("close",t=>{if(this.heartbeat&&clearInterval(this.heartbeat),t===4001)m.error("control plane rejected this runner version (protocol mismatch). Update with: npm install -g @ticketpilot/runner");else if(t===4003){m.error("this runner has been revoked from the control plane UI. Re-enroll with a fresh token if this was not intended."),this.closed=!0;return}if(this.closed)return;let n=Math.random()*.3+.85,s=Math.round(this.backoffMs*n);m.warn(`disconnected (code ${t}); reconnecting in ${Math.round(s/1e3)}s`),setTimeout(()=>this.connect(),s),this.backoffMs=Math.min(this.backoffMs*2,Wg)}),e.on("error",t=>{m.warn(`websocket error: ${t.message}`)})}handle(e){if(e.type==="hello.ack"){this.bootAnnounced=!0,m.info(`connected as runner "${e.runnerName}" (${e.runnerId})`);return}if(e.type==="run.claim.result"||e.type==="deploy.claim.result"){let t=this.pending.get(e.requestId);t&&(clearTimeout(t.timer),this.pending.delete(e.requestId),t.resolve(e));return}if(e.type==="config")return this.events.onConfig(e);if(e.type==="project.test")return this.events.onProjectTest(e);if(e.type==="rule.diagnose")return this.events.onRuleDiagnose(e);if(e.type==="run.cancel")return this.events.onCancel(e.runId);if(e.type==="run.approved")return this.events.onApproved(e.runId,e.headSha);if(e.type==="run.rejected")return this.events.onRejected(e.runId);if(e.type==="run.retryPush")return this.events.onRetryPush(e.runId);if(e.type==="deploy.start")return this.events.onDeployStart(e);if(e.type==="deploy.suggest")return this.events.onDeploySuggest(e);if(e.type==="env.preflight")return this.events.onEnvPreflight(e);if(e.type==="chat.turn")return this.events.onChatTurn(e);if(e.type==="chat.create.ticket")return this.events.onChatCreateTicket(e);if(e.type==="chat.list")return this.events.onChatList(e);if(e.type==="chat.load")return this.events.onChatLoad(e);if(e.type==="board.fetch")return this.events.onBoardFetch(e);if(e.type==="board.trigger")return this.events.onBoardTrigger(e);if(e.type==="audit.start")return this.events.onAuditStart(e);if(e.type==="audit.list")return this.events.onAuditList(e);if(e.type==="audit.get")return this.events.onAuditGet(e);if(e.type==="audit.review")return this.events.onAuditReview(e);if(e.type==="knowledge.list")return this.events.onKnowledgeList(e);if(e.type==="knowledge.save")return this.events.onKnowledgeSave(e);if(e.type==="epic.list")return this.events.onEpicList(e);if(e.type==="epic.suggest")return this.events.onEpicSuggest(e);if(e.type==="team.creds")return this.events.onTeamCreds(e);if(e.type==="jira.users")return this.events.onJiraUsers(e)}sendNow(e){this.ws?.send(JSON.stringify(e))}send(e){if(this.connected){this.sendNow(e);return}if(this.queue.length>=Jg){let t=this.queue.findIndex(n=>n.type==="run.log");t>=0?this.queue.splice(t,1):this.queue.shift()}this.queue.push(e)}async claimRun(e){if(!this.connected)return{accepted:!1,reason:"control plane offline"};let t=Ho.default.randomUUID(),n=await new Promise(s=>{let i=setTimeout(()=>{this.pending.delete(t),s(null)},15e3);this.pending.set(t,{resolve:s,timer:i}),this.sendNow({type:"run.claim",requestId:t,...e})});return!n||n.type!=="run.claim.result"?{accepted:!1,reason:"claim timed out"}:{accepted:n.accepted,runId:n.runId,reason:n.reason,claudeProfile:n.claudeProfile,actorEmail:n.actorEmail}}async claimDeploy(e){if(!this.connected)return{accepted:!1,reason:"control plane offline"};let t=Ho.default.randomUUID(),n=await new Promise(s=>{let i=setTimeout(()=>{this.pending.delete(t),s(null)},15e3);this.pending.set(t,{resolve:s,timer:i}),this.sendNow({type:"deploy.claim",requestId:t,...e})});return!n||n.type!=="deploy.claim.result"?{accepted:!1,reason:"deploy authorization timed out"}:{accepted:n.accepted,runId:n.runId,environment:n.environment,reason:n.reason,code:n.code}}sendDeploySuggestResult(e,t){this.send({type:"deploy.suggest.result",requestId:e,...t})}sendChatTurnResult(e,t){this.send({type:"chat.turn.result",requestId:e,...t})}sendChatCreateTicketResult(e,t){this.send({type:"chat.create.ticket.result",requestId:e,...t,childKeys:t.childKeys??[]})}sendChatListResult(e,t){this.send({type:"chat.list.result",requestId:e,sessions:t})}sendChatLoadResult(e,t){this.send({type:"chat.load.result",requestId:e,...t})}sendBoardFetchResult(e,t){this.send({type:"board.fetch.result",requestId:e,...t,browseBaseUrl:t.browseBaseUrl??""})}sendAuditStartResult(e,t){this.send({type:"audit.start.result",requestId:e,...t})}sendAuditListResult(e,t){this.send({type:"audit.list.result",requestId:e,ok:t.ok,error:t.error,audits:t.audits??[]})}sendAuditGetResult(e,t){this.send({type:"audit.get.result",requestId:e,...t})}sendAuditReviewResult(e,t){this.send({type:"audit.review.result",requestId:e,...t})}sendKnowledgeListResult(e,t){this.send({type:"knowledge.list.result",requestId:e,ok:t.ok,error:t.error,files:t.files??[]})}sendKnowledgeSaveResult(e,t){this.send({type:"knowledge.save.result",requestId:e,...t})}sendEpicListResult(e,t){this.send({type:"epic.list.result",requestId:e,ok:t.ok,error:t.error,epics:t.epics??[],children:t.children??[]})}sendEpicSuggestResult(e,t){this.send({type:"epic.suggest.result",requestId:e,ok:t.ok,error:t.error,issueKey:t.issueKey??"",reason:t.reason??"",considered:t.considered??0})}sendTeamCredsResult(e,t){this.send({type:"team.creds.result",requestId:e,ok:t.ok,error:t.error,githubShared:t.githubShared??!1,sharedGithubLogin:t.sharedGithubLogin??"",entries:t.entries??[]})}sendBoardTriggerResult(e,t){this.send({type:"board.trigger.result",requestId:e,...t})}sendEnvPreflightResult(e,t){this.send({type:"env.preflight.result",requestId:e,...t})}sendJiraUsersResult(e,t){this.send({type:"jira.users.result",requestId:e,...t})}sendProjectTestResult(e,t,n){this.send({type:"project.test.result",requestId:e,ok:t,checks:n})}sendRuleDiagnoseResult(e,t){this.send({type:"rule.diagnose.result",requestId:e,...t})}};var fn=$(require("node:fs"),1),Go=$(require("node:path"),1),nd=require("node:child_process"),sd=require("node:util");var rd=(0,sd.promisify)(nd.execFile);async function ei(r,e,t=[]){let n=[],s=r.repos[e.repoName]?.jira??r.jira;if(!s)n.push({name:"jira-credentials",ok:!1,detail:"no Jira credentials configured on this runner"});else{let o=new ze(s);try{let a=await o.myself();n.push({name:"jira-auth",ok:!0,detail:`authenticated as ${a.displayName}`});try{await o.search(`project = "${e.jiraProjectKey}" ORDER BY created DESC`,1),n.push({name:"jira-project",ok:!0,detail:`project ${e.jiraProjectKey} is readable`})}catch(u){n.push({name:"jira-project",ok:!1,detail:`cannot read project ${e.jiraProjectKey}: ${Vn(u)}`})}}catch(a){n.push({name:"jira-auth",ok:!1,detail:`Jira auth failed: ${Vn(a)}`})}}let i=r.repos[e.repoName];if(i&&fn.default.existsSync(i.path)){let o=Go.default.join(i.path,"CLAUDE.md"),a=fn.default.existsSync(o)&&fn.default.readFileSync(o,"utf8").trim().length>0;n.push({name:"memory-file",ok:a,detail:a?"CLAUDE.md present \u2014 the agent has project memory":"MISSING: CLAUDE.md at the repo root. Rules can't be enabled until the project has a memory file \u2014 it is what makes every run smarter than the last."});let u=bo(i.path);n.push({name:"deploy-doc",ok:u!==null,detail:u?`${u.path} present \u2014 deploy suggestions will follow it`:"MISSING: DEPLOY.md (or .ticketpilot/deploy.md). Environments can't be created until the repo documents how it deploys."})}if(!i)n.push({name:"repo-path",ok:!1,detail:`no local path mapped for repo "${e.repoName}" \u2014 run: allwright repo add "${e.repoName}" /path/to/checkout`});else if(!fn.default.existsSync(i.path))n.push({name:"repo-path",ok:!1,detail:`path does not exist: ${i.path}`});else{let o=fn.default.existsSync(Go.default.join(i.path,".git"));n.push({name:"repo-path",ok:!0,detail:`${i.path}${o?" (git checkout)":" (warning: not a git checkout)"}`})}try{let{stdout:o}=await rd(r.claudeBin,["--version"],{timeout:15e3});n.push({name:"claude-code",ok:!0,detail:o.trim().slice(0,100)})}catch(o){n.push({name:"claude-code",ok:!1,detail:`cannot run "${r.claudeBin}": ${Vn(o)}`})}try{let{stdout:o}=await rd("git",["--version"],{timeout:15e3});n.push({name:"git",ok:!0,detail:o.trim().slice(0,100)})}catch(o){n.push({name:"git",ok:!1,detail:`cannot run git: ${Vn(o)}`})}if(r.github?.token)try{let{GitHubClient:o}=await Promise.resolve().then(()=>(ut(),Qr)),a=await new o(r.github.token).whoami();n.push({name:"github-token",ok:!0,detail:`authenticated as ${a}`})}catch(o){n.push({name:"github-token",ok:!1,detail:Vn(o)})}else n.push({name:"github-token",ok:!0,detail:"not set \u2014 needed only for implement rules (allwright github set-token)"});if(t.length){r.deploy.enabled?n.push({name:"deploy",ok:!0,detail:"deployments enabled on this runner"}):n.push({name:"deploy",ok:!1,detail:"deployments are disabled on this runner \u2014 run `allwright deploy enable` to allow it to execute your saved deploy steps"});for(let o of t){let a=Wt(r,e.repoName,o.name),u=o.requiredSecrets.filter(l=>!a[l]&&!process.env[l]);n.push({name:`env:${o.name}`,ok:u.length===0,detail:u.length?`missing secret(s): ${u.join(", ")} \u2014 allwright env set "${e.repoName}" "${o.name}" ${u[0]}=...`:`${o.steps.length} step(s), ${o.requiredSecrets.length} secret(s) present`+(o.branch?`, deploys origin/${o.branch}`:"")})}}return n}function Vn(r){return(r instanceof Error?r.message:String(r)).slice(0,300)}var ae=new ga;ae.name("allwright").description("Allwright runner \u2014 runs on YOUR machine, holds YOUR credentials locally, connects outbound-only to the control plane. Your Jira token, Anthropic key and source code never leave this host.").version(gs);ae.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",id.default.hostname()).option("--jira-url <url>","Jira base URL, e.g. https://yourorg.atlassian.net").option("--jira-email <email>","Jira account email").option("--jira-token <token>","Jira API token (stored locally only)").action(async r=>{let e=Ir.default.createInterface({input:process.stdin,output:process.stdout}),t=async(n,s,i=!1)=>{if(s)return s;let o=await e.question(`${n}: `);if(!o.trim())throw new Error(`${n} is required`);return o.trim()};try{let n=await t("Control plane URL",r.cpUrl),s=await t("Enrolment token (from the web UI)",r.enrollToken),i=await t("Jira base URL (https://yourorg.atlassian.net)",r.jiraUrl),o=await t("Jira account email",r.jiraEmail),a=await t("Jira API token (create at id.atlassian.com/manage-profile/security/api-tokens)",r.jiraToken,!0),u=wi.parse({controlPlaneUrl:n,runnerName:r.name,jira:{baseUrl:i,email:o,apiToken:a}}),l=await new ze(u.jira).myself();m.info(`Jira credential OK \u2014 authenticated as ${l.displayName}`),u=await cc(u,s),m.info(`Enrolled as runner "${u.runnerName}" (${u.runnerId})`),m.info(`Credentials saved to ${wt()} (mode 600, this machine only)`),m.info("Next: map your repo with `allwright repo add <repoName> <localPath>`, then `allwright start`")}finally{e.close()}});var Jo=ae.command("repo").description("Map control-plane repo names to local checkouts");Jo.command("add <repoName> <localPath>").description("Map a repo name (as configured in the web UI) to a local checkout path").action(async(r,e)=>{let t=Q();t.repos[r]={path:e},ie(t),m.info(`mapped repo "${r}" -> ${e}`);try{let{originUrl:n}=await Promise.resolve().then(()=>(mr(),_c));m.info(` origin remote: ${await n(e)} \u2014 make sure this is the repo you meant`)}catch{m.warn(` could not read an origin remote at ${e} \u2014 is it a git checkout?`)}});Jo.command("list").description("Show configured repo mappings").action(()=>{let r=Q(),e=Object.entries(r.repos);if(!e.length)return m.info("no repos mapped yet");for(let[t,n]of e)m.info(`${t} -> ${n.path}`)});var ad=ae.command("claude").description("Per-user Claude login profiles \u2014 each teammate's runs bill their OWN Claude account");ad.command("login <profileName>").description("Create (or re-login) a named Claude profile. Opens Claude Code interactively with its own config directory \u2014 have the PERSON WHOSE ACCOUNT IT IS complete the /login flow with their credentials, then exit. Assign the profile to their user on the dashboard's Team page.").action(async r=>{if(!/^[a-zA-Z0-9._-]+$/.test(r))throw new Error("profile name: letters, digits, dots, dashes and underscores only");let e=Q(),t=e.claudeProfiles[r]?.configDir??`${wt().replace(/runner\.json$/,"")}claude-profiles/${r}`;pn.default.mkdirSync(t,{recursive:!0,mode:448}),e.claudeProfiles[r]={configDir:t},ie(e),m.info(`profile "${r}" -> ${t}`),m.info("Opening Claude Code with this profile. In it: run /login, complete the browser flow"),m.info("with the account this profile belongs to, then exit Claude (ctrl+c twice or /exit).");let n=(0,Hn.spawn)(e.claudeBin,[],{env:{...process.env,CLAUDE_CONFIG_DIR:t},stdio:"inherit"});await new Promise(s=>n.on("exit",()=>s())),m.info(`Done. Assign it on the dashboard: Team -> the user -> Claude profile = "${r}".`),m.info("Restart the background runner for this to take effect: allwright stop && allwright start")});ad.command("list").description("Show configured Claude profiles and whether each looks logged in").action(()=>{let r=Q(),e=Object.entries(r.claudeProfiles);if(m.info("default: this OS user's own Claude login (no profile)"),!e.length)return m.info("no named profiles yet \u2014 allwright claude login <name>");for(let[t,n]of e){let s=pn.default.existsSync(n.configDir)&&pn.default.readdirSync(n.configDir).length>0;m.info(`${t} -> ${n.configDir} ${s?"(logged in)":"(NOT logged in yet)"}`)}});Jo.command("remove <repoName>").description("Unmap a repo from this runner: removes the mapping plus its per-repo Jira/GitHub overrides and env secrets from the config. Does NOT touch the checkout on disk or anything in the control plane \u2014 delete the project on the dashboard separately.").action(r=>{let e=Q();if(!e.repos[r]){let i=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${r}" \u2014 mapped repos: ${i}`)}let t=e.repos[r].path;delete e.repos[r];let n=Object.keys(e.environments).filter(i=>i.startsWith(`${r}:`));for(let i of n)delete e.environments[i];let s=e.auditSchedules.length;e.auditSchedules=e.auditSchedules.filter(i=>i.repoName!==r),ie(e),m.info(`Removed "${r}" (was ${t})`),n.length&&m.info(`Also removed ${n.length} environment secret set(s): ${n.join(", ")}`),e.auditSchedules.length!==s&&m.info("Also removed its audit schedule(s)"),m.info("The checkout on disk was NOT touched \u2014 remove it yourself if you want it gone."),m.info("Restart the runner to apply. Dashboard project (if any) is deleted separately there.")});var Yo=ae.command("service").description("Run the runner as a system service (starts on boot, restarts on crash)");Yo.command("install").description("Install + start the systemd service \u2014 detects node, this script, your user and home; no hand-written unit files. Run with sudo. (--print shows the unit without installing.)").option("--print","print the generated unit file and exit").action(r=>{if(r.print){m.info(`
|
|
660
|
+
`+Wi(Gi()));return}xc(m)});Yo.command("uninstall").description("Stop and remove the systemd service (config/credentials untouched)").action(()=>Cc(m));Yo.command("status").description("systemctl status for the runner service").action(()=>{(0,Hn.spawn)("systemctl",["status","allwright","--no-pager"],{stdio:"inherit"}).on("exit",e=>process.exit(e??0))});ae.command("update").description("Update the runner to the latest published version (npm install -g allwright@latest). Restart the runner afterwards \u2014 and only when no runs are active.").action(async()=>{m.info("Updating: npm install -g allwright@latest");let r=(0,Hn.spawn)("npm",["install","-g","allwright@latest"],{stdio:"inherit"});await new Promise((e,t)=>{r.on("exit",n=>n===0?e():t(new Error(`npm exited with code ${n}`))),r.on("error",t)}),m.info("Updated. Restart the runner service to load the new version (check active runs first).")});var Gn=ae.command("jira").description("Per-repo Jira site overrides \u2014 for projects living on a different Atlassian site");Gn.command("set <repoName>").description("Store Jira credentials for ONE repo's project (e.g. a project on a different *.atlassian.net site than the runner's main credential). Prompts on stdin; stored locally only, like every other credential.").action(async r=>{let e=Q();if(!e.repos[r]){let n=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${r}" \u2014 mapped repos: ${n}. Run \`allwright repo add\` first.`)}let t=Ir.default.createInterface({input:process.stdin,output:process.stdout});try{let n=(await t.question("Jira base URL for this repo (https://yourorg.atlassian.net): ")).trim(),s=(await t.question("Jira account email: ")).trim(),i=(await t.question("Jira API token (id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!n||!s||!i)throw new Error("all three values are required");let o={baseUrl:n,email:s,apiToken:i},a=await new ze(o).myself();m.info(`Jira credential OK \u2014 authenticated as ${a.displayName} on ${n}`),e.repos[r].jira=o,ie(e),m.info(`Saved: repo "${r}" now polls ${n} (other repos keep the runner-wide credential)`),m.info("Restart the background runner for this to take effect: allwright stop && allwright start")}finally{t.close()}});Gn.command("show").description("Show which Jira site each repo uses (never prints tokens)").action(()=>{let r=Q();m.info(`runner-wide: ${r.jira?`${r.jira.baseUrl} (${r.jira.email})`:"(not configured)"}`);for(let[e,t]of Object.entries(r.repos))m.info(`${e} -> ${t.jira?`${t.jira.baseUrl} (${t.jira.email})`:"(runner-wide credential)"}`)});Gn.command("user-add <ticketpilotEmail>").description("Store a PERSON's own Jira credential, so board buttons and Compose tickets they click post to Jira under THEIR Atlassian identity instead of the runner's account. Keyed by their Allwright login email. Prompts on stdin; stored locally only. Picked up on the next click \u2014 no restart needed.").action(async r=>{let e=Q(),t=r.trim().toLowerCase();if(!t.includes("@"))throw new Error(`"${r}" doesn't look like an email`);let n=Ir.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await n.question(`Their ATLASSIAN account email [${t}]: `)).trim()||t,i=(await n.question("Their Jira API token (they create it at id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!i)throw new Error("API token is required");let o=[e.jira,...Object.values(e.repos).map(l=>l.jira)].filter(l=>!!l),a=new Set,u=!1;for(let l of o)if(!a.has(l.baseUrl)){a.add(l.baseUrl);try{let d=await new ze({baseUrl:l.baseUrl,email:s,apiToken:i}).myself();m.info(`${l.baseUrl}: OK \u2014 authenticated as ${d.displayName}`),u=!0}catch{m.warn(`${l.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 \u2014 nothing saved");e.jiraUsers[t]={email:s,apiToken:i},ie(e),m.info(`Saved. Dashboard actions by ${t} now post to Jira as ${s}. No restart needed.`)}finally{n.close()}});Gn.command("user-list").description("Show which Allwright users have their own Jira credential here (never prints tokens)").action(()=>{let r=Q(),e=Object.entries(r.jiraUsers);if(!e.length)return m.info("none yet \u2014 everyone's dashboard clicks require one: allwright jira user-add <their-ticketpilot-email>");for(let[t,n]of e)m.info(`${t} -> posts to Jira as ${n.email}`)});Gn.command("user-remove <ticketpilotEmail>").description("Delete a person's stored Jira credential").action(r=>{let e=Q(),t=r.trim().toLowerCase();if(!e.jiraUsers[t])throw new Error(`no credential stored for ${t}`);delete e.jiraUsers[t],ie(e),m.info(`Removed. Dashboard actions by ${t} will now be refused until a new credential is added.`)});var mn=ae.command("github").description("GitHub credential for implement-mode rules");mn.command("set-token").description("Store a GitHub token for opening pull requests (implement rules). Stored locally only, like your Jira token. Recommended: a fine-grained PAT scoped to the repo with contents:write + pull_requests:write.").option("--token <token>","GitHub token (omit to be prompted)").action(async r=>{let e=Ir.default.createInterface({input:process.stdin,output:process.stdout});try{let t=r.token??(await e.question("GitHub token (fine-grained PAT recommended): ")).trim();if(!t)throw new Error("token is required");let{GitHubClient:n}=await Promise.resolve().then(()=>(ut(),Qr)),s=await new n(t).whoami(),i=Q();i.github={token:t,login:s},ie(i),m.info(`GitHub token OK \u2014 authenticated as ${s}`),m.info(`Saved to ${wt()} (mode 600, this machine only)`)}finally{e.close()}});mn.command("set <repoName>").description("Store a GitHub token for ONE repo only \u2014 overrides the runner-wide token for that repo's PRs and PR-watching. Useful when projects need separately revocable access. Prompts on stdin; stored locally only.").action(async r=>{let e=Q();if(!e.repos[r]){let n=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${r}" \u2014 mapped repos: ${n}. Run \`allwright repo add\` first.`)}let t=Ir.default.createInterface({input:process.stdin,output:process.stdout});try{let n=(await t.question(`GitHub token for "${r}" (fine-grained PAT scoped to just this repo): `)).trim();if(!n)throw new Error("token is required");let{GitHubClient:s}=await Promise.resolve().then(()=>(ut(),Qr)),i=await new s(n).whoami();e.repos[r].github={token:n,login:i},ie(e),m.info(`GitHub token OK \u2014 authenticated as ${i}`),m.info(`Saved: repo "${r}" now uses its own token (other repos keep the runner-wide one)`)}finally{t.close()}});mn.command("user-add <ticketpilotEmail>").description("Store a PERSON's own GitHub token, so PRs from implement runs THEY trigger are authored by their GitHub account. Keyed by their Allwright login email. Optional \u2014 without it their runs fall back to the repo/runner-wide token. Needs contents:write + pull_requests:write on the repos they'll touch.").action(async r=>{let e=Q(),t=r.trim().toLowerCase();if(!t.includes("@"))throw new Error(`"${r}" doesn't look like an email`);let n=Ir.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await n.question(`GitHub token for ${t}: `)).trim();if(!s)throw new Error("token is required");let{GitHubClient:i}=await Promise.resolve().then(()=>(ut(),Qr)),o=await new i(s).whoami();e.githubUsers[t]={token:s,login:o},ie(e),m.info(`GitHub token OK \u2014 authenticated as ${o}`),m.info(`Saved. Implement runs triggered by ${t} now open PRs as ${o}. No restart needed.`)}finally{n.close()}});mn.command("user-list").description("Show which Allwright users have their own GitHub token here (never prints tokens)").action(()=>{let r=Q(),e=Object.entries(r.githubUsers);if(!e.length)return m.info("no per-user GitHub tokens \u2014 everyone's PRs use the repo/runner-wide token");for(let[t]of e)m.info(`${t} -> own GitHub token stored`)});mn.command("user-remove <ticketpilotEmail>").description("Delete a person's stored GitHub token (their runs fall back to the shared token)").action(r=>{let e=Q(),t=r.trim().toLowerCase();if(!e.githubUsers[t])throw new Error(`no GitHub token stored for ${t}`);delete e.githubUsers[t],ie(e),m.info(`Removed. ${t}'s runs use the repo/runner-wide token again.`)});mn.command("show").description("Show which GitHub token each repo and person would use (never prints tokens)").action(()=>{let r=Q();m.info(`runner-wide: ${r.github?.token?"token set":"(not configured)"}`);for(let[t,n]of Object.entries(r.repos))m.info(`${t} -> ${n.github?.token?"own repo token":"runner-wide token"}`);let e=Object.keys(r.githubUsers);m.info(e.length?`per-user tokens: ${e.join(", ")}`:"per-user tokens: (none)")});var Xo=ae.command("audit").description("Recurring specialist audits on this runner");Xo.command("schedule <repoName> <role> <intervalHours>").description("Audit this repo's project on a cadence (role: security|testing; interval in hours, min 6). Runs on the runner's own clock; reports land in the Audits page history, where the diff-vs-previous view shows drift. Advisory only \u2014 nothing blocks.").action((r,e,t)=>{let n=Q();if(!n.repos[r]){let i=Object.keys(n.repos).join(", ")||"(none)";throw new Error(`unknown repo "${r}" \u2014 mapped repos: ${i}`)}if(e!=="security"&&e!=="testing")throw new Error('role must be "security" or "testing"');let s=parseInt(t,10);if(!Number.isInteger(s)||s<6||s>720)throw new Error("intervalHours must be 6-720");n.auditSchedules=[...n.auditSchedules.filter(i=>!(i.repoName===r&&i.role===e)),{repoName:r,role:e,intervalHours:s}],ie(n),m.info(`Scheduled: ${e} audit of "${r}" every ${s}h. Restart the runner to apply.`)});Xo.command("schedules").description("List scheduled audits").action(()=>{let r=Q();if(!r.auditSchedules.length)return m.info("no scheduled audits \u2014 allwright audit schedule <repo> <role> <hours>");for(let e of r.auditSchedules)m.info(`${e.repoName} \xB7 ${e.role} \xB7 every ${e.intervalHours}h`)});Xo.command("unschedule <repoName> <role>").description("Remove a scheduled audit").action((r,e)=>{let t=Q(),n=t.auditSchedules.length;if(t.auditSchedules=t.auditSchedules.filter(s=>!(s.repoName===r&&s.role===e)),t.auditSchedules.length===n)throw new Error("no such schedule");ie(t),m.info("Removed. Restart the runner to apply.")});var Qo=ae.command("deploy").description("Deployment settings for this machine");Qo.command("enable").description("Allow this runner to execute the deploy steps saved in the dashboard. Those steps are shell commands that run here, as this user \u2014 so this switch lives on the machine, not in the web UI, and only someone with shell access can flip it.").action(()=>{let r=Q();r.deploy={enabled:!0},ie(r),m.info("deployments ENABLED on this runner"),m.info("This runner will now execute the deploy steps configured for your environments. Review them in the dashboard before shipping to production."),m.info("Restart the background runner for this to take effect: allwright stop && allwright start")});Qo.command("disable").description("Stop this runner from executing any deploy steps").action(()=>{let r=Q();r.deploy={enabled:!1},ie(r),m.info("deployments DISABLED on this runner"),m.info("Restart the background runner for this to take effect: allwright stop && allwright start")});Qo.command("status").description("Show whether deployments are enabled here, and which env secrets are stored").action(()=>{let r=Q();m.info(`deployments: ${r.deploy.enabled?"enabled":"disabled"}`);let e=Object.entries(r.environments);if(!e.length)return m.info("no environment secrets stored");for(let[t,n]of e){let s=Object.keys(n.secrets);m.info(`${t}: ${s.length?s.join(", "):"(no secrets)"}`)}});var ea=ae.command("env").description("Per-environment deploy secrets. Values stay on this machine, like your Jira token.");ea.command("set <repoName> <envName> <assignments...>").description('Store secrets for one environment, e.g. env set acme/api production "SSH_HOST=1.2.3.4" "SSH_USER=deploy". Your deploy steps reference these as $SSH_HOST. The control plane only ever learns the NAMES.').action((r,e,t)=>{let n=Q(),s=ss(r,e),i=n.environments[s]??{secrets:{}},o=[];for(let a of t){let u=a.indexOf("=");if(u<=0)throw new Error(`expected KEY=VALUE, got "${a}"`);let l=a.slice(0,u).trim();i.secrets[l]=a.slice(u+1),o.push(l)}n.environments[s]=i,ie(n),m.info(`stored ${o.length} secret(s) for ${s}: ${o.join(", ")}`),m.info(`Saved to ${wt()} (mode 600, this machine only)`),m.info("Restart the background runner to pick these up: allwright stop && allwright start")});ea.command("unset <repoName> <envName> <names...>").description("Remove stored secrets for an environment").action((r,e,t)=>{let n=Q(),s=ss(r,e),i=n.environments[s];if(!i)return m.info(`nothing stored for ${s}`);for(let o of t)delete i.secrets[o];n.environments[s]=i,ie(n),m.info(`removed ${t.join(", ")} from ${s}`)});ea.command("list").description("Show which environments have secrets stored here (names only, never values)").action(()=>{let r=Q(),e=Object.entries(r.environments);if(!e.length)return m.info("no environment secrets stored");for(let[t,n]of e)m.info(`${t}: ${Object.keys(n.secrets).join(", ")||"(none)"}`)});ae.command("export [file]").description("Back up ALL runner state (config+secrets, knowledge, audits, chats) to one tarball").action(r=>{try{let e=Aa(r);m.info(`Backup written: ${e.file} (${e.entries.length} entries, mode 600)`),m.warn("This file CONTAINS YOUR SECRETS (Jira/GitHub tokens). Keep it private \u2014 anyone holding it can act as this runner."),m.info(`Restore on any machine with: allwright import ${od.default.basename(e.file)}`)}catch(e){m.error(e instanceof Error?e.message:String(e)),process.exitCode=1}});ae.command("import <file>").description("Restore runner state from an `export` tarball (existing config is kept as a .bak dir)").action(r=>{let e=zr();if(e&&wn(e)){m.error("the runner is running \u2014 stop it first (systemctl stop allwright, or `allwright stop` for a pid-file daemon), then import."),process.exitCode=1;return}try{let t=Ra(r);m.info(`Restored ${t.restored.length} entries into ${ee()}`),t.previousDir&&m.info(`Previous config kept at ${t.previousDir}`),m.info("Start the runner and it will reconnect with the restored identity.")}catch(t){m.error(t instanceof Error?t.message:String(t)),process.exitCode=1}});ae.command("test").description("Check local setup: Jira auth, repo mappings, Claude Code binary").action(async()=>{let r=Q(),e=Object.keys(r.repos);if(!r.jira){m.error("no Jira credentials configured \u2014 run `allwright init`"),process.exitCode=1;return}let t=e.length?e.map(s=>({jiraProjectKey:"*",repoName:s})):[{jiraProjectKey:"*",repoName:"(none mapped)"}],n=!0;for(let s of t){let i=await ei(r,s);for(let o of i){if(s.jiraProjectKey==="*"&&o.name==="jira-project")continue;let a=o.ok?"PASS":"FAIL";(o.ok?m.info:m.error)(`[${a}] ${o.name}: ${o.detail}`),n&&=o.ok}}n||(process.exitCode=1)});function Yg(r){if(!r.runnerToken)throw new Error("runner not enrolled \u2014 run `allwright init`");if(!r.jira)throw new Error("no Jira credentials \u2014 run `allwright init`");let e=new ze(r.jira),t=new Map,n=f=>{let g=r.repos[f]?.jira;if(!g)return e;let b=t.get(f);return b||(b=new ze(g),t.set(f,b)),b},s=new Map,i=(f,g)=>{let b=wc(he()??r,f,g);switch(b.kind){case"legacy":return{jira:n(f),authored:!1};case"self":return{jira:n(f),authored:!0};case"missing":return{error:b.error};case"user":{let I=`${b.creds.baseUrl}:${b.creds.email}:${b.creds.apiToken.slice(-6)}`,N=s.get(I);return N||(N=new ze(b.creds),s.set(I,N)),{jira:N,authored:!0}}}},o=new URL("/api/runner/ws",r.controlPlaneUrl);o.protocol=o.protocol==="https:"?"wss:":"ws:";let a=[],u=[],l=[],d,p={cfg:r,jiraFor:n,transport:null},v=new Set,S=f=>{let g=a.find(I=>I.id===f),b=g&&r.repos[g.repoName];return g&&b?{project:g,repoPath:b.path}:null},x={cfg:r,jiraFor:n,get transport(){return p.transport},lookup:(f,g)=>{let b=S(f),I=l.find(N=>N.projectId===f&&N.name===g);return b&&I?{...b,environment:I}:null}},w=new Qs(o.toString(),r.runnerToken,{runnerVersion:gs},{onConfig:f=>{a=f.projects,u=f.rules,l=f.environments,d.setConfig(f.projects,f.rules,f.pollingPaused,f.environments)},onProjectTest:async f=>{let g=a.find(I=>I.id===f.projectId);if(!g){w.sendProjectTestResult(f.requestId,!1,[{name:"config",ok:!1,detail:"project not in this runner's synced config yet"}]);return}m.info(`running connection test for project "${g.name}"`);let b=await ei(r,g,l.filter(I=>I.projectId===g.id));w.sendProjectTestResult(f.requestId,b.every(I=>I.ok),b)},onRuleDiagnose:async f=>{let g=u.find(z=>z.id===f.ruleId),b=g&&a.find(z=>z.id===g.projectId);if(!g||!b){w.sendRuleDiagnoseResult(f.requestId,{checks:[{name:"config",ok:!1,detail:"rule not in this runner's synced config yet"}],matchedCount:0,excludedCount:0,excludedSample:[]});return}m.info(`diagnosing rule "${g.name}"`);let I=await ei(r,b,g.action.type==="deploy"?l.filter(z=>z.projectId===b.id):[]),N=g.action.type==="implement"?I:I.filter(z=>z.name!=="github-token"),{matchedCount:V,excludedCount:W,excludedSample:J}=await d.diagnoseRule(g,b);w.sendRuleDiagnoseResult(f.requestId,{checks:N,matchedCount:V,excludedCount:W,excludedSample:J})},onCancel:f=>{m.warn(`cancel requested for run ${f} \u2014 not supported in this version, run will finish or time out`)},onApproved:(f,g)=>{if(vo(f)){Uu(x,f).catch(b=>m.error(`deploy approval crashed for ${f}: ${b instanceof Error?b.stack:b}`));return}Mn(p,f,g).catch(b=>m.error(`approval handling crashed for ${f}: ${b instanceof Error?b.stack:b}`))},onRetryPush:f=>{let g=Is(f),b=()=>Iu(p,f).catch(I=>m.error(`retry push crashed for ${f}: ${I instanceof Error?I.stack:I}`));g?d.runOnRepoQueue(g.baseRepoPath,b):b()},onRejected:f=>{if(vo(f)){qu(x,f).catch(g=>m.error(`deploy rejection crashed for ${f}: ${g instanceof Error?g.stack:g}`));return}Eu(p,f).catch(g=>m.error(`rejection handling crashed for ${f}: ${g instanceof Error?g.stack:g}`))},onDeployStart:f=>{let g=`${f.runId}#${f.attempt}`;if(v.has(g))return;v.add(g);let b=S(f.projectId);if(!b){let I="this runner has no local checkout mapped for that project \u2014 run: allwright repo add <repoName> /path/to/checkout";m.error(`deploy ${f.runId}: ${I}`),w.send({type:"run.status",runId:f.runId,status:"failed",error:I});return}m.info(`deploy ${f.runId} requested from the dashboard: ${f.issueKey} \u2192 ${f.environment.name}`),d.runOnEnvironmentQueue(f.environment.id,()=>Ms({runId:f.runId,project:b.project,environment:f.environment,issueKey:f.issueKey,issueSummary:f.issueSummary,repoPath:b.repoPath,cfg:r,jira:n(b.project.repoName),transport:w,requestedBy:f.requestedBy}).catch(I=>m.error(`deploy crashed for ${f.runId}: ${I instanceof Error?I.stack:I}`)))},onDeploySuggest:async f=>{let g=S(f.projectId);if(!g){w.sendDeploySuggestResult(f.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:"this runner has no local checkout mapped for that project"});return}m.info(`asking Claude Code for "${f.environmentName}" deploy steps in ${g.repoPath}`);let b=await Ku({repoPath:g.repoPath,repoName:g.project.repoName,environmentName:f.environmentName,notes:f.notes,timeoutSeconds:f.timeoutSeconds,cfg:r});w.sendDeploySuggestResult(f.requestId,b)},onEnvPreflight:async f=>{let g=S(f.projectId);if(!g){w.sendEnvPreflightResult(f.requestId,{ok:!1,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project"}]});return}let b=await Zu({repoPath:g.repoPath,repoName:g.project.repoName,environmentName:f.environmentName,steps:f.steps,requiredSecrets:f.requiredSecrets,workdir:f.workdir,branch:f.branch,cfg:r});w.sendEnvPreflightResult(f.requestId,b)},onChatTurn:async f=>{let g=S(f.projectId);if(!g){w.sendChatTurnResult(f.requestId,{ok:!1,sessionId:f.sessionId??"",reply:"",error:"this runner has no local checkout mapped for that project"});return}let b=f.sessionId||(0,Wo.randomUUID)(),I=!f.sessionId;if((I?0:So(b)?.messages.length??0)>=44){w.sendChatTurnResult(f.requestId,{ok:!1,sessionId:b,reply:"",error:"this chat has hit its length limit \u2014 every turn re-reads the whole conversation, so long chats get slow and expensive. Start a new chat (it keeps the repo knowledge; only the conversation resets)."});return}let V=f.files.length?ja(g.repoPath,f.requestId,f.files):null,W="```",J=I?`You are the project assistant for "${g.project.name}" \u2014 this working directory is its repository, and you have read-only access.
|
|
661
|
+
|
|
662
|
+
DEFAULT MODE IS DISCUSSION. Answer questions, explain code, weigh approaches, review ideas \u2014 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.
|
|
663
|
+
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.
|
|
664
|
+
|
|
665
|
+
ONLY when the user explicitly asks for a ticket, propose it by ending your reply with EXACTLY one fenced block in this shape:
|
|
666
|
+
${W}ticket
|
|
667
|
+
{"summary": "\u2026", "description": "\u2026"}
|
|
668
|
+
${W}
|
|
669
|
+
Before drafting, re-read this ENTIRE conversation from its first message and fold in every decision, constraint, and correction agreed along the way \u2014 the ticket reflects the final state of the whole discussion, not just the last message.
|
|
670
|
+
The description must be concrete enough that a developer (or an agent) can implement it without asking questions \u2014 and as SHORT as it can stay complete: what to build, where, and 3-6 "done" bullet points, usually under ~250 words. When completeness and brevity conflict, completeness wins. NEVER paste the conversation into the description; distill it. Refine the draft over further turns if the user asks.
|
|
671
|
+
EXCEPTION \u2014 verbatim payloads: when the user supplies literal content that must land in the ticket exactly (file contents, error logs, specs, commands), include it in the description IN FULL inside a fenced code block \u2014 the word budget applies to your own prose around it, never to the user's payload. Never summarize such content and never replace it with a placeholder like "[insert content here]": a placeholder makes the ticket unimplementable, because the implementing agent only ever sees the ticket. Inside the ${W}ticket JSON, fence such payloads with ~~~ (tildes), NEVER with triple backticks \u2014 a nested ${W} would end the outer block early and corrupt the draft.
|
|
672
|
+
EXCEPTION \u2014 big requirements: when the user asks for an epic with sub-tickets, or asks to ticket something clearly too large for one ticket, break it down instead and emit this shape in the \`\`\`ticket block:
|
|
673
|
+
{"epic": {"summary": "\u2026", "description": "\u2026"}, "tickets": [{"summary": "\u2026", "description": "\u2026"}, \u2026]}
|
|
674
|
+
3-8 tickets, each independently implementable and SHORT like above, ordered so foundations come first; the epic description is the overall goal in under 100 words.
|
|
675
|
+
|
|
676
|
+
${f.userName||"The user"} says: ${f.message}`+(V?.section??""):`${f.userName||"The user"} says: ${f.message}`+(V?.section??""),z=0,H;try{H=await Ue.run({repoPath:g.repoPath,prompt:J,timeoutSeconds:180,bin:r.claudeBin,mode:"read_only",maxTurns:25,model:f.model||"claude-sonnet-5",sessionId:b,resume:!I,onLog:(be,Ce)=>{be==="agent"&&w.send({type:"chat.stream",requestId:f.requestId,seq:z++,text:Ce.slice(0,8e3)})}})}finally{V&&pn.default.rmSync(V.dir,{recursive:!0,force:!0})}H.ok&&Ju(f.projectId,b,f.message,H.resultText),w.sendChatTurnResult(f.requestId,{ok:H.ok,sessionId:b,reply:H.resultText,error:H.ok?void 0:H.error??"the agent produced no reply"})},onChatList:f=>{w.sendChatListResult(f.requestId,Yu(f.projectId))},onChatLoad:f=>{let g=So(f.sessionId);w.sendChatLoadResult(f.requestId,{ok:g!==null,projectId:g?.projectId??"",messages:g?.messages??[],error:g?void 0:"chat not found on this runner (pruned or never existed)"})},onBoardFetch:async f=>{let g=S(f.projectId);if(!g){w.sendBoardFetchResult(f.requestId,{ok:!1,columns:[],error:"this runner has no local checkout mapped for that project"});return}try{let b=n(g.project.repoName),I;try{I=await b.searchBoard(`project = "${g.project.jiraProjectKey}" ORDER BY Rank ASC`,100)}catch{I=await b.searchBoard(`project = "${g.project.jiraProjectKey}" ORDER BY updated DESC`,100)}let N=await b.boardColumns(g.project.jiraProjectKey),V;if(N){V=N.map(z=>({name:z.name,issues:[]}));let J=new Map;for(let z of I){let H=N.findIndex(Ce=>Ce.statusIds.includes(z.statusId)),be={key:z.key,summary:z.summary,labels:z.labels};if(H>=0)V[H].issues.push(be);else{let Ce=J.get(z.status)??[];Ce.push(be),J.set(z.status,Ce)}}for(let[z,H]of J)V.push({name:z,issues:H})}else{let J=le=>le.trim().toLowerCase(),z=new Map,H=new Map;for(let le of I){let gt=J(le.status);z.has(gt)||z.set(gt,le.status.trim());let ta=H.get(gt)??[];ta.push({key:le.key,summary:le.summary,labels:le.labels}),H.set(gt,ta)}let be=[];try{be=await b.projectStatuses(g.project.jiraProjectKey)}catch{}let Ce=[];for(let le of be){let gt=J(le);!Ce.includes(gt)&&H.has(gt)&&Ce.push(gt)}for(let le of H.keys())Ce.includes(le)||Ce.push(le);V=Ce.map(le=>({name:z.get(le)??le,issues:H.get(le)??[]}))}let W=r.repos[g.project.repoName]?.jira??r.jira;w.sendBoardFetchResult(f.requestId,{ok:!0,browseBaseUrl:(W?.baseUrl??"").replace(/\/+$/,""),columns:V})}catch(b){w.sendBoardFetchResult(f.requestId,{ok:!1,columns:[],error:b instanceof Error?b.message:String(b)})}},onBoardTrigger:async f=>{let g=S(f.projectId);if(!g){w.sendBoardTriggerResult(f.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{let b=n(g.project.repoName),I=f.comment.trim()?i(g.project.repoName,f.requestedByEmail):{jira:b,authored:!1};if(I.error!==void 0){w.sendBoardTriggerResult(f.requestId,{ok:!1,error:I.error});return}if(f.reimplement){let N=await b.getIssue(f.issueKey),V=N.comments.filter(z=>Ge(z.body)),W=V.length?Math.max(...V.map(z=>new Date(z.created).getTime())):0;if(!N.comments.some(z=>!Ge(z.body)&&new Date(z.created).getTime()>W)){w.sendBoardTriggerResult(f.requestId,{ok:!1,error:`${f.issueKey} has nothing new since the last implementation \u2014 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 b.editLabels(f.issueKey,{remove:["agent-implemented"]})}f.removeLabel.trim()&&await b.editLabels(f.issueKey,{remove:[f.removeLabel.trim()]}),f.comment.trim()&&await I.jira.addTriggerComment(f.issueKey,`${f.comment.trim()}`+(!I.authored&&f.requestedBy?`
|
|
677
|
+
|
|
678
|
+
_(requested by ${f.requestedBy} via Allwright)_`:"")),m.info(`Board action on ${f.issueKey}`+(f.comment?` comment "${f.comment.trim()}"`:"")+(f.removeLabel?` -label ${f.removeLabel}`:"")+(f.requestedBy?` by ${f.requestedBy}`:"")),w.sendBoardTriggerResult(f.requestId,{ok:!0})}catch(b){w.sendBoardTriggerResult(f.requestId,{ok:!1,error:b instanceof Error?b.message:String(b)})}},onChatCreateTicket:async f=>{let g=S(f.projectId);if(!g){w.sendChatCreateTicketResult(f.requestId,{ok:!1,issueKey:"",error:"this runner has no local checkout mapped for that project"});return}try{let b=i(g.project.repoName,f.requestedByEmail);if(b.error!==void 0){w.sendChatCreateTicketResult(f.requestId,{ok:!1,issueKey:"",error:b.error});return}let I=`
|
|
679
|
+
|
|
680
|
+
---
|
|
681
|
+
_Created via Allwright Compose`+(!b.authored&&f.requestedBy?` by ${f.requestedBy}`:"")+", drafted with the project agent._",{key:N}=await b.jira.createIssue(g.project.jiraProjectKey,f.summary,(f.description||"(no description)")+I,f.asEpic?"Epic":"Task");f.files.length&&await b.jira.addAttachments(N,f.files.map(W=>({name:W.name,content:Buffer.from(W.contentBase64,"base64")}))).then(()=>m.info(`Compose attached ${f.files.length} file(s) to ${N}`)).catch(W=>m.warn(`Compose could not attach files to ${N}: ${W instanceof Error?W.message:W}`));let V=[];if(f.asEpic){for(let W of f.children){let J=await b.jira.createIssue(g.project.jiraProjectKey,W.summary,W.description||"(no description)","Task",N);V.push(J.key)}m.info(`Compose created epic ${N} with ${V.length} child ticket(s)`),w.sendChatCreateTicketResult(f.requestId,{ok:!0,issueKey:N,childKeys:V});return}f.triggerComment.trim()&&await b.jira.addTriggerComment(N,`${f.triggerComment.trim()}`+(!b.authored&&f.requestedBy?`
|
|
682
|
+
|
|
683
|
+
_(requested by ${f.requestedBy} via Allwright)_`:"")),m.info(`Compose created ${N}`+(f.requestedBy?` for ${f.requestedBy}`:"")+(f.triggerComment?` with trigger "${f.triggerComment.trim()}"`:"")),w.sendChatCreateTicketResult(f.requestId,{ok:!0,issueKey:N})}catch(b){w.sendChatCreateTicketResult(f.requestId,{ok:!1,issueKey:"",error:b instanceof Error?b.message:String(b)})}},onAuditStart:async f=>{let g=S(f.projectId);if(!g){w.sendAuditStartResult(f.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{m.info(`Audit (${f.role}) starting on ${g.project.repoName}`+(f.scope.kind!=="repo"?` scoped to ${f.scope.kind}:${f.scope.ref}`:""));let b=await Yr({projectId:f.projectId,repoPath:g.repoPath,role:f.role,scope:f.scope,model:f.model,claudeBin:r.claudeBin,jira:n(g.project.repoName)});if(!b.ok){w.sendAuditStartResult(f.requestId,{ok:!1,error:b.error});return}w.sendAuditStartResult(f.requestId,{ok:!0,audit:b.audit})}catch(b){w.sendAuditStartResult(f.requestId,{ok:!1,error:b instanceof Error?b.message:String(b)})}},onAuditList:async f=>{try{w.sendAuditListResult(f.requestId,{ok:!0,audits:Bc(f.projectId)})}catch(g){w.sendAuditListResult(f.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onAuditGet:async f=>{try{let g=Zc(f.projectId,f.auditId);if(!g){w.sendAuditGetResult(f.requestId,{ok:!1,error:"audit not found on this runner"});return}w.sendAuditGetResult(f.requestId,{ok:!0,audit:g})}catch(g){w.sendAuditGetResult(f.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onAuditReview:async f=>{try{let g=Xi(f.projectId,f.auditId,{selected:f.selected,ticketed:f.ticketed,verdicts:f.verdicts,verdictBy:f.verdictBy});if(!g){w.sendAuditReviewResult(f.requestId,{ok:!1,error:"audit not found on this runner"});return}let b=S(f.projectId);if(b&&f.verdicts.length){let I=[];for(let N of f.verdicts){if(N.verdict==="valid"||g.lessonsWritten.includes(N.findingId))continue;let V=g.findings.find(W=>W.id===N.findingId);V&&(to(b.repoPath,g.role,Jc(V,N.verdict,N.note,f.verdictBy)),I.push(N.findingId),m.info(`Lesson written (${g.role}): ${N.verdict} \u2014 ${V.title.slice(0,60)}`))}I.length&&(g=Xi(f.projectId,f.auditId,{markLessonsWritten:I})??g)}w.sendAuditReviewResult(f.requestId,{ok:!0,audit:g})}catch(g){w.sendAuditReviewResult(f.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onKnowledgeList:async f=>{let g=S(f.projectId);if(!g){w.sendKnowledgeListResult(f.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{w.sendKnowledgeListResult(f.requestId,{ok:!0,files:Xc(g.repoPath)})}catch(b){w.sendKnowledgeListResult(f.requestId,{ok:!1,error:b instanceof Error?b.message:String(b)})}},onKnowledgeSave:async f=>{let g=S(f.projectId);if(!g){w.sendKnowledgeSaveResult(f.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{f.append?to(g.repoPath,f.role,Yc(f.content,f.by),f.level):Qc(g.repoPath,f.role,f.level,f.source,f.name,f.content),m.info(`Knowledge ${f.append?"taught":"saved"}: ${f.role}/${f.level}/${f.name}`),w.sendKnowledgeSaveResult(f.requestId,{ok:!0})}catch(b){w.sendKnowledgeSaveResult(f.requestId,{ok:!1,error:b instanceof Error?b.message:String(b)})}},onEpicList:async f=>{let g=S(f.projectId);if(!g){w.sendEpicListResult(f.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{let b=n(g.project.repoName);if(f.epicKey){let I=await b.epicChildren(f.epicKey);w.sendEpicListResult(f.requestId,{ok:!0,children:I})}else{let I=await b.searchEpics(g.project.jiraProjectKey);w.sendEpicListResult(f.requestId,{ok:!0,epics:I})}}catch(b){w.sendEpicListResult(f.requestId,{ok:!1,error:b instanceof Error?b.message:String(b)})}},onEpicSuggest:async f=>{let g=S(f.projectId);if(!g){w.sendEpicSuggestResult(f.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{let b=n(g.project.repoName),I=await b.epicChildren(f.epicKey),N=Ic(I);if(!N.length){w.sendEpicSuggestResult(f.requestId,{ok:!1,error:`every child of ${f.epicKey} is already done or in an agent's hands \u2014 nothing to sequence`});return}if(N.length===1){w.sendEpicSuggestResult(f.requestId,{ok:!0,issueKey:N[0].key,reason:"It's the only pending ticket left in this epic.",considered:1});return}let V=await Promise.all(N.slice(0,12).map(async H=>{try{let be=await b.getIssue(H.key);return{...H,description:be.description}}catch{return{...H,description:""}}})),W=(await b.getIssue(f.epicKey).catch(()=>null))?.summary??"";m.info(`Epic suggest: weighing ${V.length} pending children of ${f.epicKey}`);let J=await Ue.run({repoPath:g.repoPath,prompt:Ac(f.epicKey,W,V),timeoutSeconds:150,bin:r.claudeBin,mode:"read_only",maxTurns:20,sessionId:(0,Wo.randomUUID)(),model:f.model||"claude-sonnet-5",onLog:()=>{}}),z=Rc(J.resultText,V.map(H=>H.key));if("error"in z){w.sendEpicSuggestResult(f.requestId,{ok:!1,error:z.error});return}m.info(`Epic suggest: ${f.epicKey} -> do ${z.issueKey} first`),w.sendEpicSuggestResult(f.requestId,{ok:!0,issueKey:z.issueKey,reason:z.reason,considered:V.length})}catch(b){w.sendEpicSuggestResult(f.requestId,{ok:!1,error:b instanceof Error?b.message:String(b)})}},onTeamCreds:async f=>{try{let g=he()??r;if(g.github?.token&&!g.github.login)try{let{GitHubClient:I}=await Promise.resolve().then(()=>(ut(),Qr));g.github.login=await new I(g.github.token).whoami(),ie(g)}catch{}let b=kc(g,f.emails);w.sendTeamCredsResult(f.requestId,{ok:!0,...b})}catch(g){w.sendTeamCredsResult(f.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onJiraUsers:async f=>{try{let g=await e.searchUsers(f.query);w.sendJiraUsersResult(f.requestId,{ok:!0,users:g})}catch(g){w.sendJiraUsersResult(f.requestId,{ok:!1,users:[],error:g instanceof Error?g.message:String(g)})}}});p.transport=w,d=new Ls(r,n,w);let j=Object.values(rn()).filter(f=>f.kind==="implement").map(f=>f.repoPath);zi(Object.values(r.repos).map(f=>f.path),j).catch(()=>{}),w.start(),d.start();let U=()=>{m.info("shutting down"),d.stop(),w.stop(),Ma(process.pid),process.exit(0)};process.on("SIGINT",U),process.on("SIGTERM",U)}ae.command("start").description("Start watching Jira. Runs in the background by default \u2014 close this terminal and it keeps going until you run `allwright stop`. Use --foreground to keep it attached (e.g. under systemd).").option("--foreground","run in this terminal instead of detaching to the background").action(async r=>{let e=Q();if(r.foreground){Yg(e);return}let t=zr();if(t&&wn(t)){m.info(`already running in the background (pid ${t}). Use \`allwright status\` or \`stop\`.`);return}let n=Oa(),s=(0,Hn.spawn)(process.execPath,[process.argv[1],"start","--foreground"],{detached:!0,stdio:["ignore",n,n]});s.unref(),Na(s.pid),m.info(`Runner started in the background (pid ${s.pid}).`),m.info(`Logs: ${cs()}`),m.info("It will keep polling Jira until you run `allwright stop` \u2014 closing this terminal is fine.")});ae.command("stop").description("Stop the background runner started by `start`").action(()=>{let r=zr();if(!r||!wn(r)){m.info("no background runner is running"),r&&pn.default.rmSync(bn(),{force:!0});return}process.kill(r,"SIGTERM"),m.info(`stop signal sent (pid ${r})`)});ae.command("status").description("Check whether the background runner is running").action(()=>{let r=zr();r&&wn(r)?m.info(`running in the background (pid ${r})`):m.info("not running")});ae.parseAsync().catch(r=>{m.error(r instanceof Error?r.message:String(r)),process.exit(1)});
|