allwright 1.63.0 → 1.65.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/allwright.js +228 -228
- package/package.json +1 -1
package/bin/allwright.js
CHANGED
|
@@ -1,41 +1,41 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var
|
|
3
|
-
`).replace(/^/gm," ".repeat(i))}let u=[`Usage: ${n.commandUsage(e)}`,""],
|
|
2
|
+
"use strict";var wm=Object.create;var ia=Object.defineProperty;var vm=Object.getOwnPropertyDescriptor;var km=Object.getOwnPropertyNames;var _m=Object.getPrototypeOf,Sm=Object.prototype.hasOwnProperty;var be=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var le=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}},un=(t,e)=>{for(var n in e)ia(t,n,{get:e[n],enumerable:!0})},Tm=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of km(e))!Sm.call(t,s)&&s!==n&&ia(t,s,{get:()=>e[s],enumerable:!(r=vm(e,s))||r.enumerable});return t};var I=(t,e,n)=>(n=t!=null?wm(_m(t)):{},Tm(e||!t||!t.__esModule?ia(n,"default",{value:t,enumerable:!0}):n,t));var Os=le(aa=>{var wi=class extends Error{constructor(e,n,r){super(r),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=n,this.exitCode=e,this.nestedError=void 0}},oa=class extends wi{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};aa.CommanderError=wi;aa.InvalidArgumentError=oa});var vi=le(ca=>{var{InvalidArgumentError:xm}=Os(),la=class{constructor(e,n){switch(this.description=n||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,n){return n===this.defaultValue||!Array.isArray(n)?[e]:n.concat(e)}default(e,n){return this.defaultValue=e,this.defaultValueDescription=n,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(n,r)=>{if(!this.argChoices.includes(n))throw new xm(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(n,r):n},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Rm(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}ca.Argument=la;ca.humanReadableArgName=Rm});var da=le(Bc=>{var{humanReadableArgName:Im}=vi(),ua=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let n=e.commands.filter(s=>!s._hidden),r=e._getHelpCommand();return r&&!r._hidden&&n.push(r),this.sortSubcommands&&n.sort((s,i)=>s.name().localeCompare(i.name())),n}compareOptions(e,n){let r=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return r(e).localeCompare(r(n))}visibleOptions(e){let n=e.options.filter(s=>!s.hidden),r=e._getHelpOption();if(r&&!r.hidden){let s=r.short&&e._findOption(r.short),i=r.long&&e._findOption(r.long);!s&&!i?n.push(r):r.long&&!i?n.push(e.createOption(r.long,r.description)):r.short&&!s&&n.push(e.createOption(r.short,r.description))}return this.sortOptions&&n.sort(this.compareOptions),n}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let n=[];for(let r=e.parent;r;r=r.parent){let s=r.options.filter(i=>!i.hidden);n.push(...s)}return this.sortOptions&&n.sort(this.compareOptions),n}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(n=>{n.description=n.description||e._argsDescription[n.name()]||""}),e.registeredArguments.find(n=>n.description)?e.registeredArguments:[]}subcommandTerm(e){let n=e.registeredArguments.map(r=>Im(r)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(n?" "+n:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,n){return n.visibleCommands(e).reduce((r,s)=>Math.max(r,n.subcommandTerm(s).length),0)}longestOptionTermLength(e,n){return n.visibleOptions(e).reduce((r,s)=>Math.max(r,n.optionTerm(s).length),0)}longestGlobalOptionTermLength(e,n){return n.visibleGlobalOptions(e).reduce((r,s)=>Math.max(r,n.optionTerm(s).length),0)}longestArgumentTermLength(e,n){return n.visibleArguments(e).reduce((r,s)=>Math.max(r,n.argumentTerm(s).length),0)}commandUsage(e){let n=e._name;e._aliases[0]&&(n=n+"|"+e._aliases[0]);let r="";for(let s=e.parent;s;s=s.parent)r=s.name()+" "+r;return r+n+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let n=[];return e.argChoices&&n.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&n.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&n.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&n.push(`env: ${e.envVar}`),n.length>0?`${e.description} (${n.join(", ")})`:e.description}argumentDescription(e){let n=[];if(e.argChoices&&n.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&n.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),n.length>0){let r=`(${n.join(", ")})`;return e.description?`${e.description} ${r}`:r}return e.description}formatHelp(e,n){let r=n.padWidth(e,n),s=n.helpWidth||80,i=2,o=2;function l(_,S){if(S){let A=`${_.padEnd(r+o)}${S}`;return n.wrap(A,s-i,r+o)}return _}function c(_){return _.join(`
|
|
3
|
+
`).replace(/^/gm," ".repeat(i))}let u=[`Usage: ${n.commandUsage(e)}`,""],h=n.commandDescription(e);h.length>0&&(u=u.concat([n.wrap(h,s,0),""]));let f=n.visibleArguments(e).map(_=>l(n.argumentTerm(_),n.argumentDescription(_)));f.length>0&&(u=u.concat(["Arguments:",c(f),""]));let b=n.visibleOptions(e).map(_=>l(n.optionTerm(_),n.optionDescription(_)));if(b.length>0&&(u=u.concat(["Options:",c(b),""])),this.showGlobalOptions){let _=n.visibleGlobalOptions(e).map(S=>l(n.optionTerm(S),n.optionDescription(S)));_.length>0&&(u=u.concat(["Global Options:",c(_),""]))}let w=n.visibleCommands(e).map(_=>l(n.subcommandTerm(_),n.subcommandDescription(_)));return w.length>0&&(u=u.concat(["Commands:",c(w),""])),u.join(`
|
|
4
4
|
`)}padWidth(e,n){return Math.max(n.longestOptionTermLength(e,n),n.longestGlobalOptionTermLength(e,n),n.longestSubcommandTermLength(e,n),n.longestArgumentTermLength(e,n))}wrap(e,n,r,s=40){let i=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",o=new RegExp(`[\\n][${i}]+`);if(e.match(o))return e;let l=n-r;if(l<s)return e;let c=e.slice(0,r),u=e.slice(r).replace(`\r
|
|
5
5
|
`,`
|
|
6
|
-
`),
|
|
7
|
-
|.{1,${l-1}}([${b}]|$)|[^${b}]+?([${b}]|$)`,"g"),
|
|
8
|
-
`?"":(
|
|
9
|
-
`)}};
|
|
6
|
+
`),h=" ".repeat(r),b="\\s\u200B",w=new RegExp(`
|
|
7
|
+
|.{1,${l-1}}([${b}]|$)|[^${b}]+?([${b}]|$)`,"g"),_=u.match(w)||[];return c+_.map((S,A)=>S===`
|
|
8
|
+
`?"":(A>0?h:"")+S.trimEnd()).join(`
|
|
9
|
+
`)}};Bc.Help=ua});var ma=le(fa=>{var{InvalidArgumentError:Am}=Os(),ha=class{constructor(e,n){this.flags=e,this.description=n||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let r=Cm(e);this.short=r.shortFlag,this.long=r.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,n){return this.defaultValue=e,this.defaultValueDescription=n,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let n=e;return typeof e=="string"&&(n={[e]:!0}),this.implied=Object.assign(this.implied||{},n),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,n){return n===this.defaultValue||!Array.isArray(n)?[e]:n.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(n,r)=>{if(!this.argChoices.includes(n))throw new Am(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(n,r):n},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return Em(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},pa=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(n=>{n.negate?this.negativeOptions.set(n.attributeName(),n):this.positiveOptions.set(n.attributeName(),n)}),this.negativeOptions.forEach((n,r)=>{this.positiveOptions.has(r)&&this.dualOptions.add(r)})}valueFromOption(e,n){let r=n.attributeName();if(!this.dualOptions.has(r))return!0;let s=this.negativeOptions.get(r).presetArg,i=s!==void 0?s:!1;return n.negate===(i===e)}};function Em(t){return t.split("-").reduce((e,n)=>e+n[0].toUpperCase()+n.slice(1))}function Cm(t){let e,n,r=t.split(/[ |,]+/);return r.length>1&&!/^[[<]/.test(r[1])&&(e=r.shift()),n=r.shift(),!e&&/^-[^-]$/.test(n)&&(e=n,n=void 0),{shortFlag:e,longFlag:n}}fa.Option=ha;fa.DualOptions=pa});var Kc=le(Hc=>{function $m(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);let n=[];for(let r=0;r<=t.length;r++)n[r]=[r];for(let r=0;r<=e.length;r++)n[0][r]=r;for(let r=1;r<=e.length;r++)for(let s=1;s<=t.length;s++){let i=1;t[s-1]===e[r-1]?i=0:i=1,n[s][r]=Math.min(n[s-1][r]+1,n[s][r-1]+1,n[s-1][r-1]+i),s>1&&r>1&&t[s-1]===e[r-2]&&t[s-2]===e[r-1]&&(n[s][r]=Math.min(n[s][r],n[s-2][r-2]+1))}return n[t.length][e.length]}function Pm(t,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let n=t.startsWith("--");n&&(t=t.slice(2),e=e.map(o=>o.slice(2)));let r=[],s=3,i=.4;return e.forEach(o=>{if(o.length<=1)return;let l=$m(t,o),c=Math.max(t.length,o.length);(c-l)/c>i&&(l<s?(s=l,r=[o]):l===s&&r.push(o))}),r.sort((o,l)=>o.localeCompare(l)),n&&(r=r.map(o=>`--${o}`)),r.length>1?`
|
|
10
10
|
(Did you mean one of ${r.join(", ")}?)`:r.length===1?`
|
|
11
|
-
(Did you mean ${r[0]}?)`:""}
|
|
12
|
-
- specify the name in Command constructor or using .name()`);return n=n||{},n.isDefault&&(this._defaultCommandName=e._name),(n.noHelp||n.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,n){return new
|
|
13
|
-
Expecting one of '${r.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(n):this._lifeCycleHooks[e]=[n],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=n=>{if(n.code!=="commander.executeSubCommandAsync")throw n},this}_exit(e,n,r){this._exitCallback&&this._exitCallback(new
|
|
14
|
-
- already used by option '${n.flags}'`)}this.options.push(e)}_registerCommand(e){let n=s=>[s.name()].concat(s.aliases()),r=n(e).find(s=>this._findCommand(s));if(r){let s=n(this._findCommand(r)).join("|"),i=n(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let n=e.name(),r=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(r,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(r,e.defaultValue,"default");let s=(i,o,l)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let c=this.getOptionValue(r);i!==null&&e.parseArg?i=this._callParseArg(e,i,c,o):i!==null&&e.variadic&&(i=e._concatValue(i,c)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(r,i,l)};return this.on("option:"+n,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;s(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+n,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;s(i,o,"env")}),this}_optionEx(e,n,r,s,i){if(typeof n=="object"&&n instanceof
|
|
11
|
+
(Did you mean ${r[0]}?)`:""}Hc.suggestSimilar=Pm});var Jc=le(Vc=>{var jm=require("node:events").EventEmitter,ga=require("node:child_process"),Lt=require("node:path"),ya=require("node:fs"),we=require("node:process"),{Argument:Nm,humanReadableArgName:Om}=vi(),{CommanderError:ba}=Os(),{Help:Mm}=da(),{Option:Gc,DualOptions:zm}=ma(),{suggestSimilar:Zc}=Kc(),wa=class t extends jm{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:n=>we.stdout.write(n),writeErr:n=>we.stderr.write(n),getOutHelpWidth:()=>we.stdout.isTTY?we.stdout.columns:void 0,getErrHelpWidth:()=>we.stderr.isTTY?we.stderr.columns:void 0,outputError:(n,r)=>r(n)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let n=this;n;n=n.parent)e.push(n);return e}command(e,n,r){let s=n,i=r;typeof s=="object"&&s!==null&&(i=s,s=null),i=i||{};let[,o,l]=e.match(/([^ ]+) *(.*)/),c=this.createCommand(o);return s&&(c.description(s),c._executableHandler=!0),i.isDefault&&(this._defaultCommandName=c._name),c._hidden=!!(i.noHelp||i.hidden),c._executableFile=i.executableFile||null,l&&c.arguments(l),this._registerCommand(c),c.parent=this,c.copyInheritedSettings(this),s?this:c}createCommand(e){return new t(e)}createHelp(){return Object.assign(new Mm,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,n){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
12
|
+
- specify the name in Command constructor or using .name()`);return n=n||{},n.isDefault&&(this._defaultCommandName=e._name),(n.noHelp||n.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,n){return new Nm(e,n)}argument(e,n,r,s){let i=this.createArgument(e,n);return typeof r=="function"?i.default(s).argParser(r):i.default(r),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(n=>{this.argument(n)}),this}addArgument(e){let n=this.registeredArguments.slice(-1)[0];if(n&&n.variadic)throw new Error(`only the last argument can be variadic '${n.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,n){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,r,s]=e.match(/([^ ]+) *(.*)/),i=n??"display help for command",o=this.createCommand(r);return o.helpOption(!1),s&&o.arguments(s),i&&o.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(e,n){return typeof e!="object"?(this.helpCommand(e,n),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,n){let r=["preSubcommand","preAction","postAction"];if(!r.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
13
|
+
Expecting one of '${r.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(n):this._lifeCycleHooks[e]=[n],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=n=>{if(n.code!=="commander.executeSubCommandAsync")throw n},this}_exit(e,n,r){this._exitCallback&&this._exitCallback(new ba(e,n,r)),we.exit(e)}action(e){let n=r=>{let s=this.registeredArguments.length,i=r.slice(0,s);return this._storeOptionsAsProperties?i[s]=this:i[s]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=n,this}createOption(e,n){return new Gc(e,n)}_callParseArg(e,n,r,s){try{return e.parseArg(n,r)}catch(i){if(i.code==="commander.invalidArgument"){let o=`${s} ${i.message}`;this.error(o,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){let n=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(n){let r=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${r}'
|
|
14
|
+
- already used by option '${n.flags}'`)}this.options.push(e)}_registerCommand(e){let n=s=>[s.name()].concat(s.aliases()),r=n(e).find(s=>this._findCommand(s));if(r){let s=n(this._findCommand(r)).join("|"),i=n(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let n=e.name(),r=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(r,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(r,e.defaultValue,"default");let s=(i,o,l)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let c=this.getOptionValue(r);i!==null&&e.parseArg?i=this._callParseArg(e,i,c,o):i!==null&&e.variadic&&(i=e._concatValue(i,c)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(r,i,l)};return this.on("option:"+n,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;s(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+n,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;s(i,o,"env")}),this}_optionEx(e,n,r,s,i){if(typeof n=="object"&&n instanceof Gc)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(n,r);if(o.makeOptionMandatory(!!e.mandatory),typeof s=="function")o.default(i).argParser(s);else if(s instanceof RegExp){let l=s;s=(c,u)=>{let h=l.exec(c);return h?h[0]:u},o.default(i).argParser(s)}else o.default(s);return this.addOption(o)}option(e,n,r,s){return this._optionEx({},e,n,r,s)}requiredOption(e,n,r,s){return this._optionEx({mandatory:!0},e,n,r,s)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,n){return this.setOptionValueWithSource(e,n,void 0)}setOptionValueWithSource(e,n,r){return this._storeOptionsAsProperties?this[e]=n:this._optionValues[e]=n,this._optionValueSources[e]=r,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let n;return this._getCommandAndAncestors().forEach(r=>{r.getOptionValueSource(e)!==void 0&&(n=r.getOptionValueSource(e))}),n}_prepareUserArgs(e,n){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(n=n||{},e===void 0&&n.from===void 0){we.versions?.electron&&(n.from="electron");let s=we.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(n.from="eval")}e===void 0&&(e=we.argv),this.rawArgs=e.slice();let r;switch(n.from){case void 0:case"node":this._scriptPath=e[1],r=e.slice(2);break;case"electron":we.defaultApp?(this._scriptPath=e[1],r=e.slice(2)):r=e.slice(1);break;case"user":r=e.slice(0);break;case"eval":r=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${n.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",r}parse(e,n){let r=this._prepareUserArgs(e,n);return this._parseCommand([],r),this}async parseAsync(e,n){let r=this._prepareUserArgs(e,n);return await this._parseCommand([],r),this}_executeSubCommand(e,n){n=n.slice();let r=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function i(h,f){let b=Lt.resolve(h,f);if(ya.existsSync(b))return b;if(s.includes(Lt.extname(f)))return;let w=s.find(_=>ya.existsSync(`${b}${_}`));if(w)return`${b}${w}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,l=this._executableDir||"";if(this._scriptPath){let h;try{h=ya.realpathSync(this._scriptPath)}catch{h=this._scriptPath}l=Lt.resolve(Lt.dirname(h),l)}if(l){let h=i(l,o);if(!h&&!e._executableFile&&this._scriptPath){let f=Lt.basename(this._scriptPath,Lt.extname(this._scriptPath));f!==this._name&&(h=i(l,`${f}-${e._name}`))}o=h||o}r=s.includes(Lt.extname(o));let c;we.platform!=="win32"?r?(n.unshift(o),n=Wc(we.execArgv).concat(n),c=ga.spawn(we.argv[0],n,{stdio:"inherit"})):c=ga.spawn(o,n,{stdio:"inherit"}):(n.unshift(o),n=Wc(we.execArgv).concat(n),c=ga.spawn(we.execPath,n,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{we.on(f,()=>{c.killed===!1&&c.exitCode===null&&c.kill(f)})});let u=this._exitCallback;c.on("close",h=>{h=h??1,u?u(new ba(h,"commander.executeSubCommandAsync","(close)")):we.exit(h)}),c.on("error",h=>{if(h.code==="ENOENT"){let f=l?`searched for local subcommand relative to directory '${l}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",b=`'${o}' does not exist
|
|
15
15
|
- if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
16
16
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
17
|
-
- ${f}`;throw new Error(b)}else if(
|
|
17
|
+
- ${f}`;throw new Error(b)}else if(h.code==="EACCES")throw new Error(`'${o}' not executable`);if(!u)we.exit(1);else{let f=new ba(1,"commander.executeSubCommandAsync","(error)");f.nestedError=h,u(f)}}),this.runningCommand=c}_dispatchSubcommand(e,n,r){let s=this._findCommand(e);s||this.help({error:!0});let i;return i=this._chainOrCallSubCommandHook(i,s,"preSubcommand"),i=this._chainOrCall(i,()=>{if(s._executableHandler)this._executeSubCommand(s,n.concat(r));else return s._parseCommand(n,r)}),i}_dispatchHelpCommand(e){e||this.help();let n=this._findCommand(e);return n&&!n._executableHandler&&n.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,n)=>{e.required&&this.args[n]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(r,s,i)=>{let o=s;if(s!==null&&r.parseArg){let l=`error: command-argument value '${s}' is invalid for argument '${r.name()}'.`;o=this._callParseArg(r,s,i,l)}return o};this._checkNumberOfArguments();let n=[];this.registeredArguments.forEach((r,s)=>{let i=r.defaultValue;r.variadic?s<this.args.length?(i=this.args.slice(s),r.parseArg&&(i=i.reduce((o,l)=>e(r,l,o),r.defaultValue))):i===void 0&&(i=[]):s<this.args.length&&(i=this.args[s],r.parseArg&&(i=e(r,i,r.defaultValue))),n[s]=i}),this.processedArgs=n}_chainOrCall(e,n){return e&&e.then&&typeof e.then=="function"?e.then(()=>n()):n()}_chainOrCallHooks(e,n){let r=e,s=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[n]!==void 0).forEach(i=>{i._lifeCycleHooks[n].forEach(o=>{s.push({hookedCommand:i,callback:o})})}),n==="postAction"&&s.reverse(),s.forEach(i=>{r=this._chainOrCall(r,()=>i.callback(i.hookedCommand,this))}),r}_chainOrCallSubCommandHook(e,n,r){let s=e;return this._lifeCycleHooks[r]!==void 0&&this._lifeCycleHooks[r].forEach(i=>{s=this._chainOrCall(s,()=>i(this,n))}),s}_parseCommand(e,n){let r=this.parseOptions(n);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(r.operands),n=r.unknown,this.args=e.concat(n),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),n);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(n),this._dispatchSubcommand(this._defaultCommandName,e,n);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(r.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{r.unknown.length>0&&this.unknownOption(r.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){s(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(i,e,n)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(i))s(),this._processArguments(),this.parent.emit(i,e,n);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,n);this.listenerCount("command:*")?this.emit("command:*",e,n):this.commands.length?this.unknownCommand():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(n=>n._name===e||n._aliases.includes(e))}_findOption(e){return this.options.find(n=>n.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(n=>{n.mandatory&&e.getOptionValue(n.attributeName())===void 0&&e.missingMandatoryOptionValue(n)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(r=>{let s=r.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});e.filter(r=>r.conflictsWith.length>0).forEach(r=>{let s=e.find(i=>r.conflictsWith.includes(i.attributeName()));s&&this._conflictingOption(r,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let n=[],r=[],s=n,i=e.slice();function o(c){return c.length>1&&c[0]==="-"}let l=null;for(;i.length;){let c=i.shift();if(c==="--"){s===r&&s.push(c),s.push(...i);break}if(l&&!o(c)){this.emit(`option:${l.name()}`,c);continue}if(l=null,o(c)){let u=this._findOption(c);if(u){if(u.required){let h=i.shift();h===void 0&&this.optionMissingArgument(u),this.emit(`option:${u.name()}`,h)}else if(u.optional){let h=null;i.length>0&&!o(i[0])&&(h=i.shift()),this.emit(`option:${u.name()}`,h)}else this.emit(`option:${u.name()}`);l=u.variadic?u:null;continue}}if(c.length>2&&c[0]==="-"&&c[1]!=="-"){let u=this._findOption(`-${c[1]}`);if(u){u.required||u.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${u.name()}`,c.slice(2)):(this.emit(`option:${u.name()}`),i.unshift(`-${c.slice(2)}`));continue}}if(/^--[^=]+=/.test(c)){let u=c.indexOf("="),h=this._findOption(c.slice(0,u));if(h&&(h.required||h.optional)){this.emit(`option:${h.name()}`,c.slice(u+1));continue}}if(o(c)&&(s=r),(this._enablePositionalOptions||this._passThroughOptions)&&n.length===0&&r.length===0){if(this._findCommand(c)){n.push(c),i.length>0&&r.push(...i);break}else if(this._getHelpCommand()&&c===this._getHelpCommand().name()){n.push(c),i.length>0&&n.push(...i);break}else if(this._defaultCommandName){r.push(c),i.length>0&&r.push(...i);break}}if(this._passThroughOptions){s.push(c),i.length>0&&s.push(...i);break}s.push(c)}return{operands:n,unknown:r}}opts(){if(this._storeOptionsAsProperties){let e={},n=this.options.length;for(let r=0;r<n;r++){let s=this.options[r].attributeName();e[s]=s===this._versionOptionName?this._version:this[s]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,n)=>Object.assign(e,n.opts()),{})}error(e,n){this._outputConfiguration.outputError(`${e}
|
|
18
18
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
19
19
|
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
20
|
-
`),this.outputHelp({error:!0}));let r=n||{},s=r.exitCode||1,i=r.code||"commander.error";this._exit(s,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in we.env){let n=e.attributeName();(this.getOptionValue(n)===void 0||["default","config","env"].includes(this.getOptionValueSource(n)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,we.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new
|
|
21
|
-
`),this._exit(0,"commander.version",e)}),this}description(e,n){return e===void 0&&n===void 0?this._description:(this._description=e,n&&(this._argsDescription=n),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let n=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(n=this.commands[this.commands.length-1]),e===n._name)throw new Error("Command alias can't be the same as its name");let r=this.parent?._findCommand(e);if(r){let s=[r.name()].concat(r.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return n._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(n=>this.alias(n)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let n=this.registeredArguments.map(r=>
|
|
20
|
+
`),this.outputHelp({error:!0}));let r=n||{},s=r.exitCode||1,i=r.code||"commander.error";this._exit(s,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in we.env){let n=e.attributeName();(this.getOptionValue(n)===void 0||["default","config","env"].includes(this.getOptionValueSource(n)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,we.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new zm(this.options),n=r=>this.getOptionValue(r)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(r));this.options.filter(r=>r.implied!==void 0&&n(r.attributeName())&&e.valueFromOption(this.getOptionValue(r.attributeName()),r)).forEach(r=>{Object.keys(r.implied).filter(s=>!n(s)).forEach(s=>{this.setOptionValueWithSource(s,r.implied[s],"implied")})})}missingArgument(e){let n=`error: missing required argument '${e}'`;this.error(n,{code:"commander.missingArgument"})}optionMissingArgument(e){let n=`error: option '${e.flags}' argument missing`;this.error(n,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let n=`error: required option '${e.flags}' not specified`;this.error(n,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,n){let r=o=>{let l=o.attributeName(),c=this.getOptionValue(l),u=this.options.find(f=>f.negate&&l===f.attributeName()),h=this.options.find(f=>!f.negate&&l===f.attributeName());return u&&(u.presetArg===void 0&&c===!1||u.presetArg!==void 0&&c===u.presetArg)?u:h||o},s=o=>{let l=r(o),c=l.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${l.envVar}'`:`option '${l.flags}'`},i=`error: ${s(e)} cannot be used with ${s(n)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let n="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],i=this;do{let o=i.createHelp().visibleOptions(i).filter(l=>l.long).map(l=>l.long);s=s.concat(o),i=i.parent}while(i&&!i._enablePositionalOptions);n=Zc(e,s)}let r=`error: unknown option '${e}'${n}`;this.error(r,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let n=this.registeredArguments.length,r=n===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${n} argument${r} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],n="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(i=>{s.push(i.name()),i.alias()&&s.push(i.alias())}),n=Zc(e,s)}let r=`error: unknown command '${e}'${n}`;this.error(r,{code:"commander.unknownCommand"})}version(e,n,r){if(e===void 0)return this._version;this._version=e,n=n||"-V, --version",r=r||"output the version number";let s=this.createOption(n,r);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
21
|
+
`),this._exit(0,"commander.version",e)}),this}description(e,n){return e===void 0&&n===void 0?this._description:(this._description=e,n&&(this._argsDescription=n),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let n=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(n=this.commands[this.commands.length-1]),e===n._name)throw new Error("Command alias can't be the same as its name");let r=this.parent?._findCommand(e);if(r){let s=[r.name()].concat(r.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return n._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(n=>this.alias(n)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let n=this.registeredArguments.map(r=>Om(r));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?n:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=Lt.basename(e,Lt.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let n=this.createHelp();return n.helpWidth===void 0&&(n.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),n.formatHelp(this,n)}_getHelpContext(e){e=e||{};let n={error:!!e.error},r;return n.error?r=s=>this._outputConfiguration.writeErr(s):r=s=>this._outputConfiguration.writeOut(s),n.write=e.write||r,n.command=this,n}outputHelp(e){let n;typeof e=="function"&&(n=e,e=void 0);let r=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",r)),this.emit("beforeHelp",r);let s=this.helpInformation(r);if(n&&(s=n(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");r.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",r),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",r))}helpOption(e,n){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",n=n??"display help for command",this._helpOption=this.createOption(e,n),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let n=we.exitCode||0;n===0&&e&&typeof e!="function"&&e.error&&(n=1),this._exit(n,"commander.help","(outputHelp)")}addHelpText(e,n){let r=["beforeAll","before","after","afterAll"];if(!r.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
22
22
|
Expecting one of '${r.join("', '")}'`);let s=`${e}Help`;return this.on(s,i=>{let o;typeof n=="function"?o=n({error:i.error,command:i.command}):o=n,o&&i.write(`${o}
|
|
23
|
-
`)}),this}_outputHelpIfRequested(e){let n=this._getHelpOption();n&&e.find(s=>n.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Gc(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let n,r="127.0.0.1",s="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?n=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(n=i[1],/^\d+$/.test(i[3])?s=i[3]:r=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(n=i[1],r=i[3],s=i[4]),n&&s!=="0"?`${n}=${r}:${parseInt(s)+1}`:e})}Zc.Command=ba});var Xc=ae(rt=>{var{Argument:Vc}=wi(),{Command:wa}=Wc(),{CommanderError:Em,InvalidArgumentError:Jc}=Os(),{Help:Cm}=ua(),{Option:Yc}=fa();rt.program=new wa;rt.createCommand=t=>new wa(t);rt.createOption=(t,e)=>new Yc(t,e);rt.createArgument=(t,e)=>new Vc(t,e);rt.Command=wa;rt.Option=Yc;rt.Argument=Vc;rt.Help=Cm;rt.CommanderError=Em;rt.InvalidArgumentError=Jc;rt.InvalidOptionArgumentError=Jc});var se,va,D,Tt,Ms=be(()=>{(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function n(s){throw new Error}t.assertNever=n,t.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},t.getValidEnumValues=s=>{let i=t.objectKeys(s).filter(l=>typeof s[s[l]]!="number"),o={};for(let l of i)o[l]=s[l];return t.objectValues(o)},t.objectValues=s=>t.objectKeys(s).map(function(i){return s[i]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},t.find=(s,i)=>{for(let o of s)if(i(o))return o},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(se||(se={}));(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(va||(va={}));D=se.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Tt=t=>{switch(typeof t){case"undefined":return D.undefined;case"string":return D.string;case"number":return Number.isNaN(t)?D.nan:D.number;case"boolean":return D.boolean;case"function":return D.function;case"bigint":return D.bigint;case"symbol":return D.symbol;case"object":return Array.isArray(t)?D.array:t===null?D.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?D.promise:typeof Map<"u"&&t instanceof Map?D.map:typeof Set<"u"&&t instanceof Set?D.set:typeof Date<"u"&&t instanceof Date?D.date:D.object;default:return D.unknown}}});var I,$m,Be,vi=be(()=>{Ms();I=se.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"]),$m=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Be=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(i){return i.message},r={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)r._errors.push(n(o));else{let l=r,c=0;for(;c<o.path.length;){let u=o.path[c];c===o.path.length-1?(l[u]=l[u]||{_errors:[]},l[u]._errors.push(n(o))):l[u]=l[u]||{_errors:[]},l=l[u],c++}}};return s(this),r}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,se.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];n[i]=n[i]||[],n[i].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};Be.create=t=>new Be(t)});var Pm,Ut,ka=be(()=>{vi();Ms();Pm=(t,e)=>{let n;switch(t.code){case I.invalid_type:t.received===D.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case I.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,se.jsonStringifyReplacer)}`;break;case I.unrecognized_keys:n=`Unrecognized key(s) in object: ${se.joinValues(t.keys,", ")}`;break;case I.invalid_union:n="Invalid input";break;case I.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${se.joinValues(t.options)}`;break;case I.invalid_enum_value:n=`Invalid enum value. Expected ${se.joinValues(t.options)}, received '${t.received}'`;break;case I.invalid_arguments:n="Invalid function arguments";break;case I.invalid_return_type:n="Invalid function return type";break;case I.invalid_date:n="Invalid date";break;case I.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:se.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case I.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case I.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case I.custom:n="Invalid input";break;case I.invalid_intersection_types:n="Intersection results could not be merged";break;case I.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case I.not_finite:n="Number must be finite";break;default:n=e.defaultError,se.assertNever(t)}return{message:n}},Ut=Pm});function jm(t){tu=t}function Hr(){return tu}var tu,ki=be(()=>{ka();tu=Ut});function M(t,e){let n=Hr(),r=zs({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Ut?void 0:Ut].filter(s=>!!s)});t.common.issues.push(r)}var zs,Nm,Ae,V,zn,Ee,_i,Si,dn,Kr,_a=be(()=>{ki();ka();zs=t=>{let{data:e,path:n,errorMaps:r,issueData:s}=t,i=[...n,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let l="",c=r.filter(u=>!!u).slice().reverse();for(let u of c)l=u(o,{data:e,defaultError:l}).message;return{...s,path:i,message:l}},Nm=[];Ae=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let s of n){if(s.status==="aborted")return V;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let s of n){let i=await s.key,o=await s.value;r.push({key:i,value:o})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let s of n){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return V;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(r[i.value]=o.value)}return{status:e.value,value:r}}},V=Object.freeze({status:"aborted"}),zn=t=>({status:"dirty",value:t}),Ee=t=>({status:"valid",value:t}),_i=t=>t.status==="aborted",Si=t=>t.status==="dirty",dn=t=>t.status==="valid",Kr=t=>typeof Promise<"u"&&t instanceof Promise});var nu=be(()=>{});var F,ru=be(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(F||(F={}))});function Q(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:s}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,l)=>{let{message:c}=t;return o.code==="invalid_enum_value"?{message:c??l.defaultError}:typeof l.data>"u"?{message:c??r??l.defaultError}:o.code!=="invalid_type"?{message:l.defaultError}:{message:c??n??l.defaultError}},description:s}}function au(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function Ym(t){return new RegExp(`^${au(t)}$`)}function lu(t){let e=`${ou}T${au(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function Xm(t,e){return!!((e==="v4"||!e)&&Hm.test(t)||(e==="v6"||!e)&&Gm.test(t))}function Qm(t,e){if(!Um.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function eg(t,e){return!!((e==="v4"||!e)&&Km.test(t)||(e==="v6"||!e)&&Zm.test(t))}function tg(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,i=Number.parseInt(t.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}function Gr(t){if(t instanceof He){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=st.create(Gr(r))}return new He({...t._def,shape:()=>e})}else return t instanceof Bt?new Bt({...t._def,type:Gr(t.element)}):t instanceof st?st.create(Gr(t.unwrap())):t instanceof Rt?Rt.create(Gr(t.unwrap())):t instanceof xt?xt.create(t.items.map(e=>Gr(e))):t}function Ta(t,e){let n=Tt(t),r=Tt(e);if(t===e)return{valid:!0,data:t};if(n===D.object&&r===D.object){let s=se.objectKeys(e),i=se.objectKeys(t).filter(l=>s.indexOf(l)!==-1),o={...t,...e};for(let l of i){let c=Ta(t[l],e[l]);if(!c.valid)return{valid:!1};o[l]=c.data}return{valid:!0,data:o}}else if(n===D.array&&r===D.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<t.length;i++){let o=t[i],l=e[i],c=Ta(o,l);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===D.date&&r===D.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function cu(t,e){return new Wn({values:t,typeName:J.ZodEnum,...Q(e)})}function iu(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function uu(t,e={},n){return t?pn.create().superRefine((r,s)=>{let i=t(r);if(i instanceof Promise)return i.then(o=>{if(!o){let l=iu(e,r),c=l.fatal??n??!0;s.addIssue({code:"custom",...l,fatal:c})}});if(!i){let o=iu(e,r),l=o.fatal??n??!0;s.addIssue({code:"custom",...o,fatal:l})}}):pn.create()}var it,su,re,Om,Mm,zm,Dm,Lm,Um,qm,Fm,Bm,Sa,Hm,Km,Gm,Zm,Wm,Vm,ou,Jm,hn,Dn,Ln,Un,qn,Zr,Fn,Bn,pn,Ft,yt,Wr,Bt,He,Hn,qt,Ti,Kn,xt,xi,Vr,Jr,Ri,Gn,Zn,Wn,Vn,fn,ot,st,Rt,Jn,Yn,Yr,ng,Ds,Ls,Xn,rg,J,sg,du,hu,ig,og,pu,ag,lg,cg,ug,dg,hg,pg,fg,mg,gg,yg,bg,wg,vg,kg,_g,Sg,Tg,xg,Rg,Ag,Ig,Eg,Cg,$g,Pg,jg,Ng,Og,Mg,zg,Dg,Lg,Ug,fu=be(()=>{vi();ki();ru();_a();Ms();it=class{constructor(e,n,r,s){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},su=(t,e)=>{if(dn(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new Be(t.common.issues);return this._error=n,this._error}}};re=class{get description(){return this._def.description}_getType(e){return Tt(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:Tt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ae,ctx:{common:e.parent.common,data:e.data,parsedType:Tt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(Kr(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Tt(e)},s=this._parseSync({data:e,path:r.path,parent:r});return su(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Tt(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return dn(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>dn(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Tt(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(Kr(s)?s:Promise.resolve(s));return su(r,i)}refine(e,n){let r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,i)=>{let o=e(s),l=()=>i.addIssue({code:I.custom,...r(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(l(),!1)):o?!0:(l(),!1)})}refinement(e,n){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(e){return new ot({schema:this,typeName:J.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return st.create(this,this._def)}nullable(){return Rt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Bt.create(this)}promise(){return fn.create(this,this._def)}or(e){return Hn.create([this,e],this._def)}and(e){return Kn.create(this,e,this._def)}transform(e){return new ot({...Q(this._def),schema:this,typeName:J.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new Jn({...Q(this._def),innerType:this,defaultValue:n,typeName:J.ZodDefault})}brand(){return new Ds({typeName:J.ZodBranded,type:this,...Q(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Yn({...Q(this._def),innerType:this,catchValue:n,typeName:J.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Ls.create(this,e)}readonly(){return Xn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Om=/^c[^\s-]{8,}$/i,Mm=/^[0-9a-z]+$/,zm=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Dm=/^[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,Lm=/^[a-z0-9_-]{21}$/i,Um=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,qm=/^[-+]?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)?)??$/,Fm=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Bm="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Hm=/^(?:(?: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])$/,Km=/^(?:(?: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])$/,Gm=/^(([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]))$/,Zm=/^(([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])$/,Wm=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Vm=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ou="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Jm=new RegExp(`^${ou}$`);hn=class t extends re{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==D.string){let i=this._getOrReturnCtx(e);return M(i,{code:I.invalid_type,expected:D.string,received:i.parsedType}),V}let r=new Ae,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),M(s,{code:I.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),M(s,{code:I.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,l=e.data.length<i.value;(o||l)&&(s=this._getOrReturnCtx(e,s),o?M(s,{code:I.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):l&&M(s,{code:I.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")Fm.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"email",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Sa||(Sa=new RegExp(Bm,"u")),Sa.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"emoji",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")Dm.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"uuid",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")Lm.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"nanoid",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")Om.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"cuid",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")Mm.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"cuid2",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")zm.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"ulid",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),M(s,{validation:"url",code:I.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"regex",code:I.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),M(s,{code:I.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),M(s,{code:I.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),M(s,{code:I.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?lu(i).test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{code:I.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?Jm.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{code:I.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Ym(i).test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{code:I.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?qm.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"duration",code:I.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?Xm(e.data,i.version)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"ip",code:I.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?Qm(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"jwt",code:I.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?eg(e.data,i.version)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"cidr",code:I.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?Wm.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"base64",code:I.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?Vm.test(e.data)||(s=this._getOrReturnCtx(e,s),M(s,{validation:"base64url",code:I.invalid_string,message:i.message}),r.dirty()):se.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:I.invalid_string,...F.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...F.errToObj(e)})}url(e){return this._addCheck({kind:"url",...F.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...F.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...F.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...F.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...F.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...F.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...F.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...F.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...F.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...F.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...F.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...F.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,...F.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,...F.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...F.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...F.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...F.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...F.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...F.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...F.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...F.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...F.errToObj(n)})}nonempty(e){return this.min(1,F.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};hn.create=t=>new hn({checks:[],typeName:J.ZodString,coerce:t?.coerce??!1,...Q(t)});Dn=class t extends re{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)!==D.number){let i=this._getOrReturnCtx(e);return M(i,{code:I.invalid_type,expected:D.number,received:i.parsedType}),V}let r,s=new Ae;for(let i of this._def.checks)i.kind==="int"?se.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),M(r,{code:I.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),M(r,{code:I.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),M(r,{code:I.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?tg(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),M(r,{code:I.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),M(r,{code:I.not_finite,message:i.message}),s.dirty()):se.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,F.toString(n))}gt(e,n){return this.setLimit("min",e,!1,F.toString(n))}lte(e,n){return this.setLimit("max",e,!0,F.toString(n))}lt(e,n){return this.setLimit("max",e,!1,F.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:F.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:F.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:F.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:F.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:F.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:F.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:F.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:F.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:F.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:F.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&se.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};Dn.create=t=>new Dn({checks:[],typeName:J.ZodNumber,coerce:t?.coerce||!1,...Q(t)});Ln=class t extends re{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)!==D.bigint)return this._getInvalidInput(e);let r,s=new Ae;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),M(r,{code:I.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),M(r,{code:I.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),M(r,{code:I.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):se.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return M(n,{code:I.invalid_type,expected:D.bigint,received:n.parsedType}),V}gte(e,n){return this.setLimit("min",e,!0,F.toString(n))}gt(e,n){return this.setLimit("min",e,!1,F.toString(n))}lte(e,n){return this.setLimit("max",e,!0,F.toString(n))}lt(e,n){return this.setLimit("max",e,!1,F.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:F.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:F.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:F.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:F.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:F.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:F.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};Ln.create=t=>new Ln({checks:[],typeName:J.ZodBigInt,coerce:t?.coerce??!1,...Q(t)});Un=class extends re{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==D.boolean){let r=this._getOrReturnCtx(e);return M(r,{code:I.invalid_type,expected:D.boolean,received:r.parsedType}),V}return Ee(e.data)}};Un.create=t=>new Un({typeName:J.ZodBoolean,coerce:t?.coerce||!1,...Q(t)});qn=class t extends re{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==D.date){let i=this._getOrReturnCtx(e);return M(i,{code:I.invalid_type,expected:D.date,received:i.parsedType}),V}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return M(i,{code:I.invalid_date}),V}let r=new Ae,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),M(s,{code:I.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),M(s,{code:I.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):se.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:F.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:F.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};qn.create=t=>new qn({checks:[],coerce:t?.coerce||!1,typeName:J.ZodDate,...Q(t)});Zr=class extends re{_parse(e){if(this._getType(e)!==D.symbol){let r=this._getOrReturnCtx(e);return M(r,{code:I.invalid_type,expected:D.symbol,received:r.parsedType}),V}return Ee(e.data)}};Zr.create=t=>new Zr({typeName:J.ZodSymbol,...Q(t)});Fn=class extends re{_parse(e){if(this._getType(e)!==D.undefined){let r=this._getOrReturnCtx(e);return M(r,{code:I.invalid_type,expected:D.undefined,received:r.parsedType}),V}return Ee(e.data)}};Fn.create=t=>new Fn({typeName:J.ZodUndefined,...Q(t)});Bn=class extends re{_parse(e){if(this._getType(e)!==D.null){let r=this._getOrReturnCtx(e);return M(r,{code:I.invalid_type,expected:D.null,received:r.parsedType}),V}return Ee(e.data)}};Bn.create=t=>new Bn({typeName:J.ZodNull,...Q(t)});pn=class extends re{constructor(){super(...arguments),this._any=!0}_parse(e){return Ee(e.data)}};pn.create=t=>new pn({typeName:J.ZodAny,...Q(t)});Ft=class extends re{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ee(e.data)}};Ft.create=t=>new Ft({typeName:J.ZodUnknown,...Q(t)});yt=class extends re{_parse(e){let n=this._getOrReturnCtx(e);return M(n,{code:I.invalid_type,expected:D.never,received:n.parsedType}),V}};yt.create=t=>new yt({typeName:J.ZodNever,...Q(t)});Wr=class extends re{_parse(e){if(this._getType(e)!==D.undefined){let r=this._getOrReturnCtx(e);return M(r,{code:I.invalid_type,expected:D.void,received:r.parsedType}),V}return Ee(e.data)}};Wr.create=t=>new Wr({typeName:J.ZodVoid,...Q(t)});Bt=class t extends re{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==D.array)return M(n,{code:I.invalid_type,expected:D.array,received:n.parsedType}),V;if(s.exactLength!==null){let o=n.data.length>s.exactLength.value,l=n.data.length<s.exactLength.value;(o||l)&&(M(n,{code:o?I.too_big:I.too_small,minimum:l?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(M(n,{code:I.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(M(n,{code:I.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((o,l)=>s.type._parseAsync(new it(n,o,n.path,l)))).then(o=>Ae.mergeArray(r,o));let i=[...n.data].map((o,l)=>s.type._parseSync(new it(n,o,n.path,l)));return Ae.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:F.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:F.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:F.toString(n)}})}nonempty(e){return this.min(1,e)}};Bt.create=(t,e)=>new Bt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:J.ZodArray,...Q(e)});He=class t extends re{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),n=se.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==D.object){let u=this._getOrReturnCtx(e);return M(u,{code:I.invalid_type,expected:D.object,received:u.parsedType}),V}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),l=[];if(!(this._def.catchall instanceof yt&&this._def.unknownKeys==="strip"))for(let u in s.data)o.includes(u)||l.push(u);let c=[];for(let u of o){let p=i[u],f=s.data[u];c.push({key:{status:"valid",value:u},value:p._parse(new it(s,f,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof yt){let u=this._def.unknownKeys;if(u==="passthrough")for(let p of l)c.push({key:{status:"valid",value:p},value:{status:"valid",value:s.data[p]}});else if(u==="strict")l.length>0&&(M(s,{code:I.unrecognized_keys,keys:l}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let p of l){let f=s.data[p];c.push({key:{status:"valid",value:p},value:u._parse(new it(s,f,s.path,p)),alwaysSet:p in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let u=[];for(let p of c){let f=await p.key,b=await p.value;u.push({key:f,value:b,alwaysSet:p.alwaysSet})}return u}).then(u=>Ae.mergeObjectSync(r,u)):Ae.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return F.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:F.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:J.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of se.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of se.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return Gr(this)}partial(e){let n={};for(let r of se.objectKeys(this.shape)){let s=this.shape[r];e&&!e[r]?n[r]=s:n[r]=s.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of se.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof st;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return cu(se.objectKeys(this.shape))}};He.create=(t,e)=>new He({shape:()=>t,unknownKeys:"strip",catchall:yt.create(),typeName:J.ZodObject,...Q(e)});He.strictCreate=(t,e)=>new He({shape:()=>t,unknownKeys:"strict",catchall:yt.create(),typeName:J.ZodObject,...Q(e)});He.lazycreate=(t,e)=>new He({shape:t,unknownKeys:"strip",catchall:yt.create(),typeName:J.ZodObject,...Q(e)});Hn=class extends re{_parse(e){let{ctx:n}=this._processInputParams(e),r=this._def.options;function s(i){for(let l of i)if(l.result.status==="valid")return l.result;for(let l of i)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;let o=i.map(l=>new Be(l.ctx.common.issues));return M(n,{code:I.invalid_union,unionErrors:o}),V}if(n.common.async)return Promise.all(r.map(async i=>{let o={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let c of r){let u={...n,common:{...n.common,issues:[]},parent:null},p=c._parseSync({data:n.data,path:n.path,parent:u});if(p.status==="valid")return p;p.status==="dirty"&&!i&&(i={result:p,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let l=o.map(c=>new Be(c));return M(n,{code:I.invalid_union,unionErrors:l}),V}}get options(){return this._def.options}};Hn.create=(t,e)=>new Hn({options:t,typeName:J.ZodUnion,...Q(e)});qt=t=>t instanceof Gn?qt(t.schema):t instanceof ot?qt(t.innerType()):t instanceof Zn?[t.value]:t instanceof Wn?t.options:t instanceof Vn?se.objectValues(t.enum):t instanceof Jn?qt(t._def.innerType):t instanceof Fn?[void 0]:t instanceof Bn?[null]:t instanceof st?[void 0,...qt(t.unwrap())]:t instanceof Rt?[null,...qt(t.unwrap())]:t instanceof Ds||t instanceof Xn?qt(t.unwrap()):t instanceof Yn?qt(t._def.innerType):[],Ti=class t extends re{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==D.object)return M(n,{code:I.invalid_type,expected:D.object,received:n.parsedType}),V;let r=this.discriminator,s=n.data[r],i=this.optionsMap.get(s);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(M(n,{code:I.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),V)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let s=new Map;for(let i of n){let o=qt(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let l of o){if(s.has(l))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(l)}`);s.set(l,i)}}return new t({typeName:J.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...Q(r)})}};Kn=class extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=(i,o)=>{if(_i(i)||_i(o))return V;let l=Ta(i.value,o.value);return l.valid?((Si(i)||Si(o))&&n.dirty(),{status:n.value,value:l.data}):(M(r,{code:I.invalid_intersection_types}),V)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Kn.create=(t,e,n)=>new Kn({left:t,right:e,typeName:J.ZodIntersection,...Q(n)});xt=class t extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==D.array)return M(r,{code:I.invalid_type,expected:D.array,received:r.parsedType}),V;if(r.data.length<this._def.items.length)return M(r,{code:I.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),V;!this._def.rest&&r.data.length>this._def.items.length&&(M(r,{code:I.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let i=[...r.data].map((o,l)=>{let c=this._def.items[l]||this._def.rest;return c?c._parse(new it(r,o,r.path,l)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>Ae.mergeArray(n,o)):Ae.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};xt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new xt({items:t,typeName:J.ZodTuple,rest:null,...Q(e)})};xi=class t extends re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==D.object)return M(r,{code:I.invalid_type,expected:D.object,received:r.parsedType}),V;let s=[],i=this._def.keyType,o=this._def.valueType;for(let l in r.data)s.push({key:i._parse(new it(r,l,r.path,l)),value:o._parse(new it(r,r.data[l],r.path,l)),alwaysSet:l in r.data});return r.common.async?Ae.mergeObjectAsync(n,s):Ae.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof re?new t({keyType:e,valueType:n,typeName:J.ZodRecord,...Q(r)}):new t({keyType:hn.create(),valueType:e,typeName:J.ZodRecord,...Q(n)})}},Vr=class extends re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==D.map)return M(r,{code:I.invalid_type,expected:D.map,received:r.parsedType}),V;let s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([l,c],u)=>({key:s._parse(new it(r,l,r.path,[u,"key"])),value:i._parse(new it(r,c,r.path,[u,"value"]))}));if(r.common.async){let l=new Map;return Promise.resolve().then(async()=>{for(let c of o){let u=await c.key,p=await c.value;if(u.status==="aborted"||p.status==="aborted")return V;(u.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(u.value,p.value)}return{status:n.value,value:l}})}else{let l=new Map;for(let c of o){let u=c.key,p=c.value;if(u.status==="aborted"||p.status==="aborted")return V;(u.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(u.value,p.value)}return{status:n.value,value:l}}}};Vr.create=(t,e,n)=>new Vr({valueType:e,keyType:t,typeName:J.ZodMap,...Q(n)});Jr=class t extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==D.set)return M(r,{code:I.invalid_type,expected:D.set,received:r.parsedType}),V;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(M(r,{code:I.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(M(r,{code:I.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let i=this._def.valueType;function o(c){let u=new Set;for(let p of c){if(p.status==="aborted")return V;p.status==="dirty"&&n.dirty(),u.add(p.value)}return{status:n.value,value:u}}let l=[...r.data.values()].map((c,u)=>i._parse(new it(r,c,r.path,u)));return r.common.async?Promise.all(l).then(c=>o(c)):o(l)}min(e,n){return new t({...this._def,minSize:{value:e,message:F.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:F.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};Jr.create=(t,e)=>new Jr({valueType:t,minSize:null,maxSize:null,typeName:J.ZodSet,...Q(e)});Ri=class t extends re{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==D.function)return M(n,{code:I.invalid_type,expected:D.function,received:n.parsedType}),V;function r(l,c){return zs({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Hr(),Ut].filter(u=>!!u),issueData:{code:I.invalid_arguments,argumentsError:c}})}function s(l,c){return zs({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Hr(),Ut].filter(u=>!!u),issueData:{code:I.invalid_return_type,returnTypeError:c}})}let i={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof fn){let l=this;return Ee(async function(...c){let u=new Be([]),p=await l._def.args.parseAsync(c,i).catch(w=>{throw u.addIssue(r(c,w)),u}),f=await Reflect.apply(o,this,p);return await l._def.returns._def.type.parseAsync(f,i).catch(w=>{throw u.addIssue(s(f,w)),u})})}else{let l=this;return Ee(function(...c){let u=l._def.args.safeParse(c,i);if(!u.success)throw new Be([r(c,u.error)]);let p=Reflect.apply(o,this,u.data),f=l._def.returns.safeParse(p,i);if(!f.success)throw new Be([s(p,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:xt.create(e).rest(Ft.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new t({args:e||xt.create([]).rest(Ft.create()),returns:n||Ft.create(),typeName:J.ZodFunction,...Q(r)})}},Gn=class extends re{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};Gn.create=(t,e)=>new Gn({getter:t,typeName:J.ZodLazy,...Q(e)});Zn=class extends re{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return M(n,{received:n.data,code:I.invalid_literal,expected:this._def.value}),V}return{status:"valid",value:e.data}}get value(){return this._def.value}};Zn.create=(t,e)=>new Zn({value:t,typeName:J.ZodLiteral,...Q(e)});Wn=class t extends re{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return M(n,{expected:se.joinValues(r),received:n.parsedType,code:I.invalid_type}),V}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return M(n,{received:n.data,code:I.invalid_enum_value,options:r}),V}return Ee(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};Wn.create=cu;Vn=class extends re{_parse(e){let n=se.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==D.string&&r.parsedType!==D.number){let s=se.objectValues(n);return M(r,{expected:se.joinValues(s),received:r.parsedType,code:I.invalid_type}),V}if(this._cache||(this._cache=new Set(se.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=se.objectValues(n);return M(r,{received:r.data,code:I.invalid_enum_value,options:s}),V}return Ee(e.data)}get enum(){return this._def.values}};Vn.create=(t,e)=>new Vn({values:t,typeName:J.ZodNativeEnum,...Q(e)});fn=class extends re{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==D.promise&&n.common.async===!1)return M(n,{code:I.invalid_type,expected:D.promise,received:n.parsedType}),V;let r=n.parsedType===D.promise?n.data:Promise.resolve(n.data);return Ee(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};fn.create=(t,e)=>new fn({type:t,typeName:J.ZodPromise,...Q(e)});ot=class extends re{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===J.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{M(r,o),o.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(r.data,i);if(r.common.async)return Promise.resolve(o).then(async l=>{if(n.value==="aborted")return V;let c=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return c.status==="aborted"?V:c.status==="dirty"?zn(c.value):n.value==="dirty"?zn(c.value):c});{if(n.value==="aborted")return V;let l=this._def.schema._parseSync({data:o,path:r.path,parent:r});return l.status==="aborted"?V:l.status==="dirty"?zn(l.value):n.value==="dirty"?zn(l.value):l}}if(s.type==="refinement"){let o=l=>{let c=s.refinement(l,i);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){let l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?V:(l.status==="dirty"&&n.dirty(),o(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?V:(l.status==="dirty"&&n.dirty(),o(l.value).then(()=>({status:n.value,value:l.value}))))}if(s.type==="transform")if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!dn(o))return V;let l=s.transform(o.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>dn(o)?Promise.resolve(s.transform(o.value,i)).then(l=>({status:n.value,value:l})):V);se.assertNever(s)}};ot.create=(t,e,n)=>new ot({schema:t,typeName:J.ZodEffects,effect:e,...Q(n)});ot.createWithPreprocess=(t,e,n)=>new ot({schema:e,effect:{type:"preprocess",transform:t},typeName:J.ZodEffects,...Q(n)});st=class extends re{_parse(e){return this._getType(e)===D.undefined?Ee(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};st.create=(t,e)=>new st({innerType:t,typeName:J.ZodOptional,...Q(e)});Rt=class extends re{_parse(e){return this._getType(e)===D.null?Ee(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Rt.create=(t,e)=>new Rt({innerType:t,typeName:J.ZodNullable,...Q(e)});Jn=class extends re{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===D.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Jn.create=(t,e)=>new Jn({innerType:t,typeName:J.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Q(e)});Yn=class extends re{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Kr(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Be(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Be(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Yn.create=(t,e)=>new Yn({innerType:t,typeName:J.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Q(e)});Yr=class extends re{_parse(e){if(this._getType(e)!==D.nan){let r=this._getOrReturnCtx(e);return M(r,{code:I.invalid_type,expected:D.nan,received:r.parsedType}),V}return{status:"valid",value:e.data}}};Yr.create=t=>new Yr({typeName:J.ZodNaN,...Q(t)});ng=Symbol("zod_brand"),Ds=class extends re{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},Ls=class t extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?V:i.status==="dirty"?(n.dirty(),zn(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?V:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:J.ZodPipeline})}},Xn=class extends re{_parse(e){let n=this._def.innerType._parse(e),r=s=>(dn(s)&&(s.value=Object.freeze(s.value)),s);return Kr(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};Xn.create=(t,e)=>new Xn({innerType:t,typeName:J.ZodReadonly,...Q(e)});rg={object:He.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(J||(J={}));sg=(t,e={message:`Input not instance of ${t.name}`})=>uu(n=>n instanceof t,e),du=hn.create,hu=Dn.create,ig=Yr.create,og=Ln.create,pu=Un.create,ag=qn.create,lg=Zr.create,cg=Fn.create,ug=Bn.create,dg=pn.create,hg=Ft.create,pg=yt.create,fg=Wr.create,mg=Bt.create,gg=He.create,yg=He.strictCreate,bg=Hn.create,wg=Ti.create,vg=Kn.create,kg=xt.create,_g=xi.create,Sg=Vr.create,Tg=Jr.create,xg=Ri.create,Rg=Gn.create,Ag=Zn.create,Ig=Wn.create,Eg=Vn.create,Cg=fn.create,$g=ot.create,Pg=st.create,jg=Rt.create,Ng=ot.createWithPreprocess,Og=Ls.create,Mg=()=>du().optional(),zg=()=>hu().optional(),Dg=()=>pu().optional(),Lg={string:(t=>hn.create({...t,coerce:!0})),number:(t=>Dn.create({...t,coerce:!0})),boolean:(t=>Un.create({...t,coerce:!0})),bigint:(t=>Ln.create({...t,coerce:!0})),date:(t=>qn.create({...t,coerce:!0}))},Ug=V});var _={};un(_,{BRAND:()=>ng,DIRTY:()=>zn,EMPTY_PATH:()=>Nm,INVALID:()=>V,NEVER:()=>Ug,OK:()=>Ee,ParseStatus:()=>Ae,Schema:()=>re,ZodAny:()=>pn,ZodArray:()=>Bt,ZodBigInt:()=>Ln,ZodBoolean:()=>Un,ZodBranded:()=>Ds,ZodCatch:()=>Yn,ZodDate:()=>qn,ZodDefault:()=>Jn,ZodDiscriminatedUnion:()=>Ti,ZodEffects:()=>ot,ZodEnum:()=>Wn,ZodError:()=>Be,ZodFirstPartyTypeKind:()=>J,ZodFunction:()=>Ri,ZodIntersection:()=>Kn,ZodIssueCode:()=>I,ZodLazy:()=>Gn,ZodLiteral:()=>Zn,ZodMap:()=>Vr,ZodNaN:()=>Yr,ZodNativeEnum:()=>Vn,ZodNever:()=>yt,ZodNull:()=>Bn,ZodNullable:()=>Rt,ZodNumber:()=>Dn,ZodObject:()=>He,ZodOptional:()=>st,ZodParsedType:()=>D,ZodPipeline:()=>Ls,ZodPromise:()=>fn,ZodReadonly:()=>Xn,ZodRecord:()=>xi,ZodSchema:()=>re,ZodSet:()=>Jr,ZodString:()=>hn,ZodSymbol:()=>Zr,ZodTransformer:()=>ot,ZodTuple:()=>xt,ZodType:()=>re,ZodUndefined:()=>Fn,ZodUnion:()=>Hn,ZodUnknown:()=>Ft,ZodVoid:()=>Wr,addIssueToContext:()=>M,any:()=>dg,array:()=>mg,bigint:()=>og,boolean:()=>pu,coerce:()=>Lg,custom:()=>uu,date:()=>ag,datetimeRegex:()=>lu,defaultErrorMap:()=>Ut,discriminatedUnion:()=>wg,effect:()=>$g,enum:()=>Ig,function:()=>xg,getErrorMap:()=>Hr,getParsedType:()=>Tt,instanceof:()=>sg,intersection:()=>vg,isAborted:()=>_i,isAsync:()=>Kr,isDirty:()=>Si,isValid:()=>dn,late:()=>rg,lazy:()=>Rg,literal:()=>Ag,makeIssue:()=>zs,map:()=>Sg,nan:()=>ig,nativeEnum:()=>Eg,never:()=>pg,null:()=>ug,nullable:()=>jg,number:()=>hu,object:()=>gg,objectUtil:()=>va,oboolean:()=>Dg,onumber:()=>zg,optional:()=>Pg,ostring:()=>Mg,pipeline:()=>Og,preprocess:()=>Ng,promise:()=>Cg,quotelessJson:()=>$m,record:()=>_g,set:()=>Tg,setErrorMap:()=>jm,strictObject:()=>yg,string:()=>du,symbol:()=>lg,transformer:()=>$g,tuple:()=>kg,undefined:()=>cg,union:()=>bg,unknown:()=>hg,util:()=>se,void:()=>fg});var xa=be(()=>{ki();_a();nu();Ms();fu();vi()});var Xr=be(()=>{xa();xa()});function ie(){let t=process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR;if(t)return t;let e=Ii.default.join(Ai.default.homedir(),".config","allwright"),n=Ii.default.join(Ai.default.homedir(),".config","ticketpilot");return!Ht.default.existsSync(e)&&Ht.default.existsSync(n)?n:e}function Kt(){return Ii.default.join(ie(),"runner.json")}function ve(){let t=Kt();if(!Ht.default.existsSync(t))return null;let e=JSON.parse(Ht.default.readFileSync(t,"utf8"));return Ra.parse(e)}function ye(t){let e=ie();Ht.default.mkdirSync(e,{recursive:!0,mode:448});let n=Kt(),r=n+".tmp";Ht.default.writeFileSync(r,JSON.stringify(t,null,2)+`
|
|
24
|
-
`,{mode:384}),Ht.default.renameSync(r,n),Ht.default.chmodSync(n,384)}function Ei(t,e){return`${t}:${e}`}function Gt(t,e,n){return t.environments[Ei(e,n)]?.secrets??{}}function Ci(t,e){return t.repos[e]?.jira??t.jira}function $i(t){return!t.jira&&!Object.values(t.repos).some(e=>e.jira)}function le(){let t=ve();if(!t)throw new Error(`No runner config found at ${Kt()}. Run \`allwright init\` first.`);return t}var Ht,Ai,Ii,mu,Ra,Ce=be(()=>{"use strict";Ht=A(require("node:fs"),1),Ai=A(require("node:os"),1),Ii=A(require("node:path"),1);Xr();mu=_.object({baseUrl:_.string().url(),email:_.string().email(),apiToken:_.string().min(1)}),Ra=_.object({controlPlaneUrl:_.string().url(),runnerId:_.string().optional(),runnerToken:_.string().optional(),runnerName:_.string().default(Ai.default.hostname()),jira:mu.optional(),repos:_.record(_.object({path:_.string(),jira:mu.optional(),github:_.object({token:_.string().min(1),login:_.string().optional()}).optional()})).default({}),github:_.object({token:_.string().min(1),login:_.string().optional()}).optional(),githubUsers:_.record(_.object({token:_.string().min(1),login:_.string().optional()})).default({}),deploy:_.object({enabled:_.boolean().default(!1)}).default({enabled:!1}),environments:_.record(_.object({secrets:_.record(_.string()).default({})})).default({}),claudeProfiles:_.record(_.object({configDir:_.string()})).default({}),claudeBin:_.string().default("claude"),agents:_.record(_.object({bin:_.string()})).default({}),jiraUsers:_.record(_.object({email:_.string().email(),apiToken:_.string().min(1)})).default({}),auditSchedules:_.array(_.object({repoName:_.string(),role:_.enum(["security","testing"]),intervalHours:_.number().int().min(6).max(720)})).default([]),pollIntervalSeconds:_.number().int().min(10).max(600).default(30)})});var Us=ae(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.getParsedType=de.ZodParsedType=de.objectUtil=de.util=void 0;var Ca;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function n(s){throw new Error}t.assertNever=n,t.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},t.getValidEnumValues=s=>{let i=t.objectKeys(s).filter(l=>typeof s[s[l]]!="number"),o={};for(let l of i)o[l]=s[l];return t.objectValues(o)},t.objectValues=s=>t.objectKeys(s).map(function(i){return s[i]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},t.find=(s,i)=>{for(let o of s)if(i(o))return o},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(Ca||(de.util=Ca={}));var Ru;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Ru||(de.objectUtil=Ru={}));de.ZodParsedType=Ca.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var Wg=t=>{switch(typeof t){case"undefined":return de.ZodParsedType.undefined;case"string":return de.ZodParsedType.string;case"number":return Number.isNaN(t)?de.ZodParsedType.nan:de.ZodParsedType.number;case"boolean":return de.ZodParsedType.boolean;case"function":return de.ZodParsedType.function;case"bigint":return de.ZodParsedType.bigint;case"symbol":return de.ZodParsedType.symbol;case"object":return Array.isArray(t)?de.ZodParsedType.array:t===null?de.ZodParsedType.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?de.ZodParsedType.promise:typeof Map<"u"&&t instanceof Map?de.ZodParsedType.map:typeof Set<"u"&&t instanceof Set?de.ZodParsedType.set:typeof Date<"u"&&t instanceof Date?de.ZodParsedType.date:de.ZodParsedType.object;default:return de.ZodParsedType.unknown}};de.getParsedType=Wg});var zi=ae(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.ZodError=yn.quotelessJson=yn.ZodIssueCode=void 0;var Au=Us();yn.ZodIssueCode=Au.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 Vg=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");yn.quotelessJson=Vg;var qs=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(i){return i.message},r={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)r._errors.push(n(o));else{let l=r,c=0;for(;c<o.path.length;){let u=o.path[c];c===o.path.length-1?(l[u]=l[u]||{_errors:[]},l[u]._errors.push(n(o))):l[u]=l[u]||{_errors:[]},l=l[u],c++}}};return s(this),r}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Au.util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];n[i]=n[i]||[],n[i].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};yn.ZodError=qs;qs.create=t=>new qs(t)});var Pa=ae($a=>{"use strict";Object.defineProperty($a,"__esModule",{value:!0});var $e=zi(),tr=Us(),Jg=(t,e)=>{let n;switch(t.code){case $e.ZodIssueCode.invalid_type:t.received===tr.ZodParsedType.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case $e.ZodIssueCode.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,tr.util.jsonStringifyReplacer)}`;break;case $e.ZodIssueCode.unrecognized_keys:n=`Unrecognized key(s) in object: ${tr.util.joinValues(t.keys,", ")}`;break;case $e.ZodIssueCode.invalid_union:n="Invalid input";break;case $e.ZodIssueCode.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${tr.util.joinValues(t.options)}`;break;case $e.ZodIssueCode.invalid_enum_value:n=`Invalid enum value. Expected ${tr.util.joinValues(t.options)}, received '${t.received}'`;break;case $e.ZodIssueCode.invalid_arguments:n="Invalid function arguments";break;case $e.ZodIssueCode.invalid_return_type:n="Invalid function return type";break;case $e.ZodIssueCode.invalid_date:n="Invalid date";break;case $e.ZodIssueCode.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:tr.util.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case $e.ZodIssueCode.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case $e.ZodIssueCode.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case $e.ZodIssueCode.custom:n="Invalid input";break;case $e.ZodIssueCode.invalid_intersection_types:n="Intersection results could not be merged";break;case $e.ZodIssueCode.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case $e.ZodIssueCode.not_finite:n="Number must be finite";break;default:n=e.defaultError,tr.util.assertNever(t)}return{message:n}};$a.default=Jg});var Di=ae(bn=>{"use strict";var Yg=bn&&bn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(bn,"__esModule",{value:!0});bn.defaultErrorMap=void 0;bn.setErrorMap=Xg;bn.getErrorMap=Qg;var Iu=Yg(Pa());bn.defaultErrorMap=Iu.default;var Eu=Iu.default;function Xg(t){Eu=t}function Qg(){return Eu}});var Na=ae(ue=>{"use strict";var ey=ue&&ue.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(ue,"__esModule",{value:!0});ue.isAsync=ue.isValid=ue.isDirty=ue.isAborted=ue.OK=ue.DIRTY=ue.INVALID=ue.ParseStatus=ue.EMPTY_PATH=ue.makeIssue=void 0;ue.addIssueToContext=ry;var ty=Di(),Cu=ey(Pa()),ny=t=>{let{data:e,path:n,errorMaps:r,issueData:s}=t,i=[...n,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let l="",c=r.filter(u=>!!u).slice().reverse();for(let u of c)l=u(o,{data:e,defaultError:l}).message;return{...s,path:i,message:l}};ue.makeIssue=ny;ue.EMPTY_PATH=[];function ry(t,e){let n=(0,ty.getErrorMap)(),r=(0,ue.makeIssue)({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Cu.default?void 0:Cu.default].filter(s=>!!s)});t.common.issues.push(r)}var ja=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let s of n){if(s.status==="aborted")return ue.INVALID;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let s of n){let i=await s.key,o=await s.value;r.push({key:i,value:o})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let s of n){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return ue.INVALID;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(r[i.value]=o.value)}return{status:e.value,value:r}}};ue.ParseStatus=ja;ue.INVALID=Object.freeze({status:"aborted"});var sy=t=>({status:"dirty",value:t});ue.DIRTY=sy;var iy=t=>({status:"valid",value:t});ue.OK=iy;var oy=t=>t.status==="aborted";ue.isAborted=oy;var ay=t=>t.status==="dirty";ue.isDirty=ay;var ly=t=>t.status==="valid";ue.isValid=ly;var cy=t=>typeof Promise<"u"&&t instanceof Promise;ue.isAsync=cy});var Pu=ae($u=>{"use strict";Object.defineProperty($u,"__esModule",{value:!0})});var Nu=ae(Li=>{"use strict";Object.defineProperty(Li,"__esModule",{value:!0});Li.errorUtil=void 0;var ju;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(ju||(Li.errorUtil=ju={}))});var Gu=ae(S=>{"use strict";Object.defineProperty(S,"__esModule",{value:!0});S.discriminatedUnion=S.date=S.boolean=S.bigint=S.array=S.any=S.coerce=S.ZodFirstPartyTypeKind=S.late=S.ZodSchema=S.Schema=S.ZodReadonly=S.ZodPipeline=S.ZodBranded=S.BRAND=S.ZodNaN=S.ZodCatch=S.ZodDefault=S.ZodNullable=S.ZodOptional=S.ZodTransformer=S.ZodEffects=S.ZodPromise=S.ZodNativeEnum=S.ZodEnum=S.ZodLiteral=S.ZodLazy=S.ZodFunction=S.ZodSet=S.ZodMap=S.ZodRecord=S.ZodTuple=S.ZodIntersection=S.ZodDiscriminatedUnion=S.ZodUnion=S.ZodObject=S.ZodArray=S.ZodVoid=S.ZodNever=S.ZodUnknown=S.ZodAny=S.ZodNull=S.ZodUndefined=S.ZodSymbol=S.ZodDate=S.ZodBoolean=S.ZodBigInt=S.ZodNumber=S.ZodString=S.ZodType=void 0;S.NEVER=S.void=S.unknown=S.union=S.undefined=S.tuple=S.transformer=S.symbol=S.string=S.strictObject=S.set=S.record=S.promise=S.preprocess=S.pipeline=S.ostring=S.optional=S.onumber=S.oboolean=S.object=S.number=S.nullable=S.null=S.never=S.nativeEnum=S.nan=S.map=S.literal=S.lazy=S.intersection=S.instanceof=S.function=S.enum=S.effect=void 0;S.datetimeRegex=Lu;S.custom=qu;var $=zi(),Ui=Di(),G=Nu(),x=Na(),j=Us(),lt=class{constructor(e,n,r,s){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Ou=(t,e)=>{if((0,x.isValid)(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new $.ZodError(t.common.issues);return this._error=n,this._error}}};function ee(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:s}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,l)=>{let{message:c}=t;return o.code==="invalid_enum_value"?{message:c??l.defaultError}:typeof l.data>"u"?{message:c??r??l.defaultError}:o.code!=="invalid_type"?{message:l.defaultError}:{message:c??n??l.defaultError}},description:s}}var te=class{get description(){return this._def.description}_getType(e){return(0,j.getParsedType)(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:(0,j.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new x.ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:(0,j.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if((0,x.isAsync)(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,j.getParsedType)(e)},s=this._parseSync({data:e,path:r.path,parent:r});return Ou(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,j.getParsedType)(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return(0,x.isValid)(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>(0,x.isValid)(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,j.getParsedType)(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await((0,x.isAsync)(s)?s:Promise.resolve(s));return Ou(r,i)}refine(e,n){let r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,i)=>{let o=e(s),l=()=>i.addIssue({code:$.ZodIssueCode.custom,...r(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(l(),!1)):o?!0:(l(),!1)})}refinement(e,n){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(e){return new Ve({schema:this,typeName:Y.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return at.create(this,this._def)}nullable(){return It.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Vt.create(this)}promise(){return kn.create(this,this._def)}or(e){return lr.create([this,e],this._def)}and(e){return cr.create(this,e,this._def)}transform(e){return new Ve({...ee(this._def),schema:this,typeName:Y.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new fr({...ee(this._def),innerType:this,defaultValue:n,typeName:Y.ZodDefault})}brand(){return new Fs({typeName:Y.ZodBranded,type:this,...ee(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new mr({...ee(this._def),innerType:this,catchValue:n,typeName:Y.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Bs.create(this,e)}readonly(){return gr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};S.ZodType=te;S.Schema=te;S.ZodSchema=te;var uy=/^c[^\s-]{8,}$/i,dy=/^[0-9a-z]+$/,hy=/^[0-9A-HJKMNP-TV-Z]{26}$/i,py=/^[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,fy=/^[a-z0-9_-]{21}$/i,my=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,gy=/^[-+]?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)?)??$/,yy=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,by="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Oa,wy=/^(?:(?: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])$/,vy=/^(?:(?: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])$/,ky=/^(([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]))$/,_y=/^(([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])$/,Sy=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ty=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,zu="((\\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])))",xy=new RegExp(`^${zu}$`);function Du(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function Ry(t){return new RegExp(`^${Du(t)}$`)}function Lu(t){let e=`${zu}T${Du(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function Ay(t,e){return!!((e==="v4"||!e)&&wy.test(t)||(e==="v6"||!e)&&ky.test(t))}function Iy(t,e){if(!my.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function Ey(t,e){return!!((e==="v4"||!e)&&vy.test(t)||(e==="v6"||!e)&&_y.test(t))}var wn=class t extends te{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==j.ZodParsedType.string){let i=this._getOrReturnCtx(e);return(0,x.addIssueToContext)(i,{code:$.ZodIssueCode.invalid_type,expected:j.ZodParsedType.string,received:i.parsedType}),x.INVALID}let r=new x.ParseStatus,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{code:$.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{code:$.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,l=e.data.length<i.value;(o||l)&&(s=this._getOrReturnCtx(e,s),o?(0,x.addIssueToContext)(s,{code:$.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):l&&(0,x.addIssueToContext)(s,{code:$.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")yy.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{validation:"email",code:$.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Oa||(Oa=new RegExp(by,"u")),Oa.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{validation:"emoji",code:$.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")py.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{validation:"uuid",code:$.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")fy.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{validation:"nanoid",code:$.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")uy.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{validation:"cuid",code:$.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")dy.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{validation:"cuid2",code:$.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")hy.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{validation:"ulid",code:$.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{validation:"url",code:$.ZodIssueCode.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{validation:"regex",code:$.ZodIssueCode.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{code:$.ZodIssueCode.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{code:$.ZodIssueCode.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{code:$.ZodIssueCode.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Lu(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{code:$.ZodIssueCode.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?xy.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{code:$.ZodIssueCode.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Ry(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{code:$.ZodIssueCode.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?gy.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{validation:"duration",code:$.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?Ay(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{validation:"ip",code:$.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?Iy(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{validation:"jwt",code:$.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?Ey(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{validation:"cidr",code:$.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?Sy.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{validation:"base64",code:$.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?Ty.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{validation:"base64url",code:$.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):j.util.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:$.ZodIssueCode.invalid_string,...G.errorUtil.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...G.errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...G.errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...G.errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...G.errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...G.errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...G.errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...G.errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...G.errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...G.errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...G.errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...G.errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...G.errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...G.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,...G.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,...G.errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...G.errorUtil.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...G.errorUtil.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...G.errorUtil.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...G.errorUtil.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...G.errorUtil.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...G.errorUtil.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...G.errorUtil.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...G.errorUtil.errToObj(n)})}nonempty(e){return this.min(1,G.errorUtil.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};S.ZodString=wn;wn.create=t=>new wn({checks:[],typeName:Y.ZodString,coerce:t?.coerce??!1,...ee(t)});function Cy(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,i=Number.parseInt(t.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var nr=class t extends te{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==j.ZodParsedType.number){let i=this._getOrReturnCtx(e);return(0,x.addIssueToContext)(i,{code:$.ZodIssueCode.invalid_type,expected:j.ZodParsedType.number,received:i.parsedType}),x.INVALID}let r,s=new x.ParseStatus;for(let i of this._def.checks)i.kind==="int"?j.util.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Cy(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.not_finite,message:i.message}),s.dirty()):j.util.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,G.errorUtil.toString(n))}gt(e,n){return this.setLimit("min",e,!1,G.errorUtil.toString(n))}lte(e,n){return this.setLimit("max",e,!0,G.errorUtil.toString(n))}lt(e,n){return this.setLimit("max",e,!1,G.errorUtil.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:G.errorUtil.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:G.errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:G.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:G.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:G.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:G.errorUtil.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:G.errorUtil.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:G.errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:G.errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:G.errorUtil.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&j.util.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};S.ZodNumber=nr;nr.create=t=>new nr({checks:[],typeName:Y.ZodNumber,coerce:t?.coerce||!1,...ee(t)});var rr=class t extends te{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==j.ZodParsedType.bigint)return this._getInvalidInput(e);let r,s=new x.ParseStatus;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):j.util.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return(0,x.addIssueToContext)(n,{code:$.ZodIssueCode.invalid_type,expected:j.ZodParsedType.bigint,received:n.parsedType}),x.INVALID}gte(e,n){return this.setLimit("min",e,!0,G.errorUtil.toString(n))}gt(e,n){return this.setLimit("min",e,!1,G.errorUtil.toString(n))}lte(e,n){return this.setLimit("max",e,!0,G.errorUtil.toString(n))}lt(e,n){return this.setLimit("max",e,!1,G.errorUtil.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:G.errorUtil.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:G.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:G.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:G.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:G.errorUtil.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:G.errorUtil.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};S.ZodBigInt=rr;rr.create=t=>new rr({checks:[],typeName:Y.ZodBigInt,coerce:t?.coerce??!1,...ee(t)});var sr=class extends te{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==j.ZodParsedType.boolean){let r=this._getOrReturnCtx(e);return(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.invalid_type,expected:j.ZodParsedType.boolean,received:r.parsedType}),x.INVALID}return(0,x.OK)(e.data)}};S.ZodBoolean=sr;sr.create=t=>new sr({typeName:Y.ZodBoolean,coerce:t?.coerce||!1,...ee(t)});var ir=class t extends te{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==j.ZodParsedType.date){let i=this._getOrReturnCtx(e);return(0,x.addIssueToContext)(i,{code:$.ZodIssueCode.invalid_type,expected:j.ZodParsedType.date,received:i.parsedType}),x.INVALID}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return(0,x.addIssueToContext)(i,{code:$.ZodIssueCode.invalid_date}),x.INVALID}let r=new x.ParseStatus,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{code:$.ZodIssueCode.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{code:$.ZodIssueCode.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):j.util.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:G.errorUtil.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:G.errorUtil.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};S.ZodDate=ir;ir.create=t=>new ir({checks:[],coerce:t?.coerce||!1,typeName:Y.ZodDate,...ee(t)});var ss=class extends te{_parse(e){if(this._getType(e)!==j.ZodParsedType.symbol){let r=this._getOrReturnCtx(e);return(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.invalid_type,expected:j.ZodParsedType.symbol,received:r.parsedType}),x.INVALID}return(0,x.OK)(e.data)}};S.ZodSymbol=ss;ss.create=t=>new ss({typeName:Y.ZodSymbol,...ee(t)});var or=class extends te{_parse(e){if(this._getType(e)!==j.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.invalid_type,expected:j.ZodParsedType.undefined,received:r.parsedType}),x.INVALID}return(0,x.OK)(e.data)}};S.ZodUndefined=or;or.create=t=>new or({typeName:Y.ZodUndefined,...ee(t)});var ar=class extends te{_parse(e){if(this._getType(e)!==j.ZodParsedType.null){let r=this._getOrReturnCtx(e);return(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.invalid_type,expected:j.ZodParsedType.null,received:r.parsedType}),x.INVALID}return(0,x.OK)(e.data)}};S.ZodNull=ar;ar.create=t=>new ar({typeName:Y.ZodNull,...ee(t)});var vn=class extends te{constructor(){super(...arguments),this._any=!0}_parse(e){return(0,x.OK)(e.data)}};S.ZodAny=vn;vn.create=t=>new vn({typeName:Y.ZodAny,...ee(t)});var Wt=class extends te{constructor(){super(...arguments),this._unknown=!0}_parse(e){return(0,x.OK)(e.data)}};S.ZodUnknown=Wt;Wt.create=t=>new Wt({typeName:Y.ZodUnknown,...ee(t)});var bt=class extends te{_parse(e){let n=this._getOrReturnCtx(e);return(0,x.addIssueToContext)(n,{code:$.ZodIssueCode.invalid_type,expected:j.ZodParsedType.never,received:n.parsedType}),x.INVALID}};S.ZodNever=bt;bt.create=t=>new bt({typeName:Y.ZodNever,...ee(t)});var is=class extends te{_parse(e){if(this._getType(e)!==j.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.invalid_type,expected:j.ZodParsedType.void,received:r.parsedType}),x.INVALID}return(0,x.OK)(e.data)}};S.ZodVoid=is;is.create=t=>new is({typeName:Y.ZodVoid,...ee(t)});var Vt=class t extends te{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==j.ZodParsedType.array)return(0,x.addIssueToContext)(n,{code:$.ZodIssueCode.invalid_type,expected:j.ZodParsedType.array,received:n.parsedType}),x.INVALID;if(s.exactLength!==null){let o=n.data.length>s.exactLength.value,l=n.data.length<s.exactLength.value;(o||l)&&((0,x.addIssueToContext)(n,{code:o?$.ZodIssueCode.too_big:$.ZodIssueCode.too_small,minimum:l?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&((0,x.addIssueToContext)(n,{code:$.ZodIssueCode.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&((0,x.addIssueToContext)(n,{code:$.ZodIssueCode.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((o,l)=>s.type._parseAsync(new lt(n,o,n.path,l)))).then(o=>x.ParseStatus.mergeArray(r,o));let i=[...n.data].map((o,l)=>s.type._parseSync(new lt(n,o,n.path,l)));return x.ParseStatus.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:G.errorUtil.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:G.errorUtil.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:G.errorUtil.toString(n)}})}nonempty(e){return this.min(1,e)}};S.ZodArray=Vt;Vt.create=(t,e)=>new Vt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Y.ZodArray,...ee(e)});function rs(t){if(t instanceof Ke){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=at.create(rs(r))}return new Ke({...t._def,shape:()=>e})}else return t instanceof Vt?new Vt({...t._def,type:rs(t.element)}):t instanceof at?at.create(rs(t.unwrap())):t instanceof It?It.create(rs(t.unwrap())):t instanceof At?At.create(t.items.map(e=>rs(e))):t}var Ke=class t extends te{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),n=j.util.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==j.ZodParsedType.object){let u=this._getOrReturnCtx(e);return(0,x.addIssueToContext)(u,{code:$.ZodIssueCode.invalid_type,expected:j.ZodParsedType.object,received:u.parsedType}),x.INVALID}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),l=[];if(!(this._def.catchall instanceof bt&&this._def.unknownKeys==="strip"))for(let u in s.data)o.includes(u)||l.push(u);let c=[];for(let u of o){let p=i[u],f=s.data[u];c.push({key:{status:"valid",value:u},value:p._parse(new lt(s,f,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof bt){let u=this._def.unknownKeys;if(u==="passthrough")for(let p of l)c.push({key:{status:"valid",value:p},value:{status:"valid",value:s.data[p]}});else if(u==="strict")l.length>0&&((0,x.addIssueToContext)(s,{code:$.ZodIssueCode.unrecognized_keys,keys:l}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let p of l){let f=s.data[p];c.push({key:{status:"valid",value:p},value:u._parse(new lt(s,f,s.path,p)),alwaysSet:p in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let u=[];for(let p of c){let f=await p.key,b=await p.value;u.push({key:f,value:b,alwaysSet:p.alwaysSet})}return u}).then(u=>x.ParseStatus.mergeObjectSync(r,u)):x.ParseStatus.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return G.errorUtil.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:G.errorUtil.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Y.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of j.util.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of j.util.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return rs(this)}partial(e){let n={};for(let r of j.util.objectKeys(this.shape)){let s=this.shape[r];e&&!e[r]?n[r]=s:n[r]=s.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of j.util.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof at;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return Uu(j.util.objectKeys(this.shape))}};S.ZodObject=Ke;Ke.create=(t,e)=>new Ke({shape:()=>t,unknownKeys:"strip",catchall:bt.create(),typeName:Y.ZodObject,...ee(e)});Ke.strictCreate=(t,e)=>new Ke({shape:()=>t,unknownKeys:"strict",catchall:bt.create(),typeName:Y.ZodObject,...ee(e)});Ke.lazycreate=(t,e)=>new Ke({shape:t,unknownKeys:"strip",catchall:bt.create(),typeName:Y.ZodObject,...ee(e)});var lr=class extends te{_parse(e){let{ctx:n}=this._processInputParams(e),r=this._def.options;function s(i){for(let l of i)if(l.result.status==="valid")return l.result;for(let l of i)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;let o=i.map(l=>new $.ZodError(l.ctx.common.issues));return(0,x.addIssueToContext)(n,{code:$.ZodIssueCode.invalid_union,unionErrors:o}),x.INVALID}if(n.common.async)return Promise.all(r.map(async i=>{let o={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let c of r){let u={...n,common:{...n.common,issues:[]},parent:null},p=c._parseSync({data:n.data,path:n.path,parent:u});if(p.status==="valid")return p;p.status==="dirty"&&!i&&(i={result:p,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let l=o.map(c=>new $.ZodError(c));return(0,x.addIssueToContext)(n,{code:$.ZodIssueCode.invalid_union,unionErrors:l}),x.INVALID}}get options(){return this._def.options}};S.ZodUnion=lr;lr.create=(t,e)=>new lr({options:t,typeName:Y.ZodUnion,...ee(e)});var Zt=t=>t instanceof ur?Zt(t.schema):t instanceof Ve?Zt(t.innerType()):t instanceof dr?[t.value]:t instanceof hr?t.options:t instanceof pr?j.util.objectValues(t.enum):t instanceof fr?Zt(t._def.innerType):t instanceof or?[void 0]:t instanceof ar?[null]:t instanceof at?[void 0,...Zt(t.unwrap())]:t instanceof It?[null,...Zt(t.unwrap())]:t instanceof Fs||t instanceof gr?Zt(t.unwrap()):t instanceof mr?Zt(t._def.innerType):[],qi=class t extends te{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==j.ZodParsedType.object)return(0,x.addIssueToContext)(n,{code:$.ZodIssueCode.invalid_type,expected:j.ZodParsedType.object,received:n.parsedType}),x.INVALID;let r=this.discriminator,s=n.data[r],i=this.optionsMap.get(s);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):((0,x.addIssueToContext)(n,{code:$.ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),x.INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let s=new Map;for(let i of n){let o=Zt(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let l of o){if(s.has(l))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(l)}`);s.set(l,i)}}return new t({typeName:Y.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...ee(r)})}};S.ZodDiscriminatedUnion=qi;function Ma(t,e){let n=(0,j.getParsedType)(t),r=(0,j.getParsedType)(e);if(t===e)return{valid:!0,data:t};if(n===j.ZodParsedType.object&&r===j.ZodParsedType.object){let s=j.util.objectKeys(e),i=j.util.objectKeys(t).filter(l=>s.indexOf(l)!==-1),o={...t,...e};for(let l of i){let c=Ma(t[l],e[l]);if(!c.valid)return{valid:!1};o[l]=c.data}return{valid:!0,data:o}}else if(n===j.ZodParsedType.array&&r===j.ZodParsedType.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<t.length;i++){let o=t[i],l=e[i],c=Ma(o,l);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===j.ZodParsedType.date&&r===j.ZodParsedType.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var cr=class extends te{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=(i,o)=>{if((0,x.isAborted)(i)||(0,x.isAborted)(o))return x.INVALID;let l=Ma(i.value,o.value);return l.valid?(((0,x.isDirty)(i)||(0,x.isDirty)(o))&&n.dirty(),{status:n.value,value:l.data}):((0,x.addIssueToContext)(r,{code:$.ZodIssueCode.invalid_intersection_types}),x.INVALID)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};S.ZodIntersection=cr;cr.create=(t,e,n)=>new cr({left:t,right:e,typeName:Y.ZodIntersection,...ee(n)});var At=class t extends te{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==j.ZodParsedType.array)return(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.invalid_type,expected:j.ZodParsedType.array,received:r.parsedType}),x.INVALID;if(r.data.length<this._def.items.length)return(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),x.INVALID;!this._def.rest&&r.data.length>this._def.items.length&&((0,x.addIssueToContext)(r,{code:$.ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let i=[...r.data].map((o,l)=>{let c=this._def.items[l]||this._def.rest;return c?c._parse(new lt(r,o,r.path,l)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>x.ParseStatus.mergeArray(n,o)):x.ParseStatus.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};S.ZodTuple=At;At.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new At({items:t,typeName:Y.ZodTuple,rest:null,...ee(e)})};var Fi=class t extends te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==j.ZodParsedType.object)return(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.invalid_type,expected:j.ZodParsedType.object,received:r.parsedType}),x.INVALID;let s=[],i=this._def.keyType,o=this._def.valueType;for(let l in r.data)s.push({key:i._parse(new lt(r,l,r.path,l)),value:o._parse(new lt(r,r.data[l],r.path,l)),alwaysSet:l in r.data});return r.common.async?x.ParseStatus.mergeObjectAsync(n,s):x.ParseStatus.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof te?new t({keyType:e,valueType:n,typeName:Y.ZodRecord,...ee(r)}):new t({keyType:wn.create(),valueType:e,typeName:Y.ZodRecord,...ee(n)})}};S.ZodRecord=Fi;var os=class extends te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==j.ZodParsedType.map)return(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.invalid_type,expected:j.ZodParsedType.map,received:r.parsedType}),x.INVALID;let s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([l,c],u)=>({key:s._parse(new lt(r,l,r.path,[u,"key"])),value:i._parse(new lt(r,c,r.path,[u,"value"]))}));if(r.common.async){let l=new Map;return Promise.resolve().then(async()=>{for(let c of o){let u=await c.key,p=await c.value;if(u.status==="aborted"||p.status==="aborted")return x.INVALID;(u.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(u.value,p.value)}return{status:n.value,value:l}})}else{let l=new Map;for(let c of o){let u=c.key,p=c.value;if(u.status==="aborted"||p.status==="aborted")return x.INVALID;(u.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(u.value,p.value)}return{status:n.value,value:l}}}};S.ZodMap=os;os.create=(t,e,n)=>new os({valueType:e,keyType:t,typeName:Y.ZodMap,...ee(n)});var as=class t extends te{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==j.ZodParsedType.set)return(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.invalid_type,expected:j.ZodParsedType.set,received:r.parsedType}),x.INVALID;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&((0,x.addIssueToContext)(r,{code:$.ZodIssueCode.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&((0,x.addIssueToContext)(r,{code:$.ZodIssueCode.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let i=this._def.valueType;function o(c){let u=new Set;for(let p of c){if(p.status==="aborted")return x.INVALID;p.status==="dirty"&&n.dirty(),u.add(p.value)}return{status:n.value,value:u}}let l=[...r.data.values()].map((c,u)=>i._parse(new lt(r,c,r.path,u)));return r.common.async?Promise.all(l).then(c=>o(c)):o(l)}min(e,n){return new t({...this._def,minSize:{value:e,message:G.errorUtil.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:G.errorUtil.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};S.ZodSet=as;as.create=(t,e)=>new as({valueType:t,minSize:null,maxSize:null,typeName:Y.ZodSet,...ee(e)});var Bi=class t extends te{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==j.ZodParsedType.function)return(0,x.addIssueToContext)(n,{code:$.ZodIssueCode.invalid_type,expected:j.ZodParsedType.function,received:n.parsedType}),x.INVALID;function r(l,c){return(0,x.makeIssue)({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,(0,Ui.getErrorMap)(),Ui.defaultErrorMap].filter(u=>!!u),issueData:{code:$.ZodIssueCode.invalid_arguments,argumentsError:c}})}function s(l,c){return(0,x.makeIssue)({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,(0,Ui.getErrorMap)(),Ui.defaultErrorMap].filter(u=>!!u),issueData:{code:$.ZodIssueCode.invalid_return_type,returnTypeError:c}})}let i={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof kn){let l=this;return(0,x.OK)(async function(...c){let u=new $.ZodError([]),p=await l._def.args.parseAsync(c,i).catch(w=>{throw u.addIssue(r(c,w)),u}),f=await Reflect.apply(o,this,p);return await l._def.returns._def.type.parseAsync(f,i).catch(w=>{throw u.addIssue(s(f,w)),u})})}else{let l=this;return(0,x.OK)(function(...c){let u=l._def.args.safeParse(c,i);if(!u.success)throw new $.ZodError([r(c,u.error)]);let p=Reflect.apply(o,this,u.data),f=l._def.returns.safeParse(p,i);if(!f.success)throw new $.ZodError([s(p,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:At.create(e).rest(Wt.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new t({args:e||At.create([]).rest(Wt.create()),returns:n||Wt.create(),typeName:Y.ZodFunction,...ee(r)})}};S.ZodFunction=Bi;var ur=class extends te{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};S.ZodLazy=ur;ur.create=(t,e)=>new ur({getter:t,typeName:Y.ZodLazy,...ee(e)});var dr=class extends te{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return(0,x.addIssueToContext)(n,{received:n.data,code:$.ZodIssueCode.invalid_literal,expected:this._def.value}),x.INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}};S.ZodLiteral=dr;dr.create=(t,e)=>new dr({value:t,typeName:Y.ZodLiteral,...ee(e)});function Uu(t,e){return new hr({values:t,typeName:Y.ZodEnum,...ee(e)})}var hr=class t extends te{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return(0,x.addIssueToContext)(n,{expected:j.util.joinValues(r),received:n.parsedType,code:$.ZodIssueCode.invalid_type}),x.INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return(0,x.addIssueToContext)(n,{received:n.data,code:$.ZodIssueCode.invalid_enum_value,options:r}),x.INVALID}return(0,x.OK)(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};S.ZodEnum=hr;hr.create=Uu;var pr=class extends te{_parse(e){let n=j.util.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==j.ZodParsedType.string&&r.parsedType!==j.ZodParsedType.number){let s=j.util.objectValues(n);return(0,x.addIssueToContext)(r,{expected:j.util.joinValues(s),received:r.parsedType,code:$.ZodIssueCode.invalid_type}),x.INVALID}if(this._cache||(this._cache=new Set(j.util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=j.util.objectValues(n);return(0,x.addIssueToContext)(r,{received:r.data,code:$.ZodIssueCode.invalid_enum_value,options:s}),x.INVALID}return(0,x.OK)(e.data)}get enum(){return this._def.values}};S.ZodNativeEnum=pr;pr.create=(t,e)=>new pr({values:t,typeName:Y.ZodNativeEnum,...ee(e)});var kn=class extends te{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==j.ZodParsedType.promise&&n.common.async===!1)return(0,x.addIssueToContext)(n,{code:$.ZodIssueCode.invalid_type,expected:j.ZodParsedType.promise,received:n.parsedType}),x.INVALID;let r=n.parsedType===j.ZodParsedType.promise?n.data:Promise.resolve(n.data);return(0,x.OK)(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};S.ZodPromise=kn;kn.create=(t,e)=>new kn({type:t,typeName:Y.ZodPromise,...ee(e)});var Ve=class extends te{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Y.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{(0,x.addIssueToContext)(r,o),o.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(r.data,i);if(r.common.async)return Promise.resolve(o).then(async l=>{if(n.value==="aborted")return x.INVALID;let c=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return c.status==="aborted"?x.INVALID:c.status==="dirty"||n.value==="dirty"?(0,x.DIRTY)(c.value):c});{if(n.value==="aborted")return x.INVALID;let l=this._def.schema._parseSync({data:o,path:r.path,parent:r});return l.status==="aborted"?x.INVALID:l.status==="dirty"||n.value==="dirty"?(0,x.DIRTY)(l.value):l}}if(s.type==="refinement"){let o=l=>{let c=s.refinement(l,i);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){let l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?x.INVALID:(l.status==="dirty"&&n.dirty(),o(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?x.INVALID:(l.status==="dirty"&&n.dirty(),o(l.value).then(()=>({status:n.value,value:l.value}))))}if(s.type==="transform")if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!(0,x.isValid)(o))return x.INVALID;let l=s.transform(o.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>(0,x.isValid)(o)?Promise.resolve(s.transform(o.value,i)).then(l=>({status:n.value,value:l})):x.INVALID);j.util.assertNever(s)}};S.ZodEffects=Ve;S.ZodTransformer=Ve;Ve.create=(t,e,n)=>new Ve({schema:t,typeName:Y.ZodEffects,effect:e,...ee(n)});Ve.createWithPreprocess=(t,e,n)=>new Ve({schema:e,effect:{type:"preprocess",transform:t},typeName:Y.ZodEffects,...ee(n)});var at=class extends te{_parse(e){return this._getType(e)===j.ZodParsedType.undefined?(0,x.OK)(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};S.ZodOptional=at;at.create=(t,e)=>new at({innerType:t,typeName:Y.ZodOptional,...ee(e)});var It=class extends te{_parse(e){return this._getType(e)===j.ZodParsedType.null?(0,x.OK)(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};S.ZodNullable=It;It.create=(t,e)=>new It({innerType:t,typeName:Y.ZodNullable,...ee(e)});var fr=class extends te{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===j.ZodParsedType.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};S.ZodDefault=fr;fr.create=(t,e)=>new fr({innerType:t,typeName:Y.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ee(e)});var mr=class extends te{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return(0,x.isAsync)(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new $.ZodError(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new $.ZodError(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};S.ZodCatch=mr;mr.create=(t,e)=>new mr({innerType:t,typeName:Y.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ee(e)});var ls=class extends te{_parse(e){if(this._getType(e)!==j.ZodParsedType.nan){let r=this._getOrReturnCtx(e);return(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.invalid_type,expected:j.ZodParsedType.nan,received:r.parsedType}),x.INVALID}return{status:"valid",value:e.data}}};S.ZodNaN=ls;ls.create=t=>new ls({typeName:Y.ZodNaN,...ee(t)});S.BRAND=Symbol("zod_brand");var Fs=class extends te{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}};S.ZodBranded=Fs;var Bs=class t extends te{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?x.INVALID:i.status==="dirty"?(n.dirty(),(0,x.DIRTY)(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?x.INVALID:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:Y.ZodPipeline})}};S.ZodPipeline=Bs;var gr=class extends te{_parse(e){let n=this._def.innerType._parse(e),r=s=>((0,x.isValid)(s)&&(s.value=Object.freeze(s.value)),s);return(0,x.isAsync)(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};S.ZodReadonly=gr;gr.create=(t,e)=>new gr({innerType:t,typeName:Y.ZodReadonly,...ee(e)});function Mu(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function qu(t,e={},n){return t?vn.create().superRefine((r,s)=>{let i=t(r);if(i instanceof Promise)return i.then(o=>{if(!o){let l=Mu(e,r),c=l.fatal??n??!0;s.addIssue({code:"custom",...l,fatal:c})}});if(!i){let o=Mu(e,r),l=o.fatal??n??!0;s.addIssue({code:"custom",...o,fatal:l})}}):vn.create()}S.late={object:Ke.lazycreate};var Y;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(Y||(S.ZodFirstPartyTypeKind=Y={}));var $y=(t,e={message:`Input not instance of ${t.name}`})=>qu(n=>n instanceof t,e);S.instanceof=$y;var Fu=wn.create;S.string=Fu;var Bu=nr.create;S.number=Bu;var Py=ls.create;S.nan=Py;var jy=rr.create;S.bigint=jy;var Hu=sr.create;S.boolean=Hu;var Ny=ir.create;S.date=Ny;var Oy=ss.create;S.symbol=Oy;var My=or.create;S.undefined=My;var zy=ar.create;S.null=zy;var Dy=vn.create;S.any=Dy;var Ly=Wt.create;S.unknown=Ly;var Uy=bt.create;S.never=Uy;var qy=is.create;S.void=qy;var Fy=Vt.create;S.array=Fy;var By=Ke.create;S.object=By;var Hy=Ke.strictCreate;S.strictObject=Hy;var Ky=lr.create;S.union=Ky;var Gy=qi.create;S.discriminatedUnion=Gy;var Zy=cr.create;S.intersection=Zy;var Wy=At.create;S.tuple=Wy;var Vy=Fi.create;S.record=Vy;var Jy=os.create;S.map=Jy;var Yy=as.create;S.set=Yy;var Xy=Bi.create;S.function=Xy;var Qy=ur.create;S.lazy=Qy;var eb=dr.create;S.literal=eb;var tb=hr.create;S.enum=tb;var nb=pr.create;S.nativeEnum=nb;var rb=kn.create;S.promise=rb;var Ku=Ve.create;S.effect=Ku;S.transformer=Ku;var sb=at.create;S.optional=sb;var ib=It.create;S.nullable=ib;var ob=Ve.createWithPreprocess;S.preprocess=ob;var ab=Bs.create;S.pipeline=ab;var lb=()=>Fu().optional();S.ostring=lb;var cb=()=>Bu().optional();S.onumber=cb;var ub=()=>Hu().optional();S.oboolean=ub;S.coerce={string:(t=>wn.create({...t,coerce:!0})),number:(t=>nr.create({...t,coerce:!0})),boolean:(t=>sr.create({...t,coerce:!0})),bigint:(t=>rr.create({...t,coerce:!0})),date:(t=>ir.create({...t,coerce:!0}))};S.NEVER=x.INVALID});var za=ae(ct=>{"use strict";var db=ct&&ct.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),cs=ct&&ct.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&db(e,t,n)};Object.defineProperty(ct,"__esModule",{value:!0});cs(Di(),ct);cs(Na(),ct);cs(Pu(),ct);cs(Us(),ct);cs(Gu(),ct);cs(zi(),ct)});var Vu=ae(Ge=>{"use strict";var Zu=Ge&&Ge.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),hb=Ge&&Ge.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),pb=Ge&&Ge.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&Zu(e,t,n);return hb(e,t),e},fb=Ge&&Ge.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Zu(e,t,n)};Object.defineProperty(Ge,"__esModule",{value:!0});Ge.z=void 0;var Wu=pb(za());Ge.z=Wu;fb(za(),Ge);Ge.default=Wu});var ke=ae(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.BUILTIN_REPLY_LANGUAGES=h.ChatLoadMsg=h.ChatListResultMsg=h.ChatListMsg=h.ChatUsageMsg=h.ChatStreamMsg=h.JiraUsersResultMsg=h.DeployClaimResultMsg=h.DeployClaimMsg=h.RuleDiagnoseResultMsg=h.ProjectTestResultMsg=h.RunStatusMsg=h.FailedTest=h.RunUsageMsg=h.RunLogMsg=h.RunClaimMsg=h.HeartbeatMsg=h.HelloMsg=h.RuleConfig=h.ProjectConfig=h.ActionConfig=h.DeployAction=h.EnvironmentConfig=h.PromotionMode=h.DeployStep=h.RespondAction=h.ImplementAction=h.PlanOnlyAction=h.TriggerConfig=h.StatusChangedTrigger=h.CommentKeywordTrigger=h.LabelAddedTrigger=h.ActionType=h.TriggerType=h.ACTIVE_RUN_STATUSES=h.RunStatus=h.needsInputMarkerIn=h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=h.NEEDS_INPUT_COMMENT_MARKER=h.NEEDS_INPUT_LABEL=h.NEEDS_INPUT_ASK_FENCE=h.NEEDS_INPUT_MARKER=h.BRANCH_DEPLOY_ISSUE_KEY=h.REQUIRED_AGENT_CAPABILITIES=h.DEFAULT_AGENT_ID=h.REGISTERED_AGENTS=h.DEPLOY_DOC_CANDIDATES=h.RUNNER_UNINSTALL_COMMAND=h.PROTOCOL_VERSION=h.GITHUB_TOKEN_PERMISSIONS=void 0;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.AuditExplainResultMsg=h.AuditExplainMsg=h.ChatCancelMsg=h.ChatDiagnosticResultMsg=h.ChatDiagnosticMsg=h.AuditListResultMsg=h.AuditStatsResultMsg=h.AuditStatsMsg=h.AuditListMsg=h.AuditStartResultMsg=h.AuditStartMsg=h.AuditRecord=h.AuditFinding=h.AuditDetailLevel=h.AuditScope=h.AuditSeverity=h.KnowledgeRole=h.AuditRole=h.EpicSuggestResultMsg=h.EpicSuggestMsg=h.EpicListResultMsg=h.EpicChild=h.EpicListMsg=h.BoardTriggerResultMsg=h.BoardTriggerMsg=h.BoardFetchResultMsg=h.BoardFetchMsg=h.RepoDocReadResultMsg=h.RepoDocReadMsg=h.RepoDocsResultMsg=h.RepoDocsMsg=h.ChatLoadResultMsg=h.REPLY_STYLES=void 0;h.DeploySuggestMsg=h.DeployFixMsg=h.DeployStartMsg=h.RunRetryPushMsg=h.RunRejectedMsg=h.RunApprovedMsg=h.RunCancelMsg=h.RuleDiagnoseMsg=h.ProjectTestMsg=h.RunClaimResultMsg=h.ConfigMsg=h.HelloAckMsg=h.RunnerToServerMsg=h.AutopilotReportMsg=h.AutopilotNextResultMsg=h.AutopilotPlanResultMsg=h.AutopilotPlanMsg=h.AutopilotNextMsg=h.RunnerUninstallResultMsg=h.RunnerUpdateResultMsg=h.AgentProfilesResultMsg=h.AgentProfilesMsg=h.RunPrConflictMsg=h.RunResolveConflictResultMsg=h.RunAnswerResultMsg=h.RunAnswerMsg=h.RunTestFixResultMsg=h.RunTestFixMsg=h.RunResolveConflictMsg=h.RunnerUninstallMsg=h.RunnerUpdateMsg=h.RepoDocSaveResultMsg=h.RepoDocSaveMsg=h.SetupClaudeMdSaveResultMsg=h.SetupClaudeMdSaveMsg=h.SetupAskResultMsg=h.SetupAskMsg=h.SetupClaudeMdGenerateResultMsg=h.SetupClaudeMdGenerateMsg=h.SetupRecheckResultMsg=h.SetupRecheckMsg=h.RepoUnmapResultMsg=h.RepoUnmapMsg=h.SetupStatusResultMsg=h.SetupStatusMsg=h.DeploySuggestResultMsg=h.SelfMigrationApplyResultMsg=h.SelfMigrationApplyMsg=h.SELF_MIGRATION_DIR=h.EnvPreflightResultMsg=void 0;h.DEFAULT_DEPLOY_SUGGEST_PROMPT_TEMPLATE=h.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE=h.DEPLOY_FIX_PROMPT_TEMPLATE=h.PROMPT_PRESETS=h.DEFAULT_RESPOND_PROMPT_TEMPLATE=h.BUGFIX_IMPLEMENT_PROMPT_TEMPLATE=h.BUG_INVESTIGATION_PROMPT_TEMPLATE=h.TECHNICAL_PLAN_PROMPT_TEMPLATE=h.MEMORY_UPDATE_PROMPT=h.DEFAULT_IMPLEMENT_PROMPT_TEMPLATE=h.WRITE_TESTS_PROMPT=h.FOCUSED_READING_PROMPT=h.NEEDS_INPUT_OPTIONS_PROMPT=h.DEFAULT_PLAN_PROMPT_TEMPLATE=h.EnrollResponse=h.EnrollRequest=h.ServerToRunnerMsg=h.JiraUsersMsg=void 0;h.missingAgentCapabilities=mb;h.replyPreferenceAppendix=yb;h.pendingMigrationsAppendix=bb;h.deployTargetsAppendix=wb;h.isSelfMigrationFilename=vb;h.parseRunnerMsg=kb;h.parseServerMsg=_b;var a=Vu();h.GITHUB_TOKEN_PERMISSIONS={where:"github.com/settings/personal-access-tokens/new (fine-grained token)",steps:["Resource owner: the org or user that OWNS the repo - not your personal account, unless the repo is under it","Repository access: Only select repositories -> pick this repo","Contents: Read and write - pushing the agent's branch","Pull requests: Read and write - opening the PR, and merging it when you approve","Metadata: Read-only - GitHub adds this itself and will not let you remove it","Workflows: Read and write - ONLY if changes may touch .github/workflows; without it GitHub rejects those pushes"],note:"A fine-grained token covers exactly ONE resource owner, so a repo in a different org always needs its own token. A classic token with the `repo` scope also works and is simpler, but it reaches every repository you can see - prefer fine-grained."};h.PROTOCOL_VERSION="1.76";h.RUNNER_UNINSTALL_COMMAND="sudo allwright service uninstall";h.DEPLOY_DOC_CANDIDATES=[".ticketpilot/deploy.md","DEPLOY.md","DEPLOYMENT.md","docs/DEPLOY.md","docs/deploy.md","docs/deployment.md"];h.REGISTERED_AGENTS=[{id:"claude-code",displayName:"Claude Code",capabilities:{readOnlyJail:!0,editNoShellJail:!0,sessionResume:!0,costReporting:!0,modelSelection:!0,loginProfiles:!0},suggestedModels:["claude-fable-5","claude-opus-5","claude-sonnet-5","claude-haiku-4-5-20251001"],experimental:!1},{id:"codex",displayName:"OpenAI Codex CLI (experimental)",capabilities:{readOnlyJail:!0,editNoShellJail:!1,sessionResume:!1,costReporting:!1,modelSelection:!0,loginProfiles:!1},suggestedModels:[],experimental:!0}];h.DEFAULT_AGENT_ID="claude-code";h.REQUIRED_AGENT_CAPABILITIES={plan_only:["readOnlyJail","sessionResume"],respond:["readOnlyJail"],implement:["editNoShellJail","sessionResume"],deploy:[],chat:["readOnlyJail","sessionResume"],assist:["readOnlyJail"]};function mb(t,e){let n=h.REGISTERED_AGENTS.find(r=>r.id===t);return n?(h.REQUIRED_AGENT_CAPABILITIES[e]??[]).filter(r=>!n.capabilities[r]):null}h.BRANCH_DEPLOY_ISSUE_KEY="(branch deploy)";h.NEEDS_INPUT_MARKER="NEEDS-INPUT";h.NEEDS_INPUT_ASK_FENCE="ask";h.NEEDS_INPUT_LABEL="agent-needs-input";h.NEEDS_INPUT_COMMENT_MARKER="Allwright needs your input";h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=["TicketPilot needs your input"];var gb=t=>t.includes(h.NEEDS_INPUT_COMMENT_MARKER)||h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS.some(e=>t.includes(e));h.needsInputMarkerIn=gb;h.RunStatus=a.z.enum(["queued","running","posting","awaiting_approval","needs_input","succeeded","failed","timed_out"]);h.ACTIVE_RUN_STATUSES=["queued","running","posting","awaiting_approval"];h.TriggerType=a.z.enum(["label_added","comment_keyword","status_changed"]);h.ActionType=a.z.enum(["plan_only","implement","respond","deploy"]);h.LabelAddedTrigger=a.z.object({type:a.z.literal("label_added"),label:a.z.string().min(1),doneLabel:a.z.string().min(1).default("agent-planned"),failedLabel:a.z.string().min(1).default("agent-failed")});h.CommentKeywordTrigger=a.z.object({type:a.z.literal("comment_keyword"),keyword:a.z.string().min(1),doneLabel:a.z.string().min(1).default("agent-implemented"),failedLabel:a.z.string().min(1).default("agent-failed")});h.StatusChangedTrigger=a.z.object({type:a.z.literal("status_changed"),status:a.z.string().min(1),doneLabel:a.z.string().min(1).default("agent-deployed"),failedLabel:a.z.string().min(1).default("agent-failed")});h.TriggerConfig=a.z.discriminatedUnion("type",[h.LabelAddedTrigger,h.CommentKeywordTrigger,h.StatusChangedTrigger]);h.PlanOnlyAction=a.z.object({type:a.z.literal("plan_only"),promptTemplate:a.z.string().min(1),timeoutSeconds:a.z.number().int().positive().max(3600).default(900),agent:a.z.string().default(h.DEFAULT_AGENT_ID),model:a.z.string().default("")});h.ImplementAction=a.z.object({type:a.z.literal("implement"),promptTemplate:a.z.string().min(1),timeoutSeconds:a.z.number().int().positive().max(7200).default(1800),maxTurns:a.z.number().int().positive().max(500).default(120),requireApproval:a.z.boolean().default(!0),branchTemplate:a.z.string().min(1).default("agent/{{issueKey}}").refine(t=>t.includes("{{issueKey}}"),{message:"branchTemplate must contain {{issueKey}}"}),baseBranch:a.z.string().min(1).default("main"),jiraTransition:a.z.string().optional(),jiraTransitionOnStart:a.z.string().optional(),jiraTransitionOnMerge:a.z.string().optional(),agent:a.z.string().default(h.DEFAULT_AGENT_ID),model:a.z.string().default(""),updateMemory:a.z.boolean().default(!1),writeTests:a.z.boolean().default(!0),runTests:a.z.boolean().default(!0),mergeOnApprove:a.z.boolean().default(!0),mergeMethod:a.z.enum(["squash","merge","rebase"]).default("squash"),autoMerge:a.z.boolean().default(!0)});h.RespondAction=a.z.object({type:a.z.literal("respond"),promptTemplate:a.z.string().min(1),timeoutSeconds:a.z.number().int().positive().max(3600).default(600),agent:a.z.string().default(h.DEFAULT_AGENT_ID),model:a.z.string().default("")});h.DeployStep=a.z.object({name:a.z.string().min(1).max(120),run:a.z.string().min(1).max(4e3),continueOnError:a.z.boolean().default(!1)});h.PromotionMode=a.z.enum(["deploy_only","merge_and_deploy"]);h.EnvironmentConfig=a.z.object({id:a.z.string(),projectId:a.z.string(),name:a.z.string(),rank:a.z.number().int().nonnegative(),auditBeforeDeploy:a.z.enum(["","security","testing"]).default(""),branch:a.z.string().default(""),publicUrl:a.z.string().default(""),servePath:a.z.string().default(""),useDedicatedCheckout:a.z.boolean().default(!1),promotionMode:h.PromotionMode.default("deploy_only"),ticketBranchTemplate:a.z.string().default("agent/{{issueKey}}"),steps:a.z.array(h.DeployStep).default([]),workdir:a.z.string().default(""),timeoutSeconds:a.z.number().int().positive().max(21600).default(1800),requiredSecrets:a.z.array(a.z.string()).default([]),requireApproval:a.z.boolean().default(!1),requireSyncCheck:a.z.boolean().default(!1),previousEnvBranch:a.z.string().optional(),deployFromColumn:a.z.string().default(""),deployToColumn:a.z.string().default("")});h.DeployAction=a.z.object({type:a.z.literal("deploy"),envSelection:a.z.enum(["fixed","from_comment"]).default("from_comment"),environmentId:a.z.string().optional(),requireStatus:a.z.string().optional()});h.ActionConfig=a.z.discriminatedUnion("type",[h.PlanOnlyAction,h.ImplementAction,h.RespondAction,h.DeployAction]);h.ProjectConfig=a.z.object({id:a.z.string(),name:a.z.string(),jiraProjectKey:a.z.string(),goLiveIssueKey:a.z.string().default(""),repoName:a.z.string(),jiraSiteUrl:a.z.string().default(""),defaultAgent:a.z.string().default("claude-code"),componentRoutes:a.z.array(a.z.object({component:a.z.string().min(1),repoName:a.z.string().min(1)})).default([])});h.RuleConfig=a.z.object({id:a.z.string(),projectId:a.z.string(),name:a.z.string(),enabled:a.z.boolean(),trigger:h.TriggerConfig,action:h.ActionConfig});h.HelloMsg=a.z.object({type:a.z.literal("hello"),protocolVersion:a.z.string(),runnerVersion:a.z.string(),platform:a.z.string(),justBooted:a.z.boolean().optional()});h.HeartbeatMsg=a.z.object({type:a.z.literal("heartbeat"),ts:a.z.string()});h.RunClaimMsg=a.z.object({type:a.z.literal("run.claim"),requestId:a.z.string(),ruleId:a.z.string(),issueKey:a.z.string(),issueSummary:a.z.string().default(""),triggerFingerprint:a.z.string(),dedupKey:a.z.string().optional(),triggeredByAccountId:a.z.string().optional()});h.RunLogMsg=a.z.object({type:a.z.literal("run.log"),runId:a.z.string(),seq:a.z.number().int().nonnegative(),ts:a.z.string(),level:a.z.enum(["info","warn","error","agent"]),message:a.z.string().max(16384)});h.RunUsageMsg=a.z.object({type:a.z.literal("run.usage"),runId:a.z.string(),inputTokens:a.z.number().int().nonnegative(),outputTokens:a.z.number().int().nonnegative(),cacheReadTokens:a.z.number().int().nonnegative().optional(),costUsd:a.z.number().nonnegative().optional(),turns:a.z.number().int().nonnegative().optional()});h.FailedTest=a.z.object({command:a.z.string().max(500),exitCode:a.z.number().int(),tail:a.z.string().max(4e3)});h.RunStatusMsg=a.z.object({type:a.z.literal("run.status"),runId:a.z.string(),status:h.RunStatus,error:a.z.string().optional(),errorKind:a.z.enum(["guard"]).optional(),costUsd:a.z.number().nonnegative().optional(),inputTokens:a.z.number().int().nonnegative().optional(),outputTokens:a.z.number().int().nonnegative().optional(),resultSummary:a.z.string().max(2e3).optional(),billingMode:a.z.enum(["subscription","api","unknown"]).optional(),model:a.z.string().max(200).optional(),prUrl:a.z.string().optional(),headSha:a.z.string().optional(),deployedRef:a.z.string().optional(),retryAvailable:a.z.boolean().optional(),failedTests:a.z.array(h.FailedTest).max(20).optional(),testsPassed:a.z.number().int().nonnegative().optional(),testsTotal:a.z.number().int().nonnegative().optional(),manualSteps:a.z.array(a.z.object({command:a.z.string().max(500),why:a.z.string().max(300).default("")})).max(20).optional(),goLiveDraft:a.z.string().max(4e3).optional(),inputQuestions:a.z.string().max(4e3).optional(),inputOptions:a.z.array(a.z.string().max(200)).max(5).optional()});h.ProjectTestResultMsg=a.z.object({type:a.z.literal("project.test.result"),requestId:a.z.string(),ok:a.z.boolean(),checks:a.z.array(a.z.object({name:a.z.string(),ok:a.z.boolean(),detail:a.z.string(),kind:a.z.enum(["connection","content"]).default("connection"),fix:a.z.array(a.z.string()).default([]),fixNote:a.z.string().default("")}))});h.RuleDiagnoseResultMsg=a.z.object({type:a.z.literal("rule.diagnose.result"),requestId:a.z.string(),checks:a.z.array(a.z.object({name:a.z.string(),ok:a.z.boolean(),detail:a.z.string(),kind:a.z.enum(["connection","content"]).default("connection"),fix:a.z.array(a.z.string()).default([]),fixNote:a.z.string().default("")})),matchedCount:a.z.number().int().nonnegative(),excludedCount:a.z.number().int().nonnegative(),excludedSample:a.z.array(a.z.string()).max(5)});h.DeployClaimMsg=a.z.object({type:a.z.literal("deploy.claim"),requestId:a.z.string(),projectId:a.z.string(),ruleId:a.z.string(),issueKey:a.z.string(),issueSummary:a.z.string().default(""),environmentName:a.z.string(),requestedByAccountId:a.z.string().optional(),requestedByDisplayName:a.z.string().default(""),dedupKey:a.z.string(),triggerFingerprint:a.z.string()});h.DeployClaimResultMsg=a.z.object({type:a.z.literal("deploy.claim.result"),requestId:a.z.string(),accepted:a.z.boolean(),runId:a.z.string().optional(),environment:h.EnvironmentConfig.optional(),reason:a.z.string().optional(),code:a.z.enum(["ok","duplicate","unknown_environment","not_permitted","unlinked_jira_account","promotion_order","jira_disabled","rule_disabled","cap"]).optional()});h.JiraUsersResultMsg=a.z.object({type:a.z.literal("jira.users.result"),requestId:a.z.string(),ok:a.z.boolean(),users:a.z.array(a.z.object({accountId:a.z.string(),displayName:a.z.string(),email:a.z.string().default(""),active:a.z.boolean().default(!0)})).default([]),error:a.z.string().optional()});h.ChatStreamMsg=a.z.object({type:a.z.literal("chat.stream"),requestId:a.z.string(),seq:a.z.number().int().nonnegative(),text:a.z.string().max(8e3)});h.ChatUsageMsg=a.z.object({type:a.z.literal("chat.usage"),requestId:a.z.string(),inputTokens:a.z.number().int().nonnegative(),outputTokens:a.z.number().int().nonnegative(),cacheReadTokens:a.z.number().int().nonnegative().optional(),turns:a.z.number().int().nonnegative().optional()});h.ChatListMsg=a.z.object({type:a.z.literal("chat.list"),requestId:a.z.string(),projectId:a.z.string()});h.ChatListResultMsg=a.z.object({type:a.z.literal("chat.list.result"),requestId:a.z.string(),sessions:a.z.array(a.z.object({sessionId:a.z.string(),title:a.z.string().default(""),updatedAt:a.z.string().default(""),messageCount:a.z.number().int().nonnegative().default(0)})).default([])});h.ChatLoadMsg=a.z.object({type:a.z.literal("chat.load"),requestId:a.z.string(),sessionId:a.z.string()});h.BUILTIN_REPLY_LANGUAGES=[{name:"English",instruction:"Write your prose in English."},{name:"Hindi",instruction:"Write your prose in Hindi, in the Devanagari script. Keep technical terms that have no everyday Hindi equivalent in English rather than inventing a translation."},{name:"Hinglish",instruction:"Write your prose in Hinglish: conversational Hindi written in the Latin alphabet, with English technical words left in English - the way an Indian developer talks at work."}];h.REPLY_STYLES=[{id:"technical",label:"Technical",hint:"Full detail - names files, functions and trade-offs",instruction:"Answer at full technical depth: name the files, functions and data structures involved, and state trade-offs precisely. Assume the reader reads code every day."},{id:"balanced",label:"Balanced",hint:"Plain explanation, with the technical detail that matters",instruction:"Explain in plain language first, then add the technical detail that actually matters for the decision. Assume the reader is technical but does not know this codebase."},{id:"simple",label:"Simple",hint:"Everyday words - no jargon unless it is unavoidable",instruction:"Answer in everyday words, as if to someone who does not write code. Avoid jargon; when a technical term is unavoidable, explain it in half a sentence. Prefer short paragraphs and concrete examples over precision about internals."}];function yb(t){let e=[],n=(t.language??"").trim();if(n){let s=h.BUILTIN_REPLY_LANGUAGES.find(i=>i.name.toLowerCase()===n.toLowerCase());e.push((t.languageInstruction??"").trim()||s?.instruction||`Write your prose in ${n}.`),e.push("Code, file paths, identifiers, commands, error text and log output stay exactly as they are - only your own prose changes language."),e.push("The ```ticket block is the exception: its summary and description are ALWAYS written in English, because the ticket is read by other people and by the implementing agent.")}let r=h.REPLY_STYLES.find(s=>s.id===(t.style??"").trim());return r&&e.push(r.instruction),e.length?`
|
|
23
|
+
`)}),this}_outputHelpIfRequested(e){let n=this._getHelpOption();n&&e.find(s=>n.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Wc(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let n,r="127.0.0.1",s="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?n=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(n=i[1],/^\d+$/.test(i[3])?s=i[3]:r=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(n=i[1],r=i[3],s=i[4]),n&&s!=="0"?`${n}=${r}:${parseInt(s)+1}`:e})}Vc.Command=wa});var eu=le(rt=>{var{Argument:Yc}=vi(),{Command:va}=Jc(),{CommanderError:Dm,InvalidArgumentError:Xc}=Os(),{Help:Lm}=da(),{Option:Qc}=ma();rt.program=new va;rt.createCommand=t=>new va(t);rt.createOption=(t,e)=>new Qc(t,e);rt.createArgument=(t,e)=>new Yc(t,e);rt.Command=va;rt.Option=Qc;rt.Argument=Yc;rt.Help=Lm;rt.CommanderError=Dm;rt.InvalidArgumentError=Xc;rt.InvalidOptionArgumentError=Xc});var se,ka,D,Tt,Ms=be(()=>{(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function n(s){throw new Error}t.assertNever=n,t.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},t.getValidEnumValues=s=>{let i=t.objectKeys(s).filter(l=>typeof s[s[l]]!="number"),o={};for(let l of i)o[l]=s[l];return t.objectValues(o)},t.objectValues=s=>t.objectKeys(s).map(function(i){return s[i]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},t.find=(s,i)=>{for(let o of s)if(i(o))return o},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(se||(se={}));(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(ka||(ka={}));D=se.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Tt=t=>{switch(typeof t){case"undefined":return D.undefined;case"string":return D.string;case"number":return Number.isNaN(t)?D.nan:D.number;case"boolean":return D.boolean;case"function":return D.function;case"bigint":return D.bigint;case"symbol":return D.symbol;case"object":return Array.isArray(t)?D.array:t===null?D.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?D.promise:typeof Map<"u"&&t instanceof Map?D.map:typeof Set<"u"&&t instanceof Set?D.set:typeof Date<"u"&&t instanceof Date?D.date:D.object;default:return D.unknown}}});var E,Um,Be,ki=be(()=>{Ms();E=se.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"]),Um=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Be=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(i){return i.message},r={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)r._errors.push(n(o));else{let l=r,c=0;for(;c<o.path.length;){let u=o.path[c];c===o.path.length-1?(l[u]=l[u]||{_errors:[]},l[u]._errors.push(n(o))):l[u]=l[u]||{_errors:[]},l=l[u],c++}}};return s(this),r}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,se.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];n[i]=n[i]||[],n[i].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};Be.create=t=>new Be(t)});var qm,Ut,_a=be(()=>{ki();Ms();qm=(t,e)=>{let n;switch(t.code){case E.invalid_type:t.received===D.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case E.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,se.jsonStringifyReplacer)}`;break;case E.unrecognized_keys:n=`Unrecognized key(s) in object: ${se.joinValues(t.keys,", ")}`;break;case E.invalid_union:n="Invalid input";break;case E.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${se.joinValues(t.options)}`;break;case E.invalid_enum_value:n=`Invalid enum value. Expected ${se.joinValues(t.options)}, received '${t.received}'`;break;case E.invalid_arguments:n="Invalid function arguments";break;case E.invalid_return_type:n="Invalid function return type";break;case E.invalid_date:n="Invalid date";break;case E.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:se.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case E.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case E.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case E.custom:n="Invalid input";break;case E.invalid_intersection_types:n="Intersection results could not be merged";break;case E.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case E.not_finite:n="Number must be finite";break;default:n=e.defaultError,se.assertNever(t)}return{message:n}},Ut=qm});function Fm(t){ru=t}function Hr(){return ru}var ru,_i=be(()=>{_a();ru=Ut});function O(t,e){let n=Hr(),r=zs({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Ut?void 0:Ut].filter(s=>!!s)});t.common.issues.push(r)}var zs,Bm,Ie,V,zn,Ce,Si,Ti,dn,Kr,Sa=be(()=>{_i();_a();zs=t=>{let{data:e,path:n,errorMaps:r,issueData:s}=t,i=[...n,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let l="",c=r.filter(u=>!!u).slice().reverse();for(let u of c)l=u(o,{data:e,defaultError:l}).message;return{...s,path:i,message:l}},Bm=[];Ie=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let s of n){if(s.status==="aborted")return V;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let s of n){let i=await s.key,o=await s.value;r.push({key:i,value:o})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let s of n){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return V;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(r[i.value]=o.value)}return{status:e.value,value:r}}},V=Object.freeze({status:"aborted"}),zn=t=>({status:"dirty",value:t}),Ce=t=>({status:"valid",value:t}),Si=t=>t.status==="aborted",Ti=t=>t.status==="dirty",dn=t=>t.status==="valid",Kr=t=>typeof Promise<"u"&&t instanceof Promise});var su=be(()=>{});var F,iu=be(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(F||(F={}))});function Q(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:s}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,l)=>{let{message:c}=t;return o.code==="invalid_enum_value"?{message:c??l.defaultError}:typeof l.data>"u"?{message:c??r??l.defaultError}:o.code!=="invalid_type"?{message:l.defaultError}:{message:c??n??l.defaultError}},description:s}}function cu(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function og(t){return new RegExp(`^${cu(t)}$`)}function uu(t){let e=`${lu}T${cu(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function ag(t,e){return!!((e==="v4"||!e)&&Qm.test(t)||(e==="v6"||!e)&&tg.test(t))}function lg(t,e){if(!Vm.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function cg(t,e){return!!((e==="v4"||!e)&&eg.test(t)||(e==="v6"||!e)&&ng.test(t))}function ug(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,i=Number.parseInt(t.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}function Gr(t){if(t instanceof He){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=st.create(Gr(r))}return new He({...t._def,shape:()=>e})}else return t instanceof Bt?new Bt({...t._def,type:Gr(t.element)}):t instanceof st?st.create(Gr(t.unwrap())):t instanceof Rt?Rt.create(Gr(t.unwrap())):t instanceof xt?xt.create(t.items.map(e=>Gr(e))):t}function xa(t,e){let n=Tt(t),r=Tt(e);if(t===e)return{valid:!0,data:t};if(n===D.object&&r===D.object){let s=se.objectKeys(e),i=se.objectKeys(t).filter(l=>s.indexOf(l)!==-1),o={...t,...e};for(let l of i){let c=xa(t[l],e[l]);if(!c.valid)return{valid:!1};o[l]=c.data}return{valid:!0,data:o}}else if(n===D.array&&r===D.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<t.length;i++){let o=t[i],l=e[i],c=xa(o,l);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===D.date&&r===D.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function du(t,e){return new Wn({values:t,typeName:J.ZodEnum,...Q(e)})}function au(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function hu(t,e={},n){return t?pn.create().superRefine((r,s)=>{let i=t(r);if(i instanceof Promise)return i.then(o=>{if(!o){let l=au(e,r),c=l.fatal??n??!0;s.addIssue({code:"custom",...l,fatal:c})}});if(!i){let o=au(e,r),l=o.fatal??n??!0;s.addIssue({code:"custom",...o,fatal:l})}}):pn.create()}var it,ou,re,Hm,Km,Gm,Zm,Wm,Vm,Jm,Ym,Xm,Ta,Qm,eg,tg,ng,rg,sg,lu,ig,hn,Dn,Ln,Un,qn,Zr,Fn,Bn,pn,Ft,yt,Wr,Bt,He,Hn,qt,xi,Kn,xt,Ri,Vr,Jr,Ii,Gn,Zn,Wn,Vn,fn,ot,st,Rt,Jn,Yn,Yr,dg,Ds,Ls,Xn,hg,J,pg,pu,fu,fg,mg,mu,gg,yg,bg,wg,vg,kg,_g,Sg,Tg,xg,Rg,Ig,Ag,Eg,Cg,$g,Pg,jg,Ng,Og,Mg,zg,Dg,Lg,Ug,qg,Fg,Bg,Hg,Kg,Gg,Zg,Wg,Vg,gu=be(()=>{ki();_i();iu();Sa();Ms();it=class{constructor(e,n,r,s){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},ou=(t,e)=>{if(dn(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new Be(t.common.issues);return this._error=n,this._error}}};re=class{get description(){return this._def.description}_getType(e){return Tt(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:Tt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ie,ctx:{common:e.parent.common,data:e.data,parsedType:Tt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(Kr(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Tt(e)},s=this._parseSync({data:e,path:r.path,parent:r});return ou(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Tt(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return dn(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>dn(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Tt(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(Kr(s)?s:Promise.resolve(s));return ou(r,i)}refine(e,n){let r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,i)=>{let o=e(s),l=()=>i.addIssue({code:E.custom,...r(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(l(),!1)):o?!0:(l(),!1)})}refinement(e,n){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(e){return new ot({schema:this,typeName:J.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return st.create(this,this._def)}nullable(){return Rt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Bt.create(this)}promise(){return fn.create(this,this._def)}or(e){return Hn.create([this,e],this._def)}and(e){return Kn.create(this,e,this._def)}transform(e){return new ot({...Q(this._def),schema:this,typeName:J.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new Jn({...Q(this._def),innerType:this,defaultValue:n,typeName:J.ZodDefault})}brand(){return new Ds({typeName:J.ZodBranded,type:this,...Q(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Yn({...Q(this._def),innerType:this,catchValue:n,typeName:J.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Ls.create(this,e)}readonly(){return Xn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Hm=/^c[^\s-]{8,}$/i,Km=/^[0-9a-z]+$/,Gm=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Zm=/^[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,Wm=/^[a-z0-9_-]{21}$/i,Vm=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Jm=/^[-+]?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)?)??$/,Ym=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Xm="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Qm=/^(?:(?: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])$/,eg=/^(?:(?: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])$/,tg=/^(([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]))$/,ng=/^(([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])$/,rg=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,sg=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,lu="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",ig=new RegExp(`^${lu}$`);hn=class t extends re{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==D.string){let i=this._getOrReturnCtx(e);return O(i,{code:E.invalid_type,expected:D.string,received:i.parsedType}),V}let r=new Ie,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),O(s,{code:E.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),O(s,{code:E.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,l=e.data.length<i.value;(o||l)&&(s=this._getOrReturnCtx(e,s),o?O(s,{code:E.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):l&&O(s,{code:E.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")Ym.test(e.data)||(s=this._getOrReturnCtx(e,s),O(s,{validation:"email",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Ta||(Ta=new RegExp(Xm,"u")),Ta.test(e.data)||(s=this._getOrReturnCtx(e,s),O(s,{validation:"emoji",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")Zm.test(e.data)||(s=this._getOrReturnCtx(e,s),O(s,{validation:"uuid",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")Wm.test(e.data)||(s=this._getOrReturnCtx(e,s),O(s,{validation:"nanoid",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")Hm.test(e.data)||(s=this._getOrReturnCtx(e,s),O(s,{validation:"cuid",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")Km.test(e.data)||(s=this._getOrReturnCtx(e,s),O(s,{validation:"cuid2",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")Gm.test(e.data)||(s=this._getOrReturnCtx(e,s),O(s,{validation:"ulid",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),O(s,{validation:"url",code:E.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),O(s,{validation:"regex",code:E.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),O(s,{code:E.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),O(s,{code:E.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),O(s,{code:E.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?uu(i).test(e.data)||(s=this._getOrReturnCtx(e,s),O(s,{code:E.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?ig.test(e.data)||(s=this._getOrReturnCtx(e,s),O(s,{code:E.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?og(i).test(e.data)||(s=this._getOrReturnCtx(e,s),O(s,{code:E.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?Jm.test(e.data)||(s=this._getOrReturnCtx(e,s),O(s,{validation:"duration",code:E.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?ag(e.data,i.version)||(s=this._getOrReturnCtx(e,s),O(s,{validation:"ip",code:E.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?lg(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),O(s,{validation:"jwt",code:E.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?cg(e.data,i.version)||(s=this._getOrReturnCtx(e,s),O(s,{validation:"cidr",code:E.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?rg.test(e.data)||(s=this._getOrReturnCtx(e,s),O(s,{validation:"base64",code:E.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?sg.test(e.data)||(s=this._getOrReturnCtx(e,s),O(s,{validation:"base64url",code:E.invalid_string,message:i.message}),r.dirty()):se.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:E.invalid_string,...F.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...F.errToObj(e)})}url(e){return this._addCheck({kind:"url",...F.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...F.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...F.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...F.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...F.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...F.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...F.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...F.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...F.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...F.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...F.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...F.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,...F.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,...F.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...F.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...F.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...F.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...F.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...F.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...F.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...F.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...F.errToObj(n)})}nonempty(e){return this.min(1,F.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};hn.create=t=>new hn({checks:[],typeName:J.ZodString,coerce:t?.coerce??!1,...Q(t)});Dn=class t extends re{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)!==D.number){let i=this._getOrReturnCtx(e);return O(i,{code:E.invalid_type,expected:D.number,received:i.parsedType}),V}let r,s=new Ie;for(let i of this._def.checks)i.kind==="int"?se.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),O(r,{code:E.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),O(r,{code:E.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),O(r,{code:E.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?ug(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),O(r,{code:E.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),O(r,{code:E.not_finite,message:i.message}),s.dirty()):se.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,F.toString(n))}gt(e,n){return this.setLimit("min",e,!1,F.toString(n))}lte(e,n){return this.setLimit("max",e,!0,F.toString(n))}lt(e,n){return this.setLimit("max",e,!1,F.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:F.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:F.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:F.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:F.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:F.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:F.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:F.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:F.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:F.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:F.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&se.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};Dn.create=t=>new Dn({checks:[],typeName:J.ZodNumber,coerce:t?.coerce||!1,...Q(t)});Ln=class t extends re{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)!==D.bigint)return this._getInvalidInput(e);let r,s=new Ie;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),O(r,{code:E.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),O(r,{code:E.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),O(r,{code:E.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):se.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return O(n,{code:E.invalid_type,expected:D.bigint,received:n.parsedType}),V}gte(e,n){return this.setLimit("min",e,!0,F.toString(n))}gt(e,n){return this.setLimit("min",e,!1,F.toString(n))}lte(e,n){return this.setLimit("max",e,!0,F.toString(n))}lt(e,n){return this.setLimit("max",e,!1,F.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:F.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:F.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:F.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:F.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:F.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:F.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};Ln.create=t=>new Ln({checks:[],typeName:J.ZodBigInt,coerce:t?.coerce??!1,...Q(t)});Un=class extends re{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==D.boolean){let r=this._getOrReturnCtx(e);return O(r,{code:E.invalid_type,expected:D.boolean,received:r.parsedType}),V}return Ce(e.data)}};Un.create=t=>new Un({typeName:J.ZodBoolean,coerce:t?.coerce||!1,...Q(t)});qn=class t extends re{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==D.date){let i=this._getOrReturnCtx(e);return O(i,{code:E.invalid_type,expected:D.date,received:i.parsedType}),V}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return O(i,{code:E.invalid_date}),V}let r=new Ie,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),O(s,{code:E.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),O(s,{code:E.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):se.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:F.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:F.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};qn.create=t=>new qn({checks:[],coerce:t?.coerce||!1,typeName:J.ZodDate,...Q(t)});Zr=class extends re{_parse(e){if(this._getType(e)!==D.symbol){let r=this._getOrReturnCtx(e);return O(r,{code:E.invalid_type,expected:D.symbol,received:r.parsedType}),V}return Ce(e.data)}};Zr.create=t=>new Zr({typeName:J.ZodSymbol,...Q(t)});Fn=class extends re{_parse(e){if(this._getType(e)!==D.undefined){let r=this._getOrReturnCtx(e);return O(r,{code:E.invalid_type,expected:D.undefined,received:r.parsedType}),V}return Ce(e.data)}};Fn.create=t=>new Fn({typeName:J.ZodUndefined,...Q(t)});Bn=class extends re{_parse(e){if(this._getType(e)!==D.null){let r=this._getOrReturnCtx(e);return O(r,{code:E.invalid_type,expected:D.null,received:r.parsedType}),V}return Ce(e.data)}};Bn.create=t=>new Bn({typeName:J.ZodNull,...Q(t)});pn=class extends re{constructor(){super(...arguments),this._any=!0}_parse(e){return Ce(e.data)}};pn.create=t=>new pn({typeName:J.ZodAny,...Q(t)});Ft=class extends re{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ce(e.data)}};Ft.create=t=>new Ft({typeName:J.ZodUnknown,...Q(t)});yt=class extends re{_parse(e){let n=this._getOrReturnCtx(e);return O(n,{code:E.invalid_type,expected:D.never,received:n.parsedType}),V}};yt.create=t=>new yt({typeName:J.ZodNever,...Q(t)});Wr=class extends re{_parse(e){if(this._getType(e)!==D.undefined){let r=this._getOrReturnCtx(e);return O(r,{code:E.invalid_type,expected:D.void,received:r.parsedType}),V}return Ce(e.data)}};Wr.create=t=>new Wr({typeName:J.ZodVoid,...Q(t)});Bt=class t extends re{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==D.array)return O(n,{code:E.invalid_type,expected:D.array,received:n.parsedType}),V;if(s.exactLength!==null){let o=n.data.length>s.exactLength.value,l=n.data.length<s.exactLength.value;(o||l)&&(O(n,{code:o?E.too_big:E.too_small,minimum:l?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(O(n,{code:E.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(O(n,{code:E.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((o,l)=>s.type._parseAsync(new it(n,o,n.path,l)))).then(o=>Ie.mergeArray(r,o));let i=[...n.data].map((o,l)=>s.type._parseSync(new it(n,o,n.path,l)));return Ie.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:F.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:F.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:F.toString(n)}})}nonempty(e){return this.min(1,e)}};Bt.create=(t,e)=>new Bt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:J.ZodArray,...Q(e)});He=class t extends re{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),n=se.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==D.object){let u=this._getOrReturnCtx(e);return O(u,{code:E.invalid_type,expected:D.object,received:u.parsedType}),V}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),l=[];if(!(this._def.catchall instanceof yt&&this._def.unknownKeys==="strip"))for(let u in s.data)o.includes(u)||l.push(u);let c=[];for(let u of o){let h=i[u],f=s.data[u];c.push({key:{status:"valid",value:u},value:h._parse(new it(s,f,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof yt){let u=this._def.unknownKeys;if(u==="passthrough")for(let h of l)c.push({key:{status:"valid",value:h},value:{status:"valid",value:s.data[h]}});else if(u==="strict")l.length>0&&(O(s,{code:E.unrecognized_keys,keys:l}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let h of l){let f=s.data[h];c.push({key:{status:"valid",value:h},value:u._parse(new it(s,f,s.path,h)),alwaysSet:h in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let u=[];for(let h of c){let f=await h.key,b=await h.value;u.push({key:f,value:b,alwaysSet:h.alwaysSet})}return u}).then(u=>Ie.mergeObjectSync(r,u)):Ie.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return F.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:F.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:J.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of se.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of se.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return Gr(this)}partial(e){let n={};for(let r of se.objectKeys(this.shape)){let s=this.shape[r];e&&!e[r]?n[r]=s:n[r]=s.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of se.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof st;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return du(se.objectKeys(this.shape))}};He.create=(t,e)=>new He({shape:()=>t,unknownKeys:"strip",catchall:yt.create(),typeName:J.ZodObject,...Q(e)});He.strictCreate=(t,e)=>new He({shape:()=>t,unknownKeys:"strict",catchall:yt.create(),typeName:J.ZodObject,...Q(e)});He.lazycreate=(t,e)=>new He({shape:t,unknownKeys:"strip",catchall:yt.create(),typeName:J.ZodObject,...Q(e)});Hn=class extends re{_parse(e){let{ctx:n}=this._processInputParams(e),r=this._def.options;function s(i){for(let l of i)if(l.result.status==="valid")return l.result;for(let l of i)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;let o=i.map(l=>new Be(l.ctx.common.issues));return O(n,{code:E.invalid_union,unionErrors:o}),V}if(n.common.async)return Promise.all(r.map(async i=>{let o={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let c of r){let u={...n,common:{...n.common,issues:[]},parent:null},h=c._parseSync({data:n.data,path:n.path,parent:u});if(h.status==="valid")return h;h.status==="dirty"&&!i&&(i={result:h,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let l=o.map(c=>new Be(c));return O(n,{code:E.invalid_union,unionErrors:l}),V}}get options(){return this._def.options}};Hn.create=(t,e)=>new Hn({options:t,typeName:J.ZodUnion,...Q(e)});qt=t=>t instanceof Gn?qt(t.schema):t instanceof ot?qt(t.innerType()):t instanceof Zn?[t.value]:t instanceof Wn?t.options:t instanceof Vn?se.objectValues(t.enum):t instanceof Jn?qt(t._def.innerType):t instanceof Fn?[void 0]:t instanceof Bn?[null]:t instanceof st?[void 0,...qt(t.unwrap())]:t instanceof Rt?[null,...qt(t.unwrap())]:t instanceof Ds||t instanceof Xn?qt(t.unwrap()):t instanceof Yn?qt(t._def.innerType):[],xi=class t extends re{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==D.object)return O(n,{code:E.invalid_type,expected:D.object,received:n.parsedType}),V;let r=this.discriminator,s=n.data[r],i=this.optionsMap.get(s);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(O(n,{code:E.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),V)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let s=new Map;for(let i of n){let o=qt(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let l of o){if(s.has(l))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(l)}`);s.set(l,i)}}return new t({typeName:J.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...Q(r)})}};Kn=class extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=(i,o)=>{if(Si(i)||Si(o))return V;let l=xa(i.value,o.value);return l.valid?((Ti(i)||Ti(o))&&n.dirty(),{status:n.value,value:l.data}):(O(r,{code:E.invalid_intersection_types}),V)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Kn.create=(t,e,n)=>new Kn({left:t,right:e,typeName:J.ZodIntersection,...Q(n)});xt=class t extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==D.array)return O(r,{code:E.invalid_type,expected:D.array,received:r.parsedType}),V;if(r.data.length<this._def.items.length)return O(r,{code:E.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),V;!this._def.rest&&r.data.length>this._def.items.length&&(O(r,{code:E.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let i=[...r.data].map((o,l)=>{let c=this._def.items[l]||this._def.rest;return c?c._parse(new it(r,o,r.path,l)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>Ie.mergeArray(n,o)):Ie.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};xt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new xt({items:t,typeName:J.ZodTuple,rest:null,...Q(e)})};Ri=class t extends re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==D.object)return O(r,{code:E.invalid_type,expected:D.object,received:r.parsedType}),V;let s=[],i=this._def.keyType,o=this._def.valueType;for(let l in r.data)s.push({key:i._parse(new it(r,l,r.path,l)),value:o._parse(new it(r,r.data[l],r.path,l)),alwaysSet:l in r.data});return r.common.async?Ie.mergeObjectAsync(n,s):Ie.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof re?new t({keyType:e,valueType:n,typeName:J.ZodRecord,...Q(r)}):new t({keyType:hn.create(),valueType:e,typeName:J.ZodRecord,...Q(n)})}},Vr=class extends re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==D.map)return O(r,{code:E.invalid_type,expected:D.map,received:r.parsedType}),V;let s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([l,c],u)=>({key:s._parse(new it(r,l,r.path,[u,"key"])),value:i._parse(new it(r,c,r.path,[u,"value"]))}));if(r.common.async){let l=new Map;return Promise.resolve().then(async()=>{for(let c of o){let u=await c.key,h=await c.value;if(u.status==="aborted"||h.status==="aborted")return V;(u.status==="dirty"||h.status==="dirty")&&n.dirty(),l.set(u.value,h.value)}return{status:n.value,value:l}})}else{let l=new Map;for(let c of o){let u=c.key,h=c.value;if(u.status==="aborted"||h.status==="aborted")return V;(u.status==="dirty"||h.status==="dirty")&&n.dirty(),l.set(u.value,h.value)}return{status:n.value,value:l}}}};Vr.create=(t,e,n)=>new Vr({valueType:e,keyType:t,typeName:J.ZodMap,...Q(n)});Jr=class t extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==D.set)return O(r,{code:E.invalid_type,expected:D.set,received:r.parsedType}),V;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(O(r,{code:E.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(O(r,{code:E.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let i=this._def.valueType;function o(c){let u=new Set;for(let h of c){if(h.status==="aborted")return V;h.status==="dirty"&&n.dirty(),u.add(h.value)}return{status:n.value,value:u}}let l=[...r.data.values()].map((c,u)=>i._parse(new it(r,c,r.path,u)));return r.common.async?Promise.all(l).then(c=>o(c)):o(l)}min(e,n){return new t({...this._def,minSize:{value:e,message:F.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:F.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};Jr.create=(t,e)=>new Jr({valueType:t,minSize:null,maxSize:null,typeName:J.ZodSet,...Q(e)});Ii=class t extends re{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==D.function)return O(n,{code:E.invalid_type,expected:D.function,received:n.parsedType}),V;function r(l,c){return zs({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Hr(),Ut].filter(u=>!!u),issueData:{code:E.invalid_arguments,argumentsError:c}})}function s(l,c){return zs({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Hr(),Ut].filter(u=>!!u),issueData:{code:E.invalid_return_type,returnTypeError:c}})}let i={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof fn){let l=this;return Ce(async function(...c){let u=new Be([]),h=await l._def.args.parseAsync(c,i).catch(w=>{throw u.addIssue(r(c,w)),u}),f=await Reflect.apply(o,this,h);return await l._def.returns._def.type.parseAsync(f,i).catch(w=>{throw u.addIssue(s(f,w)),u})})}else{let l=this;return Ce(function(...c){let u=l._def.args.safeParse(c,i);if(!u.success)throw new Be([r(c,u.error)]);let h=Reflect.apply(o,this,u.data),f=l._def.returns.safeParse(h,i);if(!f.success)throw new Be([s(h,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:xt.create(e).rest(Ft.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new t({args:e||xt.create([]).rest(Ft.create()),returns:n||Ft.create(),typeName:J.ZodFunction,...Q(r)})}},Gn=class extends re{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};Gn.create=(t,e)=>new Gn({getter:t,typeName:J.ZodLazy,...Q(e)});Zn=class extends re{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return O(n,{received:n.data,code:E.invalid_literal,expected:this._def.value}),V}return{status:"valid",value:e.data}}get value(){return this._def.value}};Zn.create=(t,e)=>new Zn({value:t,typeName:J.ZodLiteral,...Q(e)});Wn=class t extends re{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return O(n,{expected:se.joinValues(r),received:n.parsedType,code:E.invalid_type}),V}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return O(n,{received:n.data,code:E.invalid_enum_value,options:r}),V}return Ce(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};Wn.create=du;Vn=class extends re{_parse(e){let n=se.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==D.string&&r.parsedType!==D.number){let s=se.objectValues(n);return O(r,{expected:se.joinValues(s),received:r.parsedType,code:E.invalid_type}),V}if(this._cache||(this._cache=new Set(se.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=se.objectValues(n);return O(r,{received:r.data,code:E.invalid_enum_value,options:s}),V}return Ce(e.data)}get enum(){return this._def.values}};Vn.create=(t,e)=>new Vn({values:t,typeName:J.ZodNativeEnum,...Q(e)});fn=class extends re{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==D.promise&&n.common.async===!1)return O(n,{code:E.invalid_type,expected:D.promise,received:n.parsedType}),V;let r=n.parsedType===D.promise?n.data:Promise.resolve(n.data);return Ce(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};fn.create=(t,e)=>new fn({type:t,typeName:J.ZodPromise,...Q(e)});ot=class extends re{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===J.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{O(r,o),o.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(r.data,i);if(r.common.async)return Promise.resolve(o).then(async l=>{if(n.value==="aborted")return V;let c=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return c.status==="aborted"?V:c.status==="dirty"?zn(c.value):n.value==="dirty"?zn(c.value):c});{if(n.value==="aborted")return V;let l=this._def.schema._parseSync({data:o,path:r.path,parent:r});return l.status==="aborted"?V:l.status==="dirty"?zn(l.value):n.value==="dirty"?zn(l.value):l}}if(s.type==="refinement"){let o=l=>{let c=s.refinement(l,i);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){let l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?V:(l.status==="dirty"&&n.dirty(),o(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?V:(l.status==="dirty"&&n.dirty(),o(l.value).then(()=>({status:n.value,value:l.value}))))}if(s.type==="transform")if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!dn(o))return V;let l=s.transform(o.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>dn(o)?Promise.resolve(s.transform(o.value,i)).then(l=>({status:n.value,value:l})):V);se.assertNever(s)}};ot.create=(t,e,n)=>new ot({schema:t,typeName:J.ZodEffects,effect:e,...Q(n)});ot.createWithPreprocess=(t,e,n)=>new ot({schema:e,effect:{type:"preprocess",transform:t},typeName:J.ZodEffects,...Q(n)});st=class extends re{_parse(e){return this._getType(e)===D.undefined?Ce(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};st.create=(t,e)=>new st({innerType:t,typeName:J.ZodOptional,...Q(e)});Rt=class extends re{_parse(e){return this._getType(e)===D.null?Ce(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Rt.create=(t,e)=>new Rt({innerType:t,typeName:J.ZodNullable,...Q(e)});Jn=class extends re{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===D.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Jn.create=(t,e)=>new Jn({innerType:t,typeName:J.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Q(e)});Yn=class extends re{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Kr(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Be(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Be(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Yn.create=(t,e)=>new Yn({innerType:t,typeName:J.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Q(e)});Yr=class extends re{_parse(e){if(this._getType(e)!==D.nan){let r=this._getOrReturnCtx(e);return O(r,{code:E.invalid_type,expected:D.nan,received:r.parsedType}),V}return{status:"valid",value:e.data}}};Yr.create=t=>new Yr({typeName:J.ZodNaN,...Q(t)});dg=Symbol("zod_brand"),Ds=class extends re{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},Ls=class t extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?V:i.status==="dirty"?(n.dirty(),zn(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?V:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:J.ZodPipeline})}},Xn=class extends re{_parse(e){let n=this._def.innerType._parse(e),r=s=>(dn(s)&&(s.value=Object.freeze(s.value)),s);return Kr(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};Xn.create=(t,e)=>new Xn({innerType:t,typeName:J.ZodReadonly,...Q(e)});hg={object:He.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(J||(J={}));pg=(t,e={message:`Input not instance of ${t.name}`})=>hu(n=>n instanceof t,e),pu=hn.create,fu=Dn.create,fg=Yr.create,mg=Ln.create,mu=Un.create,gg=qn.create,yg=Zr.create,bg=Fn.create,wg=Bn.create,vg=pn.create,kg=Ft.create,_g=yt.create,Sg=Wr.create,Tg=Bt.create,xg=He.create,Rg=He.strictCreate,Ig=Hn.create,Ag=xi.create,Eg=Kn.create,Cg=xt.create,$g=Ri.create,Pg=Vr.create,jg=Jr.create,Ng=Ii.create,Og=Gn.create,Mg=Zn.create,zg=Wn.create,Dg=Vn.create,Lg=fn.create,Ug=ot.create,qg=st.create,Fg=Rt.create,Bg=ot.createWithPreprocess,Hg=Ls.create,Kg=()=>pu().optional(),Gg=()=>fu().optional(),Zg=()=>mu().optional(),Wg={string:(t=>hn.create({...t,coerce:!0})),number:(t=>Dn.create({...t,coerce:!0})),boolean:(t=>Un.create({...t,coerce:!0})),bigint:(t=>Ln.create({...t,coerce:!0})),date:(t=>qn.create({...t,coerce:!0}))},Vg=V});var k={};un(k,{BRAND:()=>dg,DIRTY:()=>zn,EMPTY_PATH:()=>Bm,INVALID:()=>V,NEVER:()=>Vg,OK:()=>Ce,ParseStatus:()=>Ie,Schema:()=>re,ZodAny:()=>pn,ZodArray:()=>Bt,ZodBigInt:()=>Ln,ZodBoolean:()=>Un,ZodBranded:()=>Ds,ZodCatch:()=>Yn,ZodDate:()=>qn,ZodDefault:()=>Jn,ZodDiscriminatedUnion:()=>xi,ZodEffects:()=>ot,ZodEnum:()=>Wn,ZodError:()=>Be,ZodFirstPartyTypeKind:()=>J,ZodFunction:()=>Ii,ZodIntersection:()=>Kn,ZodIssueCode:()=>E,ZodLazy:()=>Gn,ZodLiteral:()=>Zn,ZodMap:()=>Vr,ZodNaN:()=>Yr,ZodNativeEnum:()=>Vn,ZodNever:()=>yt,ZodNull:()=>Bn,ZodNullable:()=>Rt,ZodNumber:()=>Dn,ZodObject:()=>He,ZodOptional:()=>st,ZodParsedType:()=>D,ZodPipeline:()=>Ls,ZodPromise:()=>fn,ZodReadonly:()=>Xn,ZodRecord:()=>Ri,ZodSchema:()=>re,ZodSet:()=>Jr,ZodString:()=>hn,ZodSymbol:()=>Zr,ZodTransformer:()=>ot,ZodTuple:()=>xt,ZodType:()=>re,ZodUndefined:()=>Fn,ZodUnion:()=>Hn,ZodUnknown:()=>Ft,ZodVoid:()=>Wr,addIssueToContext:()=>O,any:()=>vg,array:()=>Tg,bigint:()=>mg,boolean:()=>mu,coerce:()=>Wg,custom:()=>hu,date:()=>gg,datetimeRegex:()=>uu,defaultErrorMap:()=>Ut,discriminatedUnion:()=>Ag,effect:()=>Ug,enum:()=>zg,function:()=>Ng,getErrorMap:()=>Hr,getParsedType:()=>Tt,instanceof:()=>pg,intersection:()=>Eg,isAborted:()=>Si,isAsync:()=>Kr,isDirty:()=>Ti,isValid:()=>dn,late:()=>hg,lazy:()=>Og,literal:()=>Mg,makeIssue:()=>zs,map:()=>Pg,nan:()=>fg,nativeEnum:()=>Dg,never:()=>_g,null:()=>wg,nullable:()=>Fg,number:()=>fu,object:()=>xg,objectUtil:()=>ka,oboolean:()=>Zg,onumber:()=>Gg,optional:()=>qg,ostring:()=>Kg,pipeline:()=>Hg,preprocess:()=>Bg,promise:()=>Lg,quotelessJson:()=>Um,record:()=>$g,set:()=>jg,setErrorMap:()=>Fm,strictObject:()=>Rg,string:()=>pu,symbol:()=>yg,transformer:()=>Ug,tuple:()=>Cg,undefined:()=>bg,union:()=>Ig,unknown:()=>kg,util:()=>se,void:()=>Sg});var Ra=be(()=>{_i();Sa();su();Ms();gu();ki()});var Xr=be(()=>{Ra();Ra()});function ie(){let t=process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR;if(t)return t;let e=Ei.default.join(Ai.default.homedir(),".config","allwright"),n=Ei.default.join(Ai.default.homedir(),".config","ticketpilot");return!Ht.default.existsSync(e)&&Ht.default.existsSync(n)?n:e}function Kt(){return Ei.default.join(ie(),"runner.json")}function ve(){let t=Kt();if(!Ht.default.existsSync(t))return null;let e=JSON.parse(Ht.default.readFileSync(t,"utf8"));return Ia.parse(e)}function ye(t){let e=ie();Ht.default.mkdirSync(e,{recursive:!0,mode:448});let n=Kt(),r=n+".tmp";Ht.default.writeFileSync(r,JSON.stringify(t,null,2)+`
|
|
24
|
+
`,{mode:384}),Ht.default.renameSync(r,n),Ht.default.chmodSync(n,384)}function Ci(t,e){return`${t}:${e}`}function Gt(t,e,n){return t.environments[Ci(e,n)]?.secrets??{}}function $i(t,e){return t.repos[e]?.jira??t.jira}function Pi(t){return!t.jira&&!Object.values(t.repos).some(e=>e.jira)}function ce(){let t=ve();if(!t)throw new Error(`No runner config found at ${Kt()}. Run \`allwright init\` first.`);return t}var Ht,Ai,Ei,yu,Ia,Ae=be(()=>{"use strict";Ht=I(require("node:fs"),1),Ai=I(require("node:os"),1),Ei=I(require("node:path"),1);Xr();yu=k.object({baseUrl:k.string().url(),email:k.string().email(),apiToken:k.string().min(1)}),Ia=k.object({controlPlaneUrl:k.string().url(),runnerId:k.string().optional(),runnerToken:k.string().optional(),runnerName:k.string().default(Ai.default.hostname()),jira:yu.optional(),repos:k.record(k.object({path:k.string(),jira:yu.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)})});var Us=le(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.getParsedType=de.ZodParsedType=de.objectUtil=de.util=void 0;var $a;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function n(s){throw new Error}t.assertNever=n,t.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},t.getValidEnumValues=s=>{let i=t.objectKeys(s).filter(l=>typeof s[s[l]]!="number"),o={};for(let l of i)o[l]=s[l];return t.objectValues(o)},t.objectValues=s=>t.objectKeys(s).map(function(i){return s[i]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},t.find=(s,i)=>{for(let o of s)if(i(o))return o},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})($a||(de.util=$a={}));var Au;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Au||(de.objectUtil=Au={}));de.ZodParsedType=$a.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var ry=t=>{switch(typeof t){case"undefined":return de.ZodParsedType.undefined;case"string":return de.ZodParsedType.string;case"number":return Number.isNaN(t)?de.ZodParsedType.nan:de.ZodParsedType.number;case"boolean":return de.ZodParsedType.boolean;case"function":return de.ZodParsedType.function;case"bigint":return de.ZodParsedType.bigint;case"symbol":return de.ZodParsedType.symbol;case"object":return Array.isArray(t)?de.ZodParsedType.array:t===null?de.ZodParsedType.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?de.ZodParsedType.promise:typeof Map<"u"&&t instanceof Map?de.ZodParsedType.map:typeof Set<"u"&&t instanceof Set?de.ZodParsedType.set:typeof Date<"u"&&t instanceof Date?de.ZodParsedType.date:de.ZodParsedType.object;default:return de.ZodParsedType.unknown}};de.getParsedType=ry});var Di=le(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.ZodError=yn.quotelessJson=yn.ZodIssueCode=void 0;var Eu=Us();yn.ZodIssueCode=Eu.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 sy=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");yn.quotelessJson=sy;var qs=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(i){return i.message},r={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)r._errors.push(n(o));else{let l=r,c=0;for(;c<o.path.length;){let u=o.path[c];c===o.path.length-1?(l[u]=l[u]||{_errors:[]},l[u]._errors.push(n(o))):l[u]=l[u]||{_errors:[]},l=l[u],c++}}};return s(this),r}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Eu.util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];n[i]=n[i]||[],n[i].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};yn.ZodError=qs;qs.create=t=>new qs(t)});var ja=le(Pa=>{"use strict";Object.defineProperty(Pa,"__esModule",{value:!0});var $e=Di(),tr=Us(),iy=(t,e)=>{let n;switch(t.code){case $e.ZodIssueCode.invalid_type:t.received===tr.ZodParsedType.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case $e.ZodIssueCode.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,tr.util.jsonStringifyReplacer)}`;break;case $e.ZodIssueCode.unrecognized_keys:n=`Unrecognized key(s) in object: ${tr.util.joinValues(t.keys,", ")}`;break;case $e.ZodIssueCode.invalid_union:n="Invalid input";break;case $e.ZodIssueCode.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${tr.util.joinValues(t.options)}`;break;case $e.ZodIssueCode.invalid_enum_value:n=`Invalid enum value. Expected ${tr.util.joinValues(t.options)}, received '${t.received}'`;break;case $e.ZodIssueCode.invalid_arguments:n="Invalid function arguments";break;case $e.ZodIssueCode.invalid_return_type:n="Invalid function return type";break;case $e.ZodIssueCode.invalid_date:n="Invalid date";break;case $e.ZodIssueCode.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:tr.util.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case $e.ZodIssueCode.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case $e.ZodIssueCode.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case $e.ZodIssueCode.custom:n="Invalid input";break;case $e.ZodIssueCode.invalid_intersection_types:n="Intersection results could not be merged";break;case $e.ZodIssueCode.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case $e.ZodIssueCode.not_finite:n="Number must be finite";break;default:n=e.defaultError,tr.util.assertNever(t)}return{message:n}};Pa.default=iy});var Li=le(bn=>{"use strict";var oy=bn&&bn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(bn,"__esModule",{value:!0});bn.defaultErrorMap=void 0;bn.setErrorMap=ay;bn.getErrorMap=ly;var Cu=oy(ja());bn.defaultErrorMap=Cu.default;var $u=Cu.default;function ay(t){$u=t}function ly(){return $u}});var Oa=le(ue=>{"use strict";var cy=ue&&ue.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(ue,"__esModule",{value:!0});ue.isAsync=ue.isValid=ue.isDirty=ue.isAborted=ue.OK=ue.DIRTY=ue.INVALID=ue.ParseStatus=ue.EMPTY_PATH=ue.makeIssue=void 0;ue.addIssueToContext=hy;var uy=Li(),Pu=cy(ja()),dy=t=>{let{data:e,path:n,errorMaps:r,issueData:s}=t,i=[...n,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let l="",c=r.filter(u=>!!u).slice().reverse();for(let u of c)l=u(o,{data:e,defaultError:l}).message;return{...s,path:i,message:l}};ue.makeIssue=dy;ue.EMPTY_PATH=[];function hy(t,e){let n=(0,uy.getErrorMap)(),r=(0,ue.makeIssue)({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Pu.default?void 0:Pu.default].filter(s=>!!s)});t.common.issues.push(r)}var Na=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let s of n){if(s.status==="aborted")return ue.INVALID;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let s of n){let i=await s.key,o=await s.value;r.push({key:i,value:o})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let s of n){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return ue.INVALID;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(r[i.value]=o.value)}return{status:e.value,value:r}}};ue.ParseStatus=Na;ue.INVALID=Object.freeze({status:"aborted"});var py=t=>({status:"dirty",value:t});ue.DIRTY=py;var fy=t=>({status:"valid",value:t});ue.OK=fy;var my=t=>t.status==="aborted";ue.isAborted=my;var gy=t=>t.status==="dirty";ue.isDirty=gy;var yy=t=>t.status==="valid";ue.isValid=yy;var by=t=>typeof Promise<"u"&&t instanceof Promise;ue.isAsync=by});var Nu=le(ju=>{"use strict";Object.defineProperty(ju,"__esModule",{value:!0})});var Mu=le(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.errorUtil=void 0;var Ou;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(Ou||(Ui.errorUtil=Ou={}))});var Wu=le(T=>{"use strict";Object.defineProperty(T,"__esModule",{value:!0});T.discriminatedUnion=T.date=T.boolean=T.bigint=T.array=T.any=T.coerce=T.ZodFirstPartyTypeKind=T.late=T.ZodSchema=T.Schema=T.ZodReadonly=T.ZodPipeline=T.ZodBranded=T.BRAND=T.ZodNaN=T.ZodCatch=T.ZodDefault=T.ZodNullable=T.ZodOptional=T.ZodTransformer=T.ZodEffects=T.ZodPromise=T.ZodNativeEnum=T.ZodEnum=T.ZodLiteral=T.ZodLazy=T.ZodFunction=T.ZodSet=T.ZodMap=T.ZodRecord=T.ZodTuple=T.ZodIntersection=T.ZodDiscriminatedUnion=T.ZodUnion=T.ZodObject=T.ZodArray=T.ZodVoid=T.ZodNever=T.ZodUnknown=T.ZodAny=T.ZodNull=T.ZodUndefined=T.ZodSymbol=T.ZodDate=T.ZodBoolean=T.ZodBigInt=T.ZodNumber=T.ZodString=T.ZodType=void 0;T.NEVER=T.void=T.unknown=T.union=T.undefined=T.tuple=T.transformer=T.symbol=T.string=T.strictObject=T.set=T.record=T.promise=T.preprocess=T.pipeline=T.ostring=T.optional=T.onumber=T.oboolean=T.object=T.number=T.nullable=T.null=T.never=T.nativeEnum=T.nan=T.map=T.literal=T.lazy=T.intersection=T.instanceof=T.function=T.enum=T.effect=void 0;T.datetimeRegex=qu;T.custom=Bu;var $=Di(),qi=Li(),Z=Mu(),x=Oa(),P=Us(),lt=class{constructor(e,n,r,s){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},zu=(t,e)=>{if((0,x.isValid)(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new $.ZodError(t.common.issues);return this._error=n,this._error}}};function ee(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:s}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,l)=>{let{message:c}=t;return o.code==="invalid_enum_value"?{message:c??l.defaultError}:typeof l.data>"u"?{message:c??r??l.defaultError}:o.code!=="invalid_type"?{message:l.defaultError}:{message:c??n??l.defaultError}},description:s}}var te=class{get description(){return this._def.description}_getType(e){return(0,P.getParsedType)(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:(0,P.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new x.ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:(0,P.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if((0,x.isAsync)(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,P.getParsedType)(e)},s=this._parseSync({data:e,path:r.path,parent:r});return zu(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,P.getParsedType)(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return(0,x.isValid)(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>(0,x.isValid)(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,P.getParsedType)(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await((0,x.isAsync)(s)?s:Promise.resolve(s));return zu(r,i)}refine(e,n){let r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,i)=>{let o=e(s),l=()=>i.addIssue({code:$.ZodIssueCode.custom,...r(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(l(),!1)):o?!0:(l(),!1)})}refinement(e,n){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(e){return new Ye({schema:this,typeName:Y.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return at.create(this,this._def)}nullable(){return At.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Vt.create(this)}promise(){return kn.create(this,this._def)}or(e){return lr.create([this,e],this._def)}and(e){return cr.create(this,e,this._def)}transform(e){return new Ye({...ee(this._def),schema:this,typeName:Y.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new fr({...ee(this._def),innerType:this,defaultValue:n,typeName:Y.ZodDefault})}brand(){return new Fs({typeName:Y.ZodBranded,type:this,...ee(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new mr({...ee(this._def),innerType:this,catchValue:n,typeName:Y.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Bs.create(this,e)}readonly(){return gr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};T.ZodType=te;T.Schema=te;T.ZodSchema=te;var wy=/^c[^\s-]{8,}$/i,vy=/^[0-9a-z]+$/,ky=/^[0-9A-HJKMNP-TV-Z]{26}$/i,_y=/^[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,Sy=/^[a-z0-9_-]{21}$/i,Ty=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,xy=/^[-+]?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)?)??$/,Ry=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Iy="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ma,Ay=/^(?:(?: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])$/,Ey=/^(?:(?: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])$/,Cy=/^(([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]))$/,$y=/^(([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])$/,Py=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,jy=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Lu="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Ny=new RegExp(`^${Lu}$`);function Uu(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function Oy(t){return new RegExp(`^${Uu(t)}$`)}function qu(t){let e=`${Lu}T${Uu(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function My(t,e){return!!((e==="v4"||!e)&&Ay.test(t)||(e==="v6"||!e)&&Cy.test(t))}function zy(t,e){if(!Ty.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function Dy(t,e){return!!((e==="v4"||!e)&&Ey.test(t)||(e==="v6"||!e)&&$y.test(t))}var wn=class t extends te{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==P.ZodParsedType.string){let i=this._getOrReturnCtx(e);return(0,x.addIssueToContext)(i,{code:$.ZodIssueCode.invalid_type,expected:P.ZodParsedType.string,received:i.parsedType}),x.INVALID}let r=new x.ParseStatus,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{code:$.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{code:$.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,l=e.data.length<i.value;(o||l)&&(s=this._getOrReturnCtx(e,s),o?(0,x.addIssueToContext)(s,{code:$.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):l&&(0,x.addIssueToContext)(s,{code:$.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")Ry.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{validation:"email",code:$.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Ma||(Ma=new RegExp(Iy,"u")),Ma.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{validation:"emoji",code:$.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")_y.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{validation:"uuid",code:$.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")Sy.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{validation:"nanoid",code:$.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")wy.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{validation:"cuid",code:$.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")vy.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{validation:"cuid2",code:$.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")ky.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{validation:"ulid",code:$.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{validation:"url",code:$.ZodIssueCode.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{validation:"regex",code:$.ZodIssueCode.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{code:$.ZodIssueCode.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{code:$.ZodIssueCode.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{code:$.ZodIssueCode.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?qu(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{code:$.ZodIssueCode.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?Ny.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{code:$.ZodIssueCode.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Oy(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{code:$.ZodIssueCode.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?xy.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{validation:"duration",code:$.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?My(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{validation:"ip",code:$.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?zy(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{validation:"jwt",code:$.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?Dy(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{validation:"cidr",code:$.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?Py.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{validation:"base64",code:$.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?jy.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{validation:"base64url",code:$.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):P.util.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:$.ZodIssueCode.invalid_string,...Z.errorUtil.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Z.errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Z.errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Z.errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Z.errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Z.errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Z.errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Z.errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Z.errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Z.errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Z.errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Z.errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Z.errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Z.errorUtil.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...Z.errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...Z.errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Z.errorUtil.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...Z.errorUtil.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...Z.errorUtil.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...Z.errorUtil.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...Z.errorUtil.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...Z.errorUtil.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...Z.errorUtil.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...Z.errorUtil.errToObj(n)})}nonempty(e){return this.min(1,Z.errorUtil.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};T.ZodString=wn;wn.create=t=>new wn({checks:[],typeName:Y.ZodString,coerce:t?.coerce??!1,...ee(t)});function Ly(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,i=Number.parseInt(t.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var nr=class t extends te{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==P.ZodParsedType.number){let i=this._getOrReturnCtx(e);return(0,x.addIssueToContext)(i,{code:$.ZodIssueCode.invalid_type,expected:P.ZodParsedType.number,received:i.parsedType}),x.INVALID}let r,s=new x.ParseStatus;for(let i of this._def.checks)i.kind==="int"?P.util.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Ly(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.not_finite,message:i.message}),s.dirty()):P.util.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,Z.errorUtil.toString(n))}gt(e,n){return this.setLimit("min",e,!1,Z.errorUtil.toString(n))}lte(e,n){return this.setLimit("max",e,!0,Z.errorUtil.toString(n))}lt(e,n){return this.setLimit("max",e,!1,Z.errorUtil.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:Z.errorUtil.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Z.errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Z.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Z.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Z.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Z.errorUtil.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:Z.errorUtil.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:Z.errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Z.errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Z.errorUtil.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&P.util.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};T.ZodNumber=nr;nr.create=t=>new nr({checks:[],typeName:Y.ZodNumber,coerce:t?.coerce||!1,...ee(t)});var rr=class t extends te{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==P.ZodParsedType.bigint)return this._getInvalidInput(e);let r,s=new x.ParseStatus;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):P.util.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return(0,x.addIssueToContext)(n,{code:$.ZodIssueCode.invalid_type,expected:P.ZodParsedType.bigint,received:n.parsedType}),x.INVALID}gte(e,n){return this.setLimit("min",e,!0,Z.errorUtil.toString(n))}gt(e,n){return this.setLimit("min",e,!1,Z.errorUtil.toString(n))}lte(e,n){return this.setLimit("max",e,!0,Z.errorUtil.toString(n))}lt(e,n){return this.setLimit("max",e,!1,Z.errorUtil.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:Z.errorUtil.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Z.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Z.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Z.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Z.errorUtil.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:Z.errorUtil.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};T.ZodBigInt=rr;rr.create=t=>new rr({checks:[],typeName:Y.ZodBigInt,coerce:t?.coerce??!1,...ee(t)});var sr=class extends te{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==P.ZodParsedType.boolean){let r=this._getOrReturnCtx(e);return(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.invalid_type,expected:P.ZodParsedType.boolean,received:r.parsedType}),x.INVALID}return(0,x.OK)(e.data)}};T.ZodBoolean=sr;sr.create=t=>new sr({typeName:Y.ZodBoolean,coerce:t?.coerce||!1,...ee(t)});var ir=class t extends te{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==P.ZodParsedType.date){let i=this._getOrReturnCtx(e);return(0,x.addIssueToContext)(i,{code:$.ZodIssueCode.invalid_type,expected:P.ZodParsedType.date,received:i.parsedType}),x.INVALID}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return(0,x.addIssueToContext)(i,{code:$.ZodIssueCode.invalid_date}),x.INVALID}let r=new x.ParseStatus,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{code:$.ZodIssueCode.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),(0,x.addIssueToContext)(s,{code:$.ZodIssueCode.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):P.util.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:Z.errorUtil.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:Z.errorUtil.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};T.ZodDate=ir;ir.create=t=>new ir({checks:[],coerce:t?.coerce||!1,typeName:Y.ZodDate,...ee(t)});var ss=class extends te{_parse(e){if(this._getType(e)!==P.ZodParsedType.symbol){let r=this._getOrReturnCtx(e);return(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.invalid_type,expected:P.ZodParsedType.symbol,received:r.parsedType}),x.INVALID}return(0,x.OK)(e.data)}};T.ZodSymbol=ss;ss.create=t=>new ss({typeName:Y.ZodSymbol,...ee(t)});var or=class extends te{_parse(e){if(this._getType(e)!==P.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.invalid_type,expected:P.ZodParsedType.undefined,received:r.parsedType}),x.INVALID}return(0,x.OK)(e.data)}};T.ZodUndefined=or;or.create=t=>new or({typeName:Y.ZodUndefined,...ee(t)});var ar=class extends te{_parse(e){if(this._getType(e)!==P.ZodParsedType.null){let r=this._getOrReturnCtx(e);return(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.invalid_type,expected:P.ZodParsedType.null,received:r.parsedType}),x.INVALID}return(0,x.OK)(e.data)}};T.ZodNull=ar;ar.create=t=>new ar({typeName:Y.ZodNull,...ee(t)});var vn=class extends te{constructor(){super(...arguments),this._any=!0}_parse(e){return(0,x.OK)(e.data)}};T.ZodAny=vn;vn.create=t=>new vn({typeName:Y.ZodAny,...ee(t)});var Wt=class extends te{constructor(){super(...arguments),this._unknown=!0}_parse(e){return(0,x.OK)(e.data)}};T.ZodUnknown=Wt;Wt.create=t=>new Wt({typeName:Y.ZodUnknown,...ee(t)});var bt=class extends te{_parse(e){let n=this._getOrReturnCtx(e);return(0,x.addIssueToContext)(n,{code:$.ZodIssueCode.invalid_type,expected:P.ZodParsedType.never,received:n.parsedType}),x.INVALID}};T.ZodNever=bt;bt.create=t=>new bt({typeName:Y.ZodNever,...ee(t)});var is=class extends te{_parse(e){if(this._getType(e)!==P.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.invalid_type,expected:P.ZodParsedType.void,received:r.parsedType}),x.INVALID}return(0,x.OK)(e.data)}};T.ZodVoid=is;is.create=t=>new is({typeName:Y.ZodVoid,...ee(t)});var Vt=class t extends te{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==P.ZodParsedType.array)return(0,x.addIssueToContext)(n,{code:$.ZodIssueCode.invalid_type,expected:P.ZodParsedType.array,received:n.parsedType}),x.INVALID;if(s.exactLength!==null){let o=n.data.length>s.exactLength.value,l=n.data.length<s.exactLength.value;(o||l)&&((0,x.addIssueToContext)(n,{code:o?$.ZodIssueCode.too_big:$.ZodIssueCode.too_small,minimum:l?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&((0,x.addIssueToContext)(n,{code:$.ZodIssueCode.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&((0,x.addIssueToContext)(n,{code:$.ZodIssueCode.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((o,l)=>s.type._parseAsync(new lt(n,o,n.path,l)))).then(o=>x.ParseStatus.mergeArray(r,o));let i=[...n.data].map((o,l)=>s.type._parseSync(new lt(n,o,n.path,l)));return x.ParseStatus.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:Z.errorUtil.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:Z.errorUtil.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:Z.errorUtil.toString(n)}})}nonempty(e){return this.min(1,e)}};T.ZodArray=Vt;Vt.create=(t,e)=>new Vt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Y.ZodArray,...ee(e)});function rs(t){if(t instanceof Ke){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=at.create(rs(r))}return new Ke({...t._def,shape:()=>e})}else return t instanceof Vt?new Vt({...t._def,type:rs(t.element)}):t instanceof at?at.create(rs(t.unwrap())):t instanceof At?At.create(rs(t.unwrap())):t instanceof It?It.create(t.items.map(e=>rs(e))):t}var Ke=class t extends te{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),n=P.util.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==P.ZodParsedType.object){let u=this._getOrReturnCtx(e);return(0,x.addIssueToContext)(u,{code:$.ZodIssueCode.invalid_type,expected:P.ZodParsedType.object,received:u.parsedType}),x.INVALID}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),l=[];if(!(this._def.catchall instanceof bt&&this._def.unknownKeys==="strip"))for(let u in s.data)o.includes(u)||l.push(u);let c=[];for(let u of o){let h=i[u],f=s.data[u];c.push({key:{status:"valid",value:u},value:h._parse(new lt(s,f,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof bt){let u=this._def.unknownKeys;if(u==="passthrough")for(let h of l)c.push({key:{status:"valid",value:h},value:{status:"valid",value:s.data[h]}});else if(u==="strict")l.length>0&&((0,x.addIssueToContext)(s,{code:$.ZodIssueCode.unrecognized_keys,keys:l}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let h of l){let f=s.data[h];c.push({key:{status:"valid",value:h},value:u._parse(new lt(s,f,s.path,h)),alwaysSet:h in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let u=[];for(let h of c){let f=await h.key,b=await h.value;u.push({key:f,value:b,alwaysSet:h.alwaysSet})}return u}).then(u=>x.ParseStatus.mergeObjectSync(r,u)):x.ParseStatus.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return Z.errorUtil.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:Z.errorUtil.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Y.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of P.util.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of P.util.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return rs(this)}partial(e){let n={};for(let r of P.util.objectKeys(this.shape)){let s=this.shape[r];e&&!e[r]?n[r]=s:n[r]=s.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of P.util.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof at;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return Fu(P.util.objectKeys(this.shape))}};T.ZodObject=Ke;Ke.create=(t,e)=>new Ke({shape:()=>t,unknownKeys:"strip",catchall:bt.create(),typeName:Y.ZodObject,...ee(e)});Ke.strictCreate=(t,e)=>new Ke({shape:()=>t,unknownKeys:"strict",catchall:bt.create(),typeName:Y.ZodObject,...ee(e)});Ke.lazycreate=(t,e)=>new Ke({shape:t,unknownKeys:"strip",catchall:bt.create(),typeName:Y.ZodObject,...ee(e)});var lr=class extends te{_parse(e){let{ctx:n}=this._processInputParams(e),r=this._def.options;function s(i){for(let l of i)if(l.result.status==="valid")return l.result;for(let l of i)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;let o=i.map(l=>new $.ZodError(l.ctx.common.issues));return(0,x.addIssueToContext)(n,{code:$.ZodIssueCode.invalid_union,unionErrors:o}),x.INVALID}if(n.common.async)return Promise.all(r.map(async i=>{let o={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let c of r){let u={...n,common:{...n.common,issues:[]},parent:null},h=c._parseSync({data:n.data,path:n.path,parent:u});if(h.status==="valid")return h;h.status==="dirty"&&!i&&(i={result:h,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let l=o.map(c=>new $.ZodError(c));return(0,x.addIssueToContext)(n,{code:$.ZodIssueCode.invalid_union,unionErrors:l}),x.INVALID}}get options(){return this._def.options}};T.ZodUnion=lr;lr.create=(t,e)=>new lr({options:t,typeName:Y.ZodUnion,...ee(e)});var Zt=t=>t instanceof ur?Zt(t.schema):t instanceof Ye?Zt(t.innerType()):t instanceof dr?[t.value]:t instanceof hr?t.options:t instanceof pr?P.util.objectValues(t.enum):t instanceof fr?Zt(t._def.innerType):t instanceof or?[void 0]:t instanceof ar?[null]:t instanceof at?[void 0,...Zt(t.unwrap())]:t instanceof At?[null,...Zt(t.unwrap())]:t instanceof Fs||t instanceof gr?Zt(t.unwrap()):t instanceof mr?Zt(t._def.innerType):[],Fi=class t extends te{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==P.ZodParsedType.object)return(0,x.addIssueToContext)(n,{code:$.ZodIssueCode.invalid_type,expected:P.ZodParsedType.object,received:n.parsedType}),x.INVALID;let r=this.discriminator,s=n.data[r],i=this.optionsMap.get(s);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):((0,x.addIssueToContext)(n,{code:$.ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),x.INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let s=new Map;for(let i of n){let o=Zt(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let l of o){if(s.has(l))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(l)}`);s.set(l,i)}}return new t({typeName:Y.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...ee(r)})}};T.ZodDiscriminatedUnion=Fi;function za(t,e){let n=(0,P.getParsedType)(t),r=(0,P.getParsedType)(e);if(t===e)return{valid:!0,data:t};if(n===P.ZodParsedType.object&&r===P.ZodParsedType.object){let s=P.util.objectKeys(e),i=P.util.objectKeys(t).filter(l=>s.indexOf(l)!==-1),o={...t,...e};for(let l of i){let c=za(t[l],e[l]);if(!c.valid)return{valid:!1};o[l]=c.data}return{valid:!0,data:o}}else if(n===P.ZodParsedType.array&&r===P.ZodParsedType.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<t.length;i++){let o=t[i],l=e[i],c=za(o,l);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===P.ZodParsedType.date&&r===P.ZodParsedType.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var cr=class extends te{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=(i,o)=>{if((0,x.isAborted)(i)||(0,x.isAborted)(o))return x.INVALID;let l=za(i.value,o.value);return l.valid?(((0,x.isDirty)(i)||(0,x.isDirty)(o))&&n.dirty(),{status:n.value,value:l.data}):((0,x.addIssueToContext)(r,{code:$.ZodIssueCode.invalid_intersection_types}),x.INVALID)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};T.ZodIntersection=cr;cr.create=(t,e,n)=>new cr({left:t,right:e,typeName:Y.ZodIntersection,...ee(n)});var It=class t extends te{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==P.ZodParsedType.array)return(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.invalid_type,expected:P.ZodParsedType.array,received:r.parsedType}),x.INVALID;if(r.data.length<this._def.items.length)return(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),x.INVALID;!this._def.rest&&r.data.length>this._def.items.length&&((0,x.addIssueToContext)(r,{code:$.ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let i=[...r.data].map((o,l)=>{let c=this._def.items[l]||this._def.rest;return c?c._parse(new lt(r,o,r.path,l)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>x.ParseStatus.mergeArray(n,o)):x.ParseStatus.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};T.ZodTuple=It;It.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new It({items:t,typeName:Y.ZodTuple,rest:null,...ee(e)})};var Bi=class t extends te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==P.ZodParsedType.object)return(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.invalid_type,expected:P.ZodParsedType.object,received:r.parsedType}),x.INVALID;let s=[],i=this._def.keyType,o=this._def.valueType;for(let l in r.data)s.push({key:i._parse(new lt(r,l,r.path,l)),value:o._parse(new lt(r,r.data[l],r.path,l)),alwaysSet:l in r.data});return r.common.async?x.ParseStatus.mergeObjectAsync(n,s):x.ParseStatus.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof te?new t({keyType:e,valueType:n,typeName:Y.ZodRecord,...ee(r)}):new t({keyType:wn.create(),valueType:e,typeName:Y.ZodRecord,...ee(n)})}};T.ZodRecord=Bi;var os=class extends te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==P.ZodParsedType.map)return(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.invalid_type,expected:P.ZodParsedType.map,received:r.parsedType}),x.INVALID;let s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([l,c],u)=>({key:s._parse(new lt(r,l,r.path,[u,"key"])),value:i._parse(new lt(r,c,r.path,[u,"value"]))}));if(r.common.async){let l=new Map;return Promise.resolve().then(async()=>{for(let c of o){let u=await c.key,h=await c.value;if(u.status==="aborted"||h.status==="aborted")return x.INVALID;(u.status==="dirty"||h.status==="dirty")&&n.dirty(),l.set(u.value,h.value)}return{status:n.value,value:l}})}else{let l=new Map;for(let c of o){let u=c.key,h=c.value;if(u.status==="aborted"||h.status==="aborted")return x.INVALID;(u.status==="dirty"||h.status==="dirty")&&n.dirty(),l.set(u.value,h.value)}return{status:n.value,value:l}}}};T.ZodMap=os;os.create=(t,e,n)=>new os({valueType:e,keyType:t,typeName:Y.ZodMap,...ee(n)});var as=class t extends te{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==P.ZodParsedType.set)return(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.invalid_type,expected:P.ZodParsedType.set,received:r.parsedType}),x.INVALID;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&((0,x.addIssueToContext)(r,{code:$.ZodIssueCode.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&((0,x.addIssueToContext)(r,{code:$.ZodIssueCode.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let i=this._def.valueType;function o(c){let u=new Set;for(let h of c){if(h.status==="aborted")return x.INVALID;h.status==="dirty"&&n.dirty(),u.add(h.value)}return{status:n.value,value:u}}let l=[...r.data.values()].map((c,u)=>i._parse(new lt(r,c,r.path,u)));return r.common.async?Promise.all(l).then(c=>o(c)):o(l)}min(e,n){return new t({...this._def,minSize:{value:e,message:Z.errorUtil.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:Z.errorUtil.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};T.ZodSet=as;as.create=(t,e)=>new as({valueType:t,minSize:null,maxSize:null,typeName:Y.ZodSet,...ee(e)});var Hi=class t extends te{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==P.ZodParsedType.function)return(0,x.addIssueToContext)(n,{code:$.ZodIssueCode.invalid_type,expected:P.ZodParsedType.function,received:n.parsedType}),x.INVALID;function r(l,c){return(0,x.makeIssue)({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,(0,qi.getErrorMap)(),qi.defaultErrorMap].filter(u=>!!u),issueData:{code:$.ZodIssueCode.invalid_arguments,argumentsError:c}})}function s(l,c){return(0,x.makeIssue)({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,(0,qi.getErrorMap)(),qi.defaultErrorMap].filter(u=>!!u),issueData:{code:$.ZodIssueCode.invalid_return_type,returnTypeError:c}})}let i={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof kn){let l=this;return(0,x.OK)(async function(...c){let u=new $.ZodError([]),h=await l._def.args.parseAsync(c,i).catch(w=>{throw u.addIssue(r(c,w)),u}),f=await Reflect.apply(o,this,h);return await l._def.returns._def.type.parseAsync(f,i).catch(w=>{throw u.addIssue(s(f,w)),u})})}else{let l=this;return(0,x.OK)(function(...c){let u=l._def.args.safeParse(c,i);if(!u.success)throw new $.ZodError([r(c,u.error)]);let h=Reflect.apply(o,this,u.data),f=l._def.returns.safeParse(h,i);if(!f.success)throw new $.ZodError([s(h,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:It.create(e).rest(Wt.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new t({args:e||It.create([]).rest(Wt.create()),returns:n||Wt.create(),typeName:Y.ZodFunction,...ee(r)})}};T.ZodFunction=Hi;var ur=class extends te{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};T.ZodLazy=ur;ur.create=(t,e)=>new ur({getter:t,typeName:Y.ZodLazy,...ee(e)});var dr=class extends te{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return(0,x.addIssueToContext)(n,{received:n.data,code:$.ZodIssueCode.invalid_literal,expected:this._def.value}),x.INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}};T.ZodLiteral=dr;dr.create=(t,e)=>new dr({value:t,typeName:Y.ZodLiteral,...ee(e)});function Fu(t,e){return new hr({values:t,typeName:Y.ZodEnum,...ee(e)})}var hr=class t extends te{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return(0,x.addIssueToContext)(n,{expected:P.util.joinValues(r),received:n.parsedType,code:$.ZodIssueCode.invalid_type}),x.INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return(0,x.addIssueToContext)(n,{received:n.data,code:$.ZodIssueCode.invalid_enum_value,options:r}),x.INVALID}return(0,x.OK)(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};T.ZodEnum=hr;hr.create=Fu;var pr=class extends te{_parse(e){let n=P.util.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==P.ZodParsedType.string&&r.parsedType!==P.ZodParsedType.number){let s=P.util.objectValues(n);return(0,x.addIssueToContext)(r,{expected:P.util.joinValues(s),received:r.parsedType,code:$.ZodIssueCode.invalid_type}),x.INVALID}if(this._cache||(this._cache=new Set(P.util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=P.util.objectValues(n);return(0,x.addIssueToContext)(r,{received:r.data,code:$.ZodIssueCode.invalid_enum_value,options:s}),x.INVALID}return(0,x.OK)(e.data)}get enum(){return this._def.values}};T.ZodNativeEnum=pr;pr.create=(t,e)=>new pr({values:t,typeName:Y.ZodNativeEnum,...ee(e)});var kn=class extends te{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==P.ZodParsedType.promise&&n.common.async===!1)return(0,x.addIssueToContext)(n,{code:$.ZodIssueCode.invalid_type,expected:P.ZodParsedType.promise,received:n.parsedType}),x.INVALID;let r=n.parsedType===P.ZodParsedType.promise?n.data:Promise.resolve(n.data);return(0,x.OK)(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};T.ZodPromise=kn;kn.create=(t,e)=>new kn({type:t,typeName:Y.ZodPromise,...ee(e)});var Ye=class extends te{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Y.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{(0,x.addIssueToContext)(r,o),o.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(r.data,i);if(r.common.async)return Promise.resolve(o).then(async l=>{if(n.value==="aborted")return x.INVALID;let c=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return c.status==="aborted"?x.INVALID:c.status==="dirty"||n.value==="dirty"?(0,x.DIRTY)(c.value):c});{if(n.value==="aborted")return x.INVALID;let l=this._def.schema._parseSync({data:o,path:r.path,parent:r});return l.status==="aborted"?x.INVALID:l.status==="dirty"||n.value==="dirty"?(0,x.DIRTY)(l.value):l}}if(s.type==="refinement"){let o=l=>{let c=s.refinement(l,i);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){let l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?x.INVALID:(l.status==="dirty"&&n.dirty(),o(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?x.INVALID:(l.status==="dirty"&&n.dirty(),o(l.value).then(()=>({status:n.value,value:l.value}))))}if(s.type==="transform")if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!(0,x.isValid)(o))return x.INVALID;let l=s.transform(o.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>(0,x.isValid)(o)?Promise.resolve(s.transform(o.value,i)).then(l=>({status:n.value,value:l})):x.INVALID);P.util.assertNever(s)}};T.ZodEffects=Ye;T.ZodTransformer=Ye;Ye.create=(t,e,n)=>new Ye({schema:t,typeName:Y.ZodEffects,effect:e,...ee(n)});Ye.createWithPreprocess=(t,e,n)=>new Ye({schema:e,effect:{type:"preprocess",transform:t},typeName:Y.ZodEffects,...ee(n)});var at=class extends te{_parse(e){return this._getType(e)===P.ZodParsedType.undefined?(0,x.OK)(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};T.ZodOptional=at;at.create=(t,e)=>new at({innerType:t,typeName:Y.ZodOptional,...ee(e)});var At=class extends te{_parse(e){return this._getType(e)===P.ZodParsedType.null?(0,x.OK)(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};T.ZodNullable=At;At.create=(t,e)=>new At({innerType:t,typeName:Y.ZodNullable,...ee(e)});var fr=class extends te{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===P.ZodParsedType.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};T.ZodDefault=fr;fr.create=(t,e)=>new fr({innerType:t,typeName:Y.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ee(e)});var mr=class extends te{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return(0,x.isAsync)(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new $.ZodError(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new $.ZodError(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};T.ZodCatch=mr;mr.create=(t,e)=>new mr({innerType:t,typeName:Y.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ee(e)});var ls=class extends te{_parse(e){if(this._getType(e)!==P.ZodParsedType.nan){let r=this._getOrReturnCtx(e);return(0,x.addIssueToContext)(r,{code:$.ZodIssueCode.invalid_type,expected:P.ZodParsedType.nan,received:r.parsedType}),x.INVALID}return{status:"valid",value:e.data}}};T.ZodNaN=ls;ls.create=t=>new ls({typeName:Y.ZodNaN,...ee(t)});T.BRAND=Symbol("zod_brand");var Fs=class extends te{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}};T.ZodBranded=Fs;var Bs=class t extends te{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?x.INVALID:i.status==="dirty"?(n.dirty(),(0,x.DIRTY)(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?x.INVALID:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:Y.ZodPipeline})}};T.ZodPipeline=Bs;var gr=class extends te{_parse(e){let n=this._def.innerType._parse(e),r=s=>((0,x.isValid)(s)&&(s.value=Object.freeze(s.value)),s);return(0,x.isAsync)(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};T.ZodReadonly=gr;gr.create=(t,e)=>new gr({innerType:t,typeName:Y.ZodReadonly,...ee(e)});function Du(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function Bu(t,e={},n){return t?vn.create().superRefine((r,s)=>{let i=t(r);if(i instanceof Promise)return i.then(o=>{if(!o){let l=Du(e,r),c=l.fatal??n??!0;s.addIssue({code:"custom",...l,fatal:c})}});if(!i){let o=Du(e,r),l=o.fatal??n??!0;s.addIssue({code:"custom",...o,fatal:l})}}):vn.create()}T.late={object:Ke.lazycreate};var Y;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(Y||(T.ZodFirstPartyTypeKind=Y={}));var Uy=(t,e={message:`Input not instance of ${t.name}`})=>Bu(n=>n instanceof t,e);T.instanceof=Uy;var Hu=wn.create;T.string=Hu;var Ku=nr.create;T.number=Ku;var qy=ls.create;T.nan=qy;var Fy=rr.create;T.bigint=Fy;var Gu=sr.create;T.boolean=Gu;var By=ir.create;T.date=By;var Hy=ss.create;T.symbol=Hy;var Ky=or.create;T.undefined=Ky;var Gy=ar.create;T.null=Gy;var Zy=vn.create;T.any=Zy;var Wy=Wt.create;T.unknown=Wy;var Vy=bt.create;T.never=Vy;var Jy=is.create;T.void=Jy;var Yy=Vt.create;T.array=Yy;var Xy=Ke.create;T.object=Xy;var Qy=Ke.strictCreate;T.strictObject=Qy;var eb=lr.create;T.union=eb;var tb=Fi.create;T.discriminatedUnion=tb;var nb=cr.create;T.intersection=nb;var rb=It.create;T.tuple=rb;var sb=Bi.create;T.record=sb;var ib=os.create;T.map=ib;var ob=as.create;T.set=ob;var ab=Hi.create;T.function=ab;var lb=ur.create;T.lazy=lb;var cb=dr.create;T.literal=cb;var ub=hr.create;T.enum=ub;var db=pr.create;T.nativeEnum=db;var hb=kn.create;T.promise=hb;var Zu=Ye.create;T.effect=Zu;T.transformer=Zu;var pb=at.create;T.optional=pb;var fb=At.create;T.nullable=fb;var mb=Ye.createWithPreprocess;T.preprocess=mb;var gb=Bs.create;T.pipeline=gb;var yb=()=>Hu().optional();T.ostring=yb;var bb=()=>Ku().optional();T.onumber=bb;var wb=()=>Gu().optional();T.oboolean=wb;T.coerce={string:(t=>wn.create({...t,coerce:!0})),number:(t=>nr.create({...t,coerce:!0})),boolean:(t=>sr.create({...t,coerce:!0})),bigint:(t=>rr.create({...t,coerce:!0})),date:(t=>ir.create({...t,coerce:!0}))};T.NEVER=x.INVALID});var Da=le(ct=>{"use strict";var vb=ct&&ct.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),cs=ct&&ct.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&vb(e,t,n)};Object.defineProperty(ct,"__esModule",{value:!0});cs(Li(),ct);cs(Oa(),ct);cs(Nu(),ct);cs(Us(),ct);cs(Wu(),ct);cs(Di(),ct)});var Yu=le(Ge=>{"use strict";var Vu=Ge&&Ge.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),kb=Ge&&Ge.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),_b=Ge&&Ge.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&Vu(e,t,n);return kb(e,t),e},Sb=Ge&&Ge.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Vu(e,t,n)};Object.defineProperty(Ge,"__esModule",{value:!0});Ge.z=void 0;var Ju=_b(Da());Ge.z=Ju;Sb(Da(),Ge);Ge.default=Ju});var ke=le(p=>{"use strict";Object.defineProperty(p,"__esModule",{value:!0});p.BUILTIN_REPLY_LANGUAGES=p.ChatLoadMsg=p.ChatListResultMsg=p.ChatListMsg=p.ChatUsageMsg=p.ChatStreamMsg=p.JiraUsersResultMsg=p.DeployClaimResultMsg=p.DeployClaimMsg=p.RuleDiagnoseResultMsg=p.ProjectTestResultMsg=p.RunStatusMsg=p.FailedTest=p.RunUsageMsg=p.RunLogMsg=p.RunClaimMsg=p.HeartbeatMsg=p.HelloMsg=p.RuleConfig=p.ProjectConfig=p.ActionConfig=p.DeployAction=p.EnvironmentConfig=p.PromotionMode=p.DeployStep=p.RespondAction=p.ImplementAction=p.PlanOnlyAction=p.TriggerConfig=p.StatusChangedTrigger=p.CommentKeywordTrigger=p.LabelAddedTrigger=p.ActionType=p.TriggerType=p.ACTIVE_RUN_STATUSES=p.RunStatus=p.needsInputMarkerIn=p.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=p.NEEDS_INPUT_COMMENT_MARKER=p.NEEDS_INPUT_LABEL=p.NEEDS_INPUT_ASK_FENCE=p.NEEDS_INPUT_MARKER=p.BRANCH_DEPLOY_ISSUE_KEY=p.REQUIRED_AGENT_CAPABILITIES=p.DEFAULT_AGENT_ID=p.REGISTERED_AGENTS=p.DEPLOY_DOC_CANDIDATES=p.RUNNER_UNINSTALL_COMMAND=p.PROTOCOL_VERSION=p.GITHUB_TOKEN_PERMISSIONS=void 0;p.EnvPreflightMsg=p.ChatCreateTicketResultMsg=p.ChatCreateTicketMsg=p.ChatTurnResultMsg=p.ChatTurnMsg=p.ChatFile=p.TeamCredsResultMsg=p.TeamCredsMsg=p.KnowledgeSaveResultMsg=p.KnowledgeSaveMsg=p.KnowledgeListResultMsg=p.KnowledgeFile=p.KnowledgeListMsg=p.AuditReviewResultMsg=p.AuditReviewMsg=p.AuditGetResultMsg=p.AuditGetMsg=p.AuditExplainResultMsg=p.AuditExplainMsg=p.ChatCancelMsg=p.ChatDiagnosticResultMsg=p.ChatDiagnosticMsg=p.AuditListResultMsg=p.AuditStatsResultMsg=p.AuditStatsMsg=p.AuditListMsg=p.AuditStartResultMsg=p.AuditStartMsg=p.AuditRecord=p.AuditFinding=p.AuditDetailLevel=p.AuditScope=p.AuditSeverity=p.KnowledgeRole=p.AuditRole=p.EpicSuggestResultMsg=p.EpicSuggestMsg=p.EpicListResultMsg=p.EpicChild=p.EpicListMsg=p.BoardTriggerResultMsg=p.BoardTriggerMsg=p.BoardFetchResultMsg=p.BoardFetchMsg=p.RepoDocReadResultMsg=p.RepoDocReadMsg=p.RepoDocsResultMsg=p.RepoDocsMsg=p.ChatLoadResultMsg=p.REPLY_STYLES=void 0;p.DeploySuggestMsg=p.DeployFixMsg=p.DeployStartMsg=p.RunRetryPushMsg=p.RunRejectedMsg=p.RunApprovedMsg=p.RunCancelMsg=p.RuleDiagnoseMsg=p.ProjectTestMsg=p.RunClaimResultMsg=p.ConfigMsg=p.HelloAckMsg=p.RunnerToServerMsg=p.AutopilotReportMsg=p.AutopilotNextResultMsg=p.AutopilotPlanResultMsg=p.AutopilotPlanMsg=p.AutopilotNextMsg=p.RunnerUninstallResultMsg=p.RunnerUpdateResultMsg=p.AgentProfilesResultMsg=p.AgentProfilesMsg=p.RunPrConflictMsg=p.RunResolveConflictResultMsg=p.RunAnswerResultMsg=p.RunAnswerMsg=p.RunTestFixResultMsg=p.RunTestFixMsg=p.RunResolveConflictMsg=p.RunnerUninstallMsg=p.RunnerUpdateMsg=p.RepoDocSaveResultMsg=p.RepoDocSaveMsg=p.SetupClaudeMdSaveResultMsg=p.SetupClaudeMdSaveMsg=p.SetupAskResultMsg=p.SetupAskMsg=p.SetupClaudeMdGenerateResultMsg=p.SetupClaudeMdGenerateMsg=p.SetupRecheckResultMsg=p.SetupRecheckMsg=p.RepoUnmapResultMsg=p.RepoUnmapMsg=p.SetupStatusResultMsg=p.SetupStatusMsg=p.DeploySuggestResultMsg=p.SelfMigrationApplyResultMsg=p.SelfMigrationApplyMsg=p.SELF_MIGRATION_DIR=p.EnvPreflightResultMsg=void 0;p.DEFAULT_DEPLOY_SUGGEST_PROMPT_TEMPLATE=p.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE=p.DEPLOY_FIX_PROMPT_TEMPLATE=p.PROMPT_PRESETS=p.DEFAULT_RESPOND_PROMPT_TEMPLATE=p.BUGFIX_IMPLEMENT_PROMPT_TEMPLATE=p.BUG_INVESTIGATION_PROMPT_TEMPLATE=p.TECHNICAL_PLAN_PROMPT_TEMPLATE=p.MEMORY_UPDATE_PROMPT=p.DEFAULT_IMPLEMENT_PROMPT_TEMPLATE=p.WRITE_TESTS_PROMPT=p.FOCUSED_READING_PROMPT=p.NEEDS_INPUT_OPTIONS_PROMPT=p.DEFAULT_PLAN_PROMPT_TEMPLATE=p.EnrollResponse=p.EnrollRequest=p.ServerToRunnerMsg=p.JiraUsersMsg=void 0;p.missingAgentCapabilities=Tb;p.replyPreferenceAppendix=Rb;p.pendingMigrationsAppendix=Ib;p.deployTargetsAppendix=Ab;p.isSelfMigrationFilename=Eb;p.parseRunnerMsg=Cb;p.parseServerMsg=$b;var a=Yu();p.GITHUB_TOKEN_PERMISSIONS={where:"github.com/settings/personal-access-tokens/new (fine-grained token)",steps:["Resource owner: the org or user that OWNS the repo - not your personal account, unless the repo is under it","Repository access: Only select repositories -> pick this repo","Contents: Read and write - pushing the agent's branch","Pull requests: Read and write - opening the PR, and merging it when you approve","Metadata: Read-only - GitHub adds this itself and will not let you remove it","Workflows: Read and write - ONLY if changes may touch .github/workflows; without it GitHub rejects those pushes"],note:"A fine-grained token covers exactly ONE resource owner, so a repo in a different org always needs its own token. A classic token with the `repo` scope also works and is simpler, but it reaches every repository you can see - prefer fine-grained."};p.PROTOCOL_VERSION="1.76";p.RUNNER_UNINSTALL_COMMAND="sudo allwright service uninstall";p.DEPLOY_DOC_CANDIDATES=[".ticketpilot/deploy.md","DEPLOY.md","DEPLOYMENT.md","docs/DEPLOY.md","docs/deploy.md","docs/deployment.md"];p.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}];p.DEFAULT_AGENT_ID="claude-code";p.REQUIRED_AGENT_CAPABILITIES={plan_only:["readOnlyJail","sessionResume"],respond:["readOnlyJail"],implement:["editNoShellJail","sessionResume"],deploy:[],chat:["readOnlyJail","sessionResume"],assist:["readOnlyJail"]};function Tb(t,e){let n=p.REGISTERED_AGENTS.find(r=>r.id===t);return n?(p.REQUIRED_AGENT_CAPABILITIES[e]??[]).filter(r=>!n.capabilities[r]):null}p.BRANCH_DEPLOY_ISSUE_KEY="(branch deploy)";p.NEEDS_INPUT_MARKER="NEEDS-INPUT";p.NEEDS_INPUT_ASK_FENCE="ask";p.NEEDS_INPUT_LABEL="agent-needs-input";p.NEEDS_INPUT_COMMENT_MARKER="Allwright needs your input";p.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=["TicketPilot needs your input"];var xb=t=>t.includes(p.NEEDS_INPUT_COMMENT_MARKER)||p.LEGACY_NEEDS_INPUT_COMMENT_MARKERS.some(e=>t.includes(e));p.needsInputMarkerIn=xb;p.RunStatus=a.z.enum(["queued","running","posting","awaiting_approval","needs_input","succeeded","failed","timed_out"]);p.ACTIVE_RUN_STATUSES=["queued","running","posting","awaiting_approval"];p.TriggerType=a.z.enum(["label_added","comment_keyword","status_changed"]);p.ActionType=a.z.enum(["plan_only","implement","respond","deploy"]);p.LabelAddedTrigger=a.z.object({type:a.z.literal("label_added"),label:a.z.string().min(1),doneLabel:a.z.string().min(1).default("agent-planned"),failedLabel:a.z.string().min(1).default("agent-failed")});p.CommentKeywordTrigger=a.z.object({type:a.z.literal("comment_keyword"),keyword:a.z.string().min(1),doneLabel:a.z.string().min(1).default("agent-implemented"),failedLabel:a.z.string().min(1).default("agent-failed")});p.StatusChangedTrigger=a.z.object({type:a.z.literal("status_changed"),status:a.z.string().min(1),doneLabel:a.z.string().min(1).default("agent-deployed"),failedLabel:a.z.string().min(1).default("agent-failed")});p.TriggerConfig=a.z.discriminatedUnion("type",[p.LabelAddedTrigger,p.CommentKeywordTrigger,p.StatusChangedTrigger]);p.PlanOnlyAction=a.z.object({type:a.z.literal("plan_only"),promptTemplate:a.z.string().min(1),timeoutSeconds:a.z.number().int().positive().max(3600).default(900),agent:a.z.string().default(p.DEFAULT_AGENT_ID),model:a.z.string().default("")});p.ImplementAction=a.z.object({type:a.z.literal("implement"),promptTemplate:a.z.string().min(1),timeoutSeconds:a.z.number().int().positive().max(7200).default(1800),maxTurns:a.z.number().int().positive().max(500).default(120),requireApproval:a.z.boolean().default(!0),branchTemplate:a.z.string().min(1).default("agent/{{issueKey}}").refine(t=>t.includes("{{issueKey}}"),{message:"branchTemplate must contain {{issueKey}}"}),baseBranch:a.z.string().min(1).default("main"),jiraTransition:a.z.string().optional(),jiraTransitionOnStart:a.z.string().optional(),jiraTransitionOnMerge:a.z.string().optional(),agent:a.z.string().default(p.DEFAULT_AGENT_ID),model:a.z.string().default(""),updateMemory:a.z.boolean().default(!1),writeTests:a.z.boolean().default(!0),runTests:a.z.boolean().default(!0),mergeOnApprove:a.z.boolean().default(!0),mergeMethod:a.z.enum(["squash","merge","rebase"]).default("squash"),autoMerge:a.z.boolean().default(!0)});p.RespondAction=a.z.object({type:a.z.literal("respond"),promptTemplate:a.z.string().min(1),timeoutSeconds:a.z.number().int().positive().max(3600).default(600),agent:a.z.string().default(p.DEFAULT_AGENT_ID),model:a.z.string().default("")});p.DeployStep=a.z.object({name:a.z.string().min(1).max(120),run:a.z.string().min(1).max(4e3),continueOnError:a.z.boolean().default(!1)});p.PromotionMode=a.z.enum(["deploy_only","merge_and_deploy"]);p.EnvironmentConfig=a.z.object({id:a.z.string(),projectId:a.z.string(),name:a.z.string(),rank:a.z.number().int().nonnegative(),auditBeforeDeploy:a.z.enum(["","security","testing"]).default(""),branch:a.z.string().default(""),publicUrl:a.z.string().default(""),servePath:a.z.string().default(""),useDedicatedCheckout:a.z.boolean().default(!1),promotionMode:p.PromotionMode.default("deploy_only"),ticketBranchTemplate:a.z.string().default("agent/{{issueKey}}"),steps:a.z.array(p.DeployStep).default([]),workdir:a.z.string().default(""),timeoutSeconds:a.z.number().int().positive().max(21600).default(1800),requiredSecrets:a.z.array(a.z.string()).default([]),requireApproval:a.z.boolean().default(!1),requireSyncCheck:a.z.boolean().default(!1),previousEnvBranch:a.z.string().optional(),deployFromColumn:a.z.string().default(""),deployToColumn:a.z.string().default("")});p.DeployAction=a.z.object({type:a.z.literal("deploy"),envSelection:a.z.enum(["fixed","from_comment"]).default("from_comment"),environmentId:a.z.string().optional(),requireStatus:a.z.string().optional()});p.ActionConfig=a.z.discriminatedUnion("type",[p.PlanOnlyAction,p.ImplementAction,p.RespondAction,p.DeployAction]);p.ProjectConfig=a.z.object({id:a.z.string(),name:a.z.string(),jiraProjectKey:a.z.string(),goLiveIssueKey:a.z.string().default(""),repoName:a.z.string(),jiraSiteUrl:a.z.string().default(""),defaultAgent:a.z.string().default("claude-code"),componentRoutes:a.z.array(a.z.object({component:a.z.string().min(1),repoName:a.z.string().min(1)})).default([])});p.RuleConfig=a.z.object({id:a.z.string(),projectId:a.z.string(),name:a.z.string(),enabled:a.z.boolean(),trigger:p.TriggerConfig,action:p.ActionConfig});p.HelloMsg=a.z.object({type:a.z.literal("hello"),protocolVersion:a.z.string(),runnerVersion:a.z.string(),platform:a.z.string(),justBooted:a.z.boolean().optional()});p.HeartbeatMsg=a.z.object({type:a.z.literal("heartbeat"),ts:a.z.string()});p.RunClaimMsg=a.z.object({type:a.z.literal("run.claim"),requestId:a.z.string(),ruleId:a.z.string(),issueKey:a.z.string(),issueSummary:a.z.string().default(""),triggerFingerprint:a.z.string(),dedupKey:a.z.string().optional(),triggeredByAccountId:a.z.string().optional()});p.RunLogMsg=a.z.object({type:a.z.literal("run.log"),runId:a.z.string(),seq:a.z.number().int().nonnegative(),ts:a.z.string(),level:a.z.enum(["info","warn","error","agent"]),message:a.z.string().max(16384)});p.RunUsageMsg=a.z.object({type:a.z.literal("run.usage"),runId:a.z.string(),inputTokens:a.z.number().int().nonnegative(),outputTokens:a.z.number().int().nonnegative(),cacheReadTokens:a.z.number().int().nonnegative().optional(),costUsd:a.z.number().nonnegative().optional(),turns:a.z.number().int().nonnegative().optional()});p.FailedTest=a.z.object({command:a.z.string().max(500),exitCode:a.z.number().int(),tail:a.z.string().max(4e3)});p.RunStatusMsg=a.z.object({type:a.z.literal("run.status"),runId:a.z.string(),status:p.RunStatus,error:a.z.string().optional(),errorKind:a.z.enum(["guard"]).optional(),costUsd:a.z.number().nonnegative().optional(),inputTokens:a.z.number().int().nonnegative().optional(),outputTokens:a.z.number().int().nonnegative().optional(),resultSummary:a.z.string().max(2e3).optional(),billingMode:a.z.enum(["subscription","api","unknown"]).optional(),model:a.z.string().max(200).optional(),prUrl:a.z.string().optional(),headSha:a.z.string().optional(),deployedRef:a.z.string().optional(),retryAvailable:a.z.boolean().optional(),failedTests:a.z.array(p.FailedTest).max(20).optional(),testsPassed:a.z.number().int().nonnegative().optional(),testsTotal:a.z.number().int().nonnegative().optional(),manualSteps:a.z.array(a.z.object({command:a.z.string().max(500),why:a.z.string().max(300).default("")})).max(20).optional(),goLiveDraft:a.z.string().max(4e3).optional(),inputQuestions:a.z.string().max(4e3).optional(),inputOptions:a.z.array(a.z.string().max(200)).max(5).optional()});p.ProjectTestResultMsg=a.z.object({type:a.z.literal("project.test.result"),requestId:a.z.string(),ok:a.z.boolean(),checks:a.z.array(a.z.object({name:a.z.string(),ok:a.z.boolean(),detail:a.z.string(),kind:a.z.enum(["connection","content"]).default("connection"),fix:a.z.array(a.z.string()).default([]),fixNote:a.z.string().default("")}))});p.RuleDiagnoseResultMsg=a.z.object({type:a.z.literal("rule.diagnose.result"),requestId:a.z.string(),checks:a.z.array(a.z.object({name:a.z.string(),ok:a.z.boolean(),detail:a.z.string(),kind:a.z.enum(["connection","content"]).default("connection"),fix:a.z.array(a.z.string()).default([]),fixNote:a.z.string().default("")})),matchedCount:a.z.number().int().nonnegative(),excludedCount:a.z.number().int().nonnegative(),excludedSample:a.z.array(a.z.string()).max(5)});p.DeployClaimMsg=a.z.object({type:a.z.literal("deploy.claim"),requestId:a.z.string(),projectId:a.z.string(),ruleId:a.z.string(),issueKey:a.z.string(),issueSummary:a.z.string().default(""),environmentName:a.z.string(),requestedByAccountId:a.z.string().optional(),requestedByDisplayName:a.z.string().default(""),dedupKey:a.z.string(),triggerFingerprint:a.z.string()});p.DeployClaimResultMsg=a.z.object({type:a.z.literal("deploy.claim.result"),requestId:a.z.string(),accepted:a.z.boolean(),runId:a.z.string().optional(),environment:p.EnvironmentConfig.optional(),reason:a.z.string().optional(),code:a.z.enum(["ok","duplicate","unknown_environment","not_permitted","unlinked_jira_account","promotion_order","jira_disabled","rule_disabled","cap"]).optional()});p.JiraUsersResultMsg=a.z.object({type:a.z.literal("jira.users.result"),requestId:a.z.string(),ok:a.z.boolean(),users:a.z.array(a.z.object({accountId:a.z.string(),displayName:a.z.string(),email:a.z.string().default(""),active:a.z.boolean().default(!0)})).default([]),error:a.z.string().optional()});p.ChatStreamMsg=a.z.object({type:a.z.literal("chat.stream"),requestId:a.z.string(),seq:a.z.number().int().nonnegative(),text:a.z.string().max(8e3)});p.ChatUsageMsg=a.z.object({type:a.z.literal("chat.usage"),requestId:a.z.string(),inputTokens:a.z.number().int().nonnegative(),outputTokens:a.z.number().int().nonnegative(),cacheReadTokens:a.z.number().int().nonnegative().optional(),turns:a.z.number().int().nonnegative().optional()});p.ChatListMsg=a.z.object({type:a.z.literal("chat.list"),requestId:a.z.string(),projectId:a.z.string()});p.ChatListResultMsg=a.z.object({type:a.z.literal("chat.list.result"),requestId:a.z.string(),sessions:a.z.array(a.z.object({sessionId:a.z.string(),title:a.z.string().default(""),updatedAt:a.z.string().default(""),messageCount:a.z.number().int().nonnegative().default(0)})).default([])});p.ChatLoadMsg=a.z.object({type:a.z.literal("chat.load"),requestId:a.z.string(),sessionId:a.z.string()});p.BUILTIN_REPLY_LANGUAGES=[{name:"English",instruction:"Write your prose in English."},{name:"Hindi",instruction:"Write your prose in Hindi, in the Devanagari script. Keep technical terms that have no everyday Hindi equivalent in English rather than inventing a translation."},{name:"Hinglish",instruction:"Write your prose in Hinglish: conversational Hindi written in the Latin alphabet, with English technical words left in English - the way an Indian developer talks at work."}];p.REPLY_STYLES=[{id:"technical",label:"Technical",hint:"Full detail - names files, functions and trade-offs",instruction:"Answer at full technical depth: name the files, functions and data structures involved, and state trade-offs precisely. Assume the reader reads code every day."},{id:"balanced",label:"Balanced",hint:"Plain explanation, with the technical detail that matters",instruction:"Explain in plain language first, then add the technical detail that actually matters for the decision. Assume the reader is technical but does not know this codebase."},{id:"simple",label:"Simple",hint:"Everyday words - no jargon unless it is unavoidable",instruction:"Answer in everyday words, as if to someone who does not write code. Avoid jargon; when a technical term is unavoidable, explain it in half a sentence. Prefer short paragraphs and concrete examples over precision about internals."}];function Rb(t){let e=[],n=(t.language??"").trim();if(n){let s=p.BUILTIN_REPLY_LANGUAGES.find(i=>i.name.toLowerCase()===n.toLowerCase());e.push((t.languageInstruction??"").trim()||s?.instruction||`Write your prose in ${n}.`),e.push("Code, file paths, identifiers, commands, error text and log output stay exactly as they are - only your own prose changes language."),e.push("The ```ticket block is the exception: its summary and description are ALWAYS written in English, because the ticket is read by other people and by the implementing agent.")}let r=p.REPLY_STYLES.find(s=>s.id===(t.style??"").trim());return r&&e.push(r.instruction),e.length?`
|
|
25
25
|
|
|
26
26
|
HOW TO WRITE THE REPLY - the person you are answering chose this, so it applies to every reply in this conversation:
|
|
27
27
|
- ${e.join(`
|
|
28
28
|
- `)}
|
|
29
|
-
`:""}function
|
|
29
|
+
`:""}function Ib(t){if(!t.length)return"";let e="```";return`
|
|
30
30
|
|
|
31
31
|
PENDING DATABASE MIGRATIONS (fact, read from this database's own ledger just now):
|
|
32
|
-
`+t.map(n=>`- ${
|
|
32
|
+
`+t.map(n=>`- ${p.SELF_MIGRATION_DIR}/${n}`).join(`
|
|
33
33
|
`)+`
|
|
34
34
|
These files are checked in but NOT applied to the database this control plane runs on. A build-check or deploy that fails on a missing column or table is almost certainly this. When the user asks about such a failure, name the exact file above - never guess at one, and never claim a migration is pending unless it is in this list. When a file above is the answer, end your reply with:
|
|
35
35
|
${e}action
|
|
36
36
|
{"type": "apply-migration", "file": "<one filename from the list above>"}
|
|
37
37
|
${e}
|
|
38
|
-
That is an action block - there is no free-form command form of any action. Never mention the block itself in your prose.`}function
|
|
38
|
+
That is an action block - there is no free-form command form of any action. Never mention the block itself in your prose.`}function Ab(t){if(!t.length)return"";let e="```";return`
|
|
39
39
|
|
|
40
40
|
DEPLOY TARGETS (fact: this project's environments, in promotion order):
|
|
41
41
|
`+t.map(n=>`- ${n}`).join(`
|
|
@@ -44,7 +44,7 @@ When your diagnosis concludes that one of these environments is running old code
|
|
|
44
44
|
${e}action
|
|
45
45
|
{"type": "deploy", "environment": "<one name from the list above>"}
|
|
46
46
|
${e}
|
|
47
|
-
The dashboard turns that into a Deploy button for the user - subject to their own permissions, which you cannot see; never promise the deploy will be allowed. Offer it only when a deploy is genuinely the fix, never as a routine suggestion, and never name an environment that is not in the list. Never mention the block itself in your prose.`}h.ChatLoadResultMsg=a.z.object({type:a.z.literal("chat.load.result"),requestId:a.z.string(),ok:a.z.boolean(),projectId:a.z.string().default(""),messages:a.z.array(a.z.object({role:a.z.enum(["user","agent"]),text:a.z.string(),steps:a.z.array(a.z.string()).default([]),files:a.z.array(a.z.string()).default([]),at:a.z.string().default(""),ms:a.z.number().int().nonnegative().default(0)})).default([]),error:a.z.string().optional()});h.RepoDocsMsg=a.z.object({type:a.z.literal("repo.docs"),requestId:a.z.string(),projectId:a.z.string()});h.RepoDocsResultMsg=a.z.object({type:a.z.literal("repo.docs.result"),requestId:a.z.string(),ok:a.z.boolean(),docs:a.z.array(a.z.object({path:a.z.string(),sizeBytes:a.z.number().int().nonnegative().default(0),updatedAt:a.z.string().default("")})).default([]),error:a.z.string().optional()});h.RepoDocReadMsg=a.z.object({type:a.z.literal("repo.doc.read"),requestId:a.z.string(),projectId:a.z.string(),path:a.z.string().max(400)});h.RepoDocReadResultMsg=a.z.object({type:a.z.literal("repo.doc.read.result"),requestId:a.z.string(),ok:a.z.boolean(),path:a.z.string().default(""),content:a.z.string().default(""),truncated:a.z.boolean().default(!1),error:a.z.string().optional()});h.BoardFetchMsg=a.z.object({type:a.z.literal("board.fetch"),requestId:a.z.string(),projectId:a.z.string()});h.BoardFetchResultMsg=a.z.object({type:a.z.literal("board.fetch.result"),requestId:a.z.string(),ok:a.z.boolean(),browseBaseUrl:a.z.string().default(""),columns:a.z.array(a.z.object({name:a.z.string(),issues:a.z.array(a.z.object({key:a.z.string(),summary:a.z.string(),labels:a.z.array(a.z.string()).default([])})).default([])})).default([]),error:a.z.string().optional()});h.BoardTriggerMsg=a.z.object({type:a.z.literal("board.trigger"),requestId:a.z.string(),projectId:a.z.string(),issueKey:a.z.string(),comment:a.z.string().max(2e3).default(""),removeLabel:a.z.string().default(""),requestedBy:a.z.string().default(""),requestedByEmail:a.z.string().default(""),reimplement:a.z.boolean().default(!1)});h.BoardTriggerResultMsg=a.z.object({type:a.z.literal("board.trigger.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional()});h.EpicListMsg=a.z.object({type:a.z.literal("epic.list"),requestId:a.z.string(),projectId:a.z.string(),epicKey:a.z.string().default("")});h.EpicChild=a.z.object({key:a.z.string(),summary:a.z.string(),status:a.z.string(),statusCategory:a.z.string(),labels:a.z.array(a.z.string()).default([])});h.EpicListResultMsg=a.z.object({type:a.z.literal("epic.list.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),epics:a.z.array(a.z.object({key:a.z.string(),summary:a.z.string(),status:a.z.string()})).default([]),children:a.z.array(h.EpicChild).default([])});h.EpicSuggestMsg=a.z.object({type:a.z.literal("epic.suggest"),requestId:a.z.string(),projectId:a.z.string(),epicKey:a.z.string().min(1),model:a.z.string().default("")});h.EpicSuggestResultMsg=a.z.object({type:a.z.literal("epic.suggest.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),issueKey:a.z.string().default(""),reason:a.z.string().default(""),considered:a.z.number().int().default(0)});h.AuditRole=a.z.enum(["security","testing","architecture","functional"]);h.KnowledgeRole=a.z.enum(["security","testing","architecture","functional","implement"]);h.AuditSeverity=a.z.enum(["critical","high","medium","low","info"]);h.AuditScope=a.z.object({kind:a.z.enum(["repo","ticket","branch"]).default("repo"),ref:a.z.string().default("")});h.AuditDetailLevel=a.z.enum(["simple","technical"]);h.AuditFinding=a.z.object({id:a.z.string().min(1),title:a.z.string().min(1),ruleId:a.z.string().max(20).default(""),severity:h.AuditSeverity,area:a.z.string().default(""),evidence:a.z.array(a.z.object({file:a.z.string().min(1),line:a.z.number().int().positive().optional(),note:a.z.string().default("")})).min(1),fix:a.z.string().default("")});h.AuditRecord=a.z.object({id:a.z.string(),role:h.AuditRole,createdAt:a.z.string(),model:a.z.string().default(""),summary:a.z.string().default(""),packNames:a.z.array(a.z.string()).default([]),findings:a.z.array(h.AuditFinding).default([]),costUsd:a.z.number().default(0),review:a.z.object({selected:a.z.array(a.z.string()),updatedAt:a.z.string()}).optional(),verdicts:a.z.record(a.z.object({verdict:a.z.enum(["valid","false-positive","wont-fix"]),note:a.z.string().default(""),by:a.z.string().default(""),at:a.z.string().default("")})).default({}),lessonsWritten:a.z.array(a.z.string()).default([]),ticketed:a.z.record(a.z.string()).default({}),scope:h.AuditScope.default({kind:"repo",ref:""}),detailLevel:h.AuditDetailLevel.default("technical"),testRun:a.z.array(a.z.object({command:a.z.string(),exitCode:a.z.number().int(),durationMs:a.z.number().int().default(0),tail:a.z.string().default("")})).optional()});h.AuditStartMsg=a.z.object({type:a.z.literal("audit.start"),requestId:a.z.string(),projectId:a.z.string(),role:h.AuditRole,model:a.z.string().default(""),scope:h.AuditScope.default({kind:"repo",ref:""}),detailLevel:h.AuditDetailLevel.default("technical"),baseUrl:a.z.string().default("")});h.AuditStartResultMsg=a.z.object({type:a.z.literal("audit.start.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),audit:h.AuditRecord.optional()});h.AuditListMsg=a.z.object({type:a.z.literal("audit.list"),requestId:a.z.string(),projectId:a.z.string()});h.AuditStatsMsg=a.z.object({type:a.z.literal("audit.stats"),requestId:a.z.string(),projectIds:a.z.array(a.z.string()).max(200).default([]),since:a.z.string().default("")});h.AuditStatsResultMsg=a.z.object({type:a.z.literal("audit.stats.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),byProject:a.z.record(a.z.object({audits:a.z.number().int().default(0),findings:a.z.number().int().default(0),valid:a.z.number().int().default(0),falsePositive:a.z.number().int().default(0),wontFix:a.z.number().int().default(0),unreviewed:a.z.number().int().default(0)})).default({})});h.AuditListResultMsg=a.z.object({type:a.z.literal("audit.list.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),audits:a.z.array(a.z.object({id:a.z.string(),role:h.AuditRole,createdAt:a.z.string(),findingCount:a.z.number().int(),bySeverity:a.z.record(a.z.number().int()).default({}),detailLevel:h.AuditDetailLevel.default("technical")})).default([])});h.ChatDiagnosticMsg=a.z.object({type:a.z.literal("chat.diagnostic"),requestId:a.z.string(),projectId:a.z.string(),command:a.z.string().max(40),args:a.z.record(a.z.unknown()).default({})});h.ChatDiagnosticResultMsg=a.z.object({type:a.z.literal("chat.diagnostic.result"),requestId:a.z.string(),ok:a.z.boolean().default(!0),commandLine:a.z.string().default(""),output:a.z.string().default("")});h.ChatCancelMsg=a.z.object({type:a.z.literal("chat.cancel"),requestId:a.z.string(),turnId:a.z.string()});h.AuditExplainMsg=a.z.object({type:a.z.literal("audit.explain"),requestId:a.z.string(),projectId:a.z.string(),auditId:a.z.string(),findingId:a.z.string()});h.AuditExplainResultMsg=a.z.object({type:a.z.literal("audit.explain.result"),requestId:a.z.string(),ok:a.z.boolean().default(!0),error:a.z.string().default(""),explanation:a.z.string().default("")});h.AuditGetMsg=a.z.object({type:a.z.literal("audit.get"),requestId:a.z.string(),projectId:a.z.string(),auditId:a.z.string()});h.AuditGetResultMsg=a.z.object({type:a.z.literal("audit.get.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),audit:h.AuditRecord.optional()});h.AuditReviewMsg=a.z.object({type:a.z.literal("audit.review"),requestId:a.z.string(),projectId:a.z.string(),auditId:a.z.string(),selected:a.z.array(a.z.string()).optional(),ticketed:a.z.array(a.z.object({findingId:a.z.string(),issueKey:a.z.string()})).default([]),verdicts:a.z.array(a.z.object({findingId:a.z.string(),verdict:a.z.enum(["valid","false-positive","wont-fix"]),note:a.z.string().max(2e3).default("")})).default([]),verdictBy:a.z.string().default("")});h.AuditReviewResultMsg=a.z.object({type:a.z.literal("audit.review.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),audit:h.AuditRecord.optional()});h.KnowledgeListMsg=a.z.object({type:a.z.literal("knowledge.list"),requestId:a.z.string(),projectId:a.z.string()});h.KnowledgeFile=a.z.object({role:h.KnowledgeRole,level:a.z.enum(["global","org","project"]),source:a.z.enum(["pack","lessons","memory"]),name:a.z.string(),content:a.z.string(),editable:a.z.boolean().default(!1)});h.KnowledgeListResultMsg=a.z.object({type:a.z.literal("knowledge.list.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),files:a.z.array(h.KnowledgeFile).default([])});h.KnowledgeSaveMsg=a.z.object({type:a.z.literal("knowledge.save"),requestId:a.z.string(),projectId:a.z.string(),role:h.KnowledgeRole,level:a.z.enum(["org","project"]),source:a.z.enum(["pack","lessons"]),name:a.z.string().min(1).max(100),content:a.z.string().max(6e4),append:a.z.boolean().default(!1),by:a.z.string().default("")});h.KnowledgeSaveResultMsg=a.z.object({type:a.z.literal("knowledge.save.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional()});h.TeamCredsMsg=a.z.object({type:a.z.literal("team.creds"),requestId:a.z.string(),emails:a.z.array(a.z.string()).max(200)});h.TeamCredsResultMsg=a.z.object({type:a.z.literal("team.creds.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),githubShared:a.z.boolean().default(!1),sharedGithubLogin:a.z.string().default(""),entries:a.z.array(a.z.object({email:a.z.string(),jira:a.z.enum(["own","runner-account","missing"]),jiraAs:a.z.string().default(""),github:a.z.enum(["own","shared","missing"]),githubAs:a.z.string().default("")})).default([])});h.ChatFile=a.z.object({name:a.z.string().min(1).max(255),contentBase64:a.z.string().min(1).max(6e6)});h.ChatTurnMsg=a.z.object({type:a.z.literal("chat.turn"),requestId:a.z.string(),projectId:a.z.string(),sessionId:a.z.string().optional(),message:a.z.string().min(1).max(2e4),userName:a.z.string().default(""),model:a.z.string().default(""),files:a.z.array(h.ChatFile).max(8).default([]),replyLanguage:a.z.string().max(60).default(""),replyLanguageInstruction:a.z.string().max(600).default(""),replyStyle:a.z.string().max(30).default(""),pendingMigrations:a.z.array(a.z.string().max(200)).max(50).default([]),environments:a.z.array(a.z.string().max(60)).max(20).default([])});h.ChatTurnResultMsg=a.z.object({type:a.z.literal("chat.turn.result"),requestId:a.z.string(),ok:a.z.boolean(),sessionId:a.z.string().default(""),reply:a.z.string().default(""),error:a.z.string().optional(),inputTokens:a.z.number().int().nonnegative().default(0),outputTokens:a.z.number().int().nonnegative().default(0),cacheReadTokens:a.z.number().int().nonnegative().default(0),costUsd:a.z.number().nonnegative().default(0),model:a.z.string().max(200).default(""),contextTokens:a.z.number().int().nonnegative().default(0),contextLimit:a.z.number().int().nonnegative().default(0),compacted:a.z.boolean().default(!1),compactedMessages:a.z.number().int().nonnegative().default(0)});h.ChatCreateTicketMsg=a.z.object({type:a.z.literal("chat.create.ticket"),requestId:a.z.string(),projectId:a.z.string(),summary:a.z.string().min(1).max(250),description:a.z.string().default(""),triggerComment:a.z.string().default(""),requestedBy:a.z.string().default(""),requestedByEmail:a.z.string().default(""),asEpic:a.z.boolean().default(!1),children:a.z.array(a.z.object({summary:a.z.string().min(1),description:a.z.string().default("")})).max(20).default([]),createAs:a.z.enum(["epic_with_children","separate_epics","separate_tasks"]).default("epic_with_children"),files:a.z.array(h.ChatFile).max(8).default([])});h.ChatCreateTicketResultMsg=a.z.object({type:a.z.literal("chat.create.ticket.result"),requestId:a.z.string(),ok:a.z.boolean(),issueKey:a.z.string().default(""),error:a.z.string().optional(),childKeys:a.z.array(a.z.string()).default([])});h.EnvPreflightMsg=a.z.object({type:a.z.literal("env.preflight"),requestId:a.z.string(),projectId:a.z.string(),environmentName:a.z.string().default(""),steps:a.z.array(h.DeployStep).default([]),requiredSecrets:a.z.array(a.z.string()).default([]),workdir:a.z.string().default(""),branch:a.z.string().default(""),publicUrl:a.z.string().default("")});h.EnvPreflightResultMsg=a.z.object({type:a.z.literal("env.preflight.result"),requestId:a.z.string(),ok:a.z.boolean(),checks:a.z.array(a.z.object({name:a.z.string(),ok:a.z.boolean(),detail:a.z.string().default(""),kind:a.z.enum(["connection","content"]).default("connection"),fix:a.z.array(a.z.string()).default([]),fixNote:a.z.string().default("")})).default([])});h.SELF_MIGRATION_DIR="apps/api/prisma/manual";function vb(t){return/^[A-Za-z0-9][A-Za-z0-9._-]*\.sql$/.test(t)&&!t.includes("..")}h.SelfMigrationApplyMsg=a.z.object({type:a.z.literal("selfmigration.apply"),requestId:a.z.string(),projectId:a.z.string(),environmentName:a.z.string().default(""),file:a.z.string(),urlSecret:a.z.string().default("DATABASE_URL")});h.SelfMigrationApplyResultMsg=a.z.object({type:a.z.literal("selfmigration.apply.result"),requestId:a.z.string(),ok:a.z.boolean(),file:a.z.string().default(""),checks:a.z.array(a.z.object({name:a.z.string(),ok:a.z.boolean(),detail:a.z.string().default(""),fix:a.z.array(a.z.string()).default([])})).default([]),output:a.z.string().max(2e4).default(""),error:a.z.string().default("")});h.DeploySuggestResultMsg=a.z.object({type:a.z.literal("deploy.suggest.result"),requestId:a.z.string(),ok:a.z.boolean(),steps:a.z.array(h.DeployStep).default([]),requiredSecrets:a.z.array(a.z.string()).default([]),notes:a.z.string().default(""),error:a.z.string().optional(),docPath:a.z.string().default(""),docContent:a.z.string().max(1e5).default("")});h.SetupStatusMsg=a.z.object({type:a.z.literal("setup.status"),requestId:a.z.string(),repoNames:a.z.array(a.z.string()).max(100).default([])});h.SetupStatusResultMsg=a.z.object({type:a.z.literal("setup.status.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),jiraConfigured:a.z.boolean().default(!1),jiraEmail:a.z.string().default(""),claude:a.z.object({installed:a.z.boolean(),version:a.z.string().default(""),loggedIn:a.z.boolean()}).optional(),githubTokenSet:a.z.boolean().default(!1),githubLogin:a.z.string().default(""),deploysEnabled:a.z.boolean().default(!1),jiraUserCount:a.z.number().int().default(0),repos:a.z.array(a.z.object({repoName:a.z.string(),path:a.z.string().default(""),mapped:a.z.boolean(),liveMapped:a.z.boolean().default(!0),pathExists:a.z.boolean().default(!1),currentBranch:a.z.string().default(""),isGit:a.z.boolean().default(!1),claudeMd:a.z.boolean().default(!1),deployMd:a.z.boolean().default(!1),testMd:a.z.boolean().default(!1),defaultBranch:a.z.string().default(""),githubToken:a.z.boolean().default(!1),githubTokenOwn:a.z.boolean().default(!1)})).default([])});h.RepoUnmapMsg=a.z.object({type:a.z.literal("repo.unmap"),requestId:a.z.string(),repoName:a.z.string()});h.RepoUnmapResultMsg=a.z.object({type:a.z.literal("repo.unmap.result"),requestId:a.z.string(),ok:a.z.boolean().default(!0),error:a.z.string().default(""),removedPath:a.z.string().default("")});h.SetupRecheckMsg=a.z.object({type:a.z.literal("setup.recheck"),requestId:a.z.string(),projectId:a.z.string(),environments:a.z.array(a.z.object({name:a.z.string(),branch:a.z.string().default(""),publicUrl:a.z.string().default(""),workdir:a.z.string().default(""),servePath:a.z.string().default("")})).default([])});h.SetupRecheckResultMsg=a.z.object({type:a.z.literal("setup.recheck.result"),requestId:a.z.string(),ok:a.z.boolean().default(!0),error:a.z.string().default(""),checks:a.z.array(a.z.object({environment:a.z.string().default(""),question:a.z.string(),ok:a.z.boolean(),detail:a.z.string().default(""),blocking:a.z.boolean().default(!0)})).default([])});h.SetupClaudeMdGenerateMsg=a.z.object({type:a.z.literal("setup.claudemd.generate"),requestId:a.z.string(),projectId:a.z.string(),kind:a.z.enum(["claude","deploy","design","unblock"]).default("claude"),blockers:a.z.array(a.z.string().max(400)).max(20).default([]),machineState:a.z.array(a.z.string().max(400)).max(40).default([]),streamId:a.z.string().default(""),environments:a.z.array(a.z.object({name:a.z.string(),branch:a.z.string().default(""),publicUrl:a.z.string().default(""),workdir:a.z.string().default(""),dedicatedCheckout:a.z.boolean().default(!1),onThisRunner:a.z.boolean().default(!0)})).default([])});h.SetupClaudeMdGenerateResultMsg=a.z.object({type:a.z.literal("setup.claudemd.generate.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),content:a.z.string().default(""),truncated:a.z.boolean().default(!1)});h.SetupAskMsg=a.z.object({type:a.z.literal("setup.ask"),requestId:a.z.string(),projectId:a.z.string(),subject:a.z.string().max(600).default(""),command:a.z.string().max(2e3).default(""),machineState:a.z.array(a.z.string().max(400)).max(40).default([]),history:a.z.array(a.z.object({role:a.z.enum(["user","agent"]),text:a.z.string().max(4e3)})).max(8).default([]),question:a.z.string().max(4e3)});h.SetupAskResultMsg=a.z.object({type:a.z.literal("setup.ask.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),answer:a.z.string().default("")});h.SetupClaudeMdSaveMsg=a.z.object({type:a.z.literal("setup.claudemd.save"),requestId:a.z.string(),projectId:a.z.string(),kind:a.z.enum(["claude","deploy","design"]).default("claude"),overwrite:a.z.boolean().default(!1),content:a.z.string().max(1e5)});h.SetupClaudeMdSaveResultMsg=a.z.object({type:a.z.literal("setup.claudemd.save.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),note:a.z.string().default("")});h.RepoDocSaveMsg=a.z.object({type:a.z.literal("repo.doc.save"),requestId:a.z.string(),projectId:a.z.string(),relPath:a.z.string().min(1).max(200),overwrite:a.z.boolean().default(!1),content:a.z.string().max(2e5)});h.RepoDocSaveResultMsg=a.z.object({type:a.z.literal("repo.doc.save.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),note:a.z.string().default("")});h.RunnerUpdateMsg=a.z.object({type:a.z.literal("runner.update"),requestId:a.z.string()});h.RunnerUninstallMsg=a.z.object({type:a.z.literal("runner.uninstall"),requestId:a.z.string()});h.RunResolveConflictMsg=a.z.object({type:a.z.literal("run.resolve.conflict"),requestId:a.z.string(),runId:a.z.string()});h.RunTestFixMsg=a.z.object({type:a.z.literal("run.testfix"),requestId:a.z.string(),runId:a.z.string(),failedTests:a.z.array(h.FailedTest).min(1).max(20)});h.RunTestFixResultMsg=a.z.object({type:a.z.literal("run.testfix.result"),requestId:a.z.string(),ok:a.z.boolean(),note:a.z.string().default(""),headSha:a.z.string().default(""),remaining:a.z.array(h.FailedTest).default([]),costUsd:a.z.number().nonnegative().optional(),inputTokens:a.z.number().int().nonnegative().optional(),outputTokens:a.z.number().int().nonnegative().optional()});h.RunAnswerMsg=a.z.object({type:a.z.literal("run.answer"),requestId:a.z.string(),runId:a.z.string(),text:a.z.string().min(1).max(4e3),answeredBy:a.z.string().default("")});h.RunAnswerResultMsg=a.z.object({type:a.z.literal("run.answer.result"),requestId:a.z.string(),ok:a.z.boolean(),note:a.z.string().default(""),error:a.z.string().optional()});h.RunResolveConflictResultMsg=a.z.object({type:a.z.literal("run.resolve.conflict.result"),requestId:a.z.string(),ok:a.z.boolean(),note:a.z.string().default(""),freeOfCharge:a.z.boolean().default(!1),headSha:a.z.string().default(""),costUsd:a.z.number().nonnegative().optional(),inputTokens:a.z.number().int().nonnegative().optional(),outputTokens:a.z.number().int().nonnegative().optional()});h.RunPrConflictMsg=a.z.object({type:a.z.literal("run.pr.conflict"),runId:a.z.string(),conflicted:a.z.boolean()});h.AgentProfilesMsg=a.z.object({type:a.z.literal("agent.profiles"),requestId:a.z.string()});h.AgentProfilesResultMsg=a.z.object({type:a.z.literal("agent.profiles.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),profiles:a.z.array(a.z.object({agent:a.z.string(),name:a.z.string(),loggedIn:a.z.boolean()})).max(200).default([]),defaultLoggedIn:a.z.boolean().default(!1),agentsWithoutProfiles:a.z.array(a.z.string()).max(20).default([])});h.RunnerUpdateResultMsg=a.z.object({type:a.z.literal("runner.update.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),note:a.z.string().default(""),scheduled:a.z.boolean().default(!1)});h.RunnerUninstallResultMsg=a.z.object({type:a.z.literal("runner.uninstall.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),note:a.z.string().default(""),serviceRemoved:a.z.boolean().default(!1),configRemoved:a.z.boolean().default(!1)});h.AutopilotNextMsg=a.z.object({type:a.z.literal("autopilot.next"),requestId:a.z.string()});h.AutopilotPlanMsg=a.z.object({type:a.z.literal("autopilot.plan"),requestId:a.z.string(),projectId:a.z.string(),batchId:a.z.string(),issueKeys:a.z.array(a.z.string()).min(1).max(50)});h.AutopilotPlanResultMsg=a.z.object({type:a.z.literal("autopilot.plan.result"),requestId:a.z.string(),ok:a.z.boolean().default(!0),error:a.z.string().default(""),order:a.z.array(a.z.string()).default([]),chains:a.z.array(a.z.array(a.z.string())).default([]),dependencies:a.z.array(a.z.tuple([a.z.string(),a.z.string()])).default([]),reasoning:a.z.string().default("")});h.AutopilotNextResultMsg=a.z.object({type:a.z.literal("autopilot.next.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),item:a.z.object({id:a.z.string(),projectId:a.z.string(),issueKey:a.z.string(),ruleId:a.z.string(),baseOverride:a.z.string().default(""),branchOverride:a.z.string().default(""),continueBranch:a.z.boolean().default(!1),batchId:a.z.string().default(""),autoMerge:a.z.boolean().default(!1)}).nullable().default(null),pausedUntil:a.z.string().default("")});h.AutopilotReportMsg=a.z.object({type:a.z.literal("autopilot.report"),requestId:a.z.string(),itemId:a.z.string(),outcome:a.z.enum(["claimed","failed","paused"]),runId:a.z.string().default(""),error:a.z.string().default("")});h.RunnerToServerMsg=a.z.discriminatedUnion("type",[h.HelloMsg,h.HeartbeatMsg,h.RunClaimMsg,h.RunLogMsg,h.RunUsageMsg,h.RunStatusMsg,h.ProjectTestResultMsg,h.RuleDiagnoseResultMsg,h.DeployClaimMsg,h.DeploySuggestResultMsg,h.EnvPreflightResultMsg,h.SelfMigrationApplyResultMsg,h.ChatTurnResultMsg,h.ChatStreamMsg,h.ChatUsageMsg,h.ChatCreateTicketResultMsg,h.ChatListResultMsg,h.RepoDocsResultMsg,h.RepoDocReadResultMsg,h.ChatLoadResultMsg,h.BoardFetchResultMsg,h.BoardTriggerResultMsg,h.TeamCredsResultMsg,h.AuditStartResultMsg,h.AuditListResultMsg,h.AuditGetResultMsg,h.AuditExplainResultMsg,h.AuditReviewResultMsg,h.KnowledgeListResultMsg,h.KnowledgeSaveResultMsg,h.EpicListResultMsg,h.EpicSuggestResultMsg,h.JiraUsersResultMsg,h.SetupStatusResultMsg,h.SetupClaudeMdGenerateResultMsg,h.SetupAskResultMsg,h.SetupRecheckResultMsg,h.RepoUnmapResultMsg,h.SetupClaudeMdSaveResultMsg,h.RepoDocSaveResultMsg,h.RunnerUpdateResultMsg,h.RunnerUninstallResultMsg,h.AgentProfilesResultMsg,h.RunPrConflictMsg,h.RunResolveConflictResultMsg,h.RunTestFixResultMsg,h.RunAnswerResultMsg,h.AuditStatsResultMsg,h.AutopilotNextMsg,h.AutopilotReportMsg,h.AutopilotPlanResultMsg,h.ChatDiagnosticResultMsg]);h.HelloAckMsg=a.z.object({type:a.z.literal("hello.ack"),runnerId:a.z.string(),runnerName:a.z.string(),serverTime:a.z.string()});h.ConfigMsg=a.z.object({type:a.z.literal("config"),projects:a.z.array(h.ProjectConfig),rules:a.z.array(h.RuleConfig),environments:a.z.array(h.EnvironmentConfig).default([]),pollingPaused:a.z.boolean().default(!1),publicIp:a.z.string().default("")});h.RunClaimResultMsg=a.z.object({type:a.z.literal("run.claim.result"),requestId:a.z.string(),accepted:a.z.boolean(),runId:a.z.string().optional(),reason:a.z.string().optional(),claudeProfile:a.z.string().optional(),actorEmail:a.z.string().optional()});h.ProjectTestMsg=a.z.object({type:a.z.literal("project.test"),requestId:a.z.string(),projectId:a.z.string()});h.RuleDiagnoseMsg=a.z.object({type:a.z.literal("rule.diagnose"),requestId:a.z.string(),ruleId:a.z.string()});h.RunCancelMsg=a.z.object({type:a.z.literal("run.cancel"),runId:a.z.string()});h.RunApprovedMsg=a.z.object({type:a.z.literal("run.approved"),runId:a.z.string(),headSha:a.z.string().optional()});h.RunRejectedMsg=a.z.object({type:a.z.literal("run.rejected"),runId:a.z.string()});h.RunRetryPushMsg=a.z.object({type:a.z.literal("run.retryPush"),runId:a.z.string()});h.DeployStartMsg=a.z.object({type:a.z.literal("deploy.start"),runId:a.z.string(),projectId:a.z.string(),issueKey:a.z.string(),issueSummary:a.z.string().default(""),environment:h.EnvironmentConfig,requestedBy:a.z.string().default(""),attempt:a.z.number().int().positive().default(1)});h.DeployFixMsg=a.z.object({type:a.z.literal("deploy.fix"),requestId:a.z.string(),projectId:a.z.string(),environmentName:a.z.string(),steps:a.z.array(a.z.object({name:a.z.string(),run:a.z.string(),continueOnError:a.z.boolean().default(!1)})),failedStep:a.z.string().default(""),errorText:a.z.string().max(8e3).default("")});h.DeploySuggestMsg=a.z.object({type:a.z.literal("deploy.suggest"),requestId:a.z.string(),projectId:a.z.string(),environmentName:a.z.string(),notes:a.z.string().default(""),timeoutSeconds:a.z.number().int().positive().max(1800).default(300)});h.JiraUsersMsg=a.z.object({type:a.z.literal("jira.users"),requestId:a.z.string(),query:a.z.string().default("")});h.ServerToRunnerMsg=a.z.discriminatedUnion("type",[h.HelloAckMsg,h.ConfigMsg,h.RunClaimResultMsg,h.ProjectTestMsg,h.RuleDiagnoseMsg,h.RunCancelMsg,h.RunApprovedMsg,h.RunRejectedMsg,h.RunRetryPushMsg,h.DeployClaimResultMsg,h.DeployStartMsg,h.DeploySuggestMsg,h.DeployFixMsg,h.EnvPreflightMsg,h.SelfMigrationApplyMsg,h.ChatTurnMsg,h.ChatCreateTicketMsg,h.ChatListMsg,h.RepoDocsMsg,h.RepoDocReadMsg,h.ChatLoadMsg,h.BoardFetchMsg,h.BoardTriggerMsg,h.TeamCredsMsg,h.AuditStartMsg,h.AuditListMsg,h.AuditGetMsg,h.AuditExplainMsg,h.ChatCancelMsg,h.ChatDiagnosticMsg,h.AuditReviewMsg,h.KnowledgeListMsg,h.KnowledgeSaveMsg,h.EpicListMsg,h.EpicSuggestMsg,h.JiraUsersMsg,h.SetupStatusMsg,h.SetupClaudeMdGenerateMsg,h.SetupAskMsg,h.SetupRecheckMsg,h.RepoUnmapMsg,h.SetupClaudeMdSaveMsg,h.RepoDocSaveMsg,h.RunnerUpdateMsg,h.RunnerUninstallMsg,h.AgentProfilesMsg,h.RunResolveConflictMsg,h.RunTestFixMsg,h.RunAnswerMsg,h.AuditStatsMsg,h.AutopilotNextResultMsg,h.AutopilotPlanMsg]);h.EnrollRequest=a.z.object({enrollToken:a.z.string().min(10),name:a.z.string().min(1).max(100),platform:a.z.string(),runnerVersion:a.z.string()});h.EnrollResponse=a.z.object({runnerId:a.z.string(),runnerToken:a.z.string(),controlPlaneWsUrl:a.z.string()});function kb(t){return h.RunnerToServerMsg.parse(t)}function _b(t){return h.ServerToRunnerMsg.parse(t)}h.DEFAULT_PLAN_PROMPT_TEMPLATE=`You are a senior engineer asked to assess a Jira ticket. You have read-only access to the repository - do not attempt to modify anything.
|
|
47
|
+
The dashboard turns that into a Deploy button for the user - subject to their own permissions, which you cannot see; never promise the deploy will be allowed. Offer it only when a deploy is genuinely the fix, never as a routine suggestion, and never name an environment that is not in the list. Never mention the block itself in your prose.`}p.ChatLoadResultMsg=a.z.object({type:a.z.literal("chat.load.result"),requestId:a.z.string(),ok:a.z.boolean(),projectId:a.z.string().default(""),messages:a.z.array(a.z.object({role:a.z.enum(["user","agent"]),text:a.z.string(),steps:a.z.array(a.z.string()).default([]),files:a.z.array(a.z.string()).default([]),at:a.z.string().default(""),ms:a.z.number().int().nonnegative().default(0)})).default([]),error:a.z.string().optional()});p.RepoDocsMsg=a.z.object({type:a.z.literal("repo.docs"),requestId:a.z.string(),projectId:a.z.string()});p.RepoDocsResultMsg=a.z.object({type:a.z.literal("repo.docs.result"),requestId:a.z.string(),ok:a.z.boolean(),docs:a.z.array(a.z.object({path:a.z.string(),sizeBytes:a.z.number().int().nonnegative().default(0),updatedAt:a.z.string().default("")})).default([]),error:a.z.string().optional()});p.RepoDocReadMsg=a.z.object({type:a.z.literal("repo.doc.read"),requestId:a.z.string(),projectId:a.z.string(),path:a.z.string().max(400)});p.RepoDocReadResultMsg=a.z.object({type:a.z.literal("repo.doc.read.result"),requestId:a.z.string(),ok:a.z.boolean(),path:a.z.string().default(""),content:a.z.string().default(""),truncated:a.z.boolean().default(!1),error:a.z.string().optional()});p.BoardFetchMsg=a.z.object({type:a.z.literal("board.fetch"),requestId:a.z.string(),projectId:a.z.string()});p.BoardFetchResultMsg=a.z.object({type:a.z.literal("board.fetch.result"),requestId:a.z.string(),ok:a.z.boolean(),browseBaseUrl:a.z.string().default(""),columns:a.z.array(a.z.object({name:a.z.string(),issues:a.z.array(a.z.object({key:a.z.string(),summary:a.z.string(),labels:a.z.array(a.z.string()).default([])})).default([])})).default([]),error:a.z.string().optional()});p.BoardTriggerMsg=a.z.object({type:a.z.literal("board.trigger"),requestId:a.z.string(),projectId:a.z.string(),issueKey:a.z.string(),comment:a.z.string().max(2e3).default(""),removeLabel:a.z.string().default(""),requestedBy:a.z.string().default(""),requestedByEmail:a.z.string().default(""),reimplement:a.z.boolean().default(!1)});p.BoardTriggerResultMsg=a.z.object({type:a.z.literal("board.trigger.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional()});p.EpicListMsg=a.z.object({type:a.z.literal("epic.list"),requestId:a.z.string(),projectId:a.z.string(),epicKey:a.z.string().default("")});p.EpicChild=a.z.object({key:a.z.string(),summary:a.z.string(),status:a.z.string(),statusCategory:a.z.string(),labels:a.z.array(a.z.string()).default([])});p.EpicListResultMsg=a.z.object({type:a.z.literal("epic.list.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),epics:a.z.array(a.z.object({key:a.z.string(),summary:a.z.string(),status:a.z.string()})).default([]),children:a.z.array(p.EpicChild).default([])});p.EpicSuggestMsg=a.z.object({type:a.z.literal("epic.suggest"),requestId:a.z.string(),projectId:a.z.string(),epicKey:a.z.string().min(1),model:a.z.string().default("")});p.EpicSuggestResultMsg=a.z.object({type:a.z.literal("epic.suggest.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),issueKey:a.z.string().default(""),reason:a.z.string().default(""),considered:a.z.number().int().default(0)});p.AuditRole=a.z.enum(["security","testing","architecture","functional"]);p.KnowledgeRole=a.z.enum(["security","testing","architecture","functional","implement"]);p.AuditSeverity=a.z.enum(["critical","high","medium","low","info"]);p.AuditScope=a.z.object({kind:a.z.enum(["repo","ticket","branch"]).default("repo"),ref:a.z.string().default("")});p.AuditDetailLevel=a.z.enum(["simple","technical"]);p.AuditFinding=a.z.object({id:a.z.string().min(1),title:a.z.string().min(1),ruleId:a.z.string().max(20).default(""),severity:p.AuditSeverity,area:a.z.string().default(""),evidence:a.z.array(a.z.object({file:a.z.string().min(1),line:a.z.number().int().positive().optional(),note:a.z.string().default("")})).min(1),fix:a.z.string().default("")});p.AuditRecord=a.z.object({id:a.z.string(),role:p.AuditRole,createdAt:a.z.string(),model:a.z.string().default(""),summary:a.z.string().default(""),packNames:a.z.array(a.z.string()).default([]),findings:a.z.array(p.AuditFinding).default([]),costUsd:a.z.number().default(0),review:a.z.object({selected:a.z.array(a.z.string()),updatedAt:a.z.string()}).optional(),verdicts:a.z.record(a.z.object({verdict:a.z.enum(["valid","false-positive","wont-fix"]),note:a.z.string().default(""),by:a.z.string().default(""),at:a.z.string().default("")})).default({}),lessonsWritten:a.z.array(a.z.string()).default([]),ticketed:a.z.record(a.z.string()).default({}),scope:p.AuditScope.default({kind:"repo",ref:""}),detailLevel:p.AuditDetailLevel.default("technical"),testRun:a.z.array(a.z.object({command:a.z.string(),exitCode:a.z.number().int(),durationMs:a.z.number().int().default(0),tail:a.z.string().default("")})).optional()});p.AuditStartMsg=a.z.object({type:a.z.literal("audit.start"),requestId:a.z.string(),projectId:a.z.string(),role:p.AuditRole,model:a.z.string().default(""),scope:p.AuditScope.default({kind:"repo",ref:""}),detailLevel:p.AuditDetailLevel.default("technical"),baseUrl:a.z.string().default("")});p.AuditStartResultMsg=a.z.object({type:a.z.literal("audit.start.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),audit:p.AuditRecord.optional()});p.AuditListMsg=a.z.object({type:a.z.literal("audit.list"),requestId:a.z.string(),projectId:a.z.string()});p.AuditStatsMsg=a.z.object({type:a.z.literal("audit.stats"),requestId:a.z.string(),projectIds:a.z.array(a.z.string()).max(200).default([]),since:a.z.string().default("")});p.AuditStatsResultMsg=a.z.object({type:a.z.literal("audit.stats.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),byProject:a.z.record(a.z.object({audits:a.z.number().int().default(0),findings:a.z.number().int().default(0),valid:a.z.number().int().default(0),falsePositive:a.z.number().int().default(0),wontFix:a.z.number().int().default(0),unreviewed:a.z.number().int().default(0)})).default({})});p.AuditListResultMsg=a.z.object({type:a.z.literal("audit.list.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),audits:a.z.array(a.z.object({id:a.z.string(),role:p.AuditRole,createdAt:a.z.string(),findingCount:a.z.number().int(),bySeverity:a.z.record(a.z.number().int()).default({}),detailLevel:p.AuditDetailLevel.default("technical")})).default([])});p.ChatDiagnosticMsg=a.z.object({type:a.z.literal("chat.diagnostic"),requestId:a.z.string(),projectId:a.z.string(),command:a.z.string().max(40),args:a.z.record(a.z.unknown()).default({})});p.ChatDiagnosticResultMsg=a.z.object({type:a.z.literal("chat.diagnostic.result"),requestId:a.z.string(),ok:a.z.boolean().default(!0),commandLine:a.z.string().default(""),output:a.z.string().default("")});p.ChatCancelMsg=a.z.object({type:a.z.literal("chat.cancel"),requestId:a.z.string(),turnId:a.z.string()});p.AuditExplainMsg=a.z.object({type:a.z.literal("audit.explain"),requestId:a.z.string(),projectId:a.z.string(),auditId:a.z.string(),findingId:a.z.string()});p.AuditExplainResultMsg=a.z.object({type:a.z.literal("audit.explain.result"),requestId:a.z.string(),ok:a.z.boolean().default(!0),error:a.z.string().default(""),explanation:a.z.string().default("")});p.AuditGetMsg=a.z.object({type:a.z.literal("audit.get"),requestId:a.z.string(),projectId:a.z.string(),auditId:a.z.string()});p.AuditGetResultMsg=a.z.object({type:a.z.literal("audit.get.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),audit:p.AuditRecord.optional()});p.AuditReviewMsg=a.z.object({type:a.z.literal("audit.review"),requestId:a.z.string(),projectId:a.z.string(),auditId:a.z.string(),selected:a.z.array(a.z.string()).optional(),ticketed:a.z.array(a.z.object({findingId:a.z.string(),issueKey:a.z.string()})).default([]),verdicts:a.z.array(a.z.object({findingId:a.z.string(),verdict:a.z.enum(["valid","false-positive","wont-fix"]),note:a.z.string().max(2e3).default("")})).default([]),verdictBy:a.z.string().default("")});p.AuditReviewResultMsg=a.z.object({type:a.z.literal("audit.review.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),audit:p.AuditRecord.optional()});p.KnowledgeListMsg=a.z.object({type:a.z.literal("knowledge.list"),requestId:a.z.string(),projectId:a.z.string()});p.KnowledgeFile=a.z.object({role:p.KnowledgeRole,level:a.z.enum(["global","org","project"]),source:a.z.enum(["pack","lessons","memory"]),name:a.z.string(),content:a.z.string(),editable:a.z.boolean().default(!1)});p.KnowledgeListResultMsg=a.z.object({type:a.z.literal("knowledge.list.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),files:a.z.array(p.KnowledgeFile).default([])});p.KnowledgeSaveMsg=a.z.object({type:a.z.literal("knowledge.save"),requestId:a.z.string(),projectId:a.z.string(),role:p.KnowledgeRole,level:a.z.enum(["org","project"]),source:a.z.enum(["pack","lessons"]),name:a.z.string().min(1).max(100),content:a.z.string().max(6e4),append:a.z.boolean().default(!1),by:a.z.string().default("")});p.KnowledgeSaveResultMsg=a.z.object({type:a.z.literal("knowledge.save.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional()});p.TeamCredsMsg=a.z.object({type:a.z.literal("team.creds"),requestId:a.z.string(),emails:a.z.array(a.z.string()).max(200)});p.TeamCredsResultMsg=a.z.object({type:a.z.literal("team.creds.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),githubShared:a.z.boolean().default(!1),sharedGithubLogin:a.z.string().default(""),entries:a.z.array(a.z.object({email:a.z.string(),jira:a.z.enum(["own","runner-account","missing"]),jiraAs:a.z.string().default(""),github:a.z.enum(["own","shared","missing"]),githubAs:a.z.string().default("")})).default([])});p.ChatFile=a.z.object({name:a.z.string().min(1).max(255),contentBase64:a.z.string().min(1).max(6e6)});p.ChatTurnMsg=a.z.object({type:a.z.literal("chat.turn"),requestId:a.z.string(),projectId:a.z.string(),sessionId:a.z.string().optional(),message:a.z.string().min(1).max(2e4),userName:a.z.string().default(""),model:a.z.string().default(""),files:a.z.array(p.ChatFile).max(8).default([]),replyLanguage:a.z.string().max(60).default(""),replyLanguageInstruction:a.z.string().max(600).default(""),replyStyle:a.z.string().max(30).default(""),pendingMigrations:a.z.array(a.z.string().max(200)).max(50).default([]),environments:a.z.array(a.z.string().max(60)).max(20).default([])});p.ChatTurnResultMsg=a.z.object({type:a.z.literal("chat.turn.result"),requestId:a.z.string(),ok:a.z.boolean(),sessionId:a.z.string().default(""),reply:a.z.string().default(""),error:a.z.string().optional(),inputTokens:a.z.number().int().nonnegative().default(0),outputTokens:a.z.number().int().nonnegative().default(0),cacheReadTokens:a.z.number().int().nonnegative().default(0),costUsd:a.z.number().nonnegative().default(0),model:a.z.string().max(200).default(""),contextTokens:a.z.number().int().nonnegative().default(0),contextLimit:a.z.number().int().nonnegative().default(0),compacted:a.z.boolean().default(!1),compactedMessages:a.z.number().int().nonnegative().default(0)});p.ChatCreateTicketMsg=a.z.object({type:a.z.literal("chat.create.ticket"),requestId:a.z.string(),projectId:a.z.string(),summary:a.z.string().min(1).max(250),description:a.z.string().default(""),triggerComment:a.z.string().default(""),requestedBy:a.z.string().default(""),requestedByEmail:a.z.string().default(""),asEpic:a.z.boolean().default(!1),children:a.z.array(a.z.object({summary:a.z.string().min(1),description:a.z.string().default("")})).max(20).default([]),createAs:a.z.enum(["epic_with_children","separate_epics","separate_tasks"]).default("epic_with_children"),files:a.z.array(p.ChatFile).max(8).default([])});p.ChatCreateTicketResultMsg=a.z.object({type:a.z.literal("chat.create.ticket.result"),requestId:a.z.string(),ok:a.z.boolean(),issueKey:a.z.string().default(""),error:a.z.string().optional(),childKeys:a.z.array(a.z.string()).default([])});p.EnvPreflightMsg=a.z.object({type:a.z.literal("env.preflight"),requestId:a.z.string(),projectId:a.z.string(),environmentName:a.z.string().default(""),steps:a.z.array(p.DeployStep).default([]),requiredSecrets:a.z.array(a.z.string()).default([]),workdir:a.z.string().default(""),branch:a.z.string().default(""),publicUrl:a.z.string().default("")});p.EnvPreflightResultMsg=a.z.object({type:a.z.literal("env.preflight.result"),requestId:a.z.string(),ok:a.z.boolean(),checks:a.z.array(a.z.object({name:a.z.string(),ok:a.z.boolean(),detail:a.z.string().default(""),kind:a.z.enum(["connection","content"]).default("connection"),fix:a.z.array(a.z.string()).default([]),fixNote:a.z.string().default("")})).default([])});p.SELF_MIGRATION_DIR="apps/api/prisma/manual";function Eb(t){return/^[A-Za-z0-9][A-Za-z0-9._-]*\.sql$/.test(t)&&!t.includes("..")}p.SelfMigrationApplyMsg=a.z.object({type:a.z.literal("selfmigration.apply"),requestId:a.z.string(),projectId:a.z.string(),environmentName:a.z.string().default(""),file:a.z.string(),urlSecret:a.z.string().default("DATABASE_URL")});p.SelfMigrationApplyResultMsg=a.z.object({type:a.z.literal("selfmigration.apply.result"),requestId:a.z.string(),ok:a.z.boolean(),file:a.z.string().default(""),checks:a.z.array(a.z.object({name:a.z.string(),ok:a.z.boolean(),detail:a.z.string().default(""),fix:a.z.array(a.z.string()).default([])})).default([]),output:a.z.string().max(2e4).default(""),error:a.z.string().default("")});p.DeploySuggestResultMsg=a.z.object({type:a.z.literal("deploy.suggest.result"),requestId:a.z.string(),ok:a.z.boolean(),steps:a.z.array(p.DeployStep).default([]),requiredSecrets:a.z.array(a.z.string()).default([]),notes:a.z.string().default(""),error:a.z.string().optional(),docPath:a.z.string().default(""),docContent:a.z.string().max(1e5).default("")});p.SetupStatusMsg=a.z.object({type:a.z.literal("setup.status"),requestId:a.z.string(),repoNames:a.z.array(a.z.string()).max(100).default([])});p.SetupStatusResultMsg=a.z.object({type:a.z.literal("setup.status.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),jiraConfigured:a.z.boolean().default(!1),jiraEmail:a.z.string().default(""),claude:a.z.object({installed:a.z.boolean(),version:a.z.string().default(""),loggedIn:a.z.boolean()}).optional(),githubTokenSet:a.z.boolean().default(!1),githubLogin:a.z.string().default(""),deploysEnabled:a.z.boolean().default(!1),jiraUserCount:a.z.number().int().default(0),repos:a.z.array(a.z.object({repoName:a.z.string(),path:a.z.string().default(""),mapped:a.z.boolean(),liveMapped:a.z.boolean().default(!0),pathExists:a.z.boolean().default(!1),currentBranch:a.z.string().default(""),isGit:a.z.boolean().default(!1),claudeMd:a.z.boolean().default(!1),deployMd:a.z.boolean().default(!1),testMd:a.z.boolean().default(!1),defaultBranch:a.z.string().default(""),githubToken:a.z.boolean().default(!1),githubTokenOwn:a.z.boolean().default(!1)})).default([])});p.RepoUnmapMsg=a.z.object({type:a.z.literal("repo.unmap"),requestId:a.z.string(),repoName:a.z.string()});p.RepoUnmapResultMsg=a.z.object({type:a.z.literal("repo.unmap.result"),requestId:a.z.string(),ok:a.z.boolean().default(!0),error:a.z.string().default(""),removedPath:a.z.string().default("")});p.SetupRecheckMsg=a.z.object({type:a.z.literal("setup.recheck"),requestId:a.z.string(),projectId:a.z.string(),environments:a.z.array(a.z.object({name:a.z.string(),branch:a.z.string().default(""),publicUrl:a.z.string().default(""),workdir:a.z.string().default(""),servePath:a.z.string().default("")})).default([])});p.SetupRecheckResultMsg=a.z.object({type:a.z.literal("setup.recheck.result"),requestId:a.z.string(),ok:a.z.boolean().default(!0),error:a.z.string().default(""),checks:a.z.array(a.z.object({environment:a.z.string().default(""),question:a.z.string(),ok:a.z.boolean(),detail:a.z.string().default(""),blocking:a.z.boolean().default(!0)})).default([])});p.SetupClaudeMdGenerateMsg=a.z.object({type:a.z.literal("setup.claudemd.generate"),requestId:a.z.string(),projectId:a.z.string(),kind:a.z.enum(["claude","deploy","design","unblock"]).default("claude"),blockers:a.z.array(a.z.string().max(400)).max(20).default([]),machineState:a.z.array(a.z.string().max(400)).max(40).default([]),streamId:a.z.string().default(""),environments:a.z.array(a.z.object({name:a.z.string(),branch:a.z.string().default(""),publicUrl:a.z.string().default(""),workdir:a.z.string().default(""),dedicatedCheckout:a.z.boolean().default(!1),onThisRunner:a.z.boolean().default(!0)})).default([])});p.SetupClaudeMdGenerateResultMsg=a.z.object({type:a.z.literal("setup.claudemd.generate.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),content:a.z.string().default(""),truncated:a.z.boolean().default(!1)});p.SetupAskMsg=a.z.object({type:a.z.literal("setup.ask"),requestId:a.z.string(),projectId:a.z.string(),subject:a.z.string().max(600).default(""),command:a.z.string().max(2e3).default(""),machineState:a.z.array(a.z.string().max(400)).max(40).default([]),history:a.z.array(a.z.object({role:a.z.enum(["user","agent"]),text:a.z.string().max(4e3)})).max(8).default([]),question:a.z.string().max(4e3)});p.SetupAskResultMsg=a.z.object({type:a.z.literal("setup.ask.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),answer:a.z.string().default("")});p.SetupClaudeMdSaveMsg=a.z.object({type:a.z.literal("setup.claudemd.save"),requestId:a.z.string(),projectId:a.z.string(),kind:a.z.enum(["claude","deploy","design"]).default("claude"),overwrite:a.z.boolean().default(!1),content:a.z.string().max(1e5)});p.SetupClaudeMdSaveResultMsg=a.z.object({type:a.z.literal("setup.claudemd.save.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),note:a.z.string().default("")});p.RepoDocSaveMsg=a.z.object({type:a.z.literal("repo.doc.save"),requestId:a.z.string(),projectId:a.z.string(),relPath:a.z.string().min(1).max(200),overwrite:a.z.boolean().default(!1),content:a.z.string().max(2e5)});p.RepoDocSaveResultMsg=a.z.object({type:a.z.literal("repo.doc.save.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),note:a.z.string().default("")});p.RunnerUpdateMsg=a.z.object({type:a.z.literal("runner.update"),requestId:a.z.string()});p.RunnerUninstallMsg=a.z.object({type:a.z.literal("runner.uninstall"),requestId:a.z.string()});p.RunResolveConflictMsg=a.z.object({type:a.z.literal("run.resolve.conflict"),requestId:a.z.string(),runId:a.z.string()});p.RunTestFixMsg=a.z.object({type:a.z.literal("run.testfix"),requestId:a.z.string(),runId:a.z.string(),failedTests:a.z.array(p.FailedTest).min(1).max(20)});p.RunTestFixResultMsg=a.z.object({type:a.z.literal("run.testfix.result"),requestId:a.z.string(),ok:a.z.boolean(),note:a.z.string().default(""),headSha:a.z.string().default(""),remaining:a.z.array(p.FailedTest).default([]),costUsd:a.z.number().nonnegative().optional(),inputTokens:a.z.number().int().nonnegative().optional(),outputTokens:a.z.number().int().nonnegative().optional()});p.RunAnswerMsg=a.z.object({type:a.z.literal("run.answer"),requestId:a.z.string(),runId:a.z.string(),text:a.z.string().min(1).max(4e3),answeredBy:a.z.string().default("")});p.RunAnswerResultMsg=a.z.object({type:a.z.literal("run.answer.result"),requestId:a.z.string(),ok:a.z.boolean(),note:a.z.string().default(""),error:a.z.string().optional()});p.RunResolveConflictResultMsg=a.z.object({type:a.z.literal("run.resolve.conflict.result"),requestId:a.z.string(),ok:a.z.boolean(),note:a.z.string().default(""),freeOfCharge:a.z.boolean().default(!1),headSha:a.z.string().default(""),costUsd:a.z.number().nonnegative().optional(),inputTokens:a.z.number().int().nonnegative().optional(),outputTokens:a.z.number().int().nonnegative().optional()});p.RunPrConflictMsg=a.z.object({type:a.z.literal("run.pr.conflict"),runId:a.z.string(),conflicted:a.z.boolean()});p.AgentProfilesMsg=a.z.object({type:a.z.literal("agent.profiles"),requestId:a.z.string()});p.AgentProfilesResultMsg=a.z.object({type:a.z.literal("agent.profiles.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),profiles:a.z.array(a.z.object({agent:a.z.string(),name:a.z.string(),loggedIn:a.z.boolean()})).max(200).default([]),defaultLoggedIn:a.z.boolean().default(!1),agentsWithoutProfiles:a.z.array(a.z.string()).max(20).default([])});p.RunnerUpdateResultMsg=a.z.object({type:a.z.literal("runner.update.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),note:a.z.string().default(""),scheduled:a.z.boolean().default(!1)});p.RunnerUninstallResultMsg=a.z.object({type:a.z.literal("runner.uninstall.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),note:a.z.string().default(""),serviceRemoved:a.z.boolean().default(!1),configRemoved:a.z.boolean().default(!1)});p.AutopilotNextMsg=a.z.object({type:a.z.literal("autopilot.next"),requestId:a.z.string()});p.AutopilotPlanMsg=a.z.object({type:a.z.literal("autopilot.plan"),requestId:a.z.string(),projectId:a.z.string(),batchId:a.z.string(),issueKeys:a.z.array(a.z.string()).min(1).max(50)});p.AutopilotPlanResultMsg=a.z.object({type:a.z.literal("autopilot.plan.result"),requestId:a.z.string(),ok:a.z.boolean().default(!0),error:a.z.string().default(""),order:a.z.array(a.z.string()).default([]),chains:a.z.array(a.z.array(a.z.string())).default([]),dependencies:a.z.array(a.z.tuple([a.z.string(),a.z.string()])).default([]),reasoning:a.z.string().default("")});p.AutopilotNextResultMsg=a.z.object({type:a.z.literal("autopilot.next.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),item:a.z.object({id:a.z.string(),projectId:a.z.string(),issueKey:a.z.string(),ruleId:a.z.string(),baseOverride:a.z.string().default(""),branchOverride:a.z.string().default(""),continueBranch:a.z.boolean().default(!1),batchId:a.z.string().default(""),autoMerge:a.z.boolean().default(!1)}).nullable().default(null),pausedUntil:a.z.string().default("")});p.AutopilotReportMsg=a.z.object({type:a.z.literal("autopilot.report"),requestId:a.z.string(),itemId:a.z.string(),outcome:a.z.enum(["claimed","failed","paused"]),runId:a.z.string().default(""),error:a.z.string().default("")});p.RunnerToServerMsg=a.z.discriminatedUnion("type",[p.HelloMsg,p.HeartbeatMsg,p.RunClaimMsg,p.RunLogMsg,p.RunUsageMsg,p.RunStatusMsg,p.ProjectTestResultMsg,p.RuleDiagnoseResultMsg,p.DeployClaimMsg,p.DeploySuggestResultMsg,p.EnvPreflightResultMsg,p.SelfMigrationApplyResultMsg,p.ChatTurnResultMsg,p.ChatStreamMsg,p.ChatUsageMsg,p.ChatCreateTicketResultMsg,p.ChatListResultMsg,p.RepoDocsResultMsg,p.RepoDocReadResultMsg,p.ChatLoadResultMsg,p.BoardFetchResultMsg,p.BoardTriggerResultMsg,p.TeamCredsResultMsg,p.AuditStartResultMsg,p.AuditListResultMsg,p.AuditGetResultMsg,p.AuditExplainResultMsg,p.AuditReviewResultMsg,p.KnowledgeListResultMsg,p.KnowledgeSaveResultMsg,p.EpicListResultMsg,p.EpicSuggestResultMsg,p.JiraUsersResultMsg,p.SetupStatusResultMsg,p.SetupClaudeMdGenerateResultMsg,p.SetupAskResultMsg,p.SetupRecheckResultMsg,p.RepoUnmapResultMsg,p.SetupClaudeMdSaveResultMsg,p.RepoDocSaveResultMsg,p.RunnerUpdateResultMsg,p.RunnerUninstallResultMsg,p.AgentProfilesResultMsg,p.RunPrConflictMsg,p.RunResolveConflictResultMsg,p.RunTestFixResultMsg,p.RunAnswerResultMsg,p.AuditStatsResultMsg,p.AutopilotNextMsg,p.AutopilotReportMsg,p.AutopilotPlanResultMsg,p.ChatDiagnosticResultMsg]);p.HelloAckMsg=a.z.object({type:a.z.literal("hello.ack"),runnerId:a.z.string(),runnerName:a.z.string(),serverTime:a.z.string()});p.ConfigMsg=a.z.object({type:a.z.literal("config"),projects:a.z.array(p.ProjectConfig),rules:a.z.array(p.RuleConfig),environments:a.z.array(p.EnvironmentConfig).default([]),pollingPaused:a.z.boolean().default(!1),publicIp:a.z.string().default("")});p.RunClaimResultMsg=a.z.object({type:a.z.literal("run.claim.result"),requestId:a.z.string(),accepted:a.z.boolean(),runId:a.z.string().optional(),reason:a.z.string().optional(),claudeProfile:a.z.string().optional(),actorEmail:a.z.string().optional()});p.ProjectTestMsg=a.z.object({type:a.z.literal("project.test"),requestId:a.z.string(),projectId:a.z.string()});p.RuleDiagnoseMsg=a.z.object({type:a.z.literal("rule.diagnose"),requestId:a.z.string(),ruleId:a.z.string()});p.RunCancelMsg=a.z.object({type:a.z.literal("run.cancel"),runId:a.z.string()});p.RunApprovedMsg=a.z.object({type:a.z.literal("run.approved"),runId:a.z.string(),headSha:a.z.string().optional()});p.RunRejectedMsg=a.z.object({type:a.z.literal("run.rejected"),runId:a.z.string()});p.RunRetryPushMsg=a.z.object({type:a.z.literal("run.retryPush"),runId:a.z.string()});p.DeployStartMsg=a.z.object({type:a.z.literal("deploy.start"),runId:a.z.string(),projectId:a.z.string(),issueKey:a.z.string(),issueSummary:a.z.string().default(""),environment:p.EnvironmentConfig,requestedBy:a.z.string().default(""),attempt:a.z.number().int().positive().default(1)});p.DeployFixMsg=a.z.object({type:a.z.literal("deploy.fix"),requestId:a.z.string(),projectId:a.z.string(),environmentName:a.z.string(),steps:a.z.array(a.z.object({name:a.z.string(),run:a.z.string(),continueOnError:a.z.boolean().default(!1)})),failedStep:a.z.string().default(""),errorText:a.z.string().max(8e3).default("")});p.DeploySuggestMsg=a.z.object({type:a.z.literal("deploy.suggest"),requestId:a.z.string(),projectId:a.z.string(),environmentName:a.z.string(),notes:a.z.string().default(""),timeoutSeconds:a.z.number().int().positive().max(1800).default(300)});p.JiraUsersMsg=a.z.object({type:a.z.literal("jira.users"),requestId:a.z.string(),query:a.z.string().default("")});p.ServerToRunnerMsg=a.z.discriminatedUnion("type",[p.HelloAckMsg,p.ConfigMsg,p.RunClaimResultMsg,p.ProjectTestMsg,p.RuleDiagnoseMsg,p.RunCancelMsg,p.RunApprovedMsg,p.RunRejectedMsg,p.RunRetryPushMsg,p.DeployClaimResultMsg,p.DeployStartMsg,p.DeploySuggestMsg,p.DeployFixMsg,p.EnvPreflightMsg,p.SelfMigrationApplyMsg,p.ChatTurnMsg,p.ChatCreateTicketMsg,p.ChatListMsg,p.RepoDocsMsg,p.RepoDocReadMsg,p.ChatLoadMsg,p.BoardFetchMsg,p.BoardTriggerMsg,p.TeamCredsMsg,p.AuditStartMsg,p.AuditListMsg,p.AuditGetMsg,p.AuditExplainMsg,p.ChatCancelMsg,p.ChatDiagnosticMsg,p.AuditReviewMsg,p.KnowledgeListMsg,p.KnowledgeSaveMsg,p.EpicListMsg,p.EpicSuggestMsg,p.JiraUsersMsg,p.SetupStatusMsg,p.SetupClaudeMdGenerateMsg,p.SetupAskMsg,p.SetupRecheckMsg,p.RepoUnmapMsg,p.SetupClaudeMdSaveMsg,p.RepoDocSaveMsg,p.RunnerUpdateMsg,p.RunnerUninstallMsg,p.AgentProfilesMsg,p.RunResolveConflictMsg,p.RunTestFixMsg,p.RunAnswerMsg,p.AuditStatsMsg,p.AutopilotNextResultMsg,p.AutopilotPlanMsg]);p.EnrollRequest=a.z.object({enrollToken:a.z.string().min(10),name:a.z.string().min(1).max(100),platform:a.z.string(),runnerVersion:a.z.string()});p.EnrollResponse=a.z.object({runnerId:a.z.string(),runnerToken:a.z.string(),controlPlaneWsUrl:a.z.string()});function Cb(t){return p.RunnerToServerMsg.parse(t)}function $b(t){return p.ServerToRunnerMsg.parse(t)}p.DEFAULT_PLAN_PROMPT_TEMPLATE=`You are a senior engineer asked to assess a Jira ticket. You have read-only access to the repository - do not attempt to modify anything.
|
|
48
48
|
|
|
49
49
|
Ticket {{issueKey}}: {{summary}}
|
|
50
50
|
|
|
@@ -65,21 +65,21 @@ YOUR ANSWER WILL BE POSTED AS A JIRA COMMENT, AND THE PERSON READING IT IS USUAL
|
|
|
65
65
|
- Do not describe your exploration process or list implementation steps - the developer doing the work will figure those out from the code.
|
|
66
66
|
|
|
67
67
|
IF THE TICKET IS TOO AMBIGUOUS to assess honestly - you cannot tell what is being asked, or two reasonable readings lead to very different work - do NOT guess. Instead make your ENTIRE final message start with the line:
|
|
68
|
-
${
|
|
69
|
-
followed by at most 3 numbered questions, in the same plain language, that the ticket author can answer without reading code. They will be posted as a comment on the ticket, and you will be resumed - with this exact conversation, not a fresh one - as soon as someone replies. Minor ambiguity is NOT a reason to ask - prefer a stated assumption; ask only when you are truly blocked.`;
|
|
68
|
+
${p.NEEDS_INPUT_MARKER}
|
|
69
|
+
followed by at most 3 numbered questions, in the same plain language, that the ticket author can answer without reading code. They will be posted as a comment on the ticket, and you will be resumed - with this exact conversation, not a fresh one - as soon as someone replies. Minor ambiguity is NOT a reason to ask - prefer a stated assumption; ask only when you are truly blocked.`;p.NEEDS_INPUT_OPTIONS_PROMPT=`
|
|
70
70
|
|
|
71
|
-
IF YOU ASK (the ${
|
|
72
|
-
\`\`\`${
|
|
71
|
+
IF YOU ASK (the ${p.NEEDS_INPUT_MARKER} case above) and the sensible answers are countable, you may END your message - after the questions - with this block:
|
|
72
|
+
\`\`\`${p.NEEDS_INPUT_ASK_FENCE}
|
|
73
73
|
{"options": ["\u2026", "\u2026"]}
|
|
74
74
|
\`\`\`
|
|
75
|
-
2 to 5 options, each a complete answer the person could have typed, shortest first. They become one-click buttons on the run page, and the person can always write something else instead. Never mention the block in your prose, and skip it entirely when the answer is genuinely open-ended - a wrong guess costs more than no guess.`;
|
|
75
|
+
2 to 5 options, each a complete answer the person could have typed, shortest first. They become one-click buttons on the run page, and the person can always write something else instead. Never mention the block in your prose, and skip it entirely when the answer is genuinely open-ended - a wrong guess costs more than no guess.`;p.FOCUSED_READING_PROMPT=`
|
|
76
76
|
|
|
77
77
|
READ WITH INTENT - tokens are the customer's money:
|
|
78
78
|
- When the ticket names files or paths, open those FIRST; sweep the wider tree only when they fall short.
|
|
79
79
|
- When a DOCUMENT INDEX section is present below, use it: Read a long document's relevant section with offset/limit instead of the whole file.
|
|
80
|
-
- CLAUDE.md has already told you where things live - trust it before running discovery searches.`;
|
|
80
|
+
- CLAUDE.md has already told you where things live - trust it before running discovery searches.`;p.WRITE_TESTS_PROMPT=`
|
|
81
81
|
|
|
82
|
-
TESTS: add or update tests for what you changed, following whatever this repository already uses - same framework, same layout, same naming. Cover the behaviour the ticket describes and the edge cases you had to think about while implementing it. If the repo has no test setup at all, say so in your summary instead of inventing one.`;
|
|
82
|
+
TESTS: add or update tests for what you changed, following whatever this repository already uses - same framework, same layout, same naming. Cover the behaviour the ticket describes and the edge cases you had to think about while implementing it. If the repo has no test setup at all, say so in your summary instead of inventing one.`;p.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.
|
|
83
83
|
|
|
84
84
|
Ticket {{issueKey}}: {{summary}}
|
|
85
85
|
|
|
@@ -96,7 +96,7 @@ Explore the repository, then implement the change.
|
|
|
96
96
|
DELETING FILES: you cannot delete a file directly. If the ticket requires removing files, create a file named .ticketpilot-delete at the repository root containing one repo-relative path per line - those files are deleted automatically just before your work is committed (CI/workflow paths are refused, and the manifest itself is never committed). Mention the deletions in your summary.
|
|
97
97
|
|
|
98
98
|
BEFORE editing anything: if the ticket is too ambiguous to implement - you cannot tell what is being asked, or two reasonable readings lead to very different code - do NOT guess and do NOT edit any file. Instead make your ENTIRE final message start with the line:
|
|
99
|
-
${
|
|
99
|
+
${p.NEEDS_INPUT_MARKER}
|
|
100
100
|
followed by at most 3 numbered questions in plain, non-technical language that the ticket author can answer without reading code. They will be posted as a comment on the ticket, and you will be resumed - with this exact conversation, not a fresh one - as soon as someone replies. Minor ambiguity is NOT a reason to ask - prefer a stated assumption; ask only when you are truly blocked.
|
|
101
101
|
|
|
102
102
|
When you are done, END your final message with a section titled "## Summary of changes" describing:
|
|
@@ -104,9 +104,9 @@ When you are done, END your final message with a section titled "## Summary of c
|
|
|
104
104
|
2. Anything you could NOT verify because you cannot run tests or commands.
|
|
105
105
|
3. Anything ambiguous in the ticket and the assumption you made.
|
|
106
106
|
|
|
107
|
-
That summary will become the pull request description a human reviews - write it for them.`;
|
|
107
|
+
That summary will become the pull request description a human reviews - write it for them.`;p.MEMORY_UPDATE_PROMPT=`
|
|
108
108
|
|
|
109
|
-
ALSO: after the implementation is complete, update the CLAUDE.md file at the repository root (create it if it does not exist). Record only durable knowledge about this codebase that would help someone working on a FUTURE ticket: where key modules live, non-obvious conventions, tricky couplings, gotchas you hit while working. Keep it short and general - do NOT log what this ticket changed, and do not repeat what the file already says. If nothing durable was learned, leave the file unchanged.`;
|
|
109
|
+
ALSO: after the implementation is complete, update the CLAUDE.md file at the repository root (create it if it does not exist). Record only durable knowledge about this codebase that would help someone working on a FUTURE ticket: where key modules live, non-obvious conventions, tricky couplings, gotchas you hit while working. Keep it short and general - do NOT log what this ticket changed, and do not repeat what the file already says. If nothing durable was learned, leave the file unchanged.`;p.TECHNICAL_PLAN_PROMPT_TEMPLATE=`You are a senior engineer asked to produce an implementation plan for a Jira ticket. You have read-only access to the repository - do not attempt to modify anything.
|
|
110
110
|
|
|
111
111
|
Ticket {{issueKey}}: {{summary}}
|
|
112
112
|
|
|
@@ -128,8 +128,8 @@ Explore the repository as needed, then write a concise implementation plan with:
|
|
|
128
128
|
Write the plan in Markdown. It will be posted as a comment on the ticket for a developer to review - be specific to THIS codebase, not generic.
|
|
129
129
|
|
|
130
130
|
IF THE TICKET IS TOO AMBIGUOUS to plan honestly, do NOT guess. Instead make your ENTIRE final message start with the line:
|
|
131
|
-
${
|
|
132
|
-
followed by at most 3 numbered questions the ticket author can answer. They will be posted as a comment on the ticket, and you will be resumed - with this exact conversation, not a fresh one - as soon as someone replies. Minor ambiguity is NOT a reason to ask - prefer a stated assumption; ask only when you are truly blocked.`;
|
|
131
|
+
${p.NEEDS_INPUT_MARKER}
|
|
132
|
+
followed by at most 3 numbered questions the ticket author can answer. They will be posted as a comment on the ticket, and you will be resumed - with this exact conversation, not a fresh one - as soon as someone replies. Minor ambiguity is NOT a reason to ask - prefer a stated assumption; ask only when you are truly blocked.`;p.BUG_INVESTIGATION_PROMPT_TEMPLATE=`You are a senior engineer investigating a bug reported in a Jira ticket. You have read-only access to the repository - do not attempt to modify anything.
|
|
133
133
|
|
|
134
134
|
Ticket {{issueKey}}: {{summary}}
|
|
135
135
|
|
|
@@ -150,8 +150,8 @@ Trace the reported behavior through the code, then write, in Markdown:
|
|
|
150
150
|
The reader is a developer. Do not pad - a short, confident answer beats a long, hedged one.
|
|
151
151
|
|
|
152
152
|
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:
|
|
153
|
-
${
|
|
154
|
-
followed by at most 3 numbered questions (steps to reproduce, expected vs actual behavior). They will be posted on the ticket, and you will be resumed - with this exact conversation, not a fresh one - as soon as someone replies.`;
|
|
153
|
+
${p.NEEDS_INPUT_MARKER}
|
|
154
|
+
followed by at most 3 numbered questions (steps to reproduce, expected vs actual behavior). They will be posted on the ticket, and you will be resumed - with this exact conversation, not a fresh one - as soon as someone replies.`;p.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.
|
|
155
155
|
|
|
156
156
|
Ticket {{issueKey}}: {{summary}}
|
|
157
157
|
|
|
@@ -168,7 +168,7 @@ Find the root cause, then make the SMALLEST change that fixes it. Do not refacto
|
|
|
168
168
|
DELETING FILES: you cannot delete a file directly. If the fix requires removing a file, create a file named .ticketpilot-delete at the repository root containing one repo-relative path per line - those files are deleted automatically just before your work is committed (CI/workflow paths are refused, and the manifest itself is never committed). Mention the deletions in your summary.
|
|
169
169
|
|
|
170
170
|
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:
|
|
171
|
-
${
|
|
171
|
+
${p.NEEDS_INPUT_MARKER}
|
|
172
172
|
followed by at most 3 numbered questions (steps to reproduce, expected vs actual behavior). They will be posted on the ticket, and you will be resumed - with this exact conversation, not a fresh one - as soon as someone replies.
|
|
173
173
|
|
|
174
174
|
When you are done, END your final message with a section titled "## Summary of changes" describing:
|
|
@@ -176,7 +176,7 @@ When you are done, END your final message with a section titled "## Summary of c
|
|
|
176
176
|
2. The fix, file by file.
|
|
177
177
|
3. Regression risk, and what you could not verify (you cannot run tests).
|
|
178
178
|
|
|
179
|
-
That summary will become the pull request description a human reviews - write it for them.`;
|
|
179
|
+
That summary will become the pull request description a human reviews - write it for them.`;p.DEFAULT_RESPOND_PROMPT_TEMPLATE=`You are the engineering assistant for this repository, answering a question asked in a Jira ticket comment. You have read-only access to the code - explore it as needed to answer accurately.
|
|
180
180
|
|
|
181
181
|
Ticket {{issueKey}}: {{summary}}
|
|
182
182
|
|
|
@@ -191,7 +191,7 @@ The comments are in chronological order and may supersede the description: when
|
|
|
191
191
|
The question you are answering, asked by {{questionAuthor}}:
|
|
192
192
|
{{question}}
|
|
193
193
|
|
|
194
|
-
Write your answer as a Jira comment addressed to {{questionAuthor}}. Match their technical level - if they sound non-technical, answer in plain language with no jargon or code. Be direct, and only as long as the answer needs. If the code contradicts an assumption in the question, say so plainly. If you cannot answer from the ticket and the code alone, say exactly what information you would need - your reply IS the conversation, so just ask.`;
|
|
194
|
+
Write your answer as a Jira comment addressed to {{questionAuthor}}. Match their technical level - if they sound non-technical, answer in plain language with no jargon or code. Be direct, and only as long as the answer needs. If the code contradicts an assumption in the question, say so plainly. If you cannot answer from the ticket and the code alone, say exactly what information you would need - your reply IS the conversation, so just ask.`;p.PROMPT_PRESETS=[{id:"plan-simple",name:"Simple plan - plain language",action:"plan_only",whenToUse:"Default. The Jira comment is read by non-technical people: short, no jargon, describes the work in product terms.",template:p.DEFAULT_PLAN_PROMPT_TEMPLATE},{id:"plan-technical",name:"Technical plan - for developers",action:"plan_only",whenToUse:"The readers are developers: files to change, ordered steps, risks, and a size estimate.",template:p.TECHNICAL_PLAN_PROMPT_TEMPLATE},{id:"plan-bug",name:"Bug investigation",action:"plan_only",whenToUse:"The ticket reports a bug: trace the root cause in the code and propose the fix - without changing anything.",template:p.BUG_INVESTIGATION_PROMPT_TEMPLATE},{id:"impl-standard",name:"Standard implement",action:"implement",whenToUse:"Default. Careful, minimal implementation that follows the existing code style.",template:p.DEFAULT_IMPLEMENT_PROMPT_TEMPLATE},{id:"impl-bugfix",name:"Bug fix - smallest change",action:"implement",whenToUse:"The ticket is a bug: find the root cause and make the smallest possible fix, nothing else.",template:p.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:p.DEFAULT_RESPOND_PROMPT_TEMPLATE}];p.DEPLOY_FIX_PROMPT_TEMPLATE=`You are a release engineer investigating a FAILED deploy of "{{envName}}". You have read-only access to the repository. The runner has already gathered hard facts about the machine - trust them over guesses.
|
|
195
195
|
|
|
196
196
|
THE SAVED STEPS (these ran, in order):
|
|
197
197
|
{{steps}}
|
|
@@ -235,7 +235,7 @@ One sentence per changed step: what changes and why that fixes the cause above.
|
|
|
235
235
|
|
|
236
236
|
Then the COMPLETE corrected step list (every step, changed or not, same order) as a \`\`\`json block: an array of {"name": "...", "run": "...", "continueOnError": false}. Rules: when CAUSE TYPE is CODE or MACHINE, return the steps EXACTLY as they are - byte for byte - and put what the human must fix in DIAGNOSIS; otherwise change as little as possible; never delete a safety step; if the cause lives outside the steps (uncommitted work, a missing secret, a broken service), say so in DIAGNOSIS and return the steps UNCHANGED rather than inventing a workaround. NEVER propose a change that would break the RUNNING service: when the machine facts show the app's runtime differs from the runner's (different node/python versions), pin the app's own runtime by ABSOLUTE PATH in the steps - do not rebuild or reinstall the app's dependencies for the runner's runtime, which "fixes" the deploy while poisoning the app it deploys.
|
|
237
237
|
|
|
238
|
-
Finally: the deploy DOCUMENT is the answer key future suggestions are generated from. If the commands it describes are what produced the broken steps, the fix is incomplete until the document tells the new truth. In that case add, after the json block, the COMPLETE corrected document as a \`\`\`markdown block - the whole file, not a diff, changing only what the fix requires. If the document is already right, add no markdown block.`;
|
|
238
|
+
Finally: the deploy DOCUMENT is the answer key future suggestions are generated from. If the commands it describes are what produced the broken steps, the fix is incomplete until the document tells the new truth. In that case add, after the json block, the COMPLETE corrected document as a \`\`\`markdown block - the whole file, not a diff, changing only what the fix requires. If the document is already right, add no markdown block.`;p.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE=`You are a release engineer. This repository ships a deploy document written by its operators - it is the ground truth for how "{{envName}}" is deployed. Your ONLY job is to translate that document into executable steps.
|
|
239
239
|
|
|
240
240
|
The document ({{docPath}}):
|
|
241
241
|
---
|
|
@@ -275,7 +275,7 @@ Rules for the steps:
|
|
|
275
275
|
- If the build writes into the same directory the running process serves from, put the build and the restart next to each other and say why in "notes": between them, the old process is serving files that no longer exist. Never emit a step whose description promises the running site is untouched when the build has already overwritten its artifacts.
|
|
276
276
|
- Health checks must fail CLOSED: assert the good state, not the absence of one known error string. A check that greps for one specific failure message passes for every other kind of failure.
|
|
277
277
|
- Anchor checks to something stable - a health/version endpoint, an id, a data- attribute - not to page copy. A headline edit must not turn a healthy deploy red.
|
|
278
|
-
- If the document's own unresolved items make a real deploy impossible (no restart mechanism, no supervisor, a required secret with no home), return an EMPTY steps array and name the blocker in "notes". Half a recipe that stops before the restart leaves the old build serving while everything reports success.`;
|
|
278
|
+
- If the document's own unresolved items make a real deploy impossible (no restart mechanism, no supervisor, a required secret with no home), return an EMPTY steps array and name the blocker in "notes". Half a recipe that stops before the restart leaves the old build serving while everything reports success.`;p.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.
|
|
279
279
|
|
|
280
280
|
What the operator told us about this environment:
|
|
281
281
|
{{notes}}
|
|
@@ -304,50 +304,50 @@ Rules for the steps:
|
|
|
304
304
|
- "requiredSecrets" is ONLY for values that must come from OUTSIDE - a token, a host, a key someone has to supply. A variable a step assigns itself (PRE=$(cat ...), POST=$(systemctl show ...)) is ordinary shell plumbing: never list it. Listing one makes every deploy refuse to start and demand a value that exists nowhere.
|
|
305
305
|
- Prefer commands that are safe to re-run; a deploy may be retried.
|
|
306
306
|
- Order matters: install, build, test (if cheap), then release.
|
|
307
|
-
- If you genuinely cannot tell how this repo is deployed, return an empty "steps" array and explain what is missing in "notes".`});var
|
|
308
|
-
`).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#"));for(let i of s.slice(0,200)){if(pe.default.isAbsolute(i)){e.refused.push(`${i} - absolute paths are not allowed`);continue}let o=pe.default.resolve(r,i);if(o!==r&&!o.startsWith(r+pe.default.sep)){e.refused.push(`${i} - escapes the worktree`);continue}let l=pe.default.relative(r,o).split(pe.default.sep).join("/");if(l===Jt)continue;if(
|
|
307
|
+
- If you genuinely cannot tell how this repo is deployed, return an empty "steps" array and explain what is missing in "notes".`});var ad={};un(ad,{DELETE_MANIFEST_FILE:()=>Jt,MAX_CHANGED_FILES:()=>_n,MAX_CHANGED_LINES:()=>Sn,abortMerge:()=>Rn,applyDeleteManifest:()=>us,branchForIssue:()=>Ha,branchSha:()=>Ji,branchesDiffer:()=>Xa,checkDiffSafety:()=>xn,checkoutBranchInWorktree:()=>Ka,commitAll:()=>br,commitMergeResolution:()=>Va,deleteStaleBranch:()=>qa,diffAgainstDefault:()=>Yi,envCheckoutPath:()=>od,envCheckoutsRoot:()=>id,fetchBase:()=>Tn,findConflictMarkers:()=>Xi,headSha:()=>Ze,mergeBaseIntoWorktree:()=>Wa,mergeTicketBranch:()=>Za,originUrl:()=>vr,parseOwnerRepo:()=>wt,prepareEnvCheckout:()=>Ga,pruneWorktrees:()=>Ba,pushBranch:()=>wr,pushEnvBranch:()=>Ya,pushWipBranch:()=>La,removeWorktree:()=>Et,resetHard:()=>ds,statusSnapshot:()=>Ua,unresolvedAmong:()=>Ja,worktreeAdd:()=>Fa,worktreeAddExisting:()=>Ks,worktreeFingerprint:()=>Vi,worktreesRoot:()=>Yt});async function K(t,e,n={}){try{let{stdout:r}=await rd("git",["-C",t,...e],{timeout:n.timeoutMs??12e4,maxBuffer:16777216,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});return r}catch(r){let s=r;throw new Error(`git ${e[0]} failed: ${(s.stderr||s.message||"").trim().slice(0,500)}`)}}async function us(t){let e={deleted:[],refused:[]},n=pe.default.join(t,Jt);if(!Te.default.existsSync(n))return e;let r=pe.default.resolve(t),s=Te.default.readFileSync(n,"utf8").split(`
|
|
308
|
+
`).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#"));for(let i of s.slice(0,200)){if(pe.default.isAbsolute(i)){e.refused.push(`${i} - absolute paths are not allowed`);continue}let o=pe.default.resolve(r,i);if(o!==r&&!o.startsWith(r+pe.default.sep)){e.refused.push(`${i} - escapes the worktree`);continue}let l=pe.default.relative(r,o).split(pe.default.sep).join("/");if(l===Jt)continue;if(sd.some(u=>u.test(l))){e.refused.push(`${i} - protected path (CI/hook files are never touched)`);continue}let c;try{c=Te.default.lstatSync(o)}catch{e.refused.push(`${i} - no such file`);continue}if(c.isDirectory()){e.refused.push(`${i} - is a directory (list the files inside it instead)`);continue}try{Te.default.rmSync(o),e.deleted.push(l)}catch(u){e.refused.push(`${i} - ${u instanceof Error?u.message:"delete failed"}`)}}return Te.default.rmSync(n,{force:!0}),e}async function La(t,e){await K(t,["push","--force","origin",`HEAD:refs/heads/${e}`],{timeoutMs:3e5})}async function Vi(t){let e=await K(t,["status","--porcelain"]),n=await K(t,["diff","--numstat"]),r=e.split(`
|
|
309
309
|
`).filter(s=>s.startsWith("??")).map(s=>s.slice(3).trim()).slice(0,500).map(s=>{try{let i=Te.default.statSync(pe.default.join(t,s));return`${s}:${i.size}:${i.mtimeMs}`}catch{return s}}).join(`
|
|
310
310
|
`);return`${e}
|
|
311
311
|
--
|
|
312
312
|
${n}
|
|
313
313
|
--
|
|
314
|
-
${r}`}async function
|
|
314
|
+
${r}`}async function Ua(t){let e=(await K(t,["rev-parse","--abbrev-ref","HEAD"])).trim(),n=(await K(t,["log","--oneline","-1"])).trim(),r=(await K(t,["status","--porcelain"])).trim(),s=r?r.split(`
|
|
315
315
|
`):[],i=s.slice(0,15).join(`
|
|
316
316
|
`),o=s.length>15?`
|
|
317
317
|
(\u2026 ${s.length-15} more)`:"";return`branch ${e} @ ${n}
|
|
318
318
|
working tree: ${s.length?`
|
|
319
|
-
${i}${o}`:"clean"}`}function Yt(){let t=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(Te.default.existsSync(pe.default.join(yr.default.homedir(),".cache","ticketpilot"))?pe.default.join(yr.default.homedir(),".cache","ticketpilot"):pe.default.join(yr.default.homedir(),".cache","allwright"));return pe.default.join(t,"worktrees")}async function Tn(t,e){try{await
|
|
320
|
-
`))i.startsWith("worktree ")&&(s=i.slice(9).trim()),i===`branch refs/heads/${e}`&&s&&s.startsWith(r)&&await
|
|
321
|
-
`).filter(Boolean),s=r.filter(u=>
|
|
322
|
-
`).map(s=>s.trim()).filter(s=>s&&!s.includes("->"))[0]??null}async function
|
|
323
|
-
`).filter(Boolean);return s.length?{ok:!1,conflicts:s}:(await
|
|
324
|
-
`).filter(Boolean))e.add(s)}catch{}let n=[];try{n=(await
|
|
325
|
-
`).filter(Boolean).filter(s=>!e.has(s))}catch{}for(let r of n)try{let s=await
|
|
319
|
+
${i}${o}`:"clean"}`}function Yt(){let t=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(Te.default.existsSync(pe.default.join(yr.default.homedir(),".cache","ticketpilot"))?pe.default.join(yr.default.homedir(),".cache","ticketpilot"):pe.default.join(yr.default.homedir(),".cache","allwright"));return pe.default.join(t,"worktrees")}async function Tn(t,e){try{await K(t,["fetch","origin",e])}catch(n){throw new Error(`could not fetch base branch "${e}" from origin - check the rule's base branch and that this machine can reach the remote (${n instanceof Error?n.message:n})`)}}async function qa(t,e){try{let n=await K(t,["worktree","list","--porcelain"]),r=Yt(),s=null;for(let i of n.split(`
|
|
320
|
+
`))i.startsWith("worktree ")&&(s=i.slice(9).trim()),i===`branch refs/heads/${e}`&&s&&s.startsWith(r)&&await K(t,["worktree","remove","--force",s]);await K(t,["worktree","prune"])}catch{}try{await K(t,["branch","-D",e])}catch{}}async function Fa(t,e,n,r){Te.default.mkdirSync(pe.default.dirname(e),{recursive:!0,mode:448}),await K(t,["worktree","add","-b",n,e,`origin/${r}`])}async function br(t,e){if(await K(t,["add","-A"]),!(await K(t,["status","--porcelain"])).trim())throw new Error("Claude wrote no changes - nothing to commit");await K(t,["-c",`user.name=${Zi}`,"-c",`user.email=${Wi}`,"commit","-m",e])}async function xn(t,e){let r=(await K(t,["diff","--name-only",`origin/${e}...HEAD`])).split(`
|
|
321
|
+
`).filter(Boolean),s=r.filter(u=>sd.some(h=>h.test(u))),i=await K(t,["diff","--shortstat",`origin/${e}...HEAD`]),o=Number(/(\d+) insertion/.exec(i)?.[1]??0),l=Number(/(\d+) deletion/.exec(i)?.[1]??0);return{ok:s.length===0&&r.length<=_n&&o+l<=Sn,files:r.length,insertions:o,deletions:l,forbidden:s}}async function wr(t,e){await K(t,["fetch","--prune","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],{timeoutMs:12e4}).catch(()=>K(t,["update-ref","-d",`refs/remotes/origin/${e}`]).catch(()=>{})),await K(t,["push","--force-with-lease","-u","origin",e],{timeoutMs:3e5})}async function Ze(t){return(await K(t,["rev-parse","HEAD"])).trim()}async function Ji(t,e){try{return(await K(t,["rev-parse","--verify",`refs/heads/${e}`])).trim()}catch{return null}}async function ds(t,e){await K(t,["reset","--hard",e])}async function Et(t,e){try{await K(t,["worktree","remove","--force",e])}catch{Te.default.rmSync(e,{recursive:!0,force:!0})}}async function Ba(t,e=[]){let n=new Set(e.map(s=>pe.default.basename(pe.default.resolve(s))).filter(s=>s.length>0)),r=Yt();if(Te.default.existsSync(r))for(let s of Te.default.readdirSync(r))n.has(s)||Te.default.rmSync(pe.default.join(r,s),{recursive:!0,force:!0});for(let s of t)try{await K(s,["worktree","prune"])}catch{}}async function Ha(t,e){return await K(t,["fetch","origin","--prune"]).catch(()=>{}),(await K(t,["branch","-r","--list",`*${e}*`])).split(`
|
|
322
|
+
`).map(s=>s.trim()).filter(s=>s&&!s.includes("->"))[0]??null}async function Yi(t,e,n=6e4){let s=(await K(t,["symbolic-ref","refs/remotes/origin/HEAD"]).catch(()=>"")).trim().replace("refs/remotes/","")||"origin/main",i=await K(t,["diff","--stat",`${s}...${e}`]),o=await K(t,["diff",`${s}...${e}`]);return{base:s,stat:i.slice(0,4e3),diff:o.slice(0,n)}}function id(){let t=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(Te.default.existsSync(pe.default.join(yr.default.homedir(),".cache","ticketpilot"))?pe.default.join(yr.default.homedir(),".cache","ticketpilot"):pe.default.join(yr.default.homedir(),".cache","allwright"));return pe.default.join(t,"env-checkouts")}function ed(t){return t.replace(/[^\w.-]+/g,"_")}async function Ka(t,e,n){await K(t,["fetch","origin"],{timeoutMs:3e5}),await K(t,["reset","--hard"]),await K(t,["checkout","-B",e,n])}function od(t,e){return pe.default.join(id(),ed(t),ed(e))}async function Ga(t){let e=od(t.repoName,t.envName);return await K(t.repoPath,["fetch","origin",t.branch],{timeoutMs:3e5}),Te.default.existsSync(pe.default.join(e,".git"))?await K(e,["fetch","origin",t.branch],{timeoutMs:3e5}):(Te.default.rmSync(e,{recursive:!0,force:!0}),Te.default.mkdirSync(pe.default.dirname(e),{recursive:!0,mode:448}),await K(t.repoPath,["worktree","prune"]).catch(()=>{}),await K(t.repoPath,["worktree","add","--detach",e,`origin/${t.branch}`])),t.attached?await K(e,["checkout","-B",t.branch,`origin/${t.branch}`]):await K(e,["checkout","--force","--detach",`origin/${t.branch}`]),e}async function Za(t,e,n){try{await K(t,["fetch","origin",e],{timeoutMs:3e5})}catch{return{ok:!1,reason:`branch "${e}" does not exist on origin - nothing to promote. Check the environment's ticket branch template against the branch your implement rule creates.`}}try{return await K(t,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyMerged:!0}}catch{}try{return await K(t,["-c",`user.name=${Zi}`,"-c",`user.email=${Wi}`,"merge","--no-ff","-m",n,`origin/${e}`]),{ok:!0}}catch(r){return await K(t,["merge","--abort"]).catch(()=>{}),{ok:!1,reason:`could not merge "${e}" into the environment branch - ${r instanceof Error?r.message:r}. Resolve it manually and deploy again.`}}}async function Wa(t,e){await K(t,["fetch","origin",e],{timeoutMs:3e5});try{return await K(t,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyUpToDate:!0}}catch{}try{return await K(t,["-c",`user.name=${Zi}`,"-c",`user.email=${Wi}`,"merge","--no-edit",`origin/${e}`]),{ok:!0,alreadyUpToDate:!1}}catch(n){let s=(await K(t,["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
|
|
323
|
+
`).filter(Boolean);return s.length?{ok:!1,conflicts:s}:(await K(t,["merge","--abort"]).catch(()=>{}),{ok:!1,conflicts:null,reason:n instanceof Error?n.message.slice(0,300):String(n)})}}async function Rn(t){await K(t,["merge","--abort"]).catch(()=>{})}async function Va(t,e){await K(t,["add","-A"]),await K(t,["-c",`user.name=${Zi}`,"-c",`user.email=${Wi}`,"commit","--no-edit","-m",e])}async function Ja(t,e){let n=new Set(await Xi(t));return e.filter(r=>n.has(r))}async function Xi(t){let e=new Set;try{let r=await K(t,["grep","-l","-I","-E","^(<{7}|>{7})( |$)"]);for(let s of r.split(`
|
|
324
|
+
`).filter(Boolean))e.add(s)}catch{}let n=[];try{n=(await K(t,["grep","-l","-I","-E","^={7}$"])).split(`
|
|
325
|
+
`).filter(Boolean).filter(s=>!e.has(s))}catch{}for(let r of n)try{let s=await K(t,["show",`HEAD:${r}`]);/^={7}$/m.test(s)||e.add(r)}catch{e.add(r)}return[...e]}async function Ks(t,e,n){Te.default.mkdirSync(pe.default.dirname(e),{recursive:!0,mode:448}),await K(t,["fetch","origin",n],{timeoutMs:3e5}),await K(t,["worktree","add","--detach",e,`origin/${n}`]),await K(e,["checkout","-B",n,`origin/${n}`])}async function Ya(t,e){try{await K(t,["push","origin",e],{timeoutMs:3e5})}catch(n){throw new Error(`could not push "${e}" - ${n instanceof Error?n.message:n}. Someone may have pushed to it since this deploy started; retry.`)}}async function Xa(t,e,n){try{return await rd("git",["-C",t,"diff","--quiet",e,n,"--"],{timeout:12e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),!1}catch(r){let s=r;if(s.code===1)return!0;throw new Error(`git diff failed comparing ${e}..${n}: ${(s.stderr||s.message||"").trim().slice(0,500)}`)}}async function vr(t){return(await K(t,["config","--get","remote.origin.url"])).trim()}function wt(t){let e=/^git@github\.com(?:-[\w.-]+)?:([^/]+)\/(.+?)(\.git)?$/.exec(t)??/^https:\/\/github\.com\/([^/]+)\/(.+?)(\.git)?\/?$/.exec(t)??/^ssh:\/\/git@github\.com(?:-[\w.-]+)?\/([^/]+)\/(.+?)(\.git)?$/.exec(t);return e?{owner:e[1],repo:e[2]}:null}var Te,yr,pe,td,nd,rd,Zi,Wi,_n,Sn,sd,Jt,Ct=be(()=>{"use strict";Te=I(require("node:fs"),1),yr=I(require("node:os"),1),pe=I(require("node:path"),1),td=require("node:child_process"),nd=require("node:util"),rd=(0,nd.promisify)(td.execFile),Zi="Allwright Agent",Wi="agent@ticketpilot.local",_n=200,Sn=2e4,sd=[/^\.github\/workflows\//,/^\.git\b/,/(^|\/)\.githooks\//];Jt=".ticketpilot-delete"});function Qi(t,e,n){let r=(n??"").trim().toLowerCase(),s=r?t.githubUsers[r]?.token:void 0;if(s)return{token:s,source:"user"};let i=t.repos[e]?.github?.token;return i?{token:i,source:"repo"}:t.github?.token?{token:t.github.token,source:"global"}:null}function je(t,e){return t.repos[e]?.github?.token??t.github?.token??null}function pd(t,e){let n=[t.jira,...Object.values(t.repos).map(l=>l.jira)].filter(l=>!!l),r=new Set(n.map(l=>l.email.toLowerCase())),s=!!t.github?.token||Object.values(t.repos).some(l=>l.github?.token),i=t.github?.login??Object.values(t.repos).find(l=>l.github?.login)?.github?.login??"",o=e.map(l=>{let c=l.trim().toLowerCase(),u=t.jiraUsers[c]?"own":r.has(c)?"runner-account":"missing",h=u==="own"?t.jiraUsers[c].email:u==="runner-account"?c:"",f=t.githubUsers[c]?"own":s?"shared":"missing",b=f==="own"?t.githubUsers[c].login??"":f==="shared"?i:"";return{email:c,jira:u,jiraAs:h,github:f,githubAs:b}});return{githubShared:s,sharedGithubLogin:i,entries:o}}var kr=be(()=>{"use strict"});var gl,y,Xt=be(()=>{"use strict";gl=()=>new Date().toISOString(),y={info:t=>console.log(`${gl()} [info] ${t}`),warn:t=>console.warn(`${gl()} [warn] ${t}`),error:t=>console.error(`${gl()} [error] ${t}`)}});var Vd={};un(Vd,{crawlSite:()=>nw,extractLinks:()=>Zd,formatCrawlReport:()=>rw,pageIssues:()=>Wd});function Zd(t,e,n){let r=new Set;for(let s of t.matchAll(/href\s*=\s*["']([^"']+)["']/gi)){let i=s[1].trim();if(!(!i||i.startsWith("#")||i.startsWith("mailto:")||i.startsWith("tel:")||i.startsWith("javascript:")))try{let o=new URL(i,e);if(o.hash="",o.origin!==n||/\.(png|jpe?g|gif|svg|webp|ico|css|js|mjs|woff2?|ttf|pdf|zip|mp4|webm)$/i.test(o.pathname))continue;r.add(o.toString())}catch{}}return[...r]}function Wd(t){let e=[],{html:n}=t;return t.status>=400&&e.push(`returns HTTP ${t.status}`),t.status===200&&((/<title[^>]*>([\s\S]*?)<\/title>/i.exec(n)?.[1]?.trim()??"")||e.push("no <title>"),/<h1[\s>]/i.test(n)||e.push("no <h1>"),t.url.startsWith("https:")&&/(?:src|href)\s*=\s*["']http:\/\//i.test(n)&&e.push("loads http:// resources from an https page (mixed content - browsers block these)"),/<a\s[^>]*href\s*=\s*["']\s*["']/i.test(n)&&e.push("has links with an empty href")),t.ms>5e3&&e.push(`took ${(t.ms/1e3).toFixed(1)}s to respond`),e}async function nw(t){let e=new URL(t),n=e.origin,r=Date.now(),s={baseUrl:e.toString(),pages:[],notes:[]},i=new Map,o=[e.toString()],l=new Set(o),c=new Map,u=async b=>{let w=Date.now();try{let _=await fetch(b,{redirect:"follow",signal:AbortSignal.timeout(15e3),headers:{"user-agent":"Allwright-functional-audit (reads pages, changes nothing)"}}),S=await _.arrayBuffer(),A=S.byteLength,z=new TextDecoder().decode(S.slice(0,3e6));return{status:_.status,html:z,ms:Date.now()-w,bytes:A}}catch{return{status:0,html:"",ms:Date.now()-w,bytes:0}}};for(;o.length&&s.pages.length<30&&Date.now()-r<12e4;){let b=o.shift(),{status:w,html:_,ms:S,bytes:A}=await u(b),z=/<title[^>]*>([\s\S]*?)<\/title>/i.exec(_)?.[1]?.trim()??"",q=Wd({status:w,html:_,url:b,ms:S});if(w===0&&q.push("did not respond at all (timeout or connection failure)"),s.pages.push({url:b,status:w,ms:S,bytes:A,title:z,linkedFrom:[...i.get(b)??[]].slice(0,3),issues:q}),z&&c.set(z,[...c.get(z)??[],b]),w===200&&_)for(let v of Zd(_,b,n))i.has(v)||i.set(v,new Set),i.get(v).add(b),l.has(v)||(l.add(v),o.push(v))}let h=[...c.entries()].filter(([,b])=>b.length>1);for(let[b,w]of h.slice(0,5))s.notes.push(`${w.length} pages share the title "${b.slice(0,60)}" (${w.slice(0,3).join(", ")})`);return(await u(new URL("/allwright-crawl-probe-404",n).toString())).status===200&&s.notes.push("an unknown path returns HTTP 200 - a catch-all is answering everything, so broken links on this site LOOK fine to a crawler and to search engines"),o.length&&s.notes.push(`stopped at ${s.pages.length} pages (cap) - ${o.length} discovered links not visited`),s.notes.push("crawled without JavaScript: what curl sees. Client-side rendering, broken interactivity and console errors are NOT covered by this evidence - do not claim they were checked."),s}function rw(t){let e=t.pages.map(n=>{let r=n.issues.length?` !! ${n.issues.join("; ")}`:"",s=n.linkedFrom.length?` (linked from ${n.linkedFrom.join(", ")})`:"";return`${n.status} ${n.ms}ms ${Math.round(n.bytes/1024)}KB ${n.url}${s}${r}`}).join(`
|
|
326
326
|
`);return`CRAWL OF THE RUNNING SITE (${t.baseUrl}) - gathered by the runner just now, GET only, same-origin only:
|
|
327
327
|
${e}
|
|
328
328
|
|
|
329
329
|
SITE-WIDE:
|
|
330
330
|
${t.notes.map(n=>`- ${n}`).join(`
|
|
331
|
-
`)}`}var
|
|
332
|
-
`).filter(f=>/reverse_proxy|proxy_pass|root\s+\*?\s*\//i.test(f)).map(f=>f.trim()).slice(0,8);i.push(`${o} mentions ${u}`+(
|
|
333
|
-
`).map(n=>n.split(/\s+/)[1]??"").map(n=>n.replace(/^refs\/heads\//,"")).filter(Boolean)}:
|
|
334
|
-
`).find(c=>c.trim())??r??"git failed with no output",o=n?`sudo -u ${n} `:"",l=`Verify it non-interactively (a plain ls-remote would just prompt you and pass): GIT_TERMINAL_PROMPT=0 GIT_ASKPASS=true git -C ${e} ls-remote --heads origin`;return/not a git repository/i.test(s)?{ok:!1,reason:"not-a-checkout",detail:`${e} is not a git checkout`,fix:`Clone the repository into ${e} first.`}:/No such remote|does not appear to be a git repository|'origin' does not appear/i.test(s)&&!/authenticat/i.test(s)?{ok:!1,reason:"no-remote",detail:`this checkout has no usable "origin" remote - ${i}`,fix:`Add it: ${o}git -C ${e} remote add origin <url>`}:/could not read (Username|Password)|terminal prompts disabled|Authentication failed|Invalid username or password|Permission denied \(publickey\)|Support for password authentication was removed|Repository not found|access rights|Host key verification failed/i.test(s)?{ok:!1,reason:"auth",detail:`cannot read origin: git has no usable credential${n?` for ${n}`:""} on this machine - ${i}. The branch may well exist; this machine simply cannot ask.`,fix:`Give ${n??"the user the deploy runs as"} a saved credential: ${o}git config --global credential.helper store, then ${o}git -C ${e} fetch origin once and paste a GitHub PAT as the password (an account password is refused). ${l}`}:/Could not resolve host|Connection (timed out|refused)|Network is unreachable|unable to access|Operation timed out/i.test(s)||r?{ok:!1,reason:"network",detail:`origin could not be reached from this machine - ${i}. This is DNS or a firewall, not a missing branch.`,fix:`Check outbound network from this machine, then re-run. ${l}`}:{ok:!1,reason:"unknown",detail:`origin could not be read - ${i}`,fix:`Run it by hand on this machine to see the whole error: ${o}git -C ${e} ls-remote --heads origin`}}function
|
|
331
|
+
`)}`}var Jd=be(()=>{"use strict"});var Tr={};un(Tr,{GitHubClient:()=>Me});var gw,Me,kt=be(()=>{"use strict";gw=process.env.TICKETPILOT_GITHUB_API??"https://api.github.com",Me=class{constructor(e){this.token=e}token;async request(e,n,r){let s=await fetch(`${gw}${n}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"allwright",...r!==void 0?{"Content-Type":"application/json"}:{}},body:r===void 0?void 0:JSON.stringify(r)}),i=await s.text(),o=null;try{o=i?JSON.parse(i):null}catch{}if(s.status===401)throw new Error("GitHub rejected the token (401) - expired or revoked? Run `allwright github set-token`");if(!s.ok&&s.status!==422){let l=o?.message??i.slice(0,300);throw new Error(`GitHub ${e} ${n} -> ${s.status}: ${l}`)}return{status:s.status,data:o}}async whoami(){let{data:e}=await this.request("GET","/user");return e.login}async createPullRequest(e,n,r){let{status:s,data:i}=await this.request("POST",`/repos/${e}/${n}/pulls`,r);if(s===422){let{data:o}=await this.request("GET",`/repos/${e}/${n}/pulls?head=${encodeURIComponent(`${e}:${r.head}`)}&state=open`);if(o?.length){let l=o[0];return{number:l.number,url:l.html_url,state:l.state,merged:l.merged??!1,headSha:l.head.sha,mergeableState:null,baseRef:l.base?.ref??""}}throw new Error(`GitHub refused the PR (422): ${i?.message??"validation failed"}`)}return{number:i.number,url:i.html_url,state:i.state,merged:i.merged??!1,headSha:i.head.sha,mergeableState:null,baseRef:r.base}}async getReviews(e,n,r){let{data:s}=await this.request("GET",`/repos/${e}/${n}/pulls/${r}/reviews?per_page=100`);return(s??[]).map(i=>({state:i.state??"",commitId:i.commit_id??"",user:i.user?.login??"",submittedAt:i.submitted_at??""}))}async getPullRequest(e,n,r){try{let{data:s}=await this.request("GET",`/repos/${e}/${n}/pulls/${r}`);return{number:s.number,url:s.html_url,state:s.state,merged:s.merged,headSha:s.head.sha,mergeableState:s.mergeable_state??null,baseRef:s.base?.ref??""}}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return null;throw s}}async mergePullRequest(e,n,r,s,i={}){try{return await this.request("PUT",`/repos/${e}/${n}/pulls/${r}/merge`,{merge_method:s,...i.sha?{sha:i.sha}:{},...i.title?{commit_title:i.title}:{}}),{merged:!0}}catch(o){let l=o instanceof Error?o.message:String(o);return l.includes("-> 405")?{merged:!1,reason:`GitHub refused the merge: the branch is not in a mergeable state, or this repository does not allow "${s}" merges. Check the PR for conflicts or required checks, then merge it there.`}:l.includes("-> 409")?{merged:!1,reason:"the branch moved since it was reviewed, so GitHub refused to merge the commit that was approved. Re-review the PR and approve again."}:l.includes("-> 403")?{merged:!1,reason:`this runner's GitHub token is not allowed to merge in ${e}/${n}. It needs write access to the repository - or merge the PR yourself.`}:{merged:!1,reason:l}}}async repoAccess(e,n){try{let{data:r}=await this.request("GET",`/repos/${e}/${n}`);return{ok:!0,canPush:!!(r.permissions?.push||r.permissions?.admin)}}catch(r){let s=r instanceof Error?r.message:String(r);return{ok:!1,canPush:!1,error:s.includes("-> 404")?"not found (private repo this token cannot see, or the name is wrong)":s.slice(0,200)}}}async closePullRequest(e,n,r){await this.request("PATCH",`/repos/${e}/${n}/pulls/${r}`,{state:"closed"})}async deleteBranch(e,n,r){try{await this.request("DELETE",`/repos/${e}/${n}/git/refs/heads/${encodeURIComponent(r)}`)}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return;throw s}}}});function Lh(t,e=512e3){try{let n=Xe.default.statSync(t);return!n.isFile()||n.size>e?null:Xe.default.readFileSync(t,"utf8")}catch{return null}}function Uh(t,e=60){try{return Xe.default.readdirSync(t).slice(0,e).map(n=>ni.default.join(t,n)).filter(n=>{try{return Xe.default.statSync(n).isFile()}catch{return!1}})}catch{return[]}}function vo(t,e=Bw){let n=t.replace(/\/+$/,"");if(!n)return[];let r=[];for(let s of e)for(let i of Uh(s)){if(!i.endsWith(".service"))continue;let o=Lh(i);if(!o||!o.includes(n))continue;let l=/^\s*ExecStart\s*=\s*(.+)$/m.exec(o)?.[1]?.trim()??"",c=/^\s*User\s*=\s*(.+)$/m.exec(o)?.[1]?.trim()??"root (no User= line)";r.push(`${ni.default.basename(i,".service")} (User=${c})`+(l?` runs: ${l}`:""))}return r}function qh(t,e=Hw,n=Kw){let r=t.map(o=>o.trim().toLowerCase()).filter(Boolean);if(!r.length)return[];let s=[...e,...n.flatMap(o=>Uh(o))],i=[];for(let o of s){let l=Lh(o);if(!l)continue;let c=l.toLowerCase(),u=r.find(f=>c.includes(f));if(!u)continue;let h=l.split(`
|
|
332
|
+
`).filter(f=>/reverse_proxy|proxy_pass|root\s+\*?\s*\//i.test(f)).map(f=>f.trim()).slice(0,8);i.push(`${o} mentions ${u}`+(h.length?` - routing lines: ${h.join(" | ")}`:" - no routing line found"))}return i}function Gw(t){return t.replace(/(\b[a-z][a-z0-9+.-]*:\/\/)[^/\s@]+@/gi,"$1***@").replace(/\b(ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{10,}/g,"$1_***").replace(/\bgithub_pat_[A-Za-z0-9_]{10,}/g,"github_pat_***")}function Zw(t){try{let e=Xe.default.statSync(t).uid;return(0,Ot.execFileSync)("id",["-nu",String(e)],{encoding:"utf8",timeout:5e3}).trim()||null}catch{return null}}function ko(t){let e=(0,Ot.spawnSync)("git",["-C",t,"ls-remote","--heads","origin"],{encoding:"utf8",timeout:25e3,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"true",GIT_SSH_COMMAND:"ssh -oBatchMode=yes"}});return e.status===0?{ok:!0,branches:(e.stdout??"").split(`
|
|
333
|
+
`).map(n=>n.split(/\s+/)[1]??"").map(n=>n.replace(/^refs\/heads\//,"")).filter(Boolean)}:Ww(`${e.stderr??""}`,t,Zw(t),e.error?.message)}function Ww(t,e,n,r){let s=Gw(t.trim()),i=s.split(`
|
|
334
|
+
`).find(c=>c.trim())??r??"git failed with no output",o=n?`sudo -u ${n} `:"",l=`Verify it non-interactively (a plain ls-remote would just prompt you and pass): GIT_TERMINAL_PROMPT=0 GIT_ASKPASS=true git -C ${e} ls-remote --heads origin`;return/not a git repository/i.test(s)?{ok:!1,reason:"not-a-checkout",detail:`${e} is not a git checkout`,fix:`Clone the repository into ${e} first.`}:/No such remote|does not appear to be a git repository|'origin' does not appear/i.test(s)&&!/authenticat/i.test(s)?{ok:!1,reason:"no-remote",detail:`this checkout has no usable "origin" remote - ${i}`,fix:`Add it: ${o}git -C ${e} remote add origin <url>`}:/could not read (Username|Password)|terminal prompts disabled|Authentication failed|Invalid username or password|Permission denied \(publickey\)|Support for password authentication was removed|Repository not found|access rights|Host key verification failed/i.test(s)?{ok:!1,reason:"auth",detail:`cannot read origin: git has no usable credential${n?` for ${n}`:""} on this machine - ${i}. The branch may well exist; this machine simply cannot ask.`,fix:`Give ${n??"the user the deploy runs as"} a saved credential: ${o}git config --global credential.helper store, then ${o}git -C ${e} fetch origin once and paste a GitHub PAT as the password (an account password is refused). ${l}`}:/Could not resolve host|Connection (timed out|refused)|Network is unreachable|unable to access|Operation timed out/i.test(s)||r?{ok:!1,reason:"network",detail:`origin could not be reached from this machine - ${i}. This is DNS or a firewall, not a missing branch.`,fix:`Check outbound network from this machine, then re-run. ${l}`}:{ok:!1,reason:"unknown",detail:`origin could not be read - ${i}`,fix:`Run it by hand on this machine to see the whole error: ${o}git -C ${e} ls-remote --heads origin`}}function ri(t){let e=l=>{try{return(0,Ot.execFileSync)("git",l,{cwd:t,encoding:"utf8",timeout:2e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"true"},stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}},n=ko(t),r=e(["branch","--format=%(refname:short)"]),s=e(["branch","-r","--format=%(refname:short)"]),i=n.ok?n.branches:null,o=[`
|
|
335
335
|
|
|
336
336
|
BRANCHES - asked of git just now by the runner, which has a shell. Do NOT conclude a branch is missing from what is under .git/refs: that only says what this checkout has fetched, and a branch pushed from somewhere else is invisible there until someone runs git fetch.`];if(o.push(n.ok?`- on origin: ${n.branches.join(", ")||"(none)"}`:`- origin could NOT be read (${n.reason}): ${n.detail} Report this as "the branch could not be verified from this machine", never as "the branch does not exist", and give this as the fix: ${n.fix}`),r&&o.push(`- local branches in this checkout: ${r.split(`
|
|
337
337
|
`).join(", ")}`),s&&o.push(`- remote-tracking refs already fetched here: ${s.split(`
|
|
338
338
|
`).join(", ")}`),i&&s){let l=new Set(s.split(`
|
|
339
339
|
`).map(u=>u.replace(/^origin\//,""))),c=i.filter(u=>!l.has(u));c.length&&o.push(`- exists on origin but NOT fetched here yet: ${c.join(", ")}. This is a \`git fetch\`, not a missing branch - never report it as a blocker.`)}return o.join(`
|
|
340
|
-
`)}function
|
|
341
|
-
`)[0]??"";if(!i.startsWith("#!"))return null;let o=i.trim(),l=/^#!\s*\/usr\/bin\/env\s+(?:-S\s+)?(\S+)/.exec(o);return{target:e,shebang:o,viaEnv:l?.[1]??null}}catch{return null}}function
|
|
340
|
+
`)}function Vw(t){try{let e=Xe.default.realpathSync(t),n=Xe.default.openSync(e,"r"),r=Buffer.alloc(128),s=Xe.default.readSync(n,r,0,128,0);Xe.default.closeSync(n);let i=r.subarray(0,s).toString("utf8").split(`
|
|
341
|
+
`)[0]??"";if(!i.startsWith("#!"))return null;let o=i.trim(),l=/^#!\s*\/usr\/bin\/env\s+(?:-S\s+)?(\S+)/.exec(o);return{target:e,shebang:o,viaEnv:l?.[1]??null}}catch{return null}}function Ml(){let t=s=>{try{return(0,Ot.execFileSync)(s,["--version"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}},e=(s,i)=>{try{return(0,Ot.execFileSync)("which",[s],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"],...i?{env:{...process.env,PATH:i}}:{}}).trim()}catch{return""}},n=[],r=!1;for(let s of["node","npm","python3","pip3","yarn","pnpm"]){let i=e(s);if(!i)continue;let o=[i,`/usr/bin/${s}`,`/usr/local/bin/${s}`].filter((l,c,u)=>u.indexOf(l)===c&&Xe.default.existsSync(l));for(let l of o){let c=t(l);if(!c)continue;let u=l===i?`${s} in the RUNNER's PATH (${l}) - deploy steps run with THIS`:`${s} at ${l}`;n.push(`- ${u}: ${c}`);let h=Vw(l);if(h)if(h.viaEnv){let f=h.viaEnv,b=e(f),w=b?t(b):null;if(n.push(` ${l}${h.target===l?"":` -> ${h.target}`} is a SCRIPT, not a binary. Its shebang is "${h.shebang}", so it runs under the FIRST ${f} in PATH`+(b?` - right now ${b}${w?` (${w})`:""}`:"")+`. Writing the absolute path to ${ni.default.basename(l)} therefore pins NOTHING.`),b&&Xe.default.existsSync(`/usr/bin/${f}`)){let _=t(`/usr/bin/${f}`),S=w;_&&S&&_!==S&&(r=!0)}}else n.push(` ${l} runs under ${h.shebang.slice(2).trim()} (fixed by its shebang).`)}}return n.length?`
|
|
342
342
|
- runtime versions (a MISMATCH between the runner's PATH and the system install is a common root cause):
|
|
343
343
|
${n.map(s=>` ${s}`).join(`
|
|
344
|
-
`)}`+(r?"\n- PINNING A RUNTIME - this machine needs it, and it is the step most contracts get wrong: a wrapper script above resolves its interpreter through PATH, and the PATH the deploy steps inherit selects a DIFFERENT version from the system one. An absolute path to the wrapper does not fix that. Pin PATH itself in any step that builds, installs or compiles, e.g. `env PATH=/usr/bin:/bin /usr/bin/npm ci`, and say in the document WHY the bare form is wrong. This matters most for native modules: they are compiled against whichever interpreter ran the install, and the service then fails to load them at runtime.":""):""}function
|
|
344
|
+
`)}`+(r?"\n- PINNING A RUNTIME - this machine needs it, and it is the step most contracts get wrong: a wrapper script above resolves its interpreter through PATH, and the PATH the deploy steps inherit selects a DIFFERENT version from the system one. An absolute path to the wrapper does not fix that. Pin PATH itself in any step that builds, installs or compiles, e.g. `env PATH=/usr/bin:/bin /usr/bin/npm ci`, and say in the document WHY the bare form is wrong. This matters most for native modules: they are compiled against whichever interpreter ran the install, and the service then fails to load them at runtime.":""):""}function Jw(){let t=o=>{try{return(0,Ot.execFileSync)("bash",["-lc",`command -v ${JSON.stringify(o)}`],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}),!0}catch{return!1}},e=o=>{try{return(0,Ot.execFileSync)("systemctl",["is-active",o],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim()==="active"}catch{return!1}},n=["caddy","nginx","apache2","haproxy","docker","pm2","systemctl","certbot"],r=n.filter(t),s=n.filter(o=>!r.includes(o)),i=["caddy","nginx","apache2","haproxy"].filter(o=>e(o));return`
|
|
345
345
|
|
|
346
346
|
WHAT THIS MACHINE ALREADY RUNS - build the answer on these, never on a tool that is not here:
|
|
347
347
|
- installed: ${r.join(", ")||"(none of the usual ones)"}
|
|
348
348
|
- NOT installed: ${s.join(", ")||"(none missing)"}
|
|
349
349
|
- reverse proxy currently running: ${i.join(", ")||"(none)"}
|
|
350
|
-
A proxy that is already running is almost certainly serving something else on this box. EXTEND its configuration; never introduce a second one. Two cannot hold port 80, so the best case is that yours refuses to start and the worst is that someone stops the running one to make room and takes an unrelated site down. Same for supervisors: if units already exist here, write one in that style rather than proposing docker or pm2 because they are more familiar.`}function
|
|
350
|
+
A proxy that is already running is almost certainly serving something else on this box. EXTEND its configuration; never introduce a second one. Two cannot hold port 80, so the best case is that yours refuses to start and the worst is that someone stops the running one to make room and takes an unrelated site down. Same for supervisors: if units already exist here, write one in that style rather than proposing docker or pm2 because they are more familiar.`}function Yw(t){try{return new URL(t).hostname}catch{return""}}function zl(t){let e=t.urls.map(Yw).filter(Boolean),n=vo(t.repoPath),r=qh(e),s=[`
|
|
351
351
|
|
|
352
352
|
ABOUT THE MACHINE THIS RUNS ON - gathered by the runner just now, read-only. Trust these over anything you infer from the repository: the repo is exactly where supervision and proxying are NOT configured, so "the repo has no systemd unit" says nothing about whether a unit exists.`];return s.push(n.length?`- systemd units pointing at this checkout (${t.repoPath}):
|
|
353
353
|
`+n.map(i=>` - ${i}`).join(`
|
|
@@ -356,7 +356,7 @@ ABOUT THE MACHINE THIS RUNS ON - gathered by the runner just now, read-only. Tru
|
|
|
356
356
|
`+r.map(i=>` - ${i}`).join(`
|
|
357
357
|
`)+`
|
|
358
358
|
Public checks must go through the public URL; a check against localhost only proves the app started, not that visitors can reach it.`:e.length?`- NO reverse-proxy file on this machine mentions ${e.join(", ")}. Either the site is served another way, or the public URL does not reach this machine at all - flag it, do not assume it works.`:"- no public URL was declared for these environments, so nothing could be checked against a proxy configuration."),s.join(`
|
|
359
|
-
`)+
|
|
359
|
+
`)+Jw()+Ml()}function Fh(t){let e=[],n=o=>o.workdir.trim()||t.repoPath,r=ko(t.repoPath),s=t.environments.map(o=>({name:o.name,dir:n(o)})),i=s.filter((o,l)=>s.findIndex(c=>c.dir===o.dir)!==l);t.environments.length>1&&e.push({environment:"",question:"Each environment has a working directory of its own",ok:i.length===0,blocking:!0,detail:i.length===0?s.map(o=>`${o.name}: ${o.dir}`).join(" \xB7 "):`${s.map(o=>`${o.name}: ${o.dir}`).join(" \xB7 ")} - a deploy of one replaces the other's checkout and build. Set the Working directory on the environment; creating the directory on the machine is not enough on its own.`});for(let o of t.environments){let l=n(o),c=vo(l);if(e.push({environment:o.name,question:`Something supervises the app in ${l}`,ok:c.length>0,blocking:!0,detail:c.length?c.join(" \xB7 "):`no systemd unit on this machine references ${l}`}),o.servePath?.trim()){let u=o.servePath.trim(),h=(_,S)=>{try{return(0,Ot.execFileSync)("git",S,{cwd:_,encoding:"utf8",timeout:1e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"true"},stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}},f=h(u,["rev-parse","HEAD"]),b=o.branch.trim()?h(t.repoPath,["rev-parse",`origin/${o.branch.trim()}`]):null,w=f&&b&&f!==b?h(t.repoPath,["rev-list","--count",`${f}..${b}`]):null;e.push({environment:o.name,question:`The live checkout at ${u} serves the latest ${o.branch.trim()||"commit"}`,ok:f!==null&&(b===null||f===b),blocking:!1,detail:f?b===null?`serving ${f.slice(0,10)}${o.branch.trim()?` (could not resolve origin/${o.branch.trim()} to compare)`:""}`:f===b?`serving ${f.slice(0,10)} = origin/${o.branch.trim()}`:`serving ${f.slice(0,10)}, but origin/${o.branch.trim()} is at ${b.slice(0,10)}`+(w?` - ${w} commit(s) behind`:"")+". The last deploy did not take effect, or none has run since those commits landed.":`cannot read a git HEAD at ${u} - wrong path, or not a git checkout`})}if(o.publicUrl){let u="";try{u=new URL(o.publicUrl).hostname}catch{u=""}let h=u?qh([u]):[];e.push({environment:o.name,question:`A reverse proxy here serves ${u||o.publicUrl}`,ok:h.length>0,blocking:!1,detail:h.length?h.join(" \xB7 "):`no proxy configuration on this machine mentions ${u||o.publicUrl}`})}if(o.publicUrl){let u="";try{u=new URL(o.publicUrl).hostname}catch{u=""}if(u){let h="";for(let f of["DEPLOY.md",".ticketpilot/deploy.md","docs/DEPLOY.md"])try{h=Xe.default.readFileSync(ni.default.join(l,f),"utf8");break}catch{}if(h){let f=h.includes(u);e.push({environment:o.name,question:`DEPLOY.md mentions ${u}`,ok:f,blocking:!1,detail:f?"":"the deploy contract never names this URL - it likely describes an older address. Re-draft DEPLOY.md from Setup (the draft reads the declared environments), then regenerate the steps."})}}}if(o.branch)if(!r.ok)e.push({environment:o.name,question:`Branch "${o.branch}" could be checked on origin`,ok:!1,blocking:!0,detail:`${r.detail} Fix: ${r.fix}`});else{let u=r.branches.includes(o.branch);e.push({environment:o.name,question:`Branch "${o.branch}" exists on origin`,ok:u,blocking:!0,detail:u?"":`origin was reached and does not have "${o.branch}" - it has: ${r.branches.join(", ")||"(no branches at all)"}`})}}return e}var Ot,Xe,ni,Bw,Hw,Kw,_o=be(()=>{"use strict";Ot=require("node:child_process"),Xe=I(require("node:fs"),1),ni=I(require("node:path"),1),Bw=["/etc/systemd/system","/lib/systemd/system","/usr/lib/systemd/system"],Hw=["/etc/caddy/Caddyfile","/usr/local/etc/caddy/Caddyfile","/etc/nginx/nginx.conf"],Kw=["/etc/nginx/sites-enabled","/etc/nginx/conf.d","/etc/caddy/conf.d","/etc/caddy/sites-enabled"]});function Ll(t){return t.replace(/([A-Za-z_][A-Za-z0-9_]*)=(\S+)/g,(e,n,r)=>Xw.test(n)?`${n}=<redacted>`:e)}function tn(t,e){try{let r=(0,Zh.execFileSync)(t,e,{encoding:"utf8",timeout:1e4,maxBuffer:2e6,stdio:["ignore","pipe","pipe"]}).trim();return r?r.slice(0,Gh):null}catch(n){let r=n,s=`${r?.stdout??""}${r?.stderr??""}`.trim();return s?s.slice(0,Gh):null}}function Qw(t){let e=["/etc/systemd/system","/lib/systemd/system"],n=[];for(let r of e){let s;try{s=Dl.default.readdirSync(r)}catch{continue}for(let i of s)if(i.endsWith(".service"))try{let o=Dl.default.readFileSync(Wh.default.join(r,i),"utf8");t&&o.includes(t)&&n.push(i.replace(/\.service$/,""))}catch{}}return[...new Set(n)].slice(0,3)}function Vh(t){let e=t.errorText.slice(-6e3),n=[],r=(o,l)=>{l&&n.push({command:o,output:Ll(l)})},s=Qw(t.repoPath);for(let o of s)r(`systemctl status ${o}`,tn("systemctl",["status",o,"--no-pager","-l"])),r(`journalctl -u ${o} -n 40`,tn("journalctl",["-u",o,"-n","40","--no-pager"])),r(`systemctl show ${o} -p ExecStart -p Environment -p WorkingDirectory -p User`,tn("systemctl",["show",o,"-p","ExecStart","-p","Environment","-p","WorkingDirectory","-p","User"]));/refused|Failed to connect|Couldn't connect|ECONNREFUSED/i.test(e)&&r("ss -ltnp",tn("bash",["-lc","ss -ltnp 2>/dev/null | head -40"]));let i=/(?:^|\s)(?:bash: )?['"\u2018]?([\w.-]+)['"\u2019]?: (?:command not found|No such file or directory)/i.exec(e);if(i){let o=i[1];r(`which ${o} (in the runner's PATH)`,tn("bash",["-lc",`command -v ${JSON.stringify(o)} || echo "not on this PATH"`])),r("ls of the usual system locations",tn("bash",["-lc",`ls -l /usr/bin/${o} /usr/local/bin/${o} 2>&1 | head -5`]))}return/ENOSPC|No space left|write error/i.test(e)&&r("df -h",tn("bash",["-lc","df -h | head -10"])),/EACCES|Permission denied|Operation not permitted/i.test(e)&&(r("id",tn("id",[])),r(`ls -ld ${t.repoPath}`,tn("bash",["-lc",`ls -ld ${JSON.stringify(t.repoPath)} 2>&1`]))),n}function Jh(t){return t.length?`
|
|
360
360
|
|
|
361
361
|
EVIDENCE FROM THE MACHINE - gathered by the runner just now, read-only, because you cannot run commands yourself. This is the part of the system the repository cannot tell you about, and it is usually where the answer is. Values that looked like credentials were redacted before you saw them.
|
|
362
362
|
|
|
@@ -365,15 +365,15 @@ ${e.output}`).join(`
|
|
|
365
365
|
|
|
366
366
|
`)+`
|
|
367
367
|
|
|
368
|
-
Reason from THIS. If it does not contain the answer, say what you would need to look at and why - naming a command someone can run beats inventing a cause that fits the little you were shown.`:""}var Dh,Ml,Lh,zh,Fw,Dl=be(()=>{"use strict";Dh=require("node:child_process"),Ml=A(require("node:fs"),1),Lh=A(require("node:path"),1),zh=4e3,Fw=/(TOKEN|KEY|SECRET|PASSWORD|PASSWD|CREDENTIAL|AUTH|COOKIE|SESSION)/i});var rp={};un(rp,{MAX_CHAIN_DEPTH:()=>np,breakChain:()=>Vl,chainOf:()=>Zl,chainSessionFor:()=>$o,loadBatchPlan:()=>Gl,nextMemberWillChain:()=>Jl,parsePlanAnswer:()=>Yl,recordChainSession:()=>Wl,saveBatchPlan:()=>iv});function iv(t){ri.default.mkdirSync(Kl(),{recursive:!0,mode:448}),ri.default.writeFileSync(Co.default.join(Kl(),`${t.batchId}.json`),JSON.stringify(t,null,2),{mode:384})}function Gl(t){if(!t)return null;try{return JSON.parse(ri.default.readFileSync(Co.default.join(Kl(),`${t}.json`),"utf8"))}catch{return null}}function Zl(t,e){return t?t.chains.find(n=>n.includes(e)&&n.length>1)??null:null}function $o(t,e,n){let r=e.indexOf(n);if(r<=0)return null;let s=Io.get(Eo(t,e));return!s||s.lastIssue!==e[r-1]||s.depth>=np||!ri.default.existsSync(s.worktreePath)?null:s}function Wl(t,e,n,r){let s=Io.get(Eo(t,e));Io.set(Eo(t,e),{sessionId:r.sessionId,worktreePath:r.worktreePath,depth:(s?.depth??0)+1,lastIssue:n})}function Vl(t,e){Io.delete(Eo(t,e))}function Jl(t,e){if(!t)return!1;let n=t.indexOf(e);return n!==-1&&n<t.length-1}function Yl(t,e){let n=/```(?:json)?\s*\n([\s\S]*?)```/.exec(t)??/(\{[\s\S]*\})/.exec(t);if(!n)return null;let r;try{r=JSON.parse(n[1])}catch{return null}let s=r,i=new Set(e),o=Array.isArray(s.order)?s.order.filter(p=>typeof p=="string"):[];if(o.length!==e.length||!o.every(p=>i.has(p))||new Set(o).size!==o.length)return null;let l=(Array.isArray(s.chains)?s.chains:[]).map(p=>Array.isArray(p)?p.filter(f=>typeof f=="string"&&i.has(f)):[]).filter(p=>p.length>1),c=(Array.isArray(s.dependencies)?s.dependencies:[]).map(p=>Array.isArray(p)?p:[]).filter(p=>p.length===2&&typeof p[0]=="string"&&typeof p[1]=="string"&&i.has(p[0])&&i.has(p[1])&&p[0]!==p[1]),u=typeof s.reasoning=="string"?s.reasoning.slice(0,1e3):"";return{order:o,chains:l,dependencies:c,reasoning:u}}var ri,Co,np,Kl,Io,Eo,Po=be(()=>{"use strict";ri=A(require("node:fs"),1),Co=A(require("node:path"),1);Ce();np=3,Kl=()=>Co.default.join(ie(),"autopilot-plans");Io=new Map,Eo=(t,e)=>`${t}:${e[0]}`});var nn=ae((ZT,Pp)=>{"use strict";var Cp=["nodebuffer","arraybuffer","fragments"],$p=typeof Blob<"u";$p&&Cp.push("blob");Pp.exports={BINARY_TYPES:Cp,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:$p,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var ii=ae((WT,Mo)=>{"use strict";var{EMPTY_BUFFER:$v}=nn(),ic=Buffer[Symbol.species];function Pv(t,e){if(t.length===0)return $v;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let s=0;s<t.length;s++){let i=t[s];n.set(i,r),r+=i.length}return r<e?new ic(n.buffer,n.byteOffset,r):n}function jp(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function Np(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function jv(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function oc(t){if(oc.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new ic(t):ArrayBuffer.isView(t)?e=new ic(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),oc.readOnly=!1),e}Mo.exports={concat:Pv,mask:jp,toArrayBuffer:jv,toBuffer:oc,unmask:Np};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");Mo.exports.mask=function(e,n,r,s,i){i<48?jp(e,n,r,s,i):t.mask(e,n,r,s,i)},Mo.exports.unmask=function(e,n){e.length<32?Np(e,n):t.unmask(e,n)}}catch{}});var zp=ae((VT,Mp)=>{"use strict";var Op=Symbol("kDone"),ac=Symbol("kRun"),lc=class{constructor(e){this[Op]=()=>{this.pending--,this[ac]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[ac]()}[ac](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Op])}}};Mp.exports=lc});var Rs=ae((JT,qp)=>{"use strict";var oi=require("zlib"),Dp=ii(),Nv=zp(),{kStatusCode:Lp}=nn(),Ov=Buffer[Symbol.species],Mv=Buffer.from([0,0,255,255]),Do=Symbol("permessage-deflate"),rn=Symbol("total-length"),Ts=Symbol("callback"),$n=Symbol("buffers"),xs=Symbol("error"),zo,cc=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,!zo){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;zo=new Nv(n)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Ts];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(s=>!(n.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>s.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let s=n[r];if(s.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(s=s[0],r==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else if(r==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=s})}),e}decompress(e,n,r){zo.add(s=>{this._decompress(e,n,(i,o)=>{s(),r(i,o)})})}compress(e,n,r){zo.add(s=>{this._compress(e,n,(i,o)=>{s(),r(i,o)})})}_decompress(e,n,r){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?oi.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=oi.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Do]=this,this._inflate[rn]=0,this._inflate[$n]=[],this._inflate.on("error",Dv),this._inflate.on("data",Up)}this._inflate[Ts]=r,this._inflate.write(e),n&&this._inflate.write(Mv),this._inflate.flush(()=>{let i=this._inflate[xs];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=Dp.concat(this._inflate[$n],this._inflate[rn]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[rn]=0,this._inflate[$n]=[],n&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,n,r){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?oi.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=oi.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[rn]=0,this._deflate[$n]=[],this._deflate.on("data",zv)}this._deflate[Ts]=r,this._deflate.write(e),this._deflate.flush(oi.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Dp.concat(this._deflate[$n],this._deflate[rn]);n&&(i=new Ov(i.buffer,i.byteOffset,i.length-4)),this._deflate[Ts]=null,this._deflate[rn]=0,this._deflate[$n]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};qp.exports=cc;function zv(t){this[$n].push(t),this[rn]+=t.length}function Up(t){if(this[rn]+=t.length,this[Do]._maxPayload<1||this[rn]<=this[Do]._maxPayload){this[$n].push(t);return}this[xs]=new RangeError("Max payload size exceeded"),this[xs].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[xs][Lp]=1009,this.removeListener("data",Up),this.reset()}function Dv(t){if(this[Do]._inflate=null,this[xs]){this[Ts](this[xs]);return}t[Lp]=1007,this[Ts](t)}});var As=ae((YT,Lo)=>{"use strict";var{isUtf8:Fp}=require("buffer"),{hasBlob:Lv}=nn(),Uv=[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 qv(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function uc(t){let e=t.length,n=0;for(;n<e;)if((t[n]&128)===0)n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function Fv(t){return Lv&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Lo.exports={isBlob:Fv,isValidStatusCode:qv,isValidUTF8:uc,tokenChars:Uv};if(Fp)Lo.exports.isValidUTF8=function(t){return t.length<24?uc(t):Fp(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");Lo.exports.isValidUTF8=function(e){return e.length<32?uc(e):t(e)}}catch{}});var mc=ae((XT,Vp)=>{"use strict";var{Writable:Bv}=require("stream"),Bp=Rs(),{BINARY_TYPES:Hv,EMPTY_BUFFER:Hp,kStatusCode:Kv,kWebSocket:Gv}=nn(),{concat:dc,toArrayBuffer:Zv,unmask:Wv}=ii(),{isValidStatusCode:Vv,isValidUTF8:Kp}=As(),Uo=Buffer[Symbol.species],pt=0,Gp=1,Zp=2,Wp=3,hc=4,pc=5,qo=6,fc=class extends Bv{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Hv[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[Gv]=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=pt}_write(e,n,r){if(this._opcode===8&&this._state==pt)return r();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){r(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new Uo(r.buffer,r.byteOffset+e,r.length-e),new Uo(r.buffer,r.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let r=this._buffers[0],s=n.length-e;e>=r.length?n.set(this._buffers.shift(),s):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new Uo(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case pt:this.getInfo(e);break;case Gp:this.getPayloadLength16(e);break;case Zp:this.getPayloadLength64(e);break;case Wp:this.getMask();break;case hc:this.getData(e);break;case pc:case qo:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let r=(n[0]&64)===64;if(r&&!this._extensions[Bp.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=Gp:this._payloadLength===127?this._state=Zp:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),r=n.readUInt32BE(0);if(r>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=r*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=Wp:this._state=hc}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=hc}getData(e){let n=Hp;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Wv(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let r=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(r);return}if(this._compressed){this._state=pc,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Bp.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return n(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(o);return}this._fragments.push(i)}this.dataMessage(n),this._state===pt&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=pt;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=dc(r,n):this._binaryType==="arraybuffer"?s=Zv(dc(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=pt):(this._state=qo,setImmediate(()=>{this.emit("message",s,!0),this._state=pt,this.startLoop(e)}))}else{let s=dc(r,n);if(!this._skipUTF8Validation&&!Kp(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===pc||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=pt):(this._state=qo,setImmediate(()=>{this.emit("message",s,!1),this._state=pt,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Hp),this.end();else{let r=e.readUInt16BE(0);if(!Vv(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new Uo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Kp(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(i);return}this._loop=!1,this.emit("conclude",r,s),this.end()}this._state=pt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=pt):(this._state=qo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=pt,this.startLoop(n)}))}createError(e,n,r,s,i){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(o,this.createError),o.code=i,o[Kv]=s,o}};Vp.exports=fc});var bc=ae((ex,Xp)=>{"use strict";var{Duplex:QT}=require("stream"),{randomFillSync:Jv}=require("crypto"),{types:{isUint8Array:Yv}}=require("util"),Jp=Rs(),{EMPTY_BUFFER:Xv,kWebSocket:Qv,NOOP:ek}=nn(),{isBlob:Is,isValidStatusCode:tk}=As(),{mask:Yp,toBuffer:zr}=ii(),ft=Symbol("kByteLength"),nk=Buffer.alloc(4),Fo=8*1024,Dr,Es=Fo,St=0,rk=1,sk=2,gc=class t{constructor(e,n,r){this._extensions=n||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=St,this.onerror=ek,this[Qv]=void 0}static frame(e,n){let r,s=!1,i=2,o=!1;n.mask&&(r=n.maskBuffer||nk,n.generateMask?n.generateMask(r):(Es===Fo&&(Dr===void 0&&(Dr=Buffer.alloc(Fo)),Jv(Dr,0,Fo),Es=0),r[0]=Dr[Es++],r[1]=Dr[Es++],r[2]=Dr[Es++],r[3]=Dr[Es++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let l;typeof e=="string"?(!n.mask||o)&&n[ft]!==void 0?l=n[ft]:(e=Buffer.from(e),l=e.length):(l=e.length,s=n.mask&&n.readOnly&&!o);let c=l;l>=65536?(i+=8,c=127):l>125&&(i+=2,c=126);let u=Buffer.allocUnsafe(s?l+i:i);return u[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(u[0]|=64),u[1]=c,c===126?u.writeUInt16BE(l,2):c===127&&(u[2]=u[3]=0,u.writeUIntBE(l,4,6)),n.mask?(u[1]|=128,u[i-4]=r[0],u[i-3]=r[1],u[i-2]=r[2],u[i-1]=r[3],o?[u,e]:s?(Yp(e,r,u,i,l),[u]):(Yp(e,r,e,0,l),[u,e])):[u,e]}close(e,n,r,s){let i;if(e===void 0)i=Xv;else{if(typeof e!="number"||!tk(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let l=Buffer.byteLength(n);if(l>123)throw new RangeError("The message must not be greater than 123 bytes");if(i=Buffer.allocUnsafe(2+l),i.writeUInt16BE(e,0),typeof n=="string")i.write(n,2);else if(Yv(n))i.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[ft]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==St?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(t.frame(i,o),s)}ping(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):Is(e)?(s=e.size,i=!1):(e=zr(e),s=e.length,i=zr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[ft]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Is(e)?this._state!==St?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==St?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}pong(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):Is(e)?(s=e.size,i=!1):(e=zr(e),s=e.length,i=zr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[ft]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Is(e)?this._state!==St?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==St?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let s=this._extensions[Jp.extensionName],i=n.binary?2:1,o=n.compress,l,c;typeof e=="string"?(l=Buffer.byteLength(e),c=!1):Is(e)?(l=e.size,c=!1):(e=zr(e),l=e.length,c=zr.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=l>=s._threshold),this._compress=o):(o=!1,i=0),n.fin&&(this._firstFragment=!0);let u={[ft]:l,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};Is(e)?this._state!==St?this.enqueue([this.getBlobData,e,this._compress,u,r]):this.getBlobData(e,this._compress,u,r):this._state!==St?this.enqueue([this.dispatch,e,this._compress,u,r]):this.dispatch(e,this._compress,u,r)}getBlobData(e,n,r,s){this._bufferedBytes+=r[ft],this._state=sk,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let l=new Error("The socket was closed while the blob was being read");process.nextTick(yc,this,l,s);return}this._bufferedBytes-=r[ft];let o=zr(i);n?this.dispatch(o,n,r,s):(this._state=St,this.sendFrame(t.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(ik,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[Jp.extensionName];this._bufferedBytes+=r[ft],this._state=rk,i.compress(e,r.fin,(o,l)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");yc(this,c,s);return}this._bufferedBytes-=r[ft],this._state=St,r.readOnly=!1,this.sendFrame(t.frame(l,r),s),this.dequeue()})}dequeue(){for(;this._state===St&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][ft],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][ft],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};Xp.exports=gc;function yc(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let s=t._queue[r],i=s[s.length-1];typeof i=="function"&&i(e)}}function ik(t,e,n){yc(t,e,n),t.onerror(e)}});var lf=ae((tx,af)=>{"use strict";var{kForOnEventAttribute:ai,kListener:wc}=nn(),Qp=Symbol("kCode"),ef=Symbol("kData"),tf=Symbol("kError"),nf=Symbol("kMessage"),rf=Symbol("kReason"),Cs=Symbol("kTarget"),sf=Symbol("kType"),of=Symbol("kWasClean"),sn=class{constructor(e){this[Cs]=null,this[sf]=e}get target(){return this[Cs]}get type(){return this[sf]}};Object.defineProperty(sn.prototype,"target",{enumerable:!0});Object.defineProperty(sn.prototype,"type",{enumerable:!0});var Lr=class extends sn{constructor(e,n={}){super(e),this[Qp]=n.code===void 0?0:n.code,this[rf]=n.reason===void 0?"":n.reason,this[of]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Qp]}get reason(){return this[rf]}get wasClean(){return this[of]}};Object.defineProperty(Lr.prototype,"code",{enumerable:!0});Object.defineProperty(Lr.prototype,"reason",{enumerable:!0});Object.defineProperty(Lr.prototype,"wasClean",{enumerable:!0});var $s=class extends sn{constructor(e,n={}){super(e),this[tf]=n.error===void 0?null:n.error,this[nf]=n.message===void 0?"":n.message}get error(){return this[tf]}get message(){return this[nf]}};Object.defineProperty($s.prototype,"error",{enumerable:!0});Object.defineProperty($s.prototype,"message",{enumerable:!0});var li=class extends sn{constructor(e,n={}){super(e),this[ef]=n.data===void 0?null:n.data}get data(){return this[ef]}};Object.defineProperty(li.prototype,"data",{enumerable:!0});var ok={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[ai]&&s[wc]===e&&!s[ai])return;let r;if(t==="message")r=function(i,o){let l=new li("message",{data:o?i:i.toString()});l[Cs]=this,Bo(e,this,l)};else if(t==="close")r=function(i,o){let l=new Lr("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});l[Cs]=this,Bo(e,this,l)};else if(t==="error")r=function(i){let o=new $s("error",{error:i,message:i.message});o[Cs]=this,Bo(e,this,o)};else if(t==="open")r=function(){let i=new sn("open");i[Cs]=this,Bo(e,this,i)};else return;r[ai]=!!n[ai],r[wc]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[wc]===e&&!n[ai]){this.removeListener(t,n);break}}};af.exports={CloseEvent:Lr,ErrorEvent:$s,Event:sn,EventTarget:ok,MessageEvent:li};function Bo(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Ho=ae((nx,cf)=>{"use strict";var{tokenChars:ci}=As();function Mt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function ak(t){let e=Object.create(null),n=Object.create(null),r=!1,s=!1,i=!1,o,l,c=-1,u=-1,p=-1,f=0;for(;f<t.length;f++)if(u=t.charCodeAt(f),o===void 0)if(p===-1&&ci[u]===1)c===-1&&(c=f);else if(f!==0&&(u===32||u===9))p===-1&&c!==-1&&(p=f);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f);let w=t.slice(c,p);u===44?(Mt(e,w,n),n=Object.create(null)):o=w,c=p=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);else if(l===void 0)if(p===-1&&ci[u]===1)c===-1&&(c=f);else if(u===32||u===9)p===-1&&c!==-1&&(p=f);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f),Mt(n,t.slice(c,p),!0),u===44&&(Mt(e,o,n),n=Object.create(null),o=void 0),c=p=-1}else if(u===61&&c!==-1&&p===-1)l=t.slice(c,f),c=p=-1;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(s){if(ci[u]!==1)throw new SyntaxError(`Unexpected character at index ${f}`);c===-1?c=f:r||(r=!0),s=!1}else if(i)if(ci[u]===1)c===-1&&(c=f);else if(u===34&&c!==-1)i=!1,p=f;else if(u===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(u===34&&t.charCodeAt(f-1)===61)i=!0;else if(p===-1&&ci[u]===1)c===-1&&(c=f);else if(c!==-1&&(u===32||u===9))p===-1&&(p=f);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f);let w=t.slice(c,p);r&&(w=w.replace(/\\/g,""),r=!1),Mt(n,l,w),u===44&&(Mt(e,o,n),n=Object.create(null),o=void 0),l=void 0,c=p=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);if(c===-1||i||u===32||u===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=f);let b=t.slice(c,p);return o===void 0?Mt(e,b,n):(l===void 0?Mt(n,b,!0):r?Mt(n,l,b.replace(/\\/g,"")):Mt(n,l,b),Mt(e,o,n)),e}function lk(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(r=>[e].concat(Object.keys(r).map(s=>{let i=r[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}cf.exports={format:lk,parse:ak}});var Wo=ae((ix,kf)=>{"use strict";var ck=require("events"),uk=require("https"),dk=require("http"),hf=require("net"),hk=require("tls"),{randomBytes:pk,createHash:fk}=require("crypto"),{Duplex:rx,Readable:sx}=require("stream"),{URL:vc}=require("url"),Pn=Rs(),mk=mc(),gk=bc(),{isBlob:yk}=As(),{BINARY_TYPES:uf,CLOSE_TIMEOUT:bk,EMPTY_BUFFER:Ko,GUID:wk,kForOnEventAttribute:kc,kListener:vk,kStatusCode:kk,kWebSocket:xe,NOOP:pf}=nn(),{EventTarget:{addEventListener:_k,removeEventListener:Sk}}=lf(),{format:Tk,parse:xk}=Ho(),{toBuffer:Rk}=ii(),ff=Symbol("kAborted"),_c=[8,13],on=["CONNECTING","OPEN","CLOSING","CLOSED"],Ak=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,me=class t extends ck{constructor(e,n,r){super(),this._binaryType=uf[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Ko,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),mf(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){uf.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,r){let s=new mk({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new gk(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[xe]=this,i[xe]=this,e[xe]=this,s.on("conclude",Ck),s.on("drain",$k),s.on("error",Pk),s.on("message",jk),s.on("ping",Nk),s.on("pong",Ok),i.onerror=Mk,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",bf),e.on("data",Zo),e.on("end",wf),e.on("error",vf),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Pn.extensionName]&&this._extensions[Pn.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Qe(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),yf(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Sc(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Ko,n,r)}pong(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Sc(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Ko,n,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Sc(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Pn.extensionName]||(s.compress=!1),this._sender.send(e||Ko,s,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Qe(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(me,"CONNECTING",{enumerable:!0,value:on.indexOf("CONNECTING")});Object.defineProperty(me.prototype,"CONNECTING",{enumerable:!0,value:on.indexOf("CONNECTING")});Object.defineProperty(me,"OPEN",{enumerable:!0,value:on.indexOf("OPEN")});Object.defineProperty(me.prototype,"OPEN",{enumerable:!0,value:on.indexOf("OPEN")});Object.defineProperty(me,"CLOSING",{enumerable:!0,value:on.indexOf("CLOSING")});Object.defineProperty(me.prototype,"CLOSING",{enumerable:!0,value:on.indexOf("CLOSING")});Object.defineProperty(me,"CLOSED",{enumerable:!0,value:on.indexOf("CLOSED")});Object.defineProperty(me.prototype,"CLOSED",{enumerable:!0,value:on.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(me.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(me.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[kc])return e[vk];return null},set(e){for(let n of this.listeners(t))if(n[kc]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[kc]:!0})}})});me.prototype.addEventListener=_k;me.prototype.removeEventListener=Sk;kf.exports=me;function mf(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:bk,protocolVersion:_c[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=s.autoPong,t._closeTimeout=s.closeTimeout,!_c.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${_c.join(", ")})`);let i;if(e instanceof vc)i=e;else try{i=new vc(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),t._url=i.href;let o=i.protocol==="wss:",l=i.protocol==="ws+unix:",c;if(i.protocol!=="ws:"&&!o&&!l?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:l&&!i.pathname?c="The URL's pathname is empty":i.hash&&(c="The URL contains a fragment identifier"),c){let T=new SyntaxError(c);if(t._redirects===0)throw T;Go(t,T);return}let u=o?443:80,p=pk(16).toString("base64"),f=o?uk.request:dk.request,b=new Set,w;if(s.createConnection=s.createConnection||(o?Ek:Ik),s.defaultPort=s.defaultPort||u,s.port=i.port||u,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(w=new Pn({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=Tk({[Pn.extensionName]:w.offer()})),n.length){for(let T of n){if(typeof T!="string"||!Ak.test(T)||b.has(T))throw new SyntaxError("An invalid or duplicated subprotocol was specified");b.add(T)}s.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),l){let T=s.path.split(":");s.socketPath=T[0],s.path=T[1]}let k;if(s.followRedirects){if(t._redirects===0){t._originalIpc=l,t._originalSecure=o,t._originalHostOrSocketPath=l?s.socketPath:i.host;let T=r&&r.headers;if(r={...r,headers:{}},T)for(let[C,P]of Object.entries(T))r.headers[C.toLowerCase()]=P}else if(t.listenerCount("redirect")===0){let T=l?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!T||t._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,T||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),k=t._req=f(s),t._redirects&&t.emit("redirect",t.url,k)}else k=t._req=f(s);s.timeout&&k.on("timeout",()=>{Qe(t,k,"Opening handshake has timed out")}),k.on("error",T=>{k===null||k[ff]||(k=t._req=null,Go(t,T))}),k.on("response",T=>{let C=T.headers.location,P=T.statusCode;if(C&&s.followRedirects&&P>=300&&P<400){if(++t._redirects>s.maxRedirects){Qe(t,k,"Maximum redirects exceeded");return}k.abort();let q;try{q=new vc(C,e)}catch{let E=new SyntaxError(`Invalid URL: ${C}`);Go(t,E);return}mf(t,q,n,r)}else t.emit("unexpected-response",k,T)||Qe(t,k,`Unexpected server response: ${T.statusCode}`)}),k.on("upgrade",(T,C,P)=>{if(t.emit("upgrade",T),t.readyState!==me.CONNECTING)return;k=t._req=null;let q=T.headers.upgrade;if(q===void 0||q.toLowerCase()!=="websocket"){Qe(t,C,"Invalid Upgrade header");return}let v=fk("sha1").update(p+wk).digest("base64");if(T.headers["sec-websocket-accept"]!==v){Qe(t,C,"Invalid Sec-WebSocket-Accept header");return}let E=T.headers["sec-websocket-protocol"],O;if(E!==void 0?b.size?b.has(E)||(O="Server sent an invalid subprotocol"):O="Server sent a subprotocol but none was requested":b.size&&(O="Server sent no subprotocol"),O){Qe(t,C,O);return}E&&(t._protocol=E);let W=T.headers["sec-websocket-extensions"];if(W!==void 0){if(!w){Qe(t,C,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let z;try{z=xk(W)}catch{Qe(t,C,"Invalid Sec-WebSocket-Extensions header");return}let d=Object.keys(z);if(d.length!==1||d[0]!==Pn.extensionName){Qe(t,C,"Server indicated an extension that was not requested");return}try{w.accept(z[Pn.extensionName])}catch{Qe(t,C,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Pn.extensionName]=w}t.setSocket(C,P,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(k,t):k.end()}function Go(t,e){t._readyState=me.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Ik(t){return t.path=t.socketPath,hf.connect(t)}function Ek(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=hf.isIP(t.host)?"":t.host),hk.connect(t)}function Qe(t,e,n){t._readyState=me.CLOSING;let r=new Error(n);Error.captureStackTrace(r,Qe),e.setHeader?(e[ff]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Go,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Sc(t,e,n){if(e){let r=yk(e)?e.size:Rk(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${on[t.readyState]})`);process.nextTick(n,r)}}function Ck(t,e){let n=this[xe];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[xe]!==void 0&&(n._socket.removeListener("data",Zo),process.nextTick(gf,n._socket),t===1005?n.close():n.close(t,e))}function $k(){let t=this[xe];t.isPaused||t._socket.resume()}function Pk(t){let e=this[xe];e._socket[xe]!==void 0&&(e._socket.removeListener("data",Zo),process.nextTick(gf,e._socket),e.close(t[kk])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function df(){this[xe].emitClose()}function jk(t,e){this[xe].emit("message",t,e)}function Nk(t){let e=this[xe];e._autoPong&&e.pong(t,!this._isServer,pf),e.emit("ping",t)}function Ok(t){this[xe].emit("pong",t)}function gf(t){t.resume()}function Mk(t){let e=this[xe];e.readyState!==me.CLOSED&&(e.readyState===me.OPEN&&(e._readyState=me.CLOSING,yf(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function yf(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function bf(){let t=this[xe];if(this.removeListener("close",bf),this.removeListener("data",Zo),this.removeListener("end",wf),t._readyState=me.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[xe]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",df),t._receiver.on("finish",df))}function Zo(t){this[xe]._receiver.write(t)||this.pause()}function wf(){let t=this[xe];t._readyState=me.CLOSING,t._receiver.end(),this.end()}function vf(){let t=this[xe];this.removeListener("error",vf),this.on("error",pf),t&&(t._readyState=me.CLOSING,this.destroy())}});var xf=ae((ax,Tf)=>{"use strict";var ox=Wo(),{Duplex:zk}=require("stream");function _f(t){t.emit("close")}function Dk(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Sf(t){this.removeListener("error",Sf),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Lk(t,e){let n=!0,r=new zk({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,o){let l=!o&&r._readableState.objectMode?i.toString():i;r.push(l)||t.pause()}),t.once("error",function(i){r.destroyed||(n=!1,r.destroy(i))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(s,i){if(t.readyState===t.CLOSED){i(s),process.nextTick(_f,r);return}let o=!1;t.once("error",function(c){o=!0,i(c)}),t.once("close",function(){o||i(s),process.nextTick(_f,r)}),n&&t.terminate()},r._final=function(s){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(s)});return}t._socket!==null&&(t._socket._writableState.finished?(s(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){s()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(s,i,o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(s,i,o)});return}t.send(s,o)},r.on("end",Dk),r.on("error",Sf),r}Tf.exports=Lk});var Tc=ae((lx,Rf)=>{"use strict";var{tokenChars:Uk}=As();function qk(t){let e=new Set,n=-1,r=-1,s=0;for(s;s<t.length;s++){let o=t.charCodeAt(s);if(r===-1&&Uk[o]===1)n===-1&&(n=s);else if(s!==0&&(o===32||o===9))r===-1&&n!==-1&&(r=s);else if(o===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${s}`);r===-1&&(r=s);let l=t.slice(n,r);if(e.has(l))throw new SyntaxError(`The "${l}" subprotocol is duplicated`);e.add(l),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(n,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}Rf.exports={parse:qk}});var jf=ae((ux,Pf)=>{"use strict";var Fk=require("events"),Vo=require("http"),{Duplex:cx}=require("stream"),{createHash:Bk}=require("crypto"),Af=Ho(),Ur=Rs(),Hk=Tc(),Kk=Wo(),{CLOSE_TIMEOUT:Gk,GUID:Zk,kWebSocket:Wk}=nn(),Vk=/^[+/0-9A-Za-z]{22}==$/,If=0,Ef=1,$f=2,xc=class extends Fk{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Gk,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Kk,...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=Vo.createServer((r,s)=>{let i=Vo.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=Jk(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=If}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===$f){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(ui,this);return}if(e&&this.once("close",e),this._state!==Ef)if(this._state=Ef,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(ui,this):process.nextTick(ui,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{ui(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,r,s){n.on("error",Cf);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,l=+e.headers["sec-websocket-version"];if(e.method!=="GET"){qr(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){qr(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!Vk.test(i)){qr(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(l!==13&&l!==8){qr(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){di(n,400);return}let c=e.headers["sec-websocket-protocol"],u=new Set;if(c!==void 0)try{u=Hk.parse(c)}catch{qr(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let p=e.headers["sec-websocket-extensions"],f={};if(this.options.perMessageDeflate&&p!==void 0){let b=new Ur({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let w=Af.parse(p);w[Ur.extensionName]&&(b.accept(w[Ur.extensionName]),f[Ur.extensionName]=b)}catch{qr(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let b={origin:e.headers[`${l===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(b,(w,k,T,C)=>{if(!w)return di(n,k||401,T,C);this.completeUpgrade(f,i,u,e,n,r,s)});return}if(!this.options.verifyClient(b))return di(n,401)}this.completeUpgrade(f,i,u,e,n,r,s)}completeUpgrade(e,n,r,s,i,o,l){if(!i.readable||!i.writable)return i.destroy();if(i[Wk])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>If)return di(i,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Bk("sha1").update(n+Zk).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(r.size){let f=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;f&&(u.push(`Sec-WebSocket-Protocol: ${f}`),p._protocol=f)}if(e[Ur.extensionName]){let f=e[Ur.extensionName].params,b=Af.format({[Ur.extensionName]:[f]});u.push(`Sec-WebSocket-Extensions: ${b}`),p._extensions=e}this.emit("headers",u,s),i.write(u.concat(`\r
|
|
368
|
+
Reason from THIS. If it does not contain the answer, say what you would need to look at and why - naming a command someone can run beats inventing a cause that fits the little you were shown.`:""}var Zh,Dl,Wh,Gh,Xw,Ul=be(()=>{"use strict";Zh=require("node:child_process"),Dl=I(require("node:fs"),1),Wh=I(require("node:path"),1),Gh=4e3,Xw=/(TOKEN|KEY|SECRET|PASSWORD|PASSWD|CREDENTIAL|AUTH|COOKIE|SESSION)/i});var hp={};un(hp,{MAX_CHAIN_DEPTH:()=>dp,breakChain:()=>Yl,chainOf:()=>Vl,chainSessionFor:()=>Po,loadBatchPlan:()=>Wl,nextMemberWillChain:()=>Xl,parsePlanAnswer:()=>Ql,recordChainSession:()=>Jl,saveBatchPlan:()=>mv});function mv(t){si.default.mkdirSync(Zl(),{recursive:!0,mode:448}),si.default.writeFileSync($o.default.join(Zl(),`${t.batchId}.json`),JSON.stringify(t,null,2),{mode:384})}function Wl(t){if(!t)return null;try{return JSON.parse(si.default.readFileSync($o.default.join(Zl(),`${t}.json`),"utf8"))}catch{return null}}function Vl(t,e){return t?t.chains.find(n=>n.includes(e)&&n.length>1)??null:null}function Po(t,e,n){let r=e.indexOf(n);if(r<=0)return null;let s=Eo.get(Co(t,e));return!s||s.lastIssue!==e[r-1]||s.depth>=dp||!si.default.existsSync(s.worktreePath)?null:s}function Jl(t,e,n,r){let s=Eo.get(Co(t,e));Eo.set(Co(t,e),{sessionId:r.sessionId,worktreePath:r.worktreePath,depth:(s?.depth??0)+1,lastIssue:n})}function Yl(t,e){Eo.delete(Co(t,e))}function Xl(t,e){if(!t)return!1;let n=t.indexOf(e);return n!==-1&&n<t.length-1}function Ql(t,e){let n=/```(?:json)?\s*\n([\s\S]*?)```/.exec(t)??/(\{[\s\S]*\})/.exec(t);if(!n)return null;let r;try{r=JSON.parse(n[1])}catch{return null}let s=r,i=new Set(e),o=Array.isArray(s.order)?s.order.filter(h=>typeof h=="string"):[];if(o.length!==e.length||!o.every(h=>i.has(h))||new Set(o).size!==o.length)return null;let l=(Array.isArray(s.chains)?s.chains:[]).map(h=>Array.isArray(h)?h.filter(f=>typeof f=="string"&&i.has(f)):[]).filter(h=>h.length>1),c=(Array.isArray(s.dependencies)?s.dependencies:[]).map(h=>Array.isArray(h)?h:[]).filter(h=>h.length===2&&typeof h[0]=="string"&&typeof h[1]=="string"&&i.has(h[0])&&i.has(h[1])&&h[0]!==h[1]),u=typeof s.reasoning=="string"?s.reasoning.slice(0,1e3):"";return{order:o,chains:l,dependencies:c,reasoning:u}}var si,$o,dp,Zl,Eo,Co,jo=be(()=>{"use strict";si=I(require("node:fs"),1),$o=I(require("node:path"),1);Ae();dp=3,Zl=()=>$o.default.join(ie(),"autopilot-plans");Eo=new Map,Co=(t,e)=>`${t}:${e[0]}`});var nn=le((ox,qp)=>{"use strict";var Lp=["nodebuffer","arraybuffer","fragments"],Up=typeof Blob<"u";Up&&Lp.push("blob");qp.exports={BINARY_TYPES:Lp,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Up,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var oi=le((ax,zo)=>{"use strict";var{EMPTY_BUFFER:qv}=nn(),ac=Buffer[Symbol.species];function Fv(t,e){if(t.length===0)return qv;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let s=0;s<t.length;s++){let i=t[s];n.set(i,r),r+=i.length}return r<e?new ac(n.buffer,n.byteOffset,r):n}function Fp(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function Bp(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function Bv(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function lc(t){if(lc.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new ac(t):ArrayBuffer.isView(t)?e=new ac(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),lc.readOnly=!1),e}zo.exports={concat:Fv,mask:Fp,toArrayBuffer:Bv,toBuffer:lc,unmask:Bp};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");zo.exports.mask=function(e,n,r,s,i){i<48?Fp(e,n,r,s,i):t.mask(e,n,r,s,i)},zo.exports.unmask=function(e,n){e.length<32?Bp(e,n):t.unmask(e,n)}}catch{}});var Gp=le((lx,Kp)=>{"use strict";var Hp=Symbol("kDone"),cc=Symbol("kRun"),uc=class{constructor(e){this[Hp]=()=>{this.pending--,this[cc]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[cc]()}[cc](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Hp])}}};Kp.exports=uc});var Rs=le((cx,Jp)=>{"use strict";var ai=require("zlib"),Zp=oi(),Hv=Gp(),{kStatusCode:Wp}=nn(),Kv=Buffer[Symbol.species],Gv=Buffer.from([0,0,255,255]),Lo=Symbol("permessage-deflate"),rn=Symbol("total-length"),Ts=Symbol("callback"),$n=Symbol("buffers"),xs=Symbol("error"),Do,dc=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,!Do){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Do=new Hv(n)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Ts];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(s=>!(n.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>s.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let s=n[r];if(s.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(s=s[0],r==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else if(r==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=s})}),e}decompress(e,n,r){Do.add(s=>{this._decompress(e,n,(i,o)=>{s(),r(i,o)})})}compress(e,n,r){Do.add(s=>{this._compress(e,n,(i,o)=>{s(),r(i,o)})})}_decompress(e,n,r){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?ai.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=ai.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Lo]=this,this._inflate[rn]=0,this._inflate[$n]=[],this._inflate.on("error",Wv),this._inflate.on("data",Vp)}this._inflate[Ts]=r,this._inflate.write(e),n&&this._inflate.write(Gv),this._inflate.flush(()=>{let i=this._inflate[xs];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=Zp.concat(this._inflate[$n],this._inflate[rn]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[rn]=0,this._inflate[$n]=[],n&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,n,r){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?ai.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=ai.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[rn]=0,this._deflate[$n]=[],this._deflate.on("data",Zv)}this._deflate[Ts]=r,this._deflate.write(e),this._deflate.flush(ai.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Zp.concat(this._deflate[$n],this._deflate[rn]);n&&(i=new Kv(i.buffer,i.byteOffset,i.length-4)),this._deflate[Ts]=null,this._deflate[rn]=0,this._deflate[$n]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};Jp.exports=dc;function Zv(t){this[$n].push(t),this[rn]+=t.length}function Vp(t){if(this[rn]+=t.length,this[Lo]._maxPayload<1||this[rn]<=this[Lo]._maxPayload){this[$n].push(t);return}this[xs]=new RangeError("Max payload size exceeded"),this[xs].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[xs][Wp]=1009,this.removeListener("data",Vp),this.reset()}function Wv(t){if(this[Lo]._inflate=null,this[xs]){this[Ts](this[xs]);return}t[Wp]=1007,this[Ts](t)}});var Is=le((ux,Uo)=>{"use strict";var{isUtf8:Yp}=require("buffer"),{hasBlob:Vv}=nn(),Jv=[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 Yv(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function hc(t){let e=t.length,n=0;for(;n<e;)if((t[n]&128)===0)n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function Xv(t){return Vv&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Uo.exports={isBlob:Xv,isValidStatusCode:Yv,isValidUTF8:hc,tokenChars:Jv};if(Yp)Uo.exports.isValidUTF8=function(t){return t.length<24?hc(t):Yp(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");Uo.exports.isValidUTF8=function(e){return e.length<32?hc(e):t(e)}}catch{}});var yc=le((dx,sf)=>{"use strict";var{Writable:Qv}=require("stream"),Xp=Rs(),{BINARY_TYPES:ek,EMPTY_BUFFER:Qp,kStatusCode:tk,kWebSocket:nk}=nn(),{concat:pc,toArrayBuffer:rk,unmask:sk}=oi(),{isValidStatusCode:ik,isValidUTF8:ef}=Is(),qo=Buffer[Symbol.species],pt=0,tf=1,nf=2,rf=3,fc=4,mc=5,Fo=6,gc=class extends Qv{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||ek[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[nk]=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=pt}_write(e,n,r){if(this._opcode===8&&this._state==pt)return r();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){r(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new qo(r.buffer,r.byteOffset+e,r.length-e),new qo(r.buffer,r.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let r=this._buffers[0],s=n.length-e;e>=r.length?n.set(this._buffers.shift(),s):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new qo(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case pt:this.getInfo(e);break;case tf:this.getPayloadLength16(e);break;case nf:this.getPayloadLength64(e);break;case rf:this.getMask();break;case fc:this.getData(e);break;case mc:case Fo:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let r=(n[0]&64)===64;if(r&&!this._extensions[Xp.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=tf:this._payloadLength===127?this._state=nf:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),r=n.readUInt32BE(0);if(r>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=r*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=rf:this._state=fc}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=fc}getData(e){let n=Qp;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&sk(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let r=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(r);return}if(this._compressed){this._state=mc,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Xp.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return n(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(o);return}this._fragments.push(i)}this.dataMessage(n),this._state===pt&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=pt;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=pc(r,n):this._binaryType==="arraybuffer"?s=rk(pc(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=pt):(this._state=Fo,setImmediate(()=>{this.emit("message",s,!0),this._state=pt,this.startLoop(e)}))}else{let s=pc(r,n);if(!this._skipUTF8Validation&&!ef(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===mc||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=pt):(this._state=Fo,setImmediate(()=>{this.emit("message",s,!1),this._state=pt,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Qp),this.end();else{let r=e.readUInt16BE(0);if(!ik(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new qo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!ef(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(i);return}this._loop=!1,this.emit("conclude",r,s),this.end()}this._state=pt;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=pt):(this._state=Fo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=pt,this.startLoop(n)}))}createError(e,n,r,s,i){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(o,this.createError),o.code=i,o[tk]=s,o}};sf.exports=gc});var vc=le((px,lf)=>{"use strict";var{Duplex:hx}=require("stream"),{randomFillSync:ok}=require("crypto"),{types:{isUint8Array:ak}}=require("util"),of=Rs(),{EMPTY_BUFFER:lk,kWebSocket:ck,NOOP:uk}=nn(),{isBlob:As,isValidStatusCode:dk}=Is(),{mask:af,toBuffer:zr}=oi(),ft=Symbol("kByteLength"),hk=Buffer.alloc(4),Bo=8*1024,Dr,Es=Bo,St=0,pk=1,fk=2,bc=class t{constructor(e,n,r){this._extensions=n||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=St,this.onerror=uk,this[ck]=void 0}static frame(e,n){let r,s=!1,i=2,o=!1;n.mask&&(r=n.maskBuffer||hk,n.generateMask?n.generateMask(r):(Es===Bo&&(Dr===void 0&&(Dr=Buffer.alloc(Bo)),ok(Dr,0,Bo),Es=0),r[0]=Dr[Es++],r[1]=Dr[Es++],r[2]=Dr[Es++],r[3]=Dr[Es++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let l;typeof e=="string"?(!n.mask||o)&&n[ft]!==void 0?l=n[ft]:(e=Buffer.from(e),l=e.length):(l=e.length,s=n.mask&&n.readOnly&&!o);let c=l;l>=65536?(i+=8,c=127):l>125&&(i+=2,c=126);let u=Buffer.allocUnsafe(s?l+i:i);return u[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(u[0]|=64),u[1]=c,c===126?u.writeUInt16BE(l,2):c===127&&(u[2]=u[3]=0,u.writeUIntBE(l,4,6)),n.mask?(u[1]|=128,u[i-4]=r[0],u[i-3]=r[1],u[i-2]=r[2],u[i-1]=r[3],o?[u,e]:s?(af(e,r,u,i,l),[u]):(af(e,r,e,0,l),[u,e])):[u,e]}close(e,n,r,s){let i;if(e===void 0)i=lk;else{if(typeof e!="number"||!dk(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let l=Buffer.byteLength(n);if(l>123)throw new RangeError("The message must not be greater than 123 bytes");if(i=Buffer.allocUnsafe(2+l),i.writeUInt16BE(e,0),typeof n=="string")i.write(n,2);else if(ak(n))i.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[ft]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==St?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(t.frame(i,o),s)}ping(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):As(e)?(s=e.size,i=!1):(e=zr(e),s=e.length,i=zr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[ft]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};As(e)?this._state!==St?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==St?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}pong(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):As(e)?(s=e.size,i=!1):(e=zr(e),s=e.length,i=zr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[ft]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};As(e)?this._state!==St?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==St?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let s=this._extensions[of.extensionName],i=n.binary?2:1,o=n.compress,l,c;typeof e=="string"?(l=Buffer.byteLength(e),c=!1):As(e)?(l=e.size,c=!1):(e=zr(e),l=e.length,c=zr.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=l>=s._threshold),this._compress=o):(o=!1,i=0),n.fin&&(this._firstFragment=!0);let u={[ft]:l,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};As(e)?this._state!==St?this.enqueue([this.getBlobData,e,this._compress,u,r]):this.getBlobData(e,this._compress,u,r):this._state!==St?this.enqueue([this.dispatch,e,this._compress,u,r]):this.dispatch(e,this._compress,u,r)}getBlobData(e,n,r,s){this._bufferedBytes+=r[ft],this._state=fk,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let l=new Error("The socket was closed while the blob was being read");process.nextTick(wc,this,l,s);return}this._bufferedBytes-=r[ft];let o=zr(i);n?this.dispatch(o,n,r,s):(this._state=St,this.sendFrame(t.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(mk,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[of.extensionName];this._bufferedBytes+=r[ft],this._state=pk,i.compress(e,r.fin,(o,l)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");wc(this,c,s);return}this._bufferedBytes-=r[ft],this._state=St,r.readOnly=!1,this.sendFrame(t.frame(l,r),s),this.dequeue()})}dequeue(){for(;this._state===St&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][ft],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][ft],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};lf.exports=bc;function wc(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let s=t._queue[r],i=s[s.length-1];typeof i=="function"&&i(e)}}function mk(t,e,n){wc(t,e,n),t.onerror(e)}});var yf=le((fx,gf)=>{"use strict";var{kForOnEventAttribute:li,kListener:kc}=nn(),cf=Symbol("kCode"),uf=Symbol("kData"),df=Symbol("kError"),hf=Symbol("kMessage"),pf=Symbol("kReason"),Cs=Symbol("kTarget"),ff=Symbol("kType"),mf=Symbol("kWasClean"),sn=class{constructor(e){this[Cs]=null,this[ff]=e}get target(){return this[Cs]}get type(){return this[ff]}};Object.defineProperty(sn.prototype,"target",{enumerable:!0});Object.defineProperty(sn.prototype,"type",{enumerable:!0});var Lr=class extends sn{constructor(e,n={}){super(e),this[cf]=n.code===void 0?0:n.code,this[pf]=n.reason===void 0?"":n.reason,this[mf]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[cf]}get reason(){return this[pf]}get wasClean(){return this[mf]}};Object.defineProperty(Lr.prototype,"code",{enumerable:!0});Object.defineProperty(Lr.prototype,"reason",{enumerable:!0});Object.defineProperty(Lr.prototype,"wasClean",{enumerable:!0});var $s=class extends sn{constructor(e,n={}){super(e),this[df]=n.error===void 0?null:n.error,this[hf]=n.message===void 0?"":n.message}get error(){return this[df]}get message(){return this[hf]}};Object.defineProperty($s.prototype,"error",{enumerable:!0});Object.defineProperty($s.prototype,"message",{enumerable:!0});var ci=class extends sn{constructor(e,n={}){super(e),this[uf]=n.data===void 0?null:n.data}get data(){return this[uf]}};Object.defineProperty(ci.prototype,"data",{enumerable:!0});var gk={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[li]&&s[kc]===e&&!s[li])return;let r;if(t==="message")r=function(i,o){let l=new ci("message",{data:o?i:i.toString()});l[Cs]=this,Ho(e,this,l)};else if(t==="close")r=function(i,o){let l=new Lr("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});l[Cs]=this,Ho(e,this,l)};else if(t==="error")r=function(i){let o=new $s("error",{error:i,message:i.message});o[Cs]=this,Ho(e,this,o)};else if(t==="open")r=function(){let i=new sn("open");i[Cs]=this,Ho(e,this,i)};else return;r[li]=!!n[li],r[kc]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[kc]===e&&!n[li]){this.removeListener(t,n);break}}};gf.exports={CloseEvent:Lr,ErrorEvent:$s,Event:sn,EventTarget:gk,MessageEvent:ci};function Ho(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Ko=le((mx,bf)=>{"use strict";var{tokenChars:ui}=Is();function Mt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function yk(t){let e=Object.create(null),n=Object.create(null),r=!1,s=!1,i=!1,o,l,c=-1,u=-1,h=-1,f=0;for(;f<t.length;f++)if(u=t.charCodeAt(f),o===void 0)if(h===-1&&ui[u]===1)c===-1&&(c=f);else if(f!==0&&(u===32||u===9))h===-1&&c!==-1&&(h=f);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);h===-1&&(h=f);let w=t.slice(c,h);u===44?(Mt(e,w,n),n=Object.create(null)):o=w,c=h=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);else if(l===void 0)if(h===-1&&ui[u]===1)c===-1&&(c=f);else if(u===32||u===9)h===-1&&c!==-1&&(h=f);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);h===-1&&(h=f),Mt(n,t.slice(c,h),!0),u===44&&(Mt(e,o,n),n=Object.create(null),o=void 0),c=h=-1}else if(u===61&&c!==-1&&h===-1)l=t.slice(c,f),c=h=-1;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(s){if(ui[u]!==1)throw new SyntaxError(`Unexpected character at index ${f}`);c===-1?c=f:r||(r=!0),s=!1}else if(i)if(ui[u]===1)c===-1&&(c=f);else if(u===34&&c!==-1)i=!1,h=f;else if(u===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(u===34&&t.charCodeAt(f-1)===61)i=!0;else if(h===-1&&ui[u]===1)c===-1&&(c=f);else if(c!==-1&&(u===32||u===9))h===-1&&(h=f);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);h===-1&&(h=f);let w=t.slice(c,h);r&&(w=w.replace(/\\/g,""),r=!1),Mt(n,l,w),u===44&&(Mt(e,o,n),n=Object.create(null),o=void 0),l=void 0,c=h=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);if(c===-1||i||u===32||u===9)throw new SyntaxError("Unexpected end of input");h===-1&&(h=f);let b=t.slice(c,h);return o===void 0?Mt(e,b,n):(l===void 0?Mt(n,b,!0):r?Mt(n,l,b.replace(/\\/g,"")):Mt(n,l,b),Mt(e,o,n)),e}function bk(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(r=>[e].concat(Object.keys(r).map(s=>{let i=r[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}bf.exports={format:bk,parse:yk}});var Vo=le((bx,Cf)=>{"use strict";var wk=require("events"),vk=require("https"),kk=require("http"),kf=require("net"),_k=require("tls"),{randomBytes:Sk,createHash:Tk}=require("crypto"),{Duplex:gx,Readable:yx}=require("stream"),{URL:_c}=require("url"),Pn=Rs(),xk=yc(),Rk=vc(),{isBlob:Ik}=Is(),{BINARY_TYPES:wf,CLOSE_TIMEOUT:Ak,EMPTY_BUFFER:Go,GUID:Ek,kForOnEventAttribute:Sc,kListener:Ck,kStatusCode:$k,kWebSocket:xe,NOOP:_f}=nn(),{EventTarget:{addEventListener:Pk,removeEventListener:jk}}=yf(),{format:Nk,parse:Ok}=Ko(),{toBuffer:Mk}=oi(),Sf=Symbol("kAborted"),Tc=[8,13],on=["CONNECTING","OPEN","CLOSING","CLOSED"],zk=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,me=class t extends wk{constructor(e,n,r){super(),this._binaryType=wf[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Go,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),Tf(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){wf.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,r){let s=new xk({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new Rk(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[xe]=this,i[xe]=this,e[xe]=this,s.on("conclude",Uk),s.on("drain",qk),s.on("error",Fk),s.on("message",Bk),s.on("ping",Hk),s.on("pong",Kk),i.onerror=Gk,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",If),e.on("data",Wo),e.on("end",Af),e.on("error",Ef),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Pn.extensionName]&&this._extensions[Pn.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Qe(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Rf(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){xc(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Go,n,r)}pong(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){xc(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Go,n,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){xc(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Pn.extensionName]||(s.compress=!1),this._sender.send(e||Go,s,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Qe(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(me,"CONNECTING",{enumerable:!0,value:on.indexOf("CONNECTING")});Object.defineProperty(me.prototype,"CONNECTING",{enumerable:!0,value:on.indexOf("CONNECTING")});Object.defineProperty(me,"OPEN",{enumerable:!0,value:on.indexOf("OPEN")});Object.defineProperty(me.prototype,"OPEN",{enumerable:!0,value:on.indexOf("OPEN")});Object.defineProperty(me,"CLOSING",{enumerable:!0,value:on.indexOf("CLOSING")});Object.defineProperty(me.prototype,"CLOSING",{enumerable:!0,value:on.indexOf("CLOSING")});Object.defineProperty(me,"CLOSED",{enumerable:!0,value:on.indexOf("CLOSED")});Object.defineProperty(me.prototype,"CLOSED",{enumerable:!0,value:on.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(me.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(me.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Sc])return e[Ck];return null},set(e){for(let n of this.listeners(t))if(n[Sc]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Sc]:!0})}})});me.prototype.addEventListener=Pk;me.prototype.removeEventListener=jk;Cf.exports=me;function Tf(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Ak,protocolVersion:Tc[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=s.autoPong,t._closeTimeout=s.closeTimeout,!Tc.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Tc.join(", ")})`);let i;if(e instanceof _c)i=e;else try{i=new _c(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),t._url=i.href;let o=i.protocol==="wss:",l=i.protocol==="ws+unix:",c;if(i.protocol!=="ws:"&&!o&&!l?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:l&&!i.pathname?c="The URL's pathname is empty":i.hash&&(c="The URL contains a fragment identifier"),c){let S=new SyntaxError(c);if(t._redirects===0)throw S;Zo(t,S);return}let u=o?443:80,h=Sk(16).toString("base64"),f=o?vk.request:kk.request,b=new Set,w;if(s.createConnection=s.createConnection||(o?Lk:Dk),s.defaultPort=s.defaultPort||u,s.port=i.port||u,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":h,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(w=new Pn({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=Nk({[Pn.extensionName]:w.offer()})),n.length){for(let S of n){if(typeof S!="string"||!zk.test(S)||b.has(S))throw new SyntaxError("An invalid or duplicated subprotocol was specified");b.add(S)}s.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),l){let S=s.path.split(":");s.socketPath=S[0],s.path=S[1]}let _;if(s.followRedirects){if(t._redirects===0){t._originalIpc=l,t._originalSecure=o,t._originalHostOrSocketPath=l?s.socketPath:i.host;let S=r&&r.headers;if(r={...r,headers:{}},S)for(let[A,z]of Object.entries(S))r.headers[A.toLowerCase()]=z}else if(t.listenerCount("redirect")===0){let S=l?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!S||t._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,S||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),_=t._req=f(s),t._redirects&&t.emit("redirect",t.url,_)}else _=t._req=f(s);s.timeout&&_.on("timeout",()=>{Qe(t,_,"Opening handshake has timed out")}),_.on("error",S=>{_===null||_[Sf]||(_=t._req=null,Zo(t,S))}),_.on("response",S=>{let A=S.headers.location,z=S.statusCode;if(A&&s.followRedirects&&z>=300&&z<400){if(++t._redirects>s.maxRedirects){Qe(t,_,"Maximum redirects exceeded");return}_.abort();let q;try{q=new _c(A,e)}catch{let C=new SyntaxError(`Invalid URL: ${A}`);Zo(t,C);return}Tf(t,q,n,r)}else t.emit("unexpected-response",_,S)||Qe(t,_,`Unexpected server response: ${S.statusCode}`)}),_.on("upgrade",(S,A,z)=>{if(t.emit("upgrade",S),t.readyState!==me.CONNECTING)return;_=t._req=null;let q=S.headers.upgrade;if(q===void 0||q.toLowerCase()!=="websocket"){Qe(t,A,"Invalid Upgrade header");return}let v=Tk("sha1").update(h+Ek).digest("base64");if(S.headers["sec-websocket-accept"]!==v){Qe(t,A,"Invalid Sec-WebSocket-Accept header");return}let C=S.headers["sec-websocket-protocol"],M;if(C!==void 0?b.size?b.has(C)||(M="Server sent an invalid subprotocol"):M="Server sent a subprotocol but none was requested":b.size&&(M="Server sent no subprotocol"),M){Qe(t,A,M);return}C&&(t._protocol=C);let B=S.headers["sec-websocket-extensions"];if(B!==void 0){if(!w){Qe(t,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let j;try{j=Ok(B)}catch{Qe(t,A,"Invalid Sec-WebSocket-Extensions header");return}let d=Object.keys(j);if(d.length!==1||d[0]!==Pn.extensionName){Qe(t,A,"Server indicated an extension that was not requested");return}try{w.accept(j[Pn.extensionName])}catch{Qe(t,A,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Pn.extensionName]=w}t.setSocket(A,z,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(_,t):_.end()}function Zo(t,e){t._readyState=me.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Dk(t){return t.path=t.socketPath,kf.connect(t)}function Lk(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=kf.isIP(t.host)?"":t.host),_k.connect(t)}function Qe(t,e,n){t._readyState=me.CLOSING;let r=new Error(n);Error.captureStackTrace(r,Qe),e.setHeader?(e[Sf]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Zo,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function xc(t,e,n){if(e){let r=Ik(e)?e.size:Mk(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${on[t.readyState]})`);process.nextTick(n,r)}}function Uk(t,e){let n=this[xe];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[xe]!==void 0&&(n._socket.removeListener("data",Wo),process.nextTick(xf,n._socket),t===1005?n.close():n.close(t,e))}function qk(){let t=this[xe];t.isPaused||t._socket.resume()}function Fk(t){let e=this[xe];e._socket[xe]!==void 0&&(e._socket.removeListener("data",Wo),process.nextTick(xf,e._socket),e.close(t[$k])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function vf(){this[xe].emitClose()}function Bk(t,e){this[xe].emit("message",t,e)}function Hk(t){let e=this[xe];e._autoPong&&e.pong(t,!this._isServer,_f),e.emit("ping",t)}function Kk(t){this[xe].emit("pong",t)}function xf(t){t.resume()}function Gk(t){let e=this[xe];e.readyState!==me.CLOSED&&(e.readyState===me.OPEN&&(e._readyState=me.CLOSING,Rf(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Rf(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function If(){let t=this[xe];if(this.removeListener("close",If),this.removeListener("data",Wo),this.removeListener("end",Af),t._readyState=me.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[xe]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",vf),t._receiver.on("finish",vf))}function Wo(t){this[xe]._receiver.write(t)||this.pause()}function Af(){let t=this[xe];t._readyState=me.CLOSING,t._receiver.end(),this.end()}function Ef(){let t=this[xe];this.removeListener("error",Ef),this.on("error",_f),t&&(t._readyState=me.CLOSING,this.destroy())}});var Nf=le((vx,jf)=>{"use strict";var wx=Vo(),{Duplex:Zk}=require("stream");function $f(t){t.emit("close")}function Wk(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Pf(t){this.removeListener("error",Pf),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Vk(t,e){let n=!0,r=new Zk({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,o){let l=!o&&r._readableState.objectMode?i.toString():i;r.push(l)||t.pause()}),t.once("error",function(i){r.destroyed||(n=!1,r.destroy(i))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(s,i){if(t.readyState===t.CLOSED){i(s),process.nextTick($f,r);return}let o=!1;t.once("error",function(c){o=!0,i(c)}),t.once("close",function(){o||i(s),process.nextTick($f,r)}),n&&t.terminate()},r._final=function(s){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(s)});return}t._socket!==null&&(t._socket._writableState.finished?(s(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){s()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(s,i,o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(s,i,o)});return}t.send(s,o)},r.on("end",Wk),r.on("error",Pf),r}jf.exports=Vk});var Rc=le((kx,Of)=>{"use strict";var{tokenChars:Jk}=Is();function Yk(t){let e=new Set,n=-1,r=-1,s=0;for(s;s<t.length;s++){let o=t.charCodeAt(s);if(r===-1&&Jk[o]===1)n===-1&&(n=s);else if(s!==0&&(o===32||o===9))r===-1&&n!==-1&&(r=s);else if(o===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${s}`);r===-1&&(r=s);let l=t.slice(n,r);if(e.has(l))throw new SyntaxError(`The "${l}" subprotocol is duplicated`);e.add(l),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(n,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}Of.exports={parse:Yk}});var Ff=le((Sx,qf)=>{"use strict";var Xk=require("events"),Jo=require("http"),{Duplex:_x}=require("stream"),{createHash:Qk}=require("crypto"),Mf=Ko(),Ur=Rs(),e_=Rc(),t_=Vo(),{CLOSE_TIMEOUT:n_,GUID:r_,kWebSocket:s_}=nn(),i_=/^[+/0-9A-Za-z]{22}==$/,zf=0,Df=1,Uf=2,Ic=class extends Xk{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:n_,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:t_,...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=Jo.createServer((r,s)=>{let i=Jo.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=o_(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=zf}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===Uf){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(di,this);return}if(e&&this.once("close",e),this._state!==Df)if(this._state=Df,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(di,this):process.nextTick(di,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{di(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,r,s){n.on("error",Lf);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,l=+e.headers["sec-websocket-version"];if(e.method!=="GET"){qr(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){qr(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!i_.test(i)){qr(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(l!==13&&l!==8){qr(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){hi(n,400);return}let c=e.headers["sec-websocket-protocol"],u=new Set;if(c!==void 0)try{u=e_.parse(c)}catch{qr(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let h=e.headers["sec-websocket-extensions"],f={};if(this.options.perMessageDeflate&&h!==void 0){let b=new Ur({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let w=Mf.parse(h);w[Ur.extensionName]&&(b.accept(w[Ur.extensionName]),f[Ur.extensionName]=b)}catch{qr(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let b={origin:e.headers[`${l===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(b,(w,_,S,A)=>{if(!w)return hi(n,_||401,S,A);this.completeUpgrade(f,i,u,e,n,r,s)});return}if(!this.options.verifyClient(b))return hi(n,401)}this.completeUpgrade(f,i,u,e,n,r,s)}completeUpgrade(e,n,r,s,i,o,l){if(!i.readable||!i.writable)return i.destroy();if(i[s_])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>zf)return hi(i,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Qk("sha1").update(n+r_).digest("base64")}`],h=new this.options.WebSocket(null,void 0,this.options);if(r.size){let f=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;f&&(u.push(`Sec-WebSocket-Protocol: ${f}`),h._protocol=f)}if(e[Ur.extensionName]){let f=e[Ur.extensionName].params,b=Mf.format({[Ur.extensionName]:[f]});u.push(`Sec-WebSocket-Extensions: ${b}`),h._extensions=e}this.emit("headers",u,s),i.write(u.concat(`\r
|
|
369
369
|
`).join(`\r
|
|
370
|
-
`)),i.removeListener("error",
|
|
370
|
+
`)),i.removeListener("error",Lf),h.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(h),h.on("close",()=>{this.clients.delete(h),this._shouldEmitClose&&!this.clients.size&&process.nextTick(di,this)})),l(h,s)}};qf.exports=Ic;function o_(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let r of Object.keys(e))t.removeListener(r,e[r])}}function di(t){t._state=Uf,t.emit("close")}function Lf(){this.destroy()}function hi(t,e,n,r){n=n||Jo.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...r},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${Jo.STATUS_CODES[e]}\r
|
|
371
371
|
`+Object.keys(r).map(s=>`${s}: ${r[s]}`).join(`\r
|
|
372
372
|
`)+`\r
|
|
373
373
|
\r
|
|
374
|
-
`+n)}function qr(t,e,n,r,s,i){if(t.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,qr),t.emit("wsClientError",o,n,e)}else
|
|
375
|
-
`)}function
|
|
376
|
-
${l}`:""}`.trim(),u=
|
|
374
|
+
`+n)}function qr(t,e,n,r,s,i){if(t.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,qr),t.emit("wsClientError",o,n,e)}else hi(n,r,s,i)}});var Yf={};un(Yf,{CATALOGUE:()=>Oc,catalogueForPrompt:()=>Mc,describeDiagnostic:()=>R_,runDiagnostic:()=>I_});function Mc(){return["service_status {unit} - is a systemd service running, and why not","service_logs {unit, lines<=200} - a service's recent journal","listeners {} - what is listening on which port","disk_space {} - disk usage","dir_list {path} - list an absolute path","read_file {path, lines<=200} - the head of a file (credential stores are refused)","http_check {url} - status code and timing of one GET","git_state {path} - a checkout's branch and last commits"].join(`
|
|
375
|
+
`)}function R_(t){let e=Oc[t.command];return e?e.describe(t.args??{}):null}async function I_(t){let e=Oc[t.command];if(!e)return{ok:!1,commandLine:t.command,output:"refused: not in the catalogue"};let n=e.build(t.args??{}),r=e.describe(t.args??{});return typeof n=="string"?{ok:!1,commandLine:r,output:n}:new Promise(s=>{(0,Jf.execFile)(n[0],n.slice(1),{timeout:T_,maxBuffer:2e6},(i,o,l)=>{let c=`${o??""}${l?`
|
|
376
|
+
${l}`:""}`.trim(),u=Ll(c).slice(0,x_)||(i?String(i.message):"(no output)");s({ok:!0,commandLine:r,output:u})})})}var Jf,Nc,T_,x_,Wf,Vf,jc,mt,ta,Oc,zc=be(()=>{"use strict";Jf=require("node:child_process"),Nc=I(require("node:fs"),1);Ul();T_=1e4,x_=8e3,Wf=/(\/\.(config|claude)\/|\/\.env($|[^a-z])|credentials|\.ssh\/|\.npmrc|runner\.json)/i,Vf=/^[a-zA-Z0-9@._-]{1,80}$/,jc=/^\/[^\0\n]{1,300}$/,mt=t=>typeof t=="string"?t.trim():"",ta=(t,e,n)=>{let r=typeof t=="number"?Math.floor(t):n;return r>0&&r<=e?r:n},Oc={service_status:{describe:t=>`systemctl status ${mt(t.unit)}`,build:t=>{let e=mt(t.unit);return Vf.test(e)?["systemctl","status",e,"--no-pager","-l"]:"refused: that is not a plausible unit name"}},service_logs:{describe:t=>`journalctl -u ${mt(t.unit)} -n ${ta(t.lines,200,50)}`,build:t=>{let e=mt(t.unit);return Vf.test(e)?["journalctl","-u",e,"-n",String(ta(t.lines,200,50)),"--no-pager"]:"refused: that is not a plausible unit name"}},listeners:{describe:()=>"ss -ltnp (what is listening on which port)",build:()=>["ss","-ltnp"]},disk_space:{describe:()=>"df -h (disk usage)",build:()=>["df","-h"]},dir_list:{describe:t=>`ls -la ${mt(t.path)}`,build:t=>{let e=mt(t.path);return jc.test(e)?Wf.test(e)?"refused: that path can hold credentials":["ls","-la",e]:"refused: absolute path required"}},read_file:{describe:t=>`head -n ${ta(t.lines,200,100)} ${mt(t.path)}`,build:t=>{let e=mt(t.path);if(!jc.test(e))return"refused: absolute path required";if(Wf.test(e))return"refused: that path can hold credentials";try{if(Nc.default.statSync(e).size>2e6)return"refused: file too large for a chat"}catch{}return["head","-n",String(ta(t.lines,200,100)),e]}},http_check:{describe:t=>`curl -sS -o /dev/null -w '%{http_code}' ${mt(t.url)}`,build:t=>{let e=mt(t.url);return/^https?:\/\/[^\s'"]{1,300}$/.test(e)?["curl","-sS","-o","/dev/null","-w","HTTP %{http_code}, %{time_total}s","--max-time","10",e]:"refused: a plain http(s) URL only"}},git_state:{describe:t=>`git -C ${mt(t.path)} status + last 3 commits`,build:t=>{let e=mt(t.path);return jc.test(e)?Nc.default.existsSync(`${e}/.git`)?["git","-C",e,"log","--oneline","-3","--decorate"]:"refused: not a git checkout":"refused: absolute path required"}}}});var lm={};un(lm,{MANAGED_MARKER:()=>ra,caddyBlock:()=>na,checkoutOwner:()=>om,detectApp:()=>em,envPrepare:()=>C_,nodeBinDir:()=>Qf,pickPort:()=>nm,portsClaimedByUnits:()=>tm,spliceCaddyBlock:()=>im,sudoersText:()=>sm,unitSlug:()=>Xf,unitText:()=>rm});function Xf(t,e){let n=r=>r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return`${n(t)}-${n(e)}`.slice(0,60)}function Qf(t){let e=n=>{try{let r=(0,jn.execFileSync)(n[0],n.slice(1),{encoding:"utf8",timeout:1e4}).trim();return r?Dt.default.dirname(r):null}catch{return null}};return t&&t!==mi.default.userInfo().username?e(["sudo","-u",t,"bash","-lc","command -v node"]):e(["bash","-lc","command -v node"])}function em(t){let e=Dt.default.join(t,"package.json");if(!Se.default.existsSync(e))return{kind:"unknown",reason:"no package.json - only Node apps are supported so far"};let n;try{n=JSON.parse(Se.default.readFileSync(e,"utf8"))}catch{return{kind:"unknown",reason:"package.json could not be parsed"}}return n.scripts?.start?{kind:"node-start"}:{kind:"static"}}function tm(){let t=new Set;try{for(let e of Se.default.readdirSync("/etc/systemd/system"))if(e.endsWith(".service"))try{let n=Se.default.readFileSync(Dt.default.join("/etc/systemd/system",e),"utf8");for(let r of n.matchAll(/^Environment=PORT=(\d+)$/gm))t.add(Number(r[1]))}catch{}}catch{}return t}async function nm(t){let e=tm(),n=r=>new Promise(s=>{let i=Dc.default.createServer();i.once("error",()=>s(!1)),i.listen(r,"127.0.0.1",()=>i.close(()=>s(!0)))});if(t){if(!await n(t))throw new Error(`port ${t} is already in use on this machine - pick another`);return t}for(let r=3e3;r<3100;r++)if(!e.has(r)&&await n(r))return r;throw new Error("no free port found between 3000 and 3099 - pass one with --port")}function rm(t){return`${ra}
|
|
377
377
|
[Unit]
|
|
378
378
|
Description=${t.repoName} ${t.envName} (Allwright-prepared)
|
|
379
379
|
After=network-online.target
|
|
@@ -403,51 +403,51 @@ RestartSec=3
|
|
|
403
403
|
|
|
404
404
|
[Install]
|
|
405
405
|
WantedBy=multi-user.target
|
|
406
|
-
`}function
|
|
406
|
+
`}function sm(t){return`${ra}
|
|
407
407
|
# Exactly two commands, exactly one unit - what a deploy needs and nothing else.
|
|
408
408
|
${t.user} ALL=(root) NOPASSWD: /usr/bin/systemctl restart ${t.slug}, /usr/bin/systemctl is-active ${t.slug}
|
|
409
|
-
`}function
|
|
409
|
+
`}function na(t){return`# BEGIN allwright ${t.slug}
|
|
410
410
|
${t.hostname} {
|
|
411
411
|
reverse_proxy 127.0.0.1:${t.port}
|
|
412
412
|
}
|
|
413
|
-
# END allwright ${t.slug}`}function
|
|
413
|
+
# END allwright ${t.slug}`}function im(t,e,n){let r=`# BEGIN allwright ${e}`,s=`# END allwright ${e}`,i=t.indexOf(r);if(i!==-1){let o=t.indexOf(s,i);if(o!==-1)return t.slice(0,i)+n+t.slice(o+s.length)}return t.replace(/\s*$/,"")+`
|
|
414
414
|
|
|
415
415
|
`+n+`
|
|
416
|
-
`}function
|
|
416
|
+
`}function om(t){let e=Se.default.statSync(t).uid;if(e===0)throw new Error(`${t} is owned by root. A web app must not run as root - chown the checkout to the user that deploys it first (sudo chown -R <user>: ${t}).`);try{return(0,jn.execFileSync)("id",["-nu",String(e)],{encoding:"utf8",timeout:5e3}).trim()}catch{return mi.default.userInfo().username}}function et(t,e){(0,jn.execFileSync)("sudo",t,{encoding:"utf8",timeout:6e4,...e!==void 0?{input:e}:{},stdio:[e!==void 0?"pipe":"inherit","inherit","inherit"]})}function A_(t){if(t.sudoers){let e=Dt.default.join(mi.default.tmpdir(),`allwright-sudoers-${process.pid}`);Se.default.writeFileSync(e,t.content,{mode:384});try{(0,jn.execFileSync)("sudo",["visudo","-cf",e],{encoding:"utf8",timeout:3e4}),et(["install","-m",t.mode,"-o","root","-g","root",e,t.path])}finally{Se.default.rmSync(e,{force:!0})}return}et(["mkdir","-p",Dt.default.dirname(t.path)]),et(["tee",t.path],t.content),et(["chmod",t.mode,t.path])}function E_(t){try{return Se.default.readFileSync(t,"utf8").includes(ra)}catch{return!0}}async function C_(t){if(!Se.default.existsSync(t.dir))throw new Error(`${t.dir} does not exist - clone the repo there first`);if(!Se.default.existsSync(Dt.default.join(t.dir,".git")))throw new Error(`${t.dir} is not a git checkout`);let e=em(t.dir);if(e.kind==="unknown")throw new Error(`cannot prepare this checkout: ${e.reason}. Write the service by hand, or ask in Compose - this command only automates what it can verify.`);let n=Xf(t.repoName,t.envName),r=t.publicUrl?$_(t.publicUrl):"";if(e.kind==="static"){if(y.info(`${t.repoName} has no "start" script - it is a static site, and a static site needs no service: the proxy serves its files directly. Nothing to supervise.`),!r){y.info("Pass --url to wire the proxy, or configure it in your web server by hand.");return}y.info("Add a site block for it to /etc/caddy/Caddyfile yourself, for example:"),y.info(`
|
|
417
417
|
${r} {
|
|
418
418
|
root * ${t.dir}/<your build output>
|
|
419
419
|
file_server
|
|
420
420
|
}
|
|
421
|
-
`);return}let s=
|
|
422
|
-
--- ${
|
|
423
|
-
${
|
|
424
|
-
${
|
|
425
|
-
${
|
|
426
|
-
`).filter(Boolean);for(let i of n)if(i.startsWith("/")||i.split("/").includes(".."))throw new Error(`refusing to import - unsafe path in archive: ${i}`);let r=ie(),s;
|
|
421
|
+
`);return}let s=vo(t.dir).filter(_=>!_.startsWith(n)),i=`/etc/systemd/system/${n}.service`;if(s.length&&!Se.default.existsSync(i)){y.info(`this checkout is already supervised: ${s.join(" \xB7 ")}. Leaving it alone - remove that unit first if you want Allwright to manage this environment.`);return}if(!E_(i))throw new Error(`${i} exists and was not written by this command - refusing to overwrite a hand-written unit. Delete it yourself if you want it replaced.`);let o=om(t.dir),l=Qf(o);if(!l)throw new Error(`node is not on ${o}'s PATH - the service will run as ${o} (the checkout's owner), so Node must be installed for THAT user (or system-wide). Install it, then re-run.`);let c=await nm(t.port),u=[{path:i,content:rm({slug:n,repoName:t.repoName,envName:t.envName,dir:t.dir,user:o,port:c,nodeBin:l}),mode:"644"},{path:`/etc/sudoers.d/allwright-${n}`,content:sm({slug:n,user:o}),mode:"440",sudoers:!0}];if(t.dryRun){y.info(`DRY RUN - nothing will be written. Planned (port ${c}, user ${o}):`);for(let _ of u)y.info(`
|
|
422
|
+
--- ${_.path} (mode ${_.mode}) ---
|
|
423
|
+
${_.content}`);r&&y.info(`--- appended to /etc/caddy/Caddyfile ---
|
|
424
|
+
${na({slug:n,hostname:r,port:c})}`);return}for(let _ of u)A_(_);let h=`/etc/allwright/env.d/${n}.env`;Se.default.existsSync(h)||(et(["install","-d","-m","755","/etc/allwright"]),et(["install","-d","-m","750","/etc/allwright/env.d"]),et(["install","-m","600","-o","root","-g","root","/dev/null",h]),y.info(`created empty ${h} - add secrets with: sudoedit ${h}`));let f=Se.default.existsSync(Dt.default.join(t.dir,".next"))||Se.default.existsSync(Dt.default.join(t.dir,"dist"));f||y.warn(`no build output in ${t.dir} yet - the service would exit immediately. Run your install+build once (or run the first deploy), then: sudo systemctl restart ${n}`),et(["systemctl","daemon-reload"]),et(["systemctl","reset-failed",n]),et(["systemctl","enable","--now",n]),r&&j_({slug:n,hostname:r,port:c});let b=f?await P_(c,3e4):!1,w=am(n);y.info(""),y.info(`${w?"\u2713":"\u2717"} service ${n}: ${w?"active":"NOT active - journalctl -u "+n+" -n 40"}`),f&&y.info(`${b?"\u2713":"\u2717"} listening on 127.0.0.1:${c}${b?"":" - not yet; check the journal"}`),y.info("\u2713 deploys may restart it without a password (sudoers drop-in installed)"),y.info(""),y.info(`Deploy steps should end with: sudo systemctl restart ${n}`),r&&y.info(`Health checks should target: http://127.0.0.1:${c}/ (and later https://${r}/)`),y.info(`DNS stays yours: point ${r||"your hostname"} at this machine when you are ready.`)}function $_(t){try{return new URL(t).hostname}catch{throw new Error(`--url must be a full URL like https://staging.example.com (got "${t}")`)}}function am(t){try{return(0,jn.execFileSync)("systemctl",["is-active",t],{encoding:"utf8",timeout:1e4}).trim()==="active"}catch{return!1}}async function P_(t,e){let n=Date.now()+e;for(;Date.now()<n;){if(await new Promise(s=>{let i=Dc.default.connect({port:t,host:"127.0.0.1",timeout:2e3});i.once("connect",()=>{i.destroy(),s(!0)}),i.once("error",()=>s(!1)),i.once("timeout",()=>{i.destroy(),s(!1)})}))return!0;await new Promise(s=>setTimeout(s,2e3))}return!1}function j_(t){let e="/etc/caddy/Caddyfile";if(!Se.default.existsSync(e)||!am("caddy")){y.warn(`caddy is not running here (or ${e} does not exist) - add this to your web server yourself:
|
|
425
|
+
${na(t)}`);return}let n;try{n=Se.default.readFileSync(e,"utf8")}catch{n=(0,jn.execFileSync)("sudo",["cat",e],{encoding:"utf8",timeout:1e4})}let r=im(n,t.slug,na(t));if(r===n){y.info(`caddy already routes ${t.hostname} - unchanged`);return}let s=Dt.default.join(mi.default.tmpdir(),`Caddyfile-allwright-${process.pid}`);Se.default.writeFileSync(s,r,{mode:420});try{(0,jn.execFileSync)("sudo",["caddy","validate","--config",s,"--adapter","caddyfile"],{encoding:"utf8",timeout:3e4}),et(["cp",e,`${e}.bak.${Math.floor(Date.now()/1e3)}`]),et(["cp",s,e]),et(["systemctl","reload","caddy"]),y.info(`\u2713 caddy: ${t.hostname} \u2192 127.0.0.1:${t.port} (validated, reloaded, backup kept)`)}finally{Se.default.rmSync(s,{force:!0})}}var jn,Se,Dc,mi,Dt,ra,cm=be(()=>{"use strict";jn=require("node:child_process"),Se=I(require("node:fs"),1),Dc=I(require("node:net"),1),mi=I(require("node:os"),1),Dt=I(require("node:path"),1);Xt();_o();ra="# managed by allwright env prepare"});var mm={};un(mm,{buildSetupReport:()=>O_,claudeLoggedIn:()=>fm,repoCurrentBranch:()=>hm,repoDefaultBranch:()=>pm});function hm(t){try{let e=(0,yi.execFileSync)("git",["-C",t,"rev-parse","--abbrev-ref","HEAD"],{encoding:"utf8",timeout:1e4}).trim();return e==="HEAD"?"":e}catch{return""}}function pm(t){let e=(...s)=>{try{return(0,yi.execFileSync)("git",["-C",t,...s],{encoding:"utf8",timeout:1e4}).trim()}catch{return null}},n=e("symbolic-ref","--short","refs/remotes/origin/HEAD");if(n?.startsWith("origin/"))return n.slice(7);let r=e("rev-parse","--abbrev-ref","HEAD");return r&&r!=="HEAD"?r:""}function fm(t=um.default.homedir()){if(Nn.default.existsSync(Br.default.join(t,".claude",".credentials.json")))return!0;try{return!!JSON.parse(Nn.default.readFileSync(Br.default.join(t,".claude.json"),"utf8")).oauthAccount}catch{return!1}}async function O_(t,e,n){let r=!1,s="";if(gi&&Date.now()-gi.at<6e4)r=gi.installed,s=gi.version;else{try{let{stdout:l}=await N_(t.claudeBin,["--version"],{timeout:1e4});r=!0,s=l.trim().slice(0,60)}catch{r=!1}gi={at:Date.now(),installed:r,version:s}}let i=e.map(l=>{let c=t.repos[l];if(!c)return{repoName:l,path:"",mapped:!1,liveMapped:!!n?.repos?.[l],pathExists:!1,isGit:!1,currentBranch:"",claudeMd:!1,deployMd:!1,testMd:!1,githubToken:!1,githubTokenOwn:!1,defaultBranch:""};let u=Nn.default.existsSync(c.path);return{repoName:l,path:c.path,mapped:!0,liveMapped:n?!!n.repos?.[l]:!0,pathExists:u,isGit:u&&Nn.default.existsSync(Br.default.join(c.path,".git")),currentBranch:u?hm(c.path):"",claudeMd:u&&Nn.default.existsSync(Br.default.join(c.path,"CLAUDE.md")),deployMd:u&&Nn.default.existsSync(Br.default.join(c.path,"DEPLOY.md")),testMd:u&&Nn.default.existsSync(Br.default.join(c.path,"TEST.md")),githubToken:!!je(t,l),githubTokenOwn:!!c.github?.token,defaultBranch:u?pm(c.path):""}}),o=Object.values(t.repos).find(l=>l.github?.token);return{jiraConfigured:!!t.jira,jiraEmail:t.jira?.email??"",claude:{installed:r,version:s,loggedIn:fm()},githubTokenSet:!!(t.github?.token||o),githubLogin:t.github?.login??o?.github?.login??"",deploysEnabled:t.deploy.enabled,jiraUserCount:Object.keys(t.jiraUsers).length,repos:i}}var yi,Nn,um,Br,dm,N_,gi,gm=be(()=>{"use strict";yi=require("node:child_process"),Nn=I(require("node:fs"),1),um=I(require("node:os"),1),Br=I(require("node:path"),1),dm=require("node:util");kr();N_=(0,dm.promisify)(yi.execFile);gi=null});var tt=I(require("node:fs"),1),bi=I(require("node:os"),1),an=I(require("node:path"),1),cn=require("node:child_process"),On=require("node:crypto"),Mn=I(require("node:readline/promises"),1);var tu=I(eu(),1),{program:K_,createCommand:G_,createArgument:Z_,createOption:W_,CommanderError:V_,InvalidArgumentError:J_,InvalidOptionArgumentError:Y_,Command:nu,Argument:X_,Option:Q_,Help:eS}=tu.default;Ae();var ji=require("node:child_process"),Je=I(require("node:fs"),1),Ni=I(require("node:path"),1);Ae();var Jg=new Set(["runner.log","runner.pid"]);function Yg(t){return Je.default.readdirSync(t).filter(e=>!Jg.has(e)&&!/\.bak-\d+$/.test(e)).sort()}function bu(t){let e=ie();if(!Je.default.existsSync(e))throw new Error(`nothing to export - ${e} does not exist`);let n=Yg(e);if(!n.length)throw new Error(`nothing to export - ${e} is empty`);let r=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),s=Ni.default.resolve(t||`ticketpilot-backup-${r}.tgz`);return Je.default.writeFileSync(s,"",{mode:384}),(0,ji.execFileSync)("tar",["-czf",s,"-C",e,...n]),Je.default.chmodSync(s,384),{file:s,entries:n}}function wu(t){let e=Ni.default.resolve(t);if(!Je.default.existsSync(e))throw new Error(`backup file not found: ${e}`);let n=(0,ji.execFileSync)("tar",["-tzf",e],{encoding:"utf8"}).split(`
|
|
426
|
+
`).filter(Boolean);for(let i of n)if(i.startsWith("/")||i.split("/").includes(".."))throw new Error(`refusing to import - unsafe path in archive: ${i}`);let r=ie(),s;Je.default.existsSync(r)&&Je.default.readdirSync(r).length&&(s=`${r}.bak-${Date.now()}`,Je.default.renameSync(r,s)),Je.default.mkdirSync(r,{recursive:!0,mode:448}),(0,ji.execFileSync)("tar",["-xzf",e,"-C",r]);for(let i of Je.default.readdirSync(r)){let o=Ni.default.join(r,i);Je.default.statSync(o).isFile()&&Je.default.chmodSync(o,384)}return{restored:n.map(i=>i.replace(/\/$/,"")).sort(),previousDir:s}}var Qr=I(require("node:fs"),1),mn=I(require("node:path"),1),Oi=".ticketpilot-attachments",Xg=15*1024*1024,Qg=50*1024*1024,vu=20;function ku(t,e){let n=mn.default.basename(t).replace(/[^\w.\- ()]/g,"_").replace(/^\.+/,"").slice(-100)||"file",r=n,s=1;for(;e.has(r);)r=`${s++}-${n}`;return e.add(r),r}async function es(t,e,n,r){if(!e.length)return"";let s=mn.default.join(n,Oi);Qr.default.mkdirSync(s,{recursive:!0});let i=new Set,o=[],l=0;for(let c of e){if(o.length>=vu){r("warn",`attachment cap reached (${vu} files) - skipping the rest`);break}if(c.size>Xg){r("warn",`skipping attachment "${c.filename}" - ${ny(c.size)} MB exceeds the 15 MB limit`);continue}if(l+c.size>Qg){r("warn",`attachment size budget reached - skipping "${c.filename}" and the rest`);break}try{let u=await t.downloadAttachment(c.contentUrl),h=ku(c.filename,i);Qr.default.writeFileSync(mn.default.join(s,h),u),l+=u.length,o.push(`- ${Oi}/${h} (${c.mimeType||"unknown type"}, ${Aa(u.length)} KB)`),r("info",`Downloaded attachment "${c.filename}" (${Aa(u.length)} KB)`)}catch(u){r("warn",`could not download attachment "${c.filename}": ${u instanceof Error?u.message:u}`)}}return o.length?`
|
|
427
427
|
|
|
428
428
|
Files attached to the Jira ticket, downloaded locally for this run. They are reference material and NOT part of the repository - never commit, copy, or edit them:
|
|
429
429
|
${o.join(`
|
|
430
430
|
`)}
|
|
431
|
-
Read them with the Read tool when relevant; images (screenshots) can be viewed directly.`:(gn(n),"")}function gn(t){Qr.default.rmSync(mn.default.join(t,
|
|
431
|
+
Read them with the Read tool when relevant; images (screenshots) can be viewed directly.`:(gn(n),"")}function gn(t){Qr.default.rmSync(mn.default.join(t,Oi),{recursive:!0,force:!0})}var ey=4*1024*1024,ty=16*1024*1024;function _u(t,e,n){let r=mn.default.join(t,Oi,`chat-${e.replace(/[^\w-]/g,"")}`);if(!n.length)return{section:"",dir:r};Qr.default.mkdirSync(r,{recursive:!0});let s=new Set,i=[],o=0,l=mn.default.relative(t,r);for(let u of n){let h=Buffer.from(u.contentBase64,"base64");if(h.length>ey||o+h.length>ty){i.push(`- (skipped "${u.name}" - over the upload size budget)`);continue}let f=ku(u.name,s);Qr.default.writeFileSync(mn.default.join(r,f),h),o+=h.length,i.push(`- ${l}/${f} (${Aa(h.length)} KB)`)}return{section:`
|
|
432
432
|
|
|
433
433
|
The user attached file(s) with this message, staged locally for you. They are reference material and NOT part of the repository - never commit, copy, or edit them. If a ticket is created from this chat, these files are attached to it automatically, so reference them by filename instead of pasting their content:
|
|
434
434
|
${i.join(`
|
|
435
435
|
`)}
|
|
436
|
-
Read them with the Read tool; images can be viewed directly.`,dir:r}}var Aa=t=>Math.max(1,Math.round(t/1024)),
|
|
436
|
+
Read them with the Read tool; images can be viewed directly.`,dir:r}}var Aa=t=>Math.max(1,Math.round(t/1024)),ny=t=>Math.round(t/(1024*1024)*10)/10;var Ee=I(require("node:fs"),1),zi=I(require("node:path"),1);Ae();function ts(){return zi.default.join(ie(),"runner.pid")}function Mi(){return zi.default.join(ie(),"runner.log")}function Su(){Ee.default.mkdirSync(ie(),{recursive:!0,mode:448});let t=Ee.default.openSync(Mi(),"a",384);try{Ee.default.chmodSync(Mi(),384)}catch{}return t}function Qn(){let t=ts();if(!Ee.default.existsSync(t))return null;let e=Number(Ee.default.readFileSync(t,"utf8").trim());return Number.isFinite(e)&&e>0?e:null}function er(t){try{return process.kill(t,0),!0}catch{return!1}}function Tu(t){Ee.default.mkdirSync(ie(),{recursive:!0,mode:448}),Ee.default.writeFileSync(ts(),String(t),{mode:384})}function xu(t){Qn()===t&&Ee.default.rmSync(ts(),{force:!0})}function Ea(){return zi.default.join(ie(),"runner.lock")}function ns(){let t=Ea();if(!Ee.default.existsSync(t))return null;let e=Number(Ee.default.readFileSync(t,"utf8").trim());return!Number.isFinite(e)||e<=0||e===process.pid?null:er(e)?e:null}function Ru(){let t=ns();return t?{ok:!1,pid:t}:(Ee.default.mkdirSync(ie(),{recursive:!0,mode:448}),Ee.default.writeFileSync(Ea(),String(process.pid),{mode:384}),{ok:!0})}function Ca(){try{let t=Ea();Ee.default.existsSync(t)&&Number(Ee.default.readFileSync(t,"utf8").trim())===process.pid&&Ee.default.rmSync(t,{force:!0})}catch{}}function Iu(t){try{let e=Ee.default.readFileSync(`/proc/${t}/cgroup`,"utf8"),n=/\/([A-Za-z0-9._@-]+)\.service/.exec(e);return n?n[1]:null}catch{return null}}var Ki=I(require("node:fs"),1),Hs=I(require("node:path"),1),Xu=I(ke(),1);Ae();async function Qu(t,e){let n=await fetch(new URL("/api/runners/enroll",t.controlPlaneUrl),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enrollToken:e,name:t.runnerName,platform:`${process.platform}/${process.arch}`,runnerVersion:Gi})});if(!n.ok){let i=await n.text().catch(()=>"");throw new Error(`enrollment failed (${n.status}): ${i.slice(0,300)}`)}let r=Xu.EnrollResponse.parse(await n.json()),s={...t,runnerId:r.runnerId,runnerToken:r.runnerToken};return ye(s),s}function Pb(){try{let t=process.argv[1]?Ki.default.realpathSync(process.argv[1]):"";for(let e of[Hs.default.dirname(t),Hs.default.dirname(Hs.default.dirname(t))]){let n=Hs.default.join(e,"package.json");if(!Ki.default.existsSync(n))continue;let r=JSON.parse(Ki.default.readFileSync(n,"utf8")).version;if(typeof r=="string"&&r)return r}}catch{}return"0.0.0"}var Gi=Pb();Ct();var cd="Posted automatically by Allwright",jb=["Posted automatically by TicketPilot"],$t=t=>t.includes(cd)||jb.some(e=>t.includes(e));var Nb="no Jira credentials on this runner - add them with `allwright jira set-default`";function el(){return new Pe({baseUrl:"",email:"",apiToken:""},!1)}var Pe=class{constructor(e,n=!0){this.auth=e;this.configured=n}auth;configured;get isConfigured(){return this.configured}assertConfigured(){if(!this.configured)throw new Error(Nb)}headers(){return{Authorization:`Basic ${Buffer.from(`${this.auth.email}:${this.auth.apiToken}`).toString("base64")}`,Accept:"application/json","Content-Type":"application/json"}}async request(e,n,r){this.assertConfigured();let s=new URL(n,this.auth.baseUrl).toString(),i=await fetch(s,{method:e,headers:this.headers(),body:r===void 0?void 0:JSON.stringify(r)});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`Jira ${e} ${n} -> ${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,n=20){let r=await this.userSearch(e,n);return r.length||!e.includes("@")?r:this.userSearch(e.slice(0,e.indexOf("@")),n)}async userSearch(e,n){return e.trim()?(await this.request("GET",`/rest/api/3/user/search?query=${encodeURIComponent(e)}&maxResults=${n}`)??[]).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,n=20){return((await this.request("POST","/rest/api/3/search/jql",{jql:e,maxResults:n,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 n=await this.request("GET",`/rest/api/3/project/${encodeURIComponent(e)}/statuses`),r=new Map;for(let i of n??[])for(let o of i.statuses??[])o.name&&!r.has(o.name)&&r.set(o.name,o.statusCategory?.key??"indeterminate");let s=i=>i==="new"?0:i==="done"?2:1;return[...r.entries()].sort((i,o)=>s(i[1])-s(o[1])).map(([i])=>i)}async searchEpics(e,n=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:n,fields:["summary","status"]})).issues??[]).map(s=>({key:s.key,summary:s.fields?.summary??"",status:s.fields?.status?.name??""}))}async epicChildren(e,n=50){return((await this.request("POST","/rest/api/3/search/jql",{jql:`parent = "${e}" ORDER BY created ASC`,maxResults:n,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,n=100){return((await this.request("POST","/rest/api/3/search/jql",{jql:e,maxResults:n,fields:["summary","status","labels"]})).issues??[]).map(s=>({key:s.key,summary:s.fields?.summary??"",status:s.fields?.status?.name??"(no status)",statusId:s.fields?.status?.id??"",labels:s.fields?.labels??[]}))}async boardColumns(e){try{let r=(await this.request("GET",`/rest/agile/1.0/board?projectKeyOrId=${encodeURIComponent(e)}`)).values?.[0]?.id;if(!r)return null;let i=((await this.request("GET",`/rest/agile/1.0/board/${r}/configuration`)).columnConfig?.columns??[]).filter(o=>(o.statuses??[]).length>0&&o.name).map(o=>({name:o.name,statusIds:(o.statuses??[]).map(l=>l.id??"").filter(Boolean)}));return i.length?i:null}catch{return null}}async getIssue(e){let n=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}?fields=summary,description,labels,comment,status,attachment`),r;try{r=await this.listAllComments(e)}catch{r=n.fields.comment?.comments??[]}let s=r.map(o=>({id:o.id??"",author:o.author?.displayName??"unknown",authorAccountId:o.author?.accountId??null,created:o.created,body:ld(o.body)})),i=(n.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:n.key,summary:n.fields.summary??"",description:ld(n.fields.description),labels:n.fields.labels??[],status:n.fields.status?.name??"",comments:s,attachments:i}}async listAllComments(e){let n=await this.fetchCommentPage(e,0),r=n.total??n.comments.length;if(r<=n.comments.length)return n.comments;let s=Math.max(0,r-200),i=s===0?[...n.comments]:[];for(;i.length<Math.min(r,200);){let o=await this.fetchCommentPage(e,s+i.length);if(!o.comments.length)break;i.push(...o.comments)}return i.slice(-200)}async fetchCommentPage(e,n){let r=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}/comment?startAt=${n}&maxResults=100`);return{comments:r.comments??[],total:r.total}}async downloadAttachment(e){this.assertConfigured();let n=await fetch(e,{headers:this.headers()});if(!n.ok)throw new Error(`attachment download failed: ${n.status}`);return Buffer.from(await n.arrayBuffer())}async lastEnteredStatus(e,n){let r=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}?expand=changelog&fields=status`),s=n.toLowerCase(),i=null;for(let o of r.changelog?.histories??[])(o.items??[]).some(c=>(c.field==="status"||c.fieldId==="status")&&(c.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,n,r,s="Task",i){return{key:(await this.request("POST","/rest/api/3/issue",{fields:{project:{key:e},issuetype:{name:s},summary:n.slice(0,250),description:Qa(r),...i?{parent:{key:i}}:{}}})).key}}async addAttachments(e,n){if(!n.length)return;this.assertConfigured();let r=new FormData;for(let l of n)r.append("file",new Blob([new Uint8Array(l.content)]),l.name.slice(0,255));let s=new URL(`/rest/api/3/issue/${encodeURIComponent(e)}/attachments`,this.auth.baseUrl).toString(),i=Buffer.from(`${this.auth.email}:${this.auth.apiToken}`).toString("base64"),o=await fetch(s,{method:"POST",headers:{Authorization:`Basic ${i}`,Accept:"application/json","X-Atlassian-Token":"no-check"},body:r});if(!o.ok)throw new Error(`Jira attachment upload failed: HTTP ${o.status}`)}async addTriggerComment(e,n){await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/comment`,{body:Qa(n)})}async addComment(e,n){let r=`${n}
|
|
437
437
|
|
|
438
438
|
---
|
|
439
|
-
_${
|
|
439
|
+
_${cd} - never treated as a trigger._`;await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/comment`,{body:Qa(r)})}async editLabels(e,n){let r=[...(n.add??[]).map(s=>({add:s})),...(n.remove??[]).map(s=>({remove:s}))];await this.request("PUT",`/rest/api/3/issue/${encodeURIComponent(e)}`,{update:{labels:r}})}async getTransitions(e){return((await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}/transitions`)).transitions??[]).map(r=>({id:r.id,name:r.name}))}async transition(e,n){await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/transitions`,{transition:{id:n}})}async transitionByName(e,n){let s=(await this.getTransitions(e)).find(i=>i.name.toLowerCase()===n.toLowerCase());return s?(await this.transition(e,s.id),!0):!1}};function ld(t){if(!t)return"";let e=[],n=r=>{r.text&&e.push(r.text),r.type==="hardBreak"&&e.push(`
|
|
440
440
|
`);for(let s of r.content??[])n(s);r.type&&["paragraph","heading","listItem","codeBlock","blockquote"].includes(r.type)&&e.push(`
|
|
441
441
|
`)};return n(t),e.join("").replace(/\n{3,}/g,`
|
|
442
442
|
|
|
443
|
-
`).trim()}function
|
|
443
|
+
`).trim()}function Qa(t){let e=t.replace(/\r\n/g,`
|
|
444
444
|
`).split(`
|
|
445
|
-
`),n=[],r=0,s=i=>{let o=[],l=/(\*\*[^*]+\*\*|`[^`]+`)/g,c=0,u;for(;(u=l.exec(i))!==null;){u.index>c&&o.push({type:"text",text:i.slice(c,u.index)});let
|
|
446
|
-
`)||" "}]});continue}let l=i.match(/^(#{1,6})\s+(.*)$/);if(l){n.push({type:"heading",attrs:{level:l[1].length},content:s(l[2])}),r++;continue}if(i.match(/^\s*[-*]\s+(.*)$/)){let f=[];for(;r<e.length;){let b=e[r].match(/^\s*[-*]\s+(.*)$/);if(!b)break;f.push({type:"listItem",content:[{type:"paragraph",content:s(b[1])}]}),r++}n.push({type:"bulletList",content:f});continue}if(i.match(/^\s*\d+[.)]\s+(.*)$/)){let f=[];for(;r<e.length;){let b=e[r].match(/^\s*\d+[.)]\s+(.*)$/);if(!b)break;f.push({type:"listItem",content:[{type:"paragraph",content:s(b[1])}]}),r++}n.push({type:"orderedList",content:f});continue}let
|
|
445
|
+
`),n=[],r=0,s=i=>{let o=[],l=/(\*\*[^*]+\*\*|`[^`]+`)/g,c=0,u;for(;(u=l.exec(i))!==null;){u.index>c&&o.push({type:"text",text:i.slice(c,u.index)});let h=u[0];h.startsWith("**")?o.push({type:"text",text:h.slice(2,-2),marks:[{type:"strong"}]}):o.push({type:"text",text:h.slice(1,-1),marks:[{type:"code"}]}),c=u.index+h.length}return c<i.length&&o.push({type:"text",text:i.slice(c)}),o.length?o:[{type:"text",text:" "}]};for(;r<e.length;){let i=e[r];if(i.trim()===""){r++;continue}let o=i.match(/^```(\w*)\s*$/);if(o){let f=[];for(r++;r<e.length&&!/^```\s*$/.test(e[r]);)f.push(e[r]),r++;r++,n.push({type:"codeBlock",attrs:o[1]?{language:o[1]}:{},content:[{type:"text",text:f.join(`
|
|
446
|
+
`)||" "}]});continue}let l=i.match(/^(#{1,6})\s+(.*)$/);if(l){n.push({type:"heading",attrs:{level:l[1].length},content:s(l[2])}),r++;continue}if(i.match(/^\s*[-*]\s+(.*)$/)){let f=[];for(;r<e.length;){let b=e[r].match(/^\s*[-*]\s+(.*)$/);if(!b)break;f.push({type:"listItem",content:[{type:"paragraph",content:s(b[1])}]}),r++}n.push({type:"bulletList",content:f});continue}if(i.match(/^\s*\d+[.)]\s+(.*)$/)){let f=[];for(;r<e.length;){let b=e[r].match(/^\s*\d+[.)]\s+(.*)$/);if(!b)break;f.push({type:"listItem",content:[{type:"paragraph",content:s(b[1])}]}),r++}n.push({type:"orderedList",content:f});continue}let h=[i];for(r++;r<e.length&&e[r].trim()!==""&&!/^(#{1,6}\s|```|\s*[-*]\s|\s*\d+[.)]\s)/.test(e[r]);)h.push(e[r]),r++;n.push({type:"paragraph",content:s(h.join(" "))})}return{type:"doc",version:1,content:n}}function ud(t,e,n){let r=t.repos[e]?.jira??t.jira;if(!r)return{kind:"legacy"};let s=n.trim().toLowerCase();if(!s)return{kind:"legacy"};if(s===r.email.toLowerCase())return{kind:"self"};let i=t.jiraUsers[s];return i?{kind:"user",creds:{baseUrl:r.baseUrl,email:i.email,apiToken:i.apiToken}}:{kind:"missing",error:`Jira actions from Allwright post under YOUR OWN Atlassian identity, and no Jira credential is set up for ${s} on the runner yet. Ask your admin to run this on the runner machine:
|
|
447
447
|
|
|
448
448
|
allwright jira user-add ${s}
|
|
449
449
|
|
|
450
|
-
It prompts for your Atlassian email and an API token (create one at id.atlassian.com -> Security -> API tokens). Takes effect immediately - then just retry this action.`}}function
|
|
450
|
+
It prompts for your Atlassian email and an API token (create one at id.atlassian.com -> Security -> API tokens). Takes effect immediately - then just retry this action.`}}function dd(t){let e=[t.jiraUrl,t.jiraEmail,t.jiraToken].filter(n=>!!n?.trim());if(t.jira===!1){if(e.length)throw new Error("--no-jira and --jira-url/--jira-email/--jira-token contradict each other - pass one or the other, never both.");return"skip"}return e.length===3?"flags":e.length?"prompt":"offer-skip"}function hd(t){return["s","skip","n","no","later"].includes(t.trim().toLowerCase())}kr();var In=require("node:child_process"),An=I(require("node:fs"),1),eo=I(require("node:os"),1),ps=I(require("node:path"),1),md=I(ke(),1);var hs="allwright",fd=`/etc/systemd/system/${hs}.service`,to="ticketpilot-runner";function nl(){let t=process.env.SUDO_USER&&process.env.SUDO_USER!=="root"?process.env.SUDO_USER:"",e=t||eo.default.userInfo().username,n=t?ps.default.join("/home",t):eo.default.homedir();return{nodePath:process.execPath,scriptPath:An.default.realpathSync(process.argv[1]),user:e,home:n}}function rl(t){let e=ps.default.dirname(t.nodePath);return`[Unit]
|
|
451
451
|
Description=Allwright runner
|
|
452
452
|
After=network-online.target
|
|
453
453
|
|
|
@@ -465,8 +465,8 @@ TimeoutStopSec=2h
|
|
|
465
465
|
|
|
466
466
|
[Install]
|
|
467
467
|
WantedBy=multi-user.target
|
|
468
|
-
`}function
|
|
469
|
-
`+n);return}try{(0,
|
|
468
|
+
`}function sl(){return process.platform==="linux"&&An.default.existsSync("/run/systemd/system")}function gd(t){if(!sl())throw new Error(process.platform==="win32"?"Windows service install isn't built in yet - use NSSM: nssm install allwright <node> <this script> start --foreground":"no systemd on this machine - run `allwright start` (background mode) instead");let e=nl(),n=rl(e);if(typeof process.getuid=="function"&&process.getuid()!==0){t.info("Root is needed to write the unit. Re-run as:"),t.info(' sudo env "PATH=$PATH" allwright service install'),t.info("(the env PATH part matters when node is installed via nvm - plain sudo can't find it)"),t.info(""),t.info(`This is exactly what it will write to ${fd}:`),t.info(`
|
|
469
|
+
`+n);return}try{(0,In.execFileSync)("systemctl",["disable","--now",to]),t.info(`stopped the old ${to} service - this one replaces it`)}catch{}let r=ns();if(r)try{process.kill(r,"SIGTERM"),t.info(`stopped the running runner (pid ${r}) - the service takes over`)}catch{}An.default.writeFileSync(fd,n),(0,In.execFileSync)("systemctl",["daemon-reload"]),(0,In.execFileSync)("systemctl",["enable","--now",hs]),(0,In.execFileSync)("systemctl",["restart",hs]),t.info(`Installed and started (runs as ${e.user}, survives reboots).`),t.info(`Watch it: journalctl -u ${hs} -f`),t.info("Status: allwright service status")}function Ob(t){if(t.override)return[ps.default.join(t.override,"runner.json")];let e=[];for(let n of t.homes)for(let r of["allwright","ticketpilot"]){let s=ps.default.join(n,".config",r,"runner.json");e.includes(s)||e.push(s)}return e}function Mb(){let t=process.env.SUDO_USER&&process.env.SUDO_USER!=="root"?process.env.SUDO_USER:"",e=[eo.default.homedir()];return t&&e.push(ps.default.join("/home",t)),Ob({override:process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR,homes:e})}function zb(){let t={removed:!1,paths:[],problems:[]};for(let e of Mb())if(An.default.existsSync(e))try{An.default.rmSync(e),t.removed=!0,t.paths.push(e)}catch(n){t.problems.push(`could not delete ${e}: ${n instanceof Error?n.message:String(n)}`)}return t}function il(){return typeof process.getuid!="function"||process.getuid()===0}function tl(t){if(il()){(0,In.execFileSync)("systemctl",t,{stdio:"ignore"});return}(0,In.execFileSync)("sudo",["-n","systemctl",...t],{stdio:"ignore"})}function Db(t){if(il()){An.default.rmSync(t);return}(0,In.execFileSync)("sudo",["-n","rm","-f",t],{stdio:"ignore"})}function Lb(){if(!sl())return{removed:!1,absent:!0,error:""};let t=[hs,to].map(e=>({name:e,file:`/etc/systemd/system/${e}.service`})).filter(e=>An.default.existsSync(e.file));if(t.length===0)return{removed:!1,absent:!0,error:""};try{for(let e of t){try{tl(["disable",e.name])}catch{}Db(e.file)}return tl(["daemon-reload"]),{removed:!0,absent:!1,error:""}}catch(e){let n=e instanceof Error?e.message:String(e);return{removed:!1,absent:!1,error:il()?`could not remove the systemd unit: ${n}`:"removing the systemd unit needs root, and this runner does not have passwordless sudo"}}}function ol(){if(sl())for(let t of[hs,to])try{tl(["stop",t])}catch{}}function al(){let t=Lb(),e={serviceRemoved:t.removed,serviceAbsent:t.absent,configRemoved:!1,removedPaths:[],problems:[]};if(t.error)return e.problems.push(`${t.error} - finish with: ${md.RUNNER_UNINSTALL_COMMAND}`),e;let n=zb();return e.configRemoved=n.removed,e.removedPaths=n.paths,e.problems=n.problems,e}function yd(t){let e=al();e.serviceRemoved?(ol(),t.info("Service stopped and removed.")):e.serviceAbsent&&t.info("No systemd service was installed here - nothing to stop.");for(let n of e.removedPaths)t.info(`Deleted ${n} - the Jira and GitHub tokens on this machine went with it.`);if(!e.configRemoved&&e.problems.length===0&&t.info("No runner config was found - there were no credentials left to delete."),t.info("Checkouts on disk were NOT touched - remove them yourself if you want them gone."),e.problems.length>0)throw new Error(e.problems.join("; "))}var bd=I(ke(),1);function wd(t){return t.filter(e=>e.statusCategory!=="done"&&!e.labels.includes("agent-implemented")&&!e.labels.includes(bd.NEEDS_INPUT_LABEL))}function vd(t,e,n){let r=n.map(s=>{let i=(s.description??"").trim().slice(0,600);return`- ${s.key} [${s.status}] ${s.summary}${i?`
|
|
470
470
|
${i.replace(/\n+/g," ")}`:""}`}).join(`
|
|
471
471
|
`);return`You are looking at this repository to help sequence work on the Jira epic ${t} ("${e}"). These child tickets are still pending:
|
|
472
472
|
|
|
@@ -477,9 +477,9 @@ Pick the ONE ticket that should be implemented FIRST. Weigh, in this order: (1)
|
|
|
477
477
|
Answer with ONLY a fenced json block, nothing after it:
|
|
478
478
|
\`\`\`json
|
|
479
479
|
{"issueKey": "<one of the keys above>", "reason": "<2-3 sentences: why this one first, and what it unblocks>"}
|
|
480
|
-
\`\`\``}function
|
|
480
|
+
\`\`\``}function kd(t,e){let r=t.match(/```(?:json)?\s*(\{[\s\S]*?\})\s*```/)?.[1]??t.match(/\{[\s\S]*"issueKey"[\s\S]*?\}/)?.[0];if(!r)return{error:"the agent's answer contained no JSON recommendation"};try{let s=JSON.parse(r),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 yl=require("node:crypto"),Yd=I(require("node:fs"),1);var ll=I(require("node:fs"),1),no=I(require("node:path"),1),ro=I(ke(),1),Ub={security:"You are a security auditor. You can READ this repository; you can never run or change anything. Audit it against the knowledge packs below and report real, exploitable-here problems - not checklist theatre.",testing:"You are a test-coverage auditor. You can READ this repository (code and tests); you can never run anything. Find what is untested and fragile against the knowledge packs below - gaps that would actually bite this product, not generic coverage philosophy.",architecture:"You are a software architecture auditor. You can READ this repository; you can never run or change anything. Judge whether it is structurally HEALTHY for what it is trying to be, against the knowledge packs below - real structural pain for this team, not textbook purity.",functional:"You are a functional tester of the RUNNING site. The runner has already crawled it - the transcript is below, and it is your primary evidence; the repository is open READ-ONLY so you can trace a broken page to its code. Report what a real visitor hits: broken links (with the page that links there), errors, missing pages, mixed content, slow responses. The crawl ran without JavaScript - never claim client-side behaviour was checked. Every finding cites a URL from the crawl AND, where you traced it, the file behind it."};function Sd(t,e,n,r={}){let s=e.map(h=>`### Pack: ${h.name}
|
|
481
481
|
|
|
482
|
-
${
|
|
482
|
+
${h.content}`).join(`
|
|
483
483
|
|
|
484
484
|
`),i=n.trim()?`
|
|
485
485
|
|
|
@@ -506,7 +506,7 @@ This transcript is your PRIMARY evidence. A URL with issues becomes a finding; t
|
|
|
506
506
|
### WRITING STYLE - plain language
|
|
507
507
|
|
|
508
508
|
This report is for a non-technical reader. Write "summary", every finding's "title" and every "fix" in plain, everyday English: no jargon, no acronyms, no framework or library names in the title, no code in the prose. For each finding say in 2-3 short sentences what the problem means for the business or for a user - what could go wrong, who it affects, what to do about it - rather than how it is implemented.
|
|
509
|
-
This changes the WORDING ONLY. "evidence" (real file, real line), "ruleId", "severity" and "area" are filled in EXACTLY as they would be otherwise - the same evidence rule applies, and a finding without real evidence is still DELETED. Never skip or soften evidence to keep the text simple.`:"";return`${
|
|
509
|
+
This changes the WORDING ONLY. "evidence" (real file, real line), "ruleId", "severity" and "area" are filled in EXACTLY as they would be otherwise - the same evidence rule applies, and a finding without real evidence is still DELETED. Never skip or soften evidence to keep the text simple.`:"";return`${Ub[t]}
|
|
510
510
|
|
|
511
511
|
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.
|
|
512
512
|
|
|
@@ -520,25 +520,25 @@ Explore the repository first - entry points, routes, storage, tests - then audit
|
|
|
520
520
|
"evidence": [{"file": "<repo-relative path>", "line": <number, omit if n/a>, "note": "<what is there>"}],
|
|
521
521
|
"fix": "<2-4 sentences: concrete fix, specific to this code>"}]}
|
|
522
522
|
\`\`\`
|
|
523
|
-
Rules: every finding needs at least one evidence file you actually read - findings without real evidence will be DELETED from your report. Max 25 findings, worst first. An empty findings list with an honest summary is a valid, good answer.`+u}function
|
|
524
|
-
`).length:0}catch{return null}}function
|
|
525
|
-
`).some(i=>i.trim()
|
|
523
|
+
Rules: every finding needs at least one evidence file you actually read - findings without real evidence will be DELETED from your report. Max 25 findings, worst first. An empty findings list with an honest summary is a valid, good answer.`+u}function Td(t){let n=t.match(/```(?:json)?\s*(\{[\s\S]*\})\s*```(?![\s\S]*```)/)?.[1]??t.match(/\{[\s\S]*"findings"[\s\S]*\}/)?.[0];if(!n)return{error:"the agent's report contained no JSON block"};let r;try{r=JSON.parse(n)}catch{return{error:"the agent's JSON report did not parse"}}if(!Array.isArray(r.findings))return{error:"the report has no findings array"};let s=[],i=0,o=new Set;for(let l of r.findings.slice(0,25)){let c=qb(l),u=c?ro.AuditFinding.safeParse(c):null;if(!u?.success){i++;continue}let h=u.data.id;for(;o.has(h);)h=`${h}-2`;o.add(h),s.push({...u.data,id:h})}return{summary:typeof r.summary=="string"?r.summary.trim().slice(0,2e3):"",findings:s,dropped:i}}function qb(t){if(typeof t!="object"||t===null)return null;let e=t,n=typeof e.severity=="string"?e.severity.toLowerCase():"",r=Array.isArray(e.evidence)?e.evidence.filter(i=>typeof i=="object"&&i!==null).map(i=>({file:typeof i.file=="string"?i.file:"",..._d(i.line)?{line:_d(i.line)}:{},note:typeof i.note=="string"?i.note:""})).filter(i=>i.file):[],s=typeof e.ruleId=="string"?e.ruleId.trim().toUpperCase():"";return{id:Fb(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:ro.AuditSeverity.options.includes(n)?n:void 0,area:typeof e.area=="string"?e.area.slice(0,60):"",evidence:r,fix:typeof e.fix=="string"?e.fix.slice(0,2e3):""}}function _d(t){let e=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):NaN;return Number.isInteger(e)&&e>0?e:void 0}function Fb(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"finding"}function Bb(t){try{let e=ll.default.readFileSync(t,"utf8");return e?e.split(`
|
|
524
|
+
`).length:0}catch{return null}}function xd(t,e){let n=no.default.resolve(t),r=[],s=[],i=0;for(let o of e){let l=[];for(let c of o.evidence){let u=c.file.trim().replace(/^\.\//,""),h=no.default.resolve(n,u);if(h!==n&&!h.startsWith(n+no.default.sep))continue;let f;try{f=ll.default.statSync(h)}catch{continue}if(f.isFile()){if(c.line!==void 0){let b=Bb(h);if(b!==null&&c.line>b){l.push({...c,line:void 0}),i++;continue}}l.push(c)}}if(!l.length){s.push({title:o.title,files:o.evidence.map(c=>c.file)});continue}r.push({...o,evidence:l})}return{findings:r,droppedFindings:s,correctedLines:i}}var Gs=I(require("node:fs"),1),cl=I(require("node:path"),1),Rd=I(ke(),1);Ae();var Hb=20;function Id(){return cl.default.join(ie(),"audits.json")}function fs(){try{return{byProject:JSON.parse(Gs.default.readFileSync(Id(),"utf8")).byProject??{}}}catch{return{byProject:{}}}}function Ad(t){let e=Id();Gs.default.mkdirSync(cl.default.dirname(e),{recursive:!0,mode:448});let n=e+".tmp";Gs.default.writeFileSync(n,JSON.stringify(t,null,2),{mode:384}),Gs.default.renameSync(n,e)}function Ed(t,e){let n=fs(),r=n.byProject[t]??[];r.unshift(Rd.AuditRecord.parse(e)),n.byProject[t]=r.slice(0,Hb),Ad(n)}function Cd(t){return(fs().byProject[t]??[]).map(e=>{let n={};for(let r of e.findings)n[r.severity]=(n[r.severity]??0)+1;return{id:e.id,role:e.role,createdAt:e.createdAt,findingCount:e.findings.length,bySeverity:n,detailLevel:e.detailLevel??"technical"}})}function $d(t,e){let n=fs(),r=e?Date.parse(e):NaN,s={};for(let i of t){let o=(n.byProject[i]??[]).filter(c=>!Number.isFinite(r)||Date.parse(c.createdAt)>=r);if(!o.length)continue;let l={audits:o.length,findings:0,valid:0,falsePositive:0,wontFix:0,unreviewed:0};for(let c of o){l.findings+=c.findings.length;for(let u of c.findings){let h=c.verdicts[u.id]?.verdict;h==="valid"?l.valid++:h==="false-positive"?l.falsePositive++:h==="wont-fix"?l.wontFix++:l.unreviewed++}}s[i]=l}return s}function ul(t,e,n){let r=fs(),i=(r.byProject[t]??[]).find(l=>l.id===e);if(!i)return null;i.ticketed??={},i.verdicts??={},i.lessonsWritten??=[];let o=new Set(i.findings.map(l=>l.id));n.selected&&(i.review={selected:n.selected.filter(l=>o.has(l)),updatedAt:new Date().toISOString()});for(let l of n.ticketed??[])o.has(l.findingId)&&(i.ticketed={...i.ticketed,[l.findingId]:l.issueKey});for(let l of n.verdicts??[])o.has(l.findingId)&&(i.verdicts={...i.verdicts,[l.findingId]:{verdict:l.verdict,note:l.note,by:n.verdictBy??"",at:new Date().toISOString()}});for(let l of n.markLessonsWritten??[])o.has(l)&&!i.lessonsWritten.includes(l)&&i.lessonsWritten.push(l);return Ad(r),i}function Pd(t,e){return(fs().byProject[t]??[]).find(s=>s.role===e&&(s.scope?.kind??"repo")==="repo")?.createdAt??null}function dl(t,e){return(fs().byProject[t]??[]).find(n=>n.id===e)??null}Ct();var ze=I(require("node:fs"),1),Pt=I(require("node:path"),1),zd=I(ke(),1);var Ne=I(require("node:fs"),1),vt=I(require("node:path"),1),Kb=25e4,Gb=2e5,jd="/.ticketpilot/memory/";function Zb(t){let e=vt.default.join(t,".git"),n;try{n=Ne.default.statSync(e)}catch{return null}if(n.isDirectory())return vt.default.join(e,"info");let r=/^gitdir:\s*(.+)$/m.exec(Ne.default.readFileSync(e,"utf8"));if(!r?.[1])return null;let s=vt.default.resolve(t,r[1].trim());try{let i=Ne.default.readFileSync(vt.default.join(s,"commondir"),"utf8").trim();return vt.default.join(vt.default.resolve(s,i),"info")}catch{return vt.default.join(s,"info")}}function Wb(t){try{let e=Zb(t);if(!e)return;let n=vt.default.join(e,"exclude"),r="";try{r=Ne.default.readFileSync(n,"utf8")}catch{}if(r.split(`
|
|
525
|
+
`).some(i=>i.trim()===jd))return;Ne.default.mkdirSync(e,{recursive:!0});let s=r&&!r.endsWith(`
|
|
526
526
|
`)?`
|
|
527
527
|
`:"";Ne.default.appendFileSync(n,`${s}# Allwright runner scratch - see .ticketpilot/memory/
|
|
528
|
-
${
|
|
529
|
-
`)}catch{}}var
|
|
528
|
+
${jd}
|
|
529
|
+
`)}catch{}}var Nd=`# Incident ledger
|
|
530
530
|
|
|
531
531
|
Machine-written facts about this repository's runs: what failed, what
|
|
532
532
|
resolved it. Appended by the Allwright runner; humans may edit freely.
|
|
533
533
|
Newest entries are at the bottom.
|
|
534
534
|
|
|
535
|
-
`;function
|
|
535
|
+
`;function hl(t){return vt.default.join(t,".ticketpilot","memory","incidents.md")}function ut(t,e){try{let n=hl(t),r=vt.default.dirname(n);Ne.default.existsSync(r)||(Ne.default.mkdirSync(r,{recursive:!0}),Wb(t));let s=Ne.default.existsSync(n)?"":Nd,i=new Date().toISOString().slice(0,10),o=e.detail?.trim();Ne.default.appendFileSync(n,s+`## ${i} \xB7 ${e.issueKey} \xB7 ${e.title} (run ${e.runId})
|
|
536
536
|
`+(o?`${o.slice(0,1500)}
|
|
537
537
|
`:"")+`
|
|
538
|
-
`),
|
|
539
|
-
## `),i=s===-1?r:r.slice(s+1);Ne.default.writeFileSync(t,
|
|
538
|
+
`),Vb(n)}catch{}}function Zs(t,e){try{return Ne.default.readFileSync(hl(t),"utf8").includes(`\xB7 ${e} \xB7`)}catch{return!1}}function Vb(t){if(Ne.default.statSync(t).size<=Kb)return;let r=Ne.default.readFileSync(t,"utf8").slice(-Gb),s=r.indexOf(`
|
|
539
|
+
## `),i=s===-1?r:r.slice(s+1);Ne.default.writeFileSync(t,Nd+`*(older entries were rotated out)*
|
|
540
540
|
|
|
541
|
-
`+i)}function
|
|
541
|
+
`+i)}function Od(t){try{return Ne.default.readFileSync(hl(t),"utf8")}catch{return null}}Ae();var Jb=`# Security baseline - what to check in any repo
|
|
542
542
|
|
|
543
543
|
Every rule has a stable id. Findings must cite the id they violate.
|
|
544
544
|
|
|
@@ -581,7 +581,7 @@ Every rule has a stable id. Findings must cite the id they violate.
|
|
|
581
581
|
- **SEC-042** TLS/redirect handling that downgrades to http.
|
|
582
582
|
|
|
583
583
|
Prioritize by real exploitability in THIS codebase, not by rule order.
|
|
584
|
-
`,
|
|
584
|
+
`,Yb=`# Test gaps - what to check in any repo
|
|
585
585
|
|
|
586
586
|
Every rule has a stable id. Findings must cite the id they violate.
|
|
587
587
|
|
|
@@ -611,7 +611,7 @@ Every rule has a stable id. Findings must cite the id they violate.
|
|
|
611
611
|
flaky suspects.
|
|
612
612
|
|
|
613
613
|
Report the GAP and why it is risky here, not generic coverage philosophy.
|
|
614
|
-
`,
|
|
614
|
+
`,Xb=`# GDPR readiness - data-protection audit for repos with EU exposure
|
|
615
615
|
|
|
616
616
|
FIRST decide exposure: if this product clearly has no EU users, no personal
|
|
617
617
|
data, or is a purely static/internal tool, say so in ONE summary sentence and
|
|
@@ -655,7 +655,7 @@ rules below. Cite the rule id AND map the area to the closest GDPR article
|
|
|
655
655
|
|
|
656
656
|
Severity: many users' data exposed or a missing legal-basis mechanism is
|
|
657
657
|
high/critical; hygiene and documentation gaps are medium/low.
|
|
658
|
-
`,
|
|
658
|
+
`,Qb=`# Architecture health - is this repository structurally sound?
|
|
659
659
|
|
|
660
660
|
Every rule has a stable id. Findings must cite the id they violate. Judge
|
|
661
661
|
against what THIS codebase is trying to be (a static site does not need
|
|
@@ -694,7 +694,7 @@ deviations.
|
|
|
694
694
|
|
|
695
695
|
Summarize with an overall verdict: is this repository HEALTHY for its
|
|
696
696
|
purpose, and what are the 2-3 structural moves with the best payoff?
|
|
697
|
-
`,
|
|
697
|
+
`,Md={security:[{name:"baseline.md",content:Jb},{name:"gdpr.md",content:Xb}],testing:[{name:"test-gaps.md",content:Yb}],architecture:[{name:"architecture-health.md",content:Qb}],functional:[],implement:[]},ew=["You are auditing code you can READ but never run or change.","You are auditing test coverage by READING code and tests","\\`area\\`"];function pl(t){return Pt.default.join(ie(),"knowledge",t)}function Dd(t,e){return Pt.default.join(t,".ticketpilot","knowledge",`${e}.md`)}function fl(t,e){return Pt.default.join(t,".ticketpilot","lessons",`${e}.md`)}function Ld(t,e){let n=[],r=pl(t),s=[];if(ze.default.existsSync(r)){for(let c of ze.default.readdirSync(r)){if(!c.endsWith(".md"))continue;let u=Pt.default.join(r,c),h=ze.default.readFileSync(u,"utf8");if(ew.some(f=>h.includes(f))&&Md[t].map(b=>b.name).includes(c)&&!h.includes("SEC-0")&&!h.includes("TEST-0")&&!h.includes("GDPR-0")){ze.default.rmSync(u);continue}s.push(c)}s.sort()}let i=new Set(s);for(let c of Md[t])i.has(c.name)||n.push({level:"global",source:"pack",name:c.name,content:c.content,editable:!1});for(let c of s)n.push({level:"org",source:"pack",name:c,content:ze.default.readFileSync(Pt.default.join(r,c),"utf8").slice(0,3e4),editable:!0});let o=Dd(e,t);ze.default.existsSync(o)&&n.push({level:"project",source:"pack",name:`${t}.md`,content:ze.default.readFileSync(o,"utf8").slice(0,3e4),editable:!0});let l=fl(e,t);return ze.default.existsSync(l)&&n.push({level:"project",source:"lessons",name:`${t}.md`,content:ze.default.readFileSync(l,"utf8").slice(0,2e4),editable:!0}),n}function so(t,e){let n=Ld(t,e);return{packs:n.filter(r=>r.source==="pack").map(r=>({name:`${r.level}/${r.name}`,content:r.content})),lessons:n.find(r=>r.source==="lessons")?.content??"",layers:n}}function ml(t,e,n,r="project"){let s=r==="org"?Pt.default.join(pl(e),"org-lessons.md"):fl(t,e);ze.default.mkdirSync(Pt.default.dirname(s),{recursive:!0});let i=ze.default.existsSync(s)?"":`# ${e} lessons (${r} level)
|
|
698
698
|
|
|
699
699
|
Human-confirmed corrections and rules. `+(e==="implement"?`Every implement run on this repo reads this BEFORE starting work.
|
|
700
700
|
|
|
@@ -702,54 +702,54 @@ Human-confirmed corrections and rules. `+(e==="implement"?`Every implement run o
|
|
|
702
702
|
|
|
703
703
|
`);ze.default.appendFileSync(s,i+n.trimEnd()+`
|
|
704
704
|
|
|
705
|
-
`)}function
|
|
705
|
+
`)}function Ud(t,e,n,r){let s=new Date().toISOString().slice(0,10),i=t.evidence[0]?` (${t.evidence[0].file}${t.evidence[0].line?`:${t.evidence[0].line}`:""})`:"",o=t.ruleId?` \xB7 rule ${t.ruleId}`:"";return`## ${s} \xB7 ${e}${o} \xB7 ${t.title}${i}
|
|
706
706
|
Finding \`${t.id}\` [${t.severity}] was marked **${e}**`+(r?` by ${r}`:"")+`.${n?` Reason: ${n}`:""}
|
|
707
|
-
`+(e==="false-positive"?"Do not raise this class of finding here again unless the code meaningfully changes.":"Known and accepted - do not re-raise; mention only if its risk materially grows.")}function
|
|
708
|
-
${t.trim()}`}function
|
|
709
|
-
`).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#"));if(s.length){if(
|
|
710
|
-
[killed: timed out]`},s);u.on("close",w=>{clearTimeout(b),c({command:i,exitCode:w??-1,durationMs:Date.now()-o,tail:
|
|
707
|
+
`+(e==="false-positive"?"Do not raise this class of finding here again unless the code meaningfully changes.":"Known and accepted - do not re-raise; mention only if its risk materially grows.")}function qd(t,e){return`## ${new Date().toISOString().slice(0,10)} \xB7 taught${e?` by ${e}`:""}
|
|
708
|
+
${t.trim()}`}function Fd(t){let e=[];for(let r of zd.KnowledgeRole.options)for(let s of Ld(r,t))e.push({role:r,...s});let n=Od(t);return n&&e.push({role:"implement",level:"project",source:"memory",name:"incidents.md",content:n.slice(-3e4),editable:!1}),e}function Bd(t,e,n,r,s,i){if(!/^[a-zA-Z0-9._-]+\.md$/.test(s))throw new Error("file name must be a simple .md name");let o=n==="org"?Pt.default.join(pl(e),s):r==="lessons"?fl(t,e):Dd(t,e);ze.default.mkdirSync(Pt.default.dirname(o),{recursive:!0}),ze.default.writeFileSync(o,i,{mode:n==="org"?384:420})}Xt();var Hd=require("node:child_process"),Kd=I(require("node:fs"),1),Gd=I(require("node:path"),1);function ms(t){for(let e of["TEST.md","TESTING.md","docs/TEST.md"]){let n=Gd.default.join(t,e);if(Kd.default.existsSync(n))return n}return null}var tw=/(^|\n)\s*(if|for|while|case|until)\s|\{\s*$|\)\s*\{|<<[-~]?\s*['"]?\w+|\\\s*$/;function gs(t){let e=[];for(let n of t.matchAll(/```(?:bash|sh|shell)?\s*\n([\s\S]*?)```/g)){let r=n[1],s=r.split(`
|
|
709
|
+
`).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#"));if(s.length){if(tw.test(r)){e.push(r.trim());continue}e.push(...s)}}return e.slice(0,10)}async function _r(t,e,n={}){let r=[],s=n.perCommandTimeoutMs??6e5;for(let i of e){n.onProgress?.(`running: ${i}`);let o=Date.now(),l=await new Promise(c=>{let u=(0,Hd.spawn)("bash",["-lc",i],{cwd:t,env:{...process.env,CI:"1",FORCE_COLOR:"0"}}),h="",f=w=>{h+=w.toString(),h.length>2e5&&(h=h.slice(-1e5))};u.stdout.on("data",f),u.stderr.on("data",f);let b=setTimeout(()=>{u.kill("SIGKILL"),h+=`
|
|
710
|
+
[killed: timed out]`},s);u.on("close",w=>{clearTimeout(b),c({command:i,exitCode:w??-1,durationMs:Date.now()-o,tail:h.slice(-4e3)})}),u.on("error",w=>{clearTimeout(b),c({command:i,exitCode:-1,durationMs:Date.now()-o,tail:String(w)})})});n.onProgress?.(`exit ${l.exitCode} in ${Math.round(l.durationMs/1e3)}s: ${i}`),r.push(l)}return r}async function ys(t){let{packs:e,lessons:n}=so(t.role,t.repoPath);if(!e.length&&t.role!=="functional")return{ok:!1,error:`no knowledge packs found for the ${t.role} role - add markdown files under ~/.config/ticketpilot/knowledge/${t.role}/ on the runner`};let r;if(t.role==="functional"){if(!t.baseUrl?.trim())return{ok:!1,error:"a functional audit needs a URL to visit - pick the environment (or type the URL) when starting it"};let{crawlSite:w,formatCrawlReport:_}=await Promise.resolve().then(()=>(Jd(),Vd));try{r=_(await w(t.baseUrl.trim()))}catch(S){return{ok:!1,error:`could not crawl ${t.baseUrl}: ${S instanceof Error?S.message:"unreachable"}`}}}let s="";if(t.scope.kind==="ticket"&&t.scope.ref){let w=t.scope.ref,_="";try{let A=await t.jira.getIssue(w);_=`Ticket ${w}: ${A.summary}
|
|
711
711
|
|
|
712
|
-
${
|
|
712
|
+
${A.description}`.slice(0,4e3)}catch{_=`Ticket ${w} (could not fetch its text from Jira).`}let S=await Ha(t.repoPath,w).catch(()=>null);if(S){let{base:A,stat:z,diff:q}=await Yi(t.repoPath,S).catch(()=>({base:"",stat:"",diff:""}));s=`${_}
|
|
713
713
|
|
|
714
|
-
Its implementation branch \`${
|
|
714
|
+
Its implementation branch \`${S}\` vs \`${A}\`:
|
|
715
715
|
\`\`\`
|
|
716
|
-
${
|
|
716
|
+
${z}\`\`\`
|
|
717
717
|
\`\`\`diff
|
|
718
718
|
${q}
|
|
719
|
-
\`\`\``}else s=`${
|
|
719
|
+
\`\`\``}else s=`${_}
|
|
720
720
|
|
|
721
|
-
No implementation branch found for ${w} - audit the parts of the codebase this ticket touches or would touch.`}else if(t.scope.kind==="branch"&&t.scope.ref){let{base:w,stat:
|
|
721
|
+
No implementation branch found for ${w} - audit the parts of the codebase this ticket touches or would touch.`}else if(t.scope.kind==="branch"&&t.scope.ref){let{base:w,stat:_,diff:S}=await Yi(t.repoPath,t.scope.ref);s=`The diff of \`${t.scope.ref}\` vs \`${w}\`:
|
|
722
722
|
\`\`\`
|
|
723
|
-
${
|
|
723
|
+
${_}\`\`\`
|
|
724
724
|
\`\`\`diff
|
|
725
|
-
${
|
|
726
|
-
\`\`\``}let i,o;if(t.role==="testing"){let w=ms(t.repoPath),
|
|
727
|
-
(exit ${
|
|
728
|
-
${
|
|
725
|
+
${S}
|
|
726
|
+
\`\`\``}let i,o;if(t.role==="testing"){let w=ms(t.repoPath),_=w?gs(Yd.default.readFileSync(w,"utf8")):[];_.length&&(y.info(`Audit (testing): executing ${_.length} TEST.md command(s)`),o=await _r(t.repoPath,_,{onProgress:S=>y.info(`[test-run] ${S}`)}),i=o.map(S=>`$ ${S.command}
|
|
727
|
+
(exit ${S.exitCode}, ${Math.round(S.durationMs/1e3)}s)
|
|
728
|
+
${S.tail.slice(-2e3)}`).join(`
|
|
729
729
|
|
|
730
730
|
---
|
|
731
731
|
|
|
732
|
-
`))}let l=t.model||t.agent.adapter.deepModel,c=t.detailLevel??"technical",u=await t.agent.adapter.run({repoPath:t.repoPath,prompt:
|
|
732
|
+
`))}let l=t.model||t.agent.adapter.deepModel,c=t.detailLevel??"technical",u=await t.agent.adapter.run({repoPath:t.repoPath,prompt:Sd(t.role,e,n,{scopeNote:s,testResults:i,crawlResults:r,detailLevel:c}),timeoutSeconds:480,bin:t.agent.bin,mode:"read_only",maxTurns:120,sessionId:(0,yl.randomUUID)(),model:l,onLog:(w,_)=>{w==="agent"&&y.info(`[audit:${t.role}] ${_.slice(0,160)}`)}}),h=Td(u.resultText);if("error"in h)return{ok:!1,error:h.error};let f=xd(t.repoPath,h.findings);for(let w of f.droppedFindings)y.warn(`[audit:${t.role}] dropped "${w.title}" - cited files do not exist: `+w.files.join(", "));let b={id:(0,yl.randomUUID)(),role:t.role,createdAt:new Date().toISOString(),model:u.model||l,summary:h.summary,packNames:e.map(w=>w.name),findings:f.findings,costUsd:u.costUsd??0,ticketed:{},verdicts:{},lessonsWritten:[],scope:t.scope,detailLevel:c,...o?{testRun:o}:{}};return Ed(t.projectId,b),y.info(`Audit (${t.role}${t.scope.kind!=="repo"?` \xB7 ${t.scope.kind}:${t.scope.ref}`:""}) done: ${f.findings.length} finding(s)`+(h.dropped?`, ${h.dropped} malformed`:"")+(f.droppedFindings.length?`, ${f.droppedFindings.length} dropped for citing files that do not exist`:"")+(f.correctedLines?`, ${f.correctedLines} bad line number(s) stripped`:"")),{ok:!0,audit:b}}var Cn=I(ke(),1);Ae();var Cl=I(require("node:fs"),1),go=I(require("node:path"),1),yo=require("node:crypto"),_e=I(ke(),1);Ae();var Sr=I(ke(),1);var bl=I(require("node:fs"),1),Xd=I(require("node:os"),1),oo=I(require("node:path"),1),Qd=require("node:child_process"),eh=I(require("node:readline"),1),th=I(ke(),1);function io(t){return`
|
|
733
733
|
|
|
734
734
|
YOUR CAPABILITIES IN THIS RUN - state them accurately, never guess:
|
|
735
735
|
- You CANNOT run shell commands, install anything, restart services, touch a database, or reach any machine. There is no shell tool here and asking for permission will not create one.
|
|
736
736
|
`+(t==="edit_no_shell"?`- You CAN read files and CREATE or EDIT files inside this working directory.
|
|
737
737
|
`:`- You can ONLY read: Read, Glob and Grep inside this working directory. You cannot create or change a single file.
|
|
738
|
-
`)+'NEVER offer to do something outside this list, and never ask "shall I do X?" when X is outside it - offering it and then failing costs the person a whole turn and their trust. Say plainly what you cannot do here, then name the route that CAN do it (a ticket, an implement run, or a command for a human to run).'}var
|
|
739
|
-
`).length>
|
|
740
|
-
`);if(o.length<
|
|
738
|
+
`)+'NEVER offer to do something outside this list, and never ask "shall I do X?" when X is outside it - offering it and then failing costs the person a whole turn and their trust. Say plainly what you cannot do here, then name the route that CAN do it (a ticket, an implement run, or a command for a human to run).'}var sw=4e3,iw={read_only:["Read(./**)","Glob(./**)","Grep(./**)"],edit_no_shell:["Read(./**)","Glob(./**)","Grep(./**)","Edit(./**)","Write(./**)"]};function ow(t){if(process.env.ANTHROPIC_API_KEY)return"API key";let e=t??oo.default.join(Xd.default.homedir(),".claude");try{if(bl.default.existsSync(oo.default.join(e,".credentials.json"))||bl.default.existsSync(oo.default.join(e,"credentials.json")))return"subscription"}catch{}return"unknown"}async function aw(t){let e=["-p","--output-format","stream-json","--verbose","--allowedTools",iw[t.mode].join(","),"--max-turns",String(t.maxTurns??60),...t.model?["--model",t.model]:[],...t.resume?["--resume",t.sessionId]:["--session-id",t.sessionId]],n=ow(t.configDir);return n!=="unknown"&&t.onLog("info",n==="subscription"?"Billing: Claude subscription - costs shown are notional list prices, not money charged":"Billing: Anthropic API key - costs shown are actual metered spend"),new Promise(r=>{let s=(0,Qd.spawn)(t.bin,e,{cwd:t.repoPath,env:t.configDir?{...process.env,CLAUDE_CONFIG_DIR:t.configDir}:process.env,stdio:["pipe","pipe","pipe"]}),i={ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,billingMode:n==="subscription"?"subscription":n==="API key"?"api":"unknown"},o=0,l=!1,c=0,u=0,h=0,f=0,b=()=>{if(!t.onUsage)return;let v=Date.now();v-f<sw||(f=v,t.onUsage({inputTokens:c,outputTokens:u,cacheReadTokens:h,turns:o}))},w=!1,_=()=>{w||(w=!0,clearTimeout(A),t.signal?.removeEventListener("abort",S),r(i))},S=()=>{i.cancelled=!0,i.error="stopped from the dashboard",t.onLog("error",i.error),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),3e3).unref()};t.signal?.addEventListener("abort",S,{once:!0});let A=setTimeout(()=>{i.timedOut=!0,i.error=`run exceeded ${t.timeoutSeconds}s wall-clock limit`,t.onLog("error",i.error),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),5e3).unref()},t.timeoutSeconds*1e3);s.stdin.write(t.prompt+io(t.mode)),s.stdin.end(),eh.default.createInterface({input:s.stdout}).on("line",v=>{if(!v.trim())return;let C;try{C=JSON.parse(v)}catch{t.onLog("agent",v.slice(0,1e3));return}if(C.type==="system"&&C.subtype==="init")i.model=typeof C.model=="string"?C.model:void 0,t.onLog("info",`Claude Code session started (model: ${C.model??"default"})`);else if(C.type==="assistant"){o+=1,l=C.message?.stop_reason==="max_tokens",l&&t.onLog("error","the agent hit its output limit mid-message - this reply is cut off, not finished");let M=C.message?.usage;if(M){c+=Number(M.input_tokens??0)+Number(M.cache_creation_input_tokens??0);let B=JSON.stringify(C.message?.content??[]).length;u+=Math.max(Number(M.output_tokens??0),Math.round(B/4)),h+=Number(M.cache_read_input_tokens??0),b()}for(let B of C.message?.content??[])if(B.type==="text"&&B.text?.trim())t.onLog("agent",B.text.trim().slice(0,4e3));else if(B.type==="tool_use"){let j=B.input??{},d=["file_path","path","pattern","command","description","url"].map(g=>typeof j[g]=="string"?`${g}=${j[g]}`:null).filter(Boolean).join(" "),m=JSON.stringify(j).slice(0,400);t.onLog("info",`tool ${B.name} ${d?`${d} `:""}${m}`)}}else C.type==="result"&&(i.costUsd=Number(C.total_cost_usd??0),i.inputTokens=Number(C.usage?.input_tokens??0)+Number(C.usage?.cache_creation_input_tokens??0),i.outputTokens=Number(C.usage?.output_tokens??0),c=Math.max(i.inputTokens,c),u=Math.max(i.outputTokens,u),i.inputTokens=c,i.outputTokens=u,h=Number(C.usage?.cache_read_input_tokens??h),i.cacheReadTokens=h,t.onUsage&&(t.onUsage({inputTokens:c,outputTokens:u,cacheReadTokens:h,costUsd:i.costUsd,turns:o}),f=Date.now()),C.subtype==="success"&&!C.is_error?(i.ok=!0,i.resultText=String(C.result??""),i.outputTruncated=l):C.subtype==="error_max_turns"?(i.turnLimitHit=!0,i.error=`hit the ${t.maxTurns??60}-turn limit before finishing`):i.error||(i.error=C.subtype==="error_during_execution"?"the agent stopped mid-work before it could finish - the session was interrupted or hit an internal limit":String(C.result??C.subtype??"unknown Claude Code error"),/rate.?limit|usage limit|limit (reached|exceeded)|overloaded/i.test(i.error)&&(i.error=`Claude usage limit hit for this account - the run will work again once the limit window resets. Original error: ${i.error.slice(0,400)}`)))});let q="";s.stderr.on("data",v=>{q=(q+v.toString()).slice(-2e3)}),s.on("error",v=>{i.error=`failed to start ${t.bin}: ${v.message}`,t.onLog("error",i.error),_()}),s.on("close",v=>{!i.ok&&!i.error&&(i.error=i.timedOut?i.error:`claude exited with code ${v}${q?`: ${q.slice(-500)}`:""}`),_()})})}var ao={id:"claude-code",displayName:"Claude Code",fastModel:"claude-sonnet-5",deepModel:"claude-fable-5",capabilities:th.REGISTERED_AGENTS.find(t=>t.id==="claude-code").capabilities,run:aw};var nh=require("node:child_process"),rh=I(require("node:readline"),1),sh=I(ke(),1);async function lw(t){if(t.mode!=="read_only")return{ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,error:"the codex adapter only supports read-only runs - its write sandbox cannot exclude shell, and Allwright never weakens a guarantee silently"};if(t.resume)return{ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,error:"the codex adapter cannot resume sessions"};let e=["exec","--json","--sandbox","read-only","--skip-git-repo-check","--cd",t.repoPath,...t.model?["--model",t.model]:[],"-"];return new Promise(n=>{let r=(0,nh.spawn)(t.bin,e,{cwd:t.repoPath,env:process.env,stdio:["pipe","pipe","pipe"]}),s={ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,cacheReadTokens:0},i="",o=!1,l=()=>{o||(o=!0,clearTimeout(c),n(s))},c=setTimeout(()=>{s.timedOut=!0,s.error=`run exceeded ${t.timeoutSeconds}s wall-clock limit`,t.onLog("error",s.error),r.kill("SIGTERM"),setTimeout(()=>r.kill("SIGKILL"),5e3).unref()},t.timeoutSeconds*1e3);r.stdin.write(t.prompt+io(t.mode)),r.stdin.end(),rh.default.createInterface({input:r.stdout}).on("line",f=>{if(!f.trim())return;let b;try{b=JSON.parse(f)}catch{t.onLog("agent",f.slice(0,1e3));return}let w=b.item??b.msg??b,_=w?.type??b.type,S=w?.text??w?.message??"";_==="agent_message"&&typeof S=="string"&&S.trim()?(i=S,t.onLog("agent",S.trim().slice(0,4e3))):_==="command_execution"||_==="exec_command_begin"?t.onLog("info",`tool ${String(w?.command??"").slice(0,300)}`):_==="error"&&typeof S=="string"&&S&&t.onLog("error",S.slice(0,1e3))});let h="";r.stderr.on("data",f=>{h=(h+f.toString()).slice(-2e3)}),r.on("error",f=>{s.error=`failed to start ${t.bin}: ${f.message} - is the Codex CLI installed and logged in?`,t.onLog("error",s.error),l()}),r.on("close",f=>{f===0&&i.trim()?(s.ok=!0,s.resultText=i):s.error||(s.error=`codex exited with code ${f}`+(i?"":" and produced no answer")+(h?`: ${h.slice(-500)}`:"")),l()})})}var wl={id:"codex",fastModel:"",deepModel:"",displayName:"OpenAI Codex CLI (experimental)",capabilities:sh.REGISTERED_AGENTS.find(t=>t.id==="codex").capabilities,run:lw};var cw={[ao.id]:ao,[wl.id]:wl};function We(t){return cw[t||Sr.DEFAULT_AGENT_ID]??null}function Ve(t,e){return!e||e===ao.id?t.claudeBin:t.agents[e]?.bin??e}function En(t,e){let n=We(t);if(!n)return`no agent adapter named "${t}" on this runner - update the runner, or set the rule's agent to "${Sr.DEFAULT_AGENT_ID}"`;let r=(0,Sr.missingAgentCapabilities)(n.id,e);return r&&r.length?`agent "${n.displayName}" cannot run ${e} rules: it cannot guarantee ${r.join(", ")}. Allwright refuses rather than weakening the isolation silently.`:null}function Oe(t,e,n){let r=e.defaultAgent||Sr.DEFAULT_AGENT_ID,s=We(r);if(!s)return{error:`this project's default agent "${r}" is not on this runner - update the runner, or change the project's agent`};let i=(0,Sr.missingAgentCapabilities)(s.id,n);return i&&i.length?{error:`this project's default agent "${s.displayName}" cannot power this - it lacks ${i.join(", ")}. Change the project's agent, or use one that can.`}:{adapter:s,bin:Ve(t,s.id)}}function Qt(t,e){return t.replace(/\{\{(\w+)\}\}/g,(n,r)=>r in e?e[r]:n)}var ks=I(ke(),1);var vl=I(require("node:fs"),1),lo=I(require("node:path"),1),uw=24,dw=120,hw=30,pw=6e3,fw=new Set(["node_modules","dist","build","out","coverage","vendor","target"]);function mw(t){let e=[],n=(r,s)=>{if(s>4||e.length>=200)return;let i;try{i=vl.default.readdirSync(r,{withFileTypes:!0})}catch{return}for(let o of i){if(o.name.startsWith(".")||fw.has(o.name))continue;let l=lo.default.join(r,o.name);o.isDirectory()?n(l,s+1):o.isFile()&&/\.md$/i.test(o.name)&&e.push(l)}};return n(t,0),e}function co(t){let e=[],n=0;for(let r of mw(t)){if(n>=uw||e.join(`
|
|
739
|
+
`).length>pw)break;let s=lo.default.relative(t,r);if(lo.default.basename(r).toUpperCase()==="CLAUDE.MD")continue;let i;try{i=vl.default.readFileSync(r,"utf8")}catch{continue}let o=i.split(`
|
|
740
|
+
`);if(o.length<dw)continue;let l=[],c=!1;for(let u=0;u<o.length;u++){let h=o[u];if(/^\s*(```|~~~)/.test(h)){c=!c;continue}if(!c&&/^#{1,3}\s+\S/.test(h)&&(l.push(` L${u+1} ${h.trim().slice(0,110)}`),l.length>=hw)){l.push(" \u2026 more headings follow in the file");break}}l.length<2||(e.push(`${s} (${o.length} lines)`),e.push(...l),n++)}return e.length?`
|
|
741
741
|
|
|
742
742
|
DOCUMENT INDEX - the repo's larger Markdown documents, with 1-based line numbers (generated; the files themselves are the truth):
|
|
743
743
|
${e.join(`
|
|
744
744
|
`)}
|
|
745
|
-
Read a document's relevant SECTION with Read offset/limit using these line numbers - read one end-to-end only when the task genuinely needs all of it.`:""}kt();kr();Ct();var De=
|
|
746
|
-
`,{mode:384}),De.default.renameSync(n,t),De.default.chmodSync(t,384)}function
|
|
745
|
+
Read a document's relevant SECTION with Read offset/limit using these line numbers - read one end-to-end only when the task genuinely needs all of it.`:""}var Ws=I(require("node:fs"),1),ih=I(require("node:path"),1);Ae();var kl=2,oh=()=>ih.default.join(ie(),"timeout-sessions.json");function ah(){try{return JSON.parse(Ws.default.readFileSync(oh(),"utf8"))}catch{return{}}}function lh(t){Ws.default.mkdirSync(ie(),{recursive:!0,mode:448}),Ws.default.writeFileSync(oh(),JSON.stringify(t,null,2),{mode:384})}var ch=(t,e)=>`${t}:${e}`;function uh(t,e,n){let r=ah();r[ch(t,e)]={...n,at:new Date().toISOString()},lh(r)}function dh(t,e,n){let r=ah(),s=ch(t,e),i=r[s];return!i||(delete r[s],lh(r),i.branch!==n)||!Ws.default.existsSync(i.worktreePath)?null:i}kt();kr();Ct();var De=I(require("node:fs"),1),bs=I(require("node:path"),1);Xr();Ae();var yw=k.object({runId:k.string(),issueKey:k.string(),repoName:k.string(),owner:k.string(),repo:k.string(),prNumber:k.number().int(),prUrl:k.string(),branch:k.string(),headSha:k.string(),doneLabel:k.string(),failedLabel:k.string(),jiraTransition:k.string().optional(),mergeOnApprove:k.boolean().default(!1),mergeMethod:k.enum(["squash","merge","rebase"]).default("squash"),autoMerge:k.boolean().default(!1),nextDecisionSeq:k.number().int().default(1e5),changesRequestedNotified:k.boolean().optional(),conflictNotified:k.boolean().optional(),agentConfigDir:k.string().optional()}),bw=k.record(yw),ww=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()}),vw=k.record(ww),kw=k.object({runId:k.string(),issueKey:k.string(),kind:k.enum(["plan","implement"]),repoPath:k.string(),sessionId:k.string(),doneLabel:k.string(),failedLabel:k.string(),timeoutSeconds:k.number(),createdAt:k.string(),questionsPostedAt:k.string(),rounds:k.number().int().default(1),nextLogSeq:k.number().int().nonnegative().default(0),baseRepoPath:k.string().optional(),repoName:k.string().optional(),branch:k.string().optional(),baseBranch:k.string().optional(),jiraTransition:k.string().optional(),jiraTransitionOnMerge:k.string().optional(),requireApproval:k.boolean().optional(),maxTurns:k.number().int().optional(),runTests:k.boolean().default(!0),mergeOnApprove:k.boolean().default(!1),mergeMethod:k.enum(["squash","merge","rebase"]).default("squash"),autoMerge:k.boolean().default(!1),issueSummary:k.string().default(""),claudeConfigDir:k.string().optional(),agent:k.string().optional(),model:k.string().optional(),actorEmail:k.string().optional()}),_w=k.object({runId:k.string(),issueKey:k.string(),issueSummary:k.string().default(""),repoName:k.string(),baseRepoPath:k.string(),branch:k.string(),baseBranch:k.string(),headSha:k.string(),requireApproval:k.boolean(),mergeOnApprove:k.boolean().default(!1),mergeMethod:k.enum(["squash","merge","rebase"]).default("squash"),autoMerge:k.boolean().default(!1),doneLabel:k.string(),failedLabel:k.string(),jiraTransition:k.string().optional(),jiraTransitionOnMerge:k.string().optional(),actorEmail:k.string().optional(),resultSummary:k.string().default(""),prSummary:k.string().default(""),costUsd:k.number().default(0),nextLogSeq:k.number().int().default(1e5),createdAt:k.string()}),Sw=k.record(_w),Tw=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()}),xw=k.record(Tw),Rw=k.record(kw);function hh(){return bs.default.join(ie(),"pending-runs.json")}function _l(){return bs.default.join(ie(),"pending-deploys.json")}function Sl(){return bs.default.join(ie(),"pending-inputs.json")}function Tl(){return bs.default.join(ie(),"merge-watch.json")}function xl(){return bs.default.join(ie(),"pending-pushes.json")}function Rl(){let t=xl();if(!De.default.existsSync(t))return{};try{return Sw.parse(JSON.parse(De.default.readFileSync(t,"utf8")))}catch{return{}}}function uo(t){let e=Rl();e[t.runId]=t,en(xl(),e)}function ho(t){return Rl()[t]??null}function Il(t){let e=Rl();t in e&&(delete e[t],en(xl(),e))}function po(){let t=Tl();if(!De.default.existsSync(t))return{};try{return xw.parse(JSON.parse(De.default.readFileSync(t,"utf8")))}catch{return{}}}function ph(t){let e=po();e[t.runId]=t,en(Tl(),e)}function Vs(t){let e=po();t in e&&(delete e[t],en(Tl(),e))}function Js(){let t=hh();if(!De.default.existsSync(t))return{};try{return bw.parse(JSON.parse(De.default.readFileSync(t,"utf8")))}catch{return{}}}function en(t,e){De.default.mkdirSync(ie(),{recursive:!0,mode:448});let n=t+".tmp";De.default.writeFileSync(n,JSON.stringify(e,null,2)+`
|
|
746
|
+
`,{mode:384}),De.default.renameSync(n,t),De.default.chmodSync(t,384)}function fh(t){en(hh(),t)}function _t(t){let e=Js();e[t.runId]=t,fh(e)}function ws(t){return Js()[t]??null}function xr(t){let e=Js();t in e&&(delete e[t],fh(e))}function Al(){let t=_l();if(!De.default.existsSync(t))return{};try{return vw.parse(JSON.parse(De.default.readFileSync(t,"utf8")))}catch{return{}}}function mh(t){let e=Al();e[t.runId]=t,en(_l(),e)}function fo(t){return Al()[t]??null}function mo(t){let e=Al();t in e&&(delete e[t],en(_l(),e))}function Rr(){let t=Sl();if(!De.default.existsSync(t))return{};try{return Rw.parse(JSON.parse(De.default.readFileSync(t,"utf8")))}catch{return{}}}function gh(t){let e=Rr();e[t.runId]=t,en(Sl(),e)}function yh(t){return Rr()[t]??null}function jt(t){let e=Rr();t in e&&(delete e[t],en(Sl(),e))}Xt();var Iw=`
|
|
747
747
|
|
|
748
|
-
NEVER create or modify CI/workflow files (.github/workflows/, .githooks/ or similar CI config) - the runner refuses to push them, and the refusal costs the whole run. When the ticket needs something enforced on every change, use a path that is yours to edit instead: add the check as a command in TEST.md (this runner executes TEST.md commands after every implement run and posts the results into the PR), wire it into a script CI already runs (package.json test/build scripts, the test suite itself), or - only if it truly must be a workflow file - put the exact proposed YAML in your summary for a human to apply by hand.`,
|
|
748
|
+
NEVER create or modify CI/workflow files (.github/workflows/, .githooks/ or similar CI config) - the runner refuses to push them, and the refusal costs the whole run. When the ticket needs something enforced on every change, use a path that is yours to edit instead: add the check as a command in TEST.md (this runner executes TEST.md commands after every implement run and posts the results into the PR), wire it into a script CI already runs (package.json test/build scripts, the test suite itself), or - only if it truly must be a workflow file - put the exact proposed YAML in your summary for a human to apply by hand.`,Aw=`
|
|
749
749
|
|
|
750
|
-
After your "## Summary of changes" section, end with one more section headed exactly "## PR summary": 4-8 short sentences in plain language for the person reviewing the pull request. Say what was built and what a user can now do, name anything you did NOT do or assumed, and anything that genuinely needs a human decision. No file paths, no function names, no jargon unless the point cannot be made without it. Complete but short.`,
|
|
750
|
+
After your "## Summary of changes" section, end with one more section headed exactly "## PR summary": 4-8 short sentences in plain language for the person reviewing the pull request. Say what was built and what a user can now do, name anything you did NOT do or assumed, and anything that genuinely needs a human decision. No file paths, no function names, no jargon unless the point cannot be made without it. Complete but short.`,Ew=`
|
|
751
751
|
|
|
752
|
-
This project keeps a living go-live checklist and manual test cases on a Jira issue. If (and only if) this ticket changes what must be checked before going live, or adds user-visible behavior a human should test by hand, end with one more section headed exactly "## Go-live draft": checklist additions/changes as short imperative bullets, then manual test cases as numbered steps a non-developer can follow. Under 1500 characters total. If nothing about going live changes, OMIT the section entirely - an empty ritual entry is noise.`;function
|
|
752
|
+
This project keeps a living go-live checklist and manual test cases on a Jira issue. If (and only if) this ticket changes what must be checked before going live, or adds user-visible behavior a human should test by hand, end with one more section headed exactly "## Go-live draft": checklist additions/changes as short imperative bullets, then manual test cases as numbered steps a non-developer can follow. Under 1500 characters total. If nothing about going live changes, OMIT the section entirely - an empty ritual entry is noise.`;function bh(t){let e=/##\s*Go-live draft\s*\n([\s\S]*?)(?=\n##\s|$)/i.exec(t),n=e?e[1].trim():"";return n?n.slice(0,3500):null}function Cw(t){let e=t.map(n=>`$ ${n.command} (exit ${n.exitCode})
|
|
753
753
|
${n.tail.slice(-2e3)}`).join(`
|
|
754
754
|
|
|
755
755
|
`);return`After you finished, the runner executed this repository's documented TEST.md commands (you cannot run them yourself - you have no shell). ${t.length} failed:
|
|
@@ -761,7 +761,7 @@ Fix what these failures point at, with the smallest change that makes them pass.
|
|
|
761
761
|
- If a failure is clearly pre-existing on the base branch and unrelated to your change, leave the code alone and say so in one sentence.
|
|
762
762
|
- Do not ask questions; if you cannot fix something safely, say what you found and stop.
|
|
763
763
|
- The runner re-runs every documented command after you finish, so a fix that breaks a previously passing command will be caught.
|
|
764
|
-
End with one short paragraph stating exactly what you changed, or why you changed nothing. Then repeat your "## PR summary" section, updated if your fix changed what a reviewer sees.`}function
|
|
764
|
+
End with one short paragraph stating exactly what you changed, or why you changed nothing. Then repeat your "## PR summary" section, updated if your fix changed what a reviewer sees.`}function $w(t){try{let{packs:e,lessons:n}=so("implement",t),r="",s=e.map(o=>`### ${o.name}
|
|
765
765
|
${o.content}`).join(`
|
|
766
766
|
|
|
767
767
|
`).trim();s&&(r+=`
|
|
@@ -771,57 +771,57 @@ This repository has working rules taught to Allwright - follow them:
|
|
|
771
771
|
\u2026${i.slice(-6e3)}`:i;r+=`
|
|
772
772
|
|
|
773
773
|
Lessons from earlier runs on this repository (human-confirmed - follow them BEFORE writing code, they exist because a run got this wrong once):
|
|
774
|
-
`+o}return r}catch{return""}}function
|
|
774
|
+
`+o}return r}catch{return""}}function $l(t){return Cl.default.existsSync(go.default.join(t,"DESIGN.md"))?`
|
|
775
775
|
|
|
776
|
-
This repository has a DESIGN.md at its root: read it before doing any user-facing work (UI, copy, styling) and follow it. Where the ticket and DESIGN.md conflict, say so instead of silently picking one.`:""}var
|
|
776
|
+
This repository has a DESIGN.md at its root: read it before doing any user-facing work (UI, copy, styling) and follow it. Where the ticket and DESIGN.md conflict, say so instead of silently picking one.`:""}var _h=5,wh=2,Pw=8,vh=2,jw="Your previous run on this ticket hit its wall-clock time limit - nothing failed. You are back in the SAME worktree with your uncommitted work intact and your own memory of the ticket. Check git status and your last steps, then continue exactly where you stopped - do not re-read files you already know or redo completed work. Finish the remaining work and end with the final summary the original instructions asked for.",Nw="You stopped because the session hit its turn limit - nothing failed. Continue exactly where you left off. Do not re-read files you already know or redo completed work; be economical with tool calls and finish the remaining work. Then end with your final summary exactly as the original instructions asked.";async function Xs(t,e,n,r){let s=Date.now(),i="";r&&(i=await r().catch(()=>""));let o=await t.run(e),l=0,c="",u=r?Pw:wh;for(;!o.ok&&o.turnLimitHit&&!o.cancelled&&t.capabilities.sessionResume;){if(l>=u){c=`resume cap (${u}) reached`;break}if(r&&l>=wh){let f=await r().catch(()=>""),b=f!==""&&f!==i;if(i=f,!b){c="the last resume produced no new work";break}if(Date.now()-s>e.timeoutSeconds*vh*1e3){c=`wall-clock budget (${vh}x the rule's timeout) exhausted`;break}}l++,n("info",`Turn limit hit mid-work - auto-resuming the same session (resume ${l}, cap ${u})`);let h=await t.run({...e,prompt:Nw,resume:!0});h.costUsd+=o.costUsd,h.inputTokens+=o.inputTokens,h.outputTokens+=o.outputTokens,o=h}return!o.ok&&o.turnLimitHit&&t.capabilities.sessionResume&&(o.error=`${o.error??"hit the turn limit"} - even after ${l} automatic same-session resume(s)${c?` (stopped: ${c})`:""}. The ticket is probably too large for one run: raise the rule's max turns, or split the ticket.`),o}var Ys=new Map;function Sh(t){let e=Ys.get(t);return e?(e.abort(),!0):!1}function Th(t){let e=new AbortController;return Ys.set(t,e),e}function xh(t){Ys.delete(t)}async function _s(t,e,n,r,s){let i=new AbortController;Ys.set(t,i);try{return await Xs(e,{...n,signal:i.signal},r,s)}finally{Ys.delete(t)}}function Ir(t,e,n=0){let r=n;return{emit:(l,c)=>{e.send({type:"run.log",runId:t,seq:r++,ts:new Date().toISOString(),level:l,message:c}),l!=="agent"&&y.info(`[run ${t}] ${c}`)},setStatus:(l,c={})=>{e.send({type:"run.status",runId:t,status:l,...c})},sendUsage:l=>{e.send({type:"run.usage",runId:t,inputTokens:Math.round(l.inputTokens),outputTokens:Math.round(l.outputTokens),cacheReadTokens:l.cacheReadTokens===void 0?void 0:Math.round(l.cacheReadTokens),costUsd:l.costUsd,turns:l.turns})},nextSeq:()=>r}}async function bo(t){return t.rule.action.type==="implement"?zw(t):t.rule.action.type==="respond"?Mw(t):Ow(t)}async function Ow(t){let{emit:e,setStatus:n,sendUsage:r,nextSeq:s}=Ir(t.runId,t.transport),{trigger:i}=t.rule,o=t.rule.action;if(o.type!=="plan_only")return;let l=En(o.agent,o.type);if(l){e("error",l),await vs(t,l),n("failed",{error:l});return}let c=(0,yo.randomUUID)();try{n("running"),e("info",`Run started for ${t.issueKey} (rule "${t.rule.name}", plan-only)`),e("info",`Fetching ${t.issueKey} from Jira`);let u=await t.jira.getIssue(t.issueKey),h=Qt(o.promptTemplate,{issueKey:u.key,summary:u.summary,description:u.description||"(no description)",comments:ei(u.comments)})+await es(t.jira,u.attachments,t.repoPath,e)+$l(t.repoPath)+co(t.repoPath)+ks.FOCUSED_READING_PROMPT+_e.NEEDS_INPUT_OPTIONS_PROMPT;e("info",`Starting Claude Code in ${t.repoPath} - read-only tools, path-jailed to the repo, timeout ${o.timeoutSeconds}s`);let f=await _s(t.runId,We(o.agent),{repoPath:t.repoPath,prompt:h,timeoutSeconds:o.timeoutSeconds,bin:Ve(t.cfg,o.agent),configDir:t.claudeConfigDir,mode:"read_only",model:o.model||void 0,sessionId:c,onLog:(_,S)=>e(_,S),onUsage:r},e),b={costUsd:f.costUsd,inputTokens:f.inputTokens,outputTokens:f.outputTokens,billingMode:f.billingMode,model:f.model};if(!f.ok||!f.resultText.trim()){let _=f.error??"Claude Code produced no output";e("error",`Run failed: ${_}`),await vs(t,_),n(f.timedOut?"timed_out":"failed",{error:_,...f.cancelled?{errorKind:"guard"}:{},...b});return}let w=ti(f.resultText);if(w){await wo({kind:"plan",runId:t.runId,issueKey:t.issueKey,repoPath:t.repoPath,sessionId:c,doneLabel:i.doneLabel,failedLabel:i.failedLabel,timeoutSeconds:o.timeoutSeconds,jira:t.jira,nextLogSeq:s(),rounds:1,claudeConfigDir:t.claudeConfigDir,agent:o.agent,model:o.model},w,e,n,b);return}await Rh({runId:t.runId,issueKey:t.issueKey,doneLabel:i.doneLabel,jira:t.jira,resultText:f.resultText,costFields:b,emit:e,setStatus:n})}catch(u){let h=u instanceof Error?u.message:String(u);e("error",`Run failed: ${h}`),await vs(t,h),n("failed",{error:h})}finally{gn(t.repoPath)}}async function Pl(t,e,n,r){let{emit:s,setStatus:i,sendUsage:o,nextSeq:l}=Ir(t.runId,r.transport,t.nextLogSeq);try{i("running"),s("info",`Reply received on ${t.issueKey} - continuing run \`${t.runId}\``);let c=Mh(e)+await es(r.jiraFor(t.repoName??""),n,t.repoPath,s),u=await _s(t.runId,We(t.agent),{repoPath:t.repoPath,prompt:c,timeoutSeconds:t.timeoutSeconds,bin:Ve(r.cfg,t.agent??""),configDir:t.claudeConfigDir,mode:"read_only",model:t.model||void 0,sessionId:t.sessionId,resume:!0,onLog:(b,w)=>s(b,w),onUsage:o},s),h={costUsd:u.costUsd,inputTokens:u.inputTokens,outputTokens:u.outputTokens,billingMode:u.billingMode,model:u.model};if(!u.ok||!u.resultText.trim()){let b=u.error??"Claude Code produced no output";s("error",`Run failed: ${b}`),await Nt(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,b),jt(t.runId),i(u.timedOut?"timed_out":"failed",{error:b,...u.cancelled?{errorKind:"guard"}:{},...h});return}let f=ti(u.resultText);if(f){if(t.rounds>=_h){await zh(r.jiraFor(t.repoName??""),t,s,i,h);return}await wo({kind:"plan",runId:t.runId,issueKey:t.issueKey,repoPath:t.repoPath,sessionId:t.sessionId,doneLabel:t.doneLabel,failedLabel:t.failedLabel,timeoutSeconds:t.timeoutSeconds,jira:r.jiraFor(t.repoName??""),nextLogSeq:l(),rounds:t.rounds+1,createdAt:t.createdAt,claudeConfigDir:t.claudeConfigDir,actorEmail:t.actorEmail,agent:t.agent,model:t.model},f,s,i,h);return}await Rh({runId:t.runId,issueKey:t.issueKey,doneLabel:t.doneLabel,jira:r.jiraFor(t.repoName??""),resultText:u.resultText,costFields:h,emit:s,setStatus:i}),jt(t.runId)}catch(c){let u=c instanceof Error?c.message:String(c);s("error",`Run failed: ${u}`),await Nt(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,u),jt(t.runId),i("failed",{error:u})}finally{gn(t.repoPath)}}async function Rh(t){let{runId:e,issueKey:n,doneLabel:r,jira:s,resultText:i,costFields:o,emit:l,setStatus:c}=t;c("posting",o),l("info",`Posting plan to ${n} (${i.length} chars)`);let u=`
|
|
777
777
|
|
|
778
778
|
---
|
|
779
|
-
_Allwright plan-only run \`${e}\` \xB7 cost $${o.costUsd.toFixed(4)} \xB7 no code was written._`;await s.addComment(n,i+u),await s.editLabels(n,{add:[r],remove:[_e.NEEDS_INPUT_LABEL]}),l("info",`Labeled ${n} with "${r}"`),c("succeeded",{...o,resultSummary:
|
|
779
|
+
_Allwright plan-only run \`${e}\` \xB7 cost $${o.costUsd.toFixed(4)} \xB7 no code was written._`;await s.addComment(n,i+u),await s.editLabels(n,{add:[r],remove:[_e.NEEDS_INPUT_LABEL]}),l("info",`Labeled ${n} with "${r}"`),c("succeeded",{...o,resultSummary:Ar(i)}),l("info",`Run succeeded \xB7 $${o.costUsd.toFixed(4)}`)}async function Mw(t){let{emit:e,setStatus:n,sendUsage:r}=Ir(t.runId,t.transport),s=t.rule.action;if(s.type!=="respond")return;let i=En(s.agent,s.type);if(i){e("error",i),await t.jira.addComment(t.issueKey,`**Allwright could not answer this question.**
|
|
780
780
|
|
|
781
|
-
${i}`).catch(()=>{}),n("failed",{error:i});return}try{n("running"),e("info",`Run started for ${t.issueKey} (rule "${t.rule.name}", respond`+(t.question?`, question from ${t.question.author}`:"")+")"),e("info",`Fetching ${t.issueKey} from Jira`);let o=await t.jira.getIssue(t.issueKey),l=Qt(s.promptTemplate,{issueKey:o.key,summary:o.summary,description:o.description||"(no description)",comments:
|
|
781
|
+
${i}`).catch(()=>{}),n("failed",{error:i});return}try{n("running"),e("info",`Run started for ${t.issueKey} (rule "${t.rule.name}", respond`+(t.question?`, question from ${t.question.author}`:"")+")"),e("info",`Fetching ${t.issueKey} from Jira`);let o=await t.jira.getIssue(t.issueKey),l=Qt(s.promptTemplate,{issueKey:o.key,summary:o.summary,description:o.description||"(no description)",comments:ei(o.comments),question:t.question?.body??"(see the latest comment on the ticket)",questionAuthor:t.question?.author??"the commenter"})+await es(t.jira,o.attachments,t.repoPath,e)+$l(t.repoPath)+co(t.repoPath)+ks.FOCUSED_READING_PROMPT;e("info",`Starting Claude Code in ${t.repoPath} - read-only tools, path-jailed, timeout ${s.timeoutSeconds}s`);let c=await _s(t.runId,We(s.agent),{repoPath:t.repoPath,prompt:l,timeoutSeconds:s.timeoutSeconds,bin:Ve(t.cfg,s.agent),configDir:t.claudeConfigDir,mode:"read_only",model:s.model||void 0,sessionId:(0,yo.randomUUID)(),onLog:(h,f)=>e(h,f),onUsage:r},e),u={costUsd:c.costUsd,inputTokens:c.inputTokens,outputTokens:c.outputTokens,billingMode:c.billingMode,model:c.model};if(!c.ok||!c.resultText.trim()){let h=c.error??"Claude Code produced no answer";e("error",`Run failed: ${h}`),await t.jira.addComment(t.issueKey,`**Allwright could not answer this question.**
|
|
782
782
|
|
|
783
|
-
Error: ${
|
|
783
|
+
Error: ${h.slice(0,800)}
|
|
784
784
|
|
|
785
|
-
Ask again in a new comment to retry. (run \`${t.runId}\`)`).catch(f=>y.error(`could not post answer failure to ${t.issueKey}: ${f}`)),n(c.timedOut?"timed_out":"failed",{error:
|
|
785
|
+
Ask again in a new comment to retry. (run \`${t.runId}\`)`).catch(f=>y.error(`could not post answer failure to ${t.issueKey}: ${f}`)),n(c.timedOut?"timed_out":"failed",{error:h,...c.cancelled?{errorKind:"guard"}:{},...u});return}n("posting",u),e("info",`Posting answer to ${t.issueKey} (${c.resultText.length} chars)`),await t.jira.addComment(t.issueKey,c.resultText),n("succeeded",{...u,resultSummary:Ar(c.resultText)}),e("info",`Run succeeded \xB7 $${c.costUsd.toFixed(4)}`)}catch(o){let l=o instanceof Error?o.message:String(o);e("error",`Run failed: ${l}`),n("failed",{error:l})}finally{gn(t.repoPath)}}async function Ih(t,e,n,r){let s=`${e}-wip`;try{return gn(t),await br(t,`WIP: turn limit exhausted (Allwright run ${n})`),await La(t,s),r("info",`Partial work preserved on branch "${s}"`),s}catch(i){return r("warn",`could not preserve partial work: ${i instanceof Error?i.message:i}`),null}}function Ah(t){return`
|
|
786
786
|
|
|
787
|
-
Partial work from this run is saved on branch \`${t}\` - it was NOT safety-checked or reviewed and never merges on its own; a future run or a developer can pick it up.`}async function
|
|
787
|
+
Partial work from this run is saved on branch \`${t}\` - it was NOT safety-checked or reviewed and never merges on its own; a future run or a developer can pick it up.`}async function zw(t){let{emit:e,setStatus:n,sendUsage:r,nextSeq:s}=Ir(t.runId,t.transport),{trigger:i}=t.rule,o=t.rule.action;if(o.type!=="implement")return;let l=En(o.agent,o.type);if(l){e("error",l),await vs(t,l),n("failed",{error:l});return}let c=Qt(o.branchTemplate,{issueKey:t.issueKey}),u=t.chain?null:dh(t.project.id,t.issueKey,c),h=t.chain?.worktreePath??u?.worktreePath??go.default.join(Yt(),t.runId),f=t.chain?.sessionId??u?.sessionId??(0,yo.randomUUID)(),b=!1,w=!1,_=!1;try{if(!Qi(ve()??t.cfg,t.project.repoName,t.actorEmail))throw new Error("no GitHub token applies to this repo - run `allwright github set-token` (runner-wide) or `github set <repoName>` (this repo only)");if(c===o.baseBranch&&!t.continueBranch)throw new Error(`rendered branch "${c}" equals the base branch - refusing (check the rule's branch template)`);if(n("running"),e("info",`Run started for ${t.issueKey} (rule "${t.rule.name}", implement)`),o.jiraTransitionOnStart)try{await t.jira.transitionByName(t.issueKey,o.jiraTransitionOnStart)?e("info",`Jira transition "${o.jiraTransitionOnStart}" applied at run start`):e("warn",`no transition named "${o.jiraTransitionOnStart}" is available from this ticket's current status - continuing anyway`)}catch(B){e("warn",`Jira start transition failed: ${B instanceof Error?B.message:B} - continuing anyway`)}let S=await vr(t.repoPath);if(e("info",`Repo origin: ${S}`),!wt(S))throw new Error(`origin "${S}" is not a GitHub remote - implement mode supports GitHub only`);e("info",`Fetching ${t.issueKey} from Jira`);let A=await t.jira.getIssue(t.issueKey),z=t.continueBranch?c:o.baseBranch;u?e("info",`Resuming the session that timed out on this ticket (timeout resume ${u.resumes}/${kl}) - same worktree, uncommitted work intact, repo context cached`):(e("info",t.continueBranch?`Continuing branch "${c}" from origin/${c} (autopilot batch)`:`Preparing worktree on branch "${c}" from origin/${o.baseBranch}`),await Tn(t.repoPath,z),await qa(t.repoPath,c),t.chain?(e("info","Chaining onto the previous ticket's workspace - resuming its agent session (repo context cached, not re-explored)"),await Ka(h,c,`origin/${o.baseBranch}`)):await Fa(t.repoPath,h,c,z)),b=!0;let q=Qt(o.promptTemplate,{issueKey:A.key,summary:A.summary,description:A.description||"(no description)",comments:ei(A.comments)})+await es(t.jira,A.attachments,h,e)+$l(h)+$w(t.repoPath)+co(h)+ks.FOCUSED_READING_PROMPT+Iw+_e.NEEDS_INPUT_OPTIONS_PROMPT+Aw+(t.project.goLiveIssueKey?Ew:"")+(o.writeTests?ks.WRITE_TESTS_PROMPT:"")+(o.updateMemory?_e.MEMORY_UPDATE_PROMPT:"");e("info",`Starting Claude Code in the worktree - edit tools enabled, path-jailed, no shell, timeout ${o.timeoutSeconds}s`);let v=await _s(t.runId,We(o.agent),{repoPath:h,prompt:u?jw:q,timeoutSeconds:o.timeoutSeconds,bin:Ve(t.cfg,o.agent),configDir:t.claudeConfigDir,mode:"edit_no_shell",model:o.model||void 0,maxTurns:o.maxTurns,sessionId:f,resume:!!t.chain||!!u,onLog:(B,j)=>e(B,j),onUsage:r},e,()=>Vi(h)),C={costUsd:v.costUsd,inputTokens:v.inputTokens,outputTokens:v.outputTokens,billingMode:v.billingMode,model:v.model};if(!v.ok){let B=v.error??"Claude Code failed";e("error",`Run failed: ${B}`);let j=B;if(v.turnLimitHit){let d=await Ih(h,c,t.runId,e);d&&(j+=Ah(d))}v.timedOut&&!v.cancelled&&We(o.agent)?.capabilities.sessionResume&&(u?.resumes??0)<kl&&(uh(t.project.id,t.issueKey,{sessionId:f,worktreePath:h,branch:c,resumes:(u?.resumes??0)+1}),w=!0,e("info","Worktree and session preserved - the next trigger on this ticket resumes here"),j+=" - the work done so far is preserved: trigger this ticket again and the run RESUMES the same session where it stopped instead of starting over"),ut(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:"implement failed",detail:B.slice(0,500)}),await vs(t,j),n(v.timedOut?"timed_out":"failed",{error:j,...v.cancelled?{errorKind:"guard"}:{},...C});return}let M=ti(v.resultText);if(M){_=!0,await wo({kind:"implement",runId:t.runId,issueKey:t.issueKey,repoPath:h,sessionId:f,doneLabel:i.doneLabel,failedLabel:i.failedLabel,timeoutSeconds:o.timeoutSeconds,jira:t.jira,nextLogSeq:s(),rounds:1,claudeConfigDir:t.claudeConfigDir,agent:o.agent,model:o.model,actorEmail:t.actorEmail,baseRepoPath:t.repoPath,repoName:t.project.repoName,branch:c,baseBranch:o.baseBranch,jiraTransition:o.jiraTransition,jiraTransitionOnMerge:o.jiraTransitionOnMerge,requireApproval:o.requireApproval,mergeOnApprove:o.mergeOnApprove,mergeMethod:o.mergeMethod,autoMerge:o.autoMerge,runTests:o.runTests,maxTurns:o.maxTurns,issueSummary:A.summary},M,e,n,C);return}gn(h),await Eh({runId:t.runId,issueKey:t.issueKey,issueSummary:A.summary,worktreePath:h,agentConfigDir:t.claudeConfigDir,baseRepoPath:t.repoPath,branch:c,baseBranch:o.baseBranch,jiraTransition:o.jiraTransition,jiraTransitionOnMerge:o.jiraTransitionOnMerge,requireApproval:o.requireApproval,doneLabel:i.doneLabel,failedLabel:i.failedLabel,repoName:t.project.repoName,jira:t.jira,cfg:t.cfg,actorEmail:t.actorEmail,resultText:v.resultText,costFields:C,runTests:o.runTests,fixSession:{sessionId:f,agent:o.agent,model:o.model,timeoutSeconds:o.timeoutSeconds,maxTurns:o.maxTurns},sendUsage:r,mergeOnApprove:o.mergeOnApprove,mergeMethod:o.mergeMethod,autoMerge:o.autoMerge,emit:e,setStatus:n}),t.onChainSession?.({sessionId:f,worktreePath:h})}catch(S){let A=S instanceof Error?S.message:String(S);e("error",`Run failed: ${A}`),ut(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:"implement failed",detail:A.slice(0,500)}),await vs(t,A),n("failed",{error:A})}finally{b&&!_&&!t.keepWorktree&&!w&&await Et(t.repoPath,h).catch(()=>{})}}async function jl(t,e,n,r){let{emit:s,setStatus:i,sendUsage:o,nextSeq:l}=Ir(t.runId,r.transport,t.nextLogSeq),c=t.repoPath,u=!1;try{if(!Qi(ve()??r.cfg,t.repoName??"",t.actorEmail))throw new Error("no GitHub token applies to this repo - run `allwright github set-token` (runner-wide) or `github set <repoName>` (this repo only)");i("running"),s("info",`Reply received on ${t.issueKey} - continuing run \`${t.runId}\``);let h=Mh(e)+await es(r.jiraFor(t.repoName??""),n,c,s),f=await _s(t.runId,We(t.agent),{repoPath:c,prompt:h,timeoutSeconds:t.timeoutSeconds,bin:Ve(r.cfg,t.agent??""),configDir:t.claudeConfigDir,mode:"edit_no_shell",model:t.model||void 0,maxTurns:t.maxTurns??120,sessionId:t.sessionId,resume:!0,onLog:(_,S)=>s(_,S),onUsage:o},s,()=>Vi(c)),b={costUsd:f.costUsd,inputTokens:f.inputTokens,outputTokens:f.outputTokens,billingMode:f.billingMode,model:f.model};if(!f.ok){let _=f.error??"Claude Code failed";s("error",`Run failed: ${_}`);let S=_;if(f.turnLimitHit&&t.branch){let A=await Ih(c,t.branch,t.runId,s);A&&(S+=Ah(A))}await Nt(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,S),jt(t.runId),i(f.timedOut?"timed_out":"failed",{error:_,...f.cancelled?{errorKind:"guard"}:{},...b});return}let w=ti(f.resultText);if(w){if(t.rounds>=_h){await zh(r.jiraFor(t.repoName??""),t,s,i,b);return}u=!0,await wo({kind:"implement",runId:t.runId,issueKey:t.issueKey,repoPath:c,sessionId:t.sessionId,doneLabel:t.doneLabel,failedLabel:t.failedLabel,timeoutSeconds:t.timeoutSeconds,jira:r.jiraFor(t.repoName??""),nextLogSeq:l(),rounds:t.rounds+1,createdAt:t.createdAt,claudeConfigDir:t.claudeConfigDir,actorEmail:t.actorEmail,agent:t.agent,model:t.model,baseRepoPath:t.baseRepoPath,repoName:t.repoName,branch:t.branch,baseBranch:t.baseBranch,jiraTransition:t.jiraTransition,jiraTransitionOnMerge:t.jiraTransitionOnMerge,requireApproval:t.requireApproval,mergeOnApprove:t.mergeOnApprove,mergeMethod:t.mergeMethod,autoMerge:t.autoMerge,runTests:t.runTests,maxTurns:t.maxTurns,issueSummary:t.issueSummary},w,s,i,b);return}gn(c),await Eh({runId:t.runId,issueKey:t.issueKey,issueSummary:t.issueSummary,worktreePath:c,agentConfigDir:t.claudeConfigDir,baseRepoPath:t.baseRepoPath??c,branch:t.branch,baseBranch:t.baseBranch,jiraTransition:t.jiraTransition,requireApproval:t.requireApproval??!0,doneLabel:t.doneLabel,failedLabel:t.failedLabel,repoName:t.repoName,jira:r.jiraFor(t.repoName??""),cfg:r.cfg,actorEmail:t.actorEmail,resultText:f.resultText,costFields:b,runTests:t.runTests,fixSession:{sessionId:t.sessionId,agent:t.agent??"",model:t.model,timeoutSeconds:t.timeoutSeconds,maxTurns:t.maxTurns},sendUsage:o,mergeOnApprove:t.mergeOnApprove,mergeMethod:t.mergeMethod,autoMerge:t.autoMerge??!1,emit:s,setStatus:i}),jt(t.runId)}catch(h){let f=h instanceof Error?h.message:String(h);s("error",`Run failed: ${f}`),await Nt(r.jiraFor(t.repoName??""),t.issueKey,t.runId,t.failedLabel,f),jt(t.runId),i("failed",{error:f})}finally{u||await Et(t.baseRepoPath??c,c).catch(()=>{})}}async function Eh(t){let{runId:e,issueKey:n,issueSummary:r,worktreePath:s,baseRepoPath:i,branch:o,baseBranch:l,jiraTransition:c,jiraTransitionOnMerge:u,requireApproval:h,doneLabel:f,failedLabel:b,repoName:w,jira:_,cfg:S,actorEmail:A,runTests:z,mergeOnApprove:q,mergeMethod:v,autoMerge:C,resultText:M,costFields:B,emit:j,setStatus:d}=t,m=await us(s);m.deleted.length&&j("info",`Deleted ${m.deleted.length} file(s) listed in ${Jt}: `+m.deleted.slice(0,10).join(", ")+(m.deleted.length>10?", \u2026":""));for(let ge of m.refused)j("warn",`${Jt} entry refused: ${ge}`);j("info","Committing changes"),await br(s,`${n}: ${r}
|
|
788
788
|
|
|
789
|
-
Allwright run ${e}`);let g=await xn(s,l);if(!g.ok){let ge=g.forbidden.length?`refusing to push: changes touch protected paths (${g.forbidden.slice(0,5).join(", ")}) - CI/workflow files can exfiltrate repo secrets and are never pushed by the agent. Apply those files' changes yourself, or re-run the ticket with them out of scope.`:`refusing to push: change is too large (${g.files} files, ${g.insertions+g.deletions} lines; limits ${_n}/${Sn})`;
|
|
790
|
-
${
|
|
791
|
-
${nt.tail.slice(-1500)}`));Fe=fe.length?`One automatic same-session fix attempt ran; the results above are AFTER it. First pass: ${gt} failure(s). ${
|
|
789
|
+
Allwright run ${e}`);let g=await xn(s,l);if(!g.ok){let ge=g.forbidden.length?`refusing to push: changes touch protected paths (${g.forbidden.slice(0,5).join(", ")}) - CI/workflow files can exfiltrate repo secrets and are never pushed by the agent. Apply those files' changes yourself, or re-run the ticket with them out of scope.`:`refusing to push: change is too large (${g.files} files, ${g.insertions+g.deletions} lines; limits ${_n}/${Sn})`;j("error",ge),await Nt(_,n,e,b,ge),d("failed",{error:ge,errorKind:"guard",...B});return}j("info",`Diff: ${g.files} file(s), +${g.insertions}/-${g.deletions}`);let R={...B},N="",G="",X,U,H;if(z){let ge=ms(s);if(!ge)j("info","No TEST.md in this repo - skipping the test run (nothing documented to run)");else{let oe=gs(Cl.default.readFileSync(ge,"utf8"));if(!oe.length)j("info",`${go.default.basename(ge)} lists no commands - nothing to run`);else{j("info",`Running ${oe.length} documented test command(s) - no tokens, plain shell`);let qe=await _r(s,oe,{perCommandTimeoutMs:15*6e4}),fe=qe.filter(ae=>ae.exitCode!==0),gt=fe.length;for(let ae of qe)j(ae.exitCode===0?"info":"warn",`${ae.exitCode===0?"PASS":"FAIL"} ${ae.command} (exit ${ae.exitCode})`+(ae.exitCode===0?"":`
|
|
790
|
+
${ae.tail.slice(-1500)}`));let Fe="";if(fe.length&&t.fixSession){let ae=await Lw({runId:e,issueKey:n,worktreePath:s,baseBranch:l,fixSession:t.fixSession,agentConfigDir:t.agentConfigDir,cfg:S,failed:fe,emit:j,sendUsage:t.sendUsage,baseCost:R});if(R.costUsd+=ae.cost.costUsd,R.inputTokens+=ae.cost.inputTokens,R.outputTokens+=ae.cost.outputTokens,ae.outcome==="cancelled"){let nt="stopped by a person during the automatic test-fix attempt - nothing was pushed";j("warn",nt),uo({runId:e,issueKey:n,issueSummary:r,mergeOnApprove:q,mergeMethod:v,autoMerge:C,repoName:w,baseRepoPath:i,branch:o,baseBranch:l,headSha:await Ze(s),requireApproval:h,doneLabel:f,failedLabel:b,jiraTransition:c,jiraTransitionOnMerge:u,actorEmail:A,resultSummary:kh(M),prSummary:El(M)??"",costUsd:R.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),await Nt(_,n,e,b,`${nt}. The commit survived on the runner - "Retry push" on the run's dashboard page ships it without a new agent run.`),d("failed",{error:nt,errorKind:"guard",retryAvailable:!0,...R});return}if(ae.outcome==="committed"){G=ae.resultText,j("info",`Re-running ${oe.length} documented test command(s) after the fix`),qe=await _r(s,oe,{perCommandTimeoutMs:15*6e4}),fe=qe.filter(nt=>nt.exitCode!==0);for(let nt of qe)j(nt.exitCode===0?"info":"warn",`${nt.exitCode===0?"PASS":"FAIL"} ${nt.command} (exit ${nt.exitCode})`+(nt.exitCode===0?"":`
|
|
791
|
+
${nt.tail.slice(-1500)}`));Fe=fe.length?`One automatic same-session fix attempt ran; the results above are AFTER it. First pass: ${gt} failure(s). ${ae.note}`:`The first pass had ${gt} failure(s); one automatic same-session fix attempt resolved them. ${ae.note}`}else Fe=ae.note}X=fe.slice(0,20).map(ae=>({command:ae.command.slice(0,500),exitCode:ae.exitCode,tail:ae.tail.slice(-4e3)})),U=qe.length-fe.length,H=qe.length,N=`
|
|
792
792
|
|
|
793
793
|
### Tests
|
|
794
|
-
`+qe.map(
|
|
794
|
+
`+qe.map(ae=>`- ${ae.exitCode===0?"PASS":"FAIL"} \`${ae.command}\``).join(`
|
|
795
795
|
`)+(fe.length?`
|
|
796
796
|
|
|
797
797
|
**${fe.length} of ${qe.length} failed.** Output is in the run log.`:`
|
|
798
798
|
|
|
799
799
|
All ${qe.length} passed.`)+(Fe?`
|
|
800
800
|
|
|
801
|
-
${Fe}`:""),fe.length&&
|
|
801
|
+
${Fe}`:""),fe.length&&j("warn",`${fe.length} test command(s) failed - the PR will say so; review before merging`),gt>0&&ut(i,{issueKey:n,runId:e,title:fe.length?`TEST.md commands failing at PR (${fe.length} of ${qe.length})`:"TEST.md failures fixed by same-session retry",detail:qe.map(ae=>`${ae.exitCode===0?"PASS":"FAIL"} ${ae.command}`).join(`
|
|
802
802
|
`)+(Fe?`
|
|
803
|
-
${Fe}`:"")})}}}let L=await vr(s),ne=wt(L);if(!ne){let ge=`origin "${L}" is not a GitHub remote - implement mode supports GitHub only`;
|
|
803
|
+
${Fe}`:"")})}}}let L=await vr(s),ne=wt(L);if(!ne){let ge=`origin "${L}" is not a GitHub remote - implement mode supports GitHub only`;j("error",ge),await Nt(_,n,e,b,ge),d("failed",{error:ge,...B});return}let W=await Ze(s),he=kh(M),Ue=(G?El(G):null)??El(M);try{await Ch({gitDir:s,ownerRepo:ne,runId:e,issueKey:n,issueSummary:r,agentConfigDir:t.agentConfigDir,branch:o,baseBranch:l,jiraTransition:c,jiraTransitionOnMerge:u,requireApproval:h,doneLabel:f,failedLabel:b,repoName:w,jira:_,cfg:S,actorEmail:A,mergeOnApprove:q,mergeMethod:v,autoMerge:C,summary:he,prSummary:Ue??void 0,cost:R,testReport:N,failedTests:X,testsPassed:U,testsTotal:H,goLiveDraft:(G?bh(G):null)??bh(M)??void 0,emit:j,setStatus:d})}catch(ge){let oe=ge instanceof Error?ge.message:String(ge);uo({runId:e,issueKey:n,issueSummary:r,mergeOnApprove:q,mergeMethod:v,autoMerge:C,repoName:w,baseRepoPath:i,branch:o,baseBranch:l,headSha:W,requireApproval:h,doneLabel:f,failedLabel:b,jiraTransition:c,jiraTransitionOnMerge:u,actorEmail:A,resultSummary:he,prSummary:Ue??"",costUsd:R.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),j("error",`Run failed: ${oe}`),j("info",`The commit itself survived on the runner (branch ${o}) - fix the cause, then use "Retry push" on this run's dashboard page.`),await Nt(_,n,e,b,`${oe}
|
|
804
804
|
|
|
805
|
-
The agent's commit survived on the runner - "Retry push" on the dashboard's run page re-pushes it without a new agent run.`),d("failed",{error:
|
|
805
|
+
The agent's commit survived on the runner - "Retry push" on the dashboard's run page re-pushes it without a new agent run.`),d("failed",{error:oe,retryAvailable:!0,...R})}}var Dw={costUsd:0,inputTokens:0,outputTokens:0};async function Lw(t){let{runId:e,issueKey:n,worktreePath:r,baseBranch:s,fixSession:i,cfg:o,failed:l,emit:c,sendUsage:u,baseCost:h}=t,f=We(i.agent);if(!f?.capabilities.sessionResume){let z=`No automatic fix attempt: the ${i.agent||"configured"} adapter cannot resume sessions.`;return c("info",z),{outcome:"skipped",note:z,cost:Dw}}c("info",`${l.length} test command(s) failed - resuming the same agent session for one fix attempt (same session = cached context, not a re-explore)`);let b=await Ze(r),w=await _s(e,f,{repoPath:r,prompt:Cw(l),timeoutSeconds:i.timeoutSeconds,bin:Ve(o,i.agent),configDir:t.agentConfigDir,mode:"edit_no_shell",model:i.model||void 0,maxTurns:Math.min(i.maxTurns??120,60),sessionId:i.sessionId,resume:!0,onLog:(z,q)=>c(z,q),onUsage:u?z=>u({...z,inputTokens:h.inputTokens+z.inputTokens,outputTokens:h.outputTokens+z.outputTokens,costUsd:z.costUsd===void 0?void 0:h.costUsd+z.costUsd}):void 0},c),_={costUsd:w.costUsd,inputTokens:w.inputTokens,outputTokens:w.outputTokens};if(w.cancelled)return{outcome:"cancelled",cost:_};if(!w.ok){let z=`One automatic fix attempt did not complete (${w.error??"agent error"}) - the results above are from the original work.`;return c("warn",z),{outcome:"agent_failed",note:z,cost:_}}if(ti(w.resultText)){let z="One automatic fix attempt asked for human input instead of fixing - the original commit ships unchanged; answer on the PR instead.";return c("warn",z),{outcome:"agent_failed",note:z,cost:_}}let S=await us(r);for(let z of S.refused)c("warn",`${Jt} entry refused: ${z}`);try{await br(r,`${n}: fix failing TEST.md commands
|
|
806
806
|
|
|
807
|
-
Allwright run ${e} (automatic test-fix attempt)`)}catch{let
|
|
807
|
+
Allwright run ${e} (automatic test-fix attempt)`)}catch{let z=`An automatic fix attempt concluded no code change was warranted: ${Ar(w.resultText)}`;return c("info",z),{outcome:"no_changes",note:z,cost:_}}let A=await xn(r,s);if(!A.ok){await ds(r,b);let z=A.forbidden.length?`An automatic fix attempt touched protected paths (${A.forbidden.slice(0,3).join(", ")}) and was discarded - the results above are from the original work.`:"An automatic fix attempt pushed the diff past the safety limits and was discarded - the results above are from the original work.";return c("warn",z),{outcome:"reverted",note:z,cost:_}}return{outcome:"committed",note:`Fix attempt: ${Ar(w.resultText)}`,resultText:w.resultText,cost:_}}async function Ch(t){let{gitDir:e,ownerRepo:n,runId:r,issueKey:s,issueSummary:i,mergeOnApprove:o,mergeMethod:l,autoMerge:c,branch:u,baseBranch:h,jiraTransition:f,jiraTransitionOnMerge:b,requireApproval:w,doneLabel:_,failedLabel:S,repoName:A,jira:z,cfg:q,actorEmail:v,summary:C,prSummary:M,cost:B,testReport:j,emit:d,setStatus:m}=t;d("info",`Pushing ${u} to origin`),await wr(e,u);let g=await Ji(e,u),N=`${M?.trim()?`${M.trim()}
|
|
808
808
|
|
|
809
809
|
<details>
|
|
810
810
|
<summary>Technical details</summary>
|
|
811
811
|
|
|
812
|
-
${
|
|
812
|
+
${C}
|
|
813
813
|
|
|
814
|
-
</details>`:
|
|
814
|
+
</details>`:C}${j??""}
|
|
815
815
|
|
|
816
816
|
---
|
|
817
817
|
Jira: ${new URL(`/browse/${s}`,q.jira?.baseUrl??"").toString()}
|
|
818
|
-
_Allwright implement run \`${r}\` \xB7 cost $${
|
|
818
|
+
_Allwright implement run \`${r}\` \xB7 cost $${B.costUsd.toFixed(4)}. `+(j?"Tests were run by the runner, not the agent._":"The agent has no shell and no tests were run here - review accordingly._");d("info","Opening pull request");let G=Qi(ve()??q,A,v);G.source==="user"&&d("info",`PR will be authored with ${v}'s own GitHub token`);let U=await new Me(G.token).createPullRequest(n.owner,n.repo,{title:`${s}: ${i}`.slice(0,250),head:u,base:h,body:N});d("info",`PR ready: ${U.url}`),ph({runId:r,issueKey:s,repoName:A,owner:n.owner,repo:n.repo,prNumber:U.number,prUrl:U.url,jiraTransitionOnMerge:b??"",createdAt:new Date().toISOString()}),m("posting",B);let H={nextDecisionSeq:1e5,runId:r,issueKey:s,repoName:A,owner:n.owner,repo:n.repo,prNumber:U.number,prUrl:U.url,branch:u,headSha:g,doneLabel:_,failedLabel:S,jiraTransition:f,mergeOnApprove:o,mergeMethod:l,autoMerge:c,agentConfigDir:t.agentConfigDir};if(w)_t(H),await z.addComment(s,`**Allwright opened a pull request for review.**
|
|
819
819
|
|
|
820
820
|
PR: ${U.url}
|
|
821
821
|
|
|
822
|
-
Approve the PR on GitHub OR on the Allwright dashboard - either completes the run. Rejecting on the dashboard closes the PR and deletes the branch. (run \`${r}\`)`),m("awaiting_approval",{...
|
|
822
|
+
Approve the PR on GitHub OR on the Allwright dashboard - either completes the run. Rejecting on the dashboard closes the PR and deletes the branch. (run \`${r}\`)`),m("awaiting_approval",{...B,prUrl:U.url,headSha:g,resultSummary:Ar(M?.trim()||C),retryAvailable:!1,...t.failedTests!==void 0?{failedTests:t.failedTests}:{},...t.testsPassed!==void 0?{testsPassed:t.testsPassed}:{},...t.testsTotal!==void 0?{testsTotal:t.testsTotal}:{},...t.goLiveDraft!==void 0?{goLiveDraft:t.goLiveDraft}:{}}),d("info",`Awaiting approval on the dashboard \xB7 $${B.costUsd.toFixed(4)}`);else{if(c){d("info",`Auto-merging PR #${U.number} (${l})`);let ne=je(q,A),W=ne?await new Me(ne).mergePullRequest(n.owner,n.repo,U.number,l,{sha:g,title:`${s} (#${U.number})`}):{merged:!1,reason:"no GitHub token applies to this repo"};W.merged?d("info",`PR #${U.number} merged`):(d("warn",`Auto-merge did not go through - ${W.reason}. The PR stays open.`),await z.addComment(s,`**Allwright:** the work is done and the PR is open, but auto-merge did not go through - ${W.reason}
|
|
823
823
|
|
|
824
|
-
PR: ${U.url}`))}let L=(ve()??q).repos[
|
|
824
|
+
PR: ${U.url}`))}let L=(ve()??q).repos[A]?.path;L&&Zs(L,s)&&ut(L,{issueKey:s,runId:r,title:"shipped after earlier failure",detail:`PR ${U.url} merged/opened straight-through.`}),await $h({jira:z,issueKey:s},H,d),m("succeeded",{...B,prUrl:U.url,headSha:g,resultSummary:Ar(M?.trim()||C),retryAvailable:!1,...t.failedTests!==void 0?{failedTests:t.failedTests}:{},...t.testsPassed!==void 0?{testsPassed:t.testsPassed}:{},...t.testsTotal!==void 0?{testsTotal:t.testsTotal}:{},...t.goLiveDraft!==void 0?{goLiveDraft:t.goLiveDraft}:{}}),d("info",`Run succeeded \xB7 ${U.url} \xB7 $${B.costUsd.toFixed(4)}`)}}async function $h(t,e,n){let r=null;if(e.jiraTransition)try{await t.jira.transitionByName(e.issueKey,e.jiraTransition)?n("info",`Jira transition "${e.jiraTransition}" applied`):(r=`no transition named "${e.jiraTransition}" is available from this ticket's current status - the PR is fine, but move the ticket manually`,n("warn",r))}catch(i){r=`Jira transition failed: ${i instanceof Error?i.message:i}`,n("warn",r)}let s=e.mergeOnApprove;return await t.jira.addComment(e.issueKey,(s?`**Allwright: implementation complete - the pull request was merged.**
|
|
825
825
|
|
|
826
826
|
PR: ${e.prUrl}`:`**Allwright: the change is approved, but NOT merged yet.**
|
|
827
827
|
|
|
@@ -831,73 +831,73 @@ This rule is set to "my team merges on GitHub", so Allwright deliberately did no
|
|
|
831
831
|
|
|
832
832
|
Note: ${r}`:"")+`
|
|
833
833
|
|
|
834
|
-
(run \`${e.runId}\`)`),await t.jira.editLabels(e.issueKey,{add:[e.doneLabel],remove:[_e.NEEDS_INPUT_LABEL]}),r}async function
|
|
834
|
+
(run \`${e.runId}\`)`),await t.jira.editLabels(e.issueKey,{add:[e.doneLabel],remove:[_e.NEEDS_INPUT_LABEL]}),r}async function Qs(t,e,n){let r=ws(e);if(!r){y.warn(`run.approved for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:s,setStatus:i}=Nh(t,e);try{let o=je(ve()??t.cfg,r.repoName);if(!o)throw new Error("GitHub token missing on this runner");let l=new Me(o);s("info",`Approval received for ${r.issueKey} - verifying PR state`);let c=await l.getPullRequest(r.owner,r.repo,r.prNumber);if(!c)throw new Error(`PR #${r.prNumber} no longer exists on GitHub`);if(c.state==="closed"&&!c.merged)throw new Error(`PR #${r.prNumber} was closed on GitHub without merging`);let u=n??r.headSha;if(c.state==="open"&&c.headSha!==u){let h=`PR #${r.prNumber} changed since review started (${u.slice(0,7)} \u2192 ${c.headSha.slice(0,7)}) - approval not applied. Re-review the PR and approve again.`;s("warn",h),await t.jiraFor(r.repoName??"").addComment(r.issueKey,`**Allwright:** ${h}`),i("awaiting_approval",{prUrl:r.prUrl,headSha:c.headSha,resultSummary:h});return}if(r.mergeOnApprove&&c.state==="open"&&!c.merged){s("info",`Merging PR #${r.prNumber} (${r.mergeMethod})`);let h=await l.mergePullRequest(r.owner,r.repo,r.prNumber,r.mergeMethod,{sha:u,title:`${r.issueKey} (#${r.prNumber})`});if(!h.merged){let f=`Approved, but the merge did not go through - ${h.reason}`;s("warn",f),await t.jiraFor(r.repoName??"").addComment(r.issueKey,`**Allwright:** ${f}
|
|
835
835
|
|
|
836
|
-
PR: ${r.prUrl}`),i("awaiting_approval",{prUrl:r.prUrl,headSha:c.headSha,resultSummary:f});return}s("info",`PR #${r.prNumber} merged`)}{let
|
|
836
|
+
PR: ${r.prUrl}`),i("awaiting_approval",{prUrl:r.prUrl,headSha:c.headSha,resultSummary:f});return}s("info",`PR #${r.prNumber} merged`)}{let h=(ve()??t.cfg).repos[r.repoName??""]?.path;h&&Zs(h,r.issueKey)&&ut(h,{issueKey:r.issueKey,runId:e,title:"shipped after earlier failure",detail:`PR ${r.prUrl} approved and completed.`})}await $h({jira:t.jiraFor(r.repoName??""),issueKey:r.issueKey},r,s),i("succeeded",{prUrl:r.prUrl,...r.mergeOnApprove?{}:{resultSummary:"Approved, but the PR was NOT merged - this rule leaves merging to your team on GitHub. Nothing ships until someone merges it."}}),s("info",r.mergeOnApprove?"Run completed after approval":'Run completed after approval - the PR is still OPEN because this rule does not merge on approval. Merge it on GitHub, or turn on "Merge the PR when I approve" in the rule.'),xr(e)}catch(o){let l=o instanceof Error?o.message:String(o);s("error",`Approval handling failed: ${l}`),await Oh(t,r,l),i("failed",{error:l}),xr(e)}}async function Ph(t,e){let n=ws(e);if(!n){y.warn(`run.rejected for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:r,setStatus:s}=Nh(t,e);try{let i=je(ve()??t.cfg,n.repoName);if(!i)throw new Error("GitHub token missing on this runner");let o=new Me(i);r("info",`Rejection received for ${n.issueKey} - closing PR #${n.prNumber}`);let l=await o.getPullRequest(n.owner,n.repo,n.prNumber);l&&l.state==="open"&&await o.closePullRequest(n.owner,n.repo,n.prNumber),l?.merged||await o.deleteBranch(n.owner,n.repo,n.branch),await t.jiraFor(n.repoName??"").addComment(n.issueKey,`**Allwright: changes rejected.**
|
|
837
837
|
|
|
838
|
-
The pull request was closed and the branch deleted. This ticket is labeled \`${n.failedLabel}\`; remove the label to try again. (run \`${n.runId}\`)`),await t.jiraFor(n.repoName??"").editLabels(n.issueKey,{add:[n.failedLabel]}),s("failed",{error:"rejected by user"}),r("info","PR closed, branch deleted, ticket labeled"),xr(e)}catch(i){let o=i instanceof Error?i.message:String(i);r("error",`Rejection handling failed: ${o}`),await
|
|
838
|
+
The pull request was closed and the branch deleted. This ticket is labeled \`${n.failedLabel}\`; remove the label to try again. (run \`${n.runId}\`)`),await t.jiraFor(n.repoName??"").editLabels(n.issueKey,{add:[n.failedLabel]}),s("failed",{error:"rejected by user"}),r("info","PR closed, branch deleted, ticket labeled"),xr(e)}catch(i){let o=i instanceof Error?i.message:String(i);r("error",`Rejection handling failed: ${o}`),await Oh(t,n,o),s("failed",{error:o}),xr(e)}}async function jh(t,e){let n=ho(e);if(!n){y.warn(`run.retryPush for ${e}: no retry record (already pushed, or invalidated?)`);let{emit:l,setStatus:c,sendUsage:u}=Ir(e,t.transport,1e5);l("error","Retry push requested, but this runner holds no retry record for the run - it was already used or never saved. Re-run the ticket instead."),c("failed",{retryAvailable:!1});return}let{emit:r,setStatus:s,sendUsage:i,nextSeq:o}=Ir(e,t.transport,n.nextLogSeq);try{let l=await Ji(n.baseRepoPath,n.branch);if(l!==n.headSha){r("error",`Retry push aborted: branch ${n.branch} no longer holds the commit this run produced (expected ${n.headSha.slice(0,7)}, ${l?`found ${l.slice(0,7)}`:"the branch is gone"}) - a newer run has likely reused the branch. Re-run the ticket instead.`),Il(e),s("failed",{retryAvailable:!1});return}let c=await vr(n.baseRepoPath),u=wt(c);if(!u)throw new Error(`origin "${c}" is not a GitHub remote`);r("info",`Retry push for ${n.issueKey}: branch ${n.branch} at ${n.headSha.slice(0,7)}`);let h=t.jiraFor(n.repoName);await Ch({gitDir:n.baseRepoPath,ownerRepo:u,runId:n.runId,issueKey:n.issueKey,issueSummary:n.issueSummary,branch:n.branch,baseBranch:n.baseBranch,jiraTransition:n.jiraTransition,jiraTransitionOnMerge:n.jiraTransitionOnMerge,requireApproval:n.requireApproval,mergeOnApprove:n.mergeOnApprove??!1,mergeMethod:n.mergeMethod??"squash",autoMerge:n.autoMerge??!1,doneLabel:n.doneLabel,failedLabel:n.failedLabel,repoName:n.repoName,jira:h,cfg:ve()??t.cfg,actorEmail:n.actorEmail,summary:n.resultSummary,prSummary:n.prSummary||void 0,cost:{costUsd:n.costUsd},emit:r,setStatus:s}),Il(e),await h.editLabels(n.issueKey,{remove:[n.failedLabel]}).catch(()=>{})}catch(l){let c=l instanceof Error?l.message:String(l);r("error",`Retry push failed: ${c}`),uo({...n,nextLogSeq:o()}),s("failed",{error:c,retryAvailable:!0})}}function Nh(t,e){let n=1e5;return{emit:(i,o)=>{t.transport.send({type:"run.log",runId:e,seq:n++,ts:new Date().toISOString(),level:i,message:o}),i!=="agent"&&y.info(`[run ${e}] ${o}`)},setStatus:(i,o={})=>{t.transport.send({type:"run.status",runId:e,status:i,...o})}}}async function Oh(t,e,n){try{await t.jiraFor(e.repoName??"").addComment(e.issueKey,`**Allwright could not complete the approval decision.**
|
|
839
839
|
|
|
840
840
|
Error: ${n.slice(0,800)}
|
|
841
841
|
|
|
842
842
|
PR: ${e.prUrl}
|
|
843
|
-
(run \`${e.runId}\`)`),await t.jiraFor(e.repoName??"").editLabels(e.issueKey,{add:[e.failedLabel]})}catch(r){y.error(`could not post decision failure to ${e.issueKey}: ${r}`)}}function
|
|
843
|
+
(run \`${e.runId}\`)`),await t.jiraFor(e.repoName??"").editLabels(e.issueKey,{add:[e.failedLabel]})}catch(r){y.error(`could not post decision failure to ${e.issueKey}: ${r}`)}}function ei(t){if(!t.length)return"(no comments)";let e=6e4,n=t.map(i=>`${i.author} (${i.created}):
|
|
844
844
|
${i.body}`),r=[],s=0;for(let i=n.length-1;i>=0;i--){if(s+=n[i].length+6,s>e){r.unshift(`(\u2026 ${i+1} earlier comment(s) omitted for length \u2026)`);break}r.unshift(n[i])}return r.join(`
|
|
845
845
|
---
|
|
846
|
-
`)}function
|
|
846
|
+
`)}function Mh(t){return`The ticket author replied:
|
|
847
847
|
|
|
848
848
|
${t}
|
|
849
849
|
|
|
850
|
-
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 ${_e.NEEDS_INPUT_MARKER} marker).`}function
|
|
850
|
+
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 ${_e.NEEDS_INPUT_MARKER} marker).`}function ti(t){let e=t.trim(),n=e.split(`
|
|
851
851
|
`,1)[0].trim(),r=o=>o.replace(/[^a-z]/gi,"").toUpperCase();if(r(n)!==r(_e.NEEDS_INPUT_MARKER))return null;let s=e.indexOf(`
|
|
852
|
-
`);return s<0?null:e.slice(s+1).trim()||null}function
|
|
852
|
+
`);return s<0?null:e.slice(s+1).trim()||null}function Uw(t){let n=[...t.matchAll(new RegExp(`\`\`\`${_e.NEEDS_INPUT_ASK_FENCE}\\s*\\n([\\s\\S]*?)\`\`\``,"g"))],r=[];for(let i=n.length-1;i>=0&&!r.length;i--)try{let o=JSON.parse(n[i][1]);r=(Array.isArray(o.options)?o.options:[]).filter(c=>typeof c=="string"&&!!c.trim()).slice(0,5).map(c=>c.trim().slice(0,200))}catch{}return{questions:t.replace(new RegExp(`\`\`\`${_e.NEEDS_INPUT_ASK_FENCE}\\s*\\n[\\s\\S]*?\`\`\``,"g"),"").trim()||t.trim(),options:r}}async function wo(t,e,n,r,s){let{questions:i,options:o}=Uw(e);n("info",`Claude needs more information - posting questions to ${t.issueKey}`),await t.jira.addComment(t.issueKey,`**${_e.NEEDS_INPUT_COMMENT_MARKER} before it can continue.**
|
|
853
853
|
|
|
854
854
|
${i}
|
|
855
855
|
|
|
856
|
-
Reply with your answers in a comment on this ticket - or answer on the run page in the Allwright dashboard. Either way this run picks up right where it left off. (run \`${t.runId}\`)`);let l=new Date().toISOString();await t.jira.editLabels(t.issueKey,{add:[_e.NEEDS_INPUT_LABEL]}),
|
|
856
|
+
Reply with your answers in a comment on this ticket - or answer on the run page in the Allwright dashboard. Either way this run picks up right where it left off. (run \`${t.runId}\`)`);let l=new Date().toISOString();await t.jira.editLabels(t.issueKey,{add:[_e.NEEDS_INPUT_LABEL]}),gh({runId:t.runId,issueKey:t.issueKey,kind:t.kind,mergeOnApprove:t.mergeOnApprove??!1,mergeMethod:t.mergeMethod??"squash",autoMerge:t.autoMerge??!1,repoPath:t.repoPath,sessionId:t.sessionId,doneLabel:t.doneLabel,failedLabel:t.failedLabel,timeoutSeconds:t.timeoutSeconds,createdAt:t.createdAt??l,questionsPostedAt:l,rounds:t.rounds,nextLogSeq:t.nextLogSeq,baseRepoPath:t.baseRepoPath,repoName:t.repoName,branch:t.branch,baseBranch:t.baseBranch,jiraTransition:t.jiraTransition,jiraTransitionOnMerge:t.jiraTransitionOnMerge,requireApproval:t.requireApproval,maxTurns:t.maxTurns,runTests:t.runTests??!0,issueSummary:t.issueSummary??"",claudeConfigDir:t.claudeConfigDir,agent:t.agent,model:t.model,actorEmail:t.actorEmail}),r("needs_input",{...s,resultSummary:Ar(i),inputQuestions:i.slice(0,4e3),inputOptions:o}),n("info",`Waiting for an answer on ${t.issueKey} (label "${_e.NEEDS_INPUT_LABEL}") or on this run page`+(o.length?` - ${o.length} suggested answer(s) offered`:""))}async function zh(t,e,n,r,s){let i=`Claude asked for clarification ${e.rounds} times without reaching a result - giving up. Answer more completely and re-trigger manually if you want another attempt.`;n("error",i),await Nt(t,e.issueKey,e.runId,e.failedLabel,i),jt(e.runId),r("failed",{error:i,...s})}async function vs(t,e){await Nt(t.jira,t.issueKey,t.runId,t.rule.trigger.failedLabel,e)}async function Nt(t,e,n,r,s){try{await t.addComment(e,`**Allwright run failed.**
|
|
857
857
|
|
|
858
858
|
Error: ${s.slice(0,800)}
|
|
859
859
|
|
|
860
|
-
This ticket has been labeled \`${r}\` and will not be retried automatically. To retry, fix the cause and remove the \`${r}\` label. (run \`${n}\`)`),await t.editLabels(e,{add:[r],remove:[_e.NEEDS_INPUT_LABEL]})}catch(i){y.error(`could not post failure comment to ${e}: ${i}`)}}function
|
|
861
|
-
`)){let n=e.replace(/^#+\s*/,"").trim();if(n.length>10)return n.slice(0,200)}return t.slice(0,200)}var Ss=
|
|
860
|
+
This ticket has been labeled \`${r}\` and will not be retried automatically. To retry, fix the cause and remove the \`${r}\` label. (run \`${n}\`)`),await t.editLabels(e,{add:[r],remove:[_e.NEEDS_INPUT_LABEL]})}catch(i){y.error(`could not post failure comment to ${e}: ${i}`)}}function kh(t){let e=t.split(/\n##\s*(?:PR summary|Go-live draft)\s*\n/i)[0],n=/##\s*Summary of changes\s*\n([\s\S]*)$/i.exec(e);return(n?n[1]:e).trim().slice(0,8e3)||"(no summary provided)"}function El(t){let e=/##\s*PR summary\s*\n([\s\S]*?)(?=\n##\s|$)/i.exec(t),n=e?e[1].trim():"";return n?n.slice(0,2e3):null}function Ar(t){for(let e of t.split(`
|
|
861
|
+
`)){let n=e.replace(/^#+\s*/,"").trim();if(n.length>10)return n.slice(0,200)}return t.slice(0,200)}var Ss=I(require("node:fs"),1);var Er=I(require("node:fs"),1),Nl=I(require("node:os"),1),Cr=I(require("node:path"),1);function qw(){try{return Nl.default.userInfo().username}catch{return"the user the runner service runs as"}}function Fw(t,e){let n=Cr.default.join(t,"apps","api","prisma","manual"),r=Cr.default.join(t,"prisma","manual");for(let s of[n,r]){let i;try{i=Er.default.readdirSync(s).filter(o=>o.endsWith(".sql")).sort()}catch{continue}for(let o of i.reverse())try{let l=Er.default.readFileSync(Cr.default.join(s,o),"utf8");if(new RegExp(`"${e}"`,"i").test(l))return o}catch{}}return null}function Ol(t,e){let n=t.slice(-4e3),r=qw(),s=e?.cwd?` -C ${e.cwd}`:"",i=/column "([^"]+)" of relation "([^"]+)" does not exist/i.exec(n)??/column ([\w.]+) does not exist/i.exec(n)??/The column `?([\w.]+)`? does not exist in the current database/i.exec(n)??/relation "([^"]+)" does not exist/i.exec(n);if(i){let u=(i[1]??"").split(".").pop()??"",h=e?.cwd?Fw(e.cwd,u):null;return{cause:`The code expects "${u}" in the database and the database does not have it. This is not a deploy-steps problem: a schema change shipped with the code, and the SQL that applies it is a HUMAN step by design`+(h?` - it is \`prisma/manual/${h}\`, checked in and not yet applied.`:"."),commands:h?[`cd apps/api && npx prisma db execute --file prisma/manual/${h} # dev/test database`,`cd apps/api && npx prisma db execute --url "$PROD_DATABASE_URL" --file prisma/manual/${h} # the live one`]:[`ls apps/api/prisma/manual/ # find the migration that adds "${u}"`,"cd apps/api && npx prisma db execute --file prisma/manual/<that file>"],note:"Apply it to EVERY database the code talks to - the test database and the live one are usually different, and applying only one turns a red build into a green build that breaks at runtime. Then re-run the deploy."}}let o=/\/usr\/bin\/env: ['\u2018]?(node|npm)['\u2019]?: No such file or directory/i.exec(n);if(o){let u="";try{let h=Cr.default.join(Nl.default.homedir(),".nvm","versions","node"),f=Er.default.readdirSync(h).sort();f.length&&(u=Cr.default.join(h,f[f.length-1],"bin"))}catch{}return{cause:`"${o[1]}" was not on the PATH of the process that ran this. npm's own first line is "#!/usr/bin/env node", so pointing at npm by absolute path does not help - npm still has to find node, and a systemd unit starts with a bare PATH that has never heard of nvm. It exits 127 immediately, and with Restart=always it does that forever while the start timestamp keeps moving, which is why a restart can look like it worked.`,commands:["sudo mkdir -p /etc/systemd/system/<your-unit>.service.d",`sudo tee /etc/systemd/system/<your-unit>.service.d/path.conf >/dev/null <<'EOF'
|
|
862
862
|
[Service]
|
|
863
863
|
Environment=PATH=${u||"<the bin directory holding node>"}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
|
|
864
|
-
EOF`,"sudo systemctl daemon-reload && sudo systemctl reset-failed <your-unit> && sudo systemctl restart <your-unit>"],note:"reset-failed because a crash loop leaves a restart counter behind. If you would rather not depend on a version-numbered nvm path, install Node system-wide instead - then /usr/bin/node exists and the bare PATH is enough."}}let l=/Failed to connect to ([\w.]+) port (\d+)|connect to ([\w.]+) port (\d+) failed|Connection refused/i.exec(n);if(l){let u=l[2]??l[4]??"",f=(Er.default.existsSync("/etc/systemd/system")?Er.default.readdirSync("/etc/systemd/system").filter(b=>b.endsWith(".service")).filter(b=>{try{let w=Er.default.readFileSync(Cr.default.join("/etc/systemd/system",b),"utf8");return e?.cwd?w.includes(e.cwd):!1}catch{return!1}}).map(b=>b.replace(/\.service$/,"")):[])[0];return{cause:`Nothing is listening on ${l[1]??l[3]??"that address"}${u?`:${u}`:""}. `+(f?`The service that runs this checkout is "${f}" - a restart moves its start timestamp even when it dies a second later, so "a restart really happened" does not mean it stayed up. Either it is crash-looping, or it bound a DIFFERENT port than this check expects.`:"No systemd unit on this machine references this checkout, so nothing here is keeping the app alive between deploys."),commands:f?[`systemctl status ${f} --no-pager -l # active (running), or restarting in a loop?`,`journalctl -u ${f} -n 40 --no-pager # the crash itself`,`systemctl show ${f} -p Environment --value # the PORT it was actually given`,"ss -ltnp | grep -E 'node|next' # what it really bound, if anything"]:["ss -ltnp | grep -E 'node|next' # is anything serving this app at all?"],note:f?"If the port differs, change either the unit's PORT or this check - they must be the same number. If it crash-loops, the journal's last lines are the reason; a wrong ExecStart path shows up as status=203/EXEC.":"Until something supervises this app, a deploy has nothing to restart and nothing survives a reboot."}}if(/could not read (Username|Password) for/i.test(n)||/Authentication failed for .*https/i.test(n)||/fatal: Authentication failed/i.test(n))return{cause:`git needs a GitHub credential for the account this deploy runs as (${r}) and has none. It tried to ask, found no terminal, and gave up. Allwright's own GitHub token is NOT used here: deploy steps are plain shell, so they see only this machine's git config - which is why the same repo can push fine from Allwright and still fail this step.`,commands:[`sudo -u ${r} git${s} ls-remote origin >/dev/null && echo "AUTH OK" || echo "AUTH FAIL"`,`sudo -u ${r} gh auth setup-git # if you signed in with the gh CLI - its login does not reach git by itself`,`sudo -u ${r} git config --global credential.helper store # then one manual 'git fetch' to save the token`],note:`Or switch the checkout to SSH and give ${r} a deploy key: git${s} remote set-url origin git@github.com:OWNER/REPO.git. Never paste a token into a deploy step - it ends up in run logs and screenshots.`};if(/Permission denied \(publickey/i.test(n))return{cause:`SSH could not authenticate to the git host as ${r}. The key either does not exist for that account, or is not the one registered with the repository.`,commands:[`sudo -u ${r} ssh -T git@github.com # expect "successfully authenticated"`,`sudo -u ${r} ls -l ~/.ssh/`],note:"Add that account's public key as a deploy key on the repository (read-only is enough to fetch)."};if(/Host key verification failed/i.test(n))return{cause:`The git host is not in ${r}'s known_hosts, and ssh will not accept it unattended.`,commands:[`sudo -u ${r} ssh-keyscan github.com >> ~/.ssh/known_hosts`],note:"Run it as that user - a known_hosts entry under your own account does nothing for the service."};let c=/(?:^|\n)(?:bash: )?([\w.-]+): command not found/i.exec(n);return c?{cause:`"${c[1]}" is not on the PATH of the account this deploy runs as (${r}). A tool installed through nvm, asdf or a shell profile usually is not: the service starts with a bare environment, not your login shell.`,commands:[`sudo -u ${r} which ${c[1]} || echo "not on this account's PATH"`,`command -v ${c[1]} # where YOUR shell finds it`],note:"Either install it system-wide, or use the absolute path in the step - the path your own shell resolves is not the one the deploy gets."}:/EACCES|Permission denied(?!\s*\(publickey)/i.test(n)?{cause:`A path in this step is not writable by the account the deploy runs as (${r}).`,commands:[`sudo -u ${r} test -w ${e?.cwd??"<the path>"} && echo writable || echo "NOT writable"`],note:"Fix the ownership of that path rather than running the deploy as root - a root-owned build directory breaks the next deploy the other way."}:null}function
|
|
864
|
+
EOF`,"sudo systemctl daemon-reload && sudo systemctl reset-failed <your-unit> && sudo systemctl restart <your-unit>"],note:"reset-failed because a crash loop leaves a restart counter behind. If you would rather not depend on a version-numbered nvm path, install Node system-wide instead - then /usr/bin/node exists and the bare PATH is enough."}}let l=/Failed to connect to ([\w.]+) port (\d+)|connect to ([\w.]+) port (\d+) failed|Connection refused/i.exec(n);if(l){let u=l[2]??l[4]??"",f=(Er.default.existsSync("/etc/systemd/system")?Er.default.readdirSync("/etc/systemd/system").filter(b=>b.endsWith(".service")).filter(b=>{try{let w=Er.default.readFileSync(Cr.default.join("/etc/systemd/system",b),"utf8");return e?.cwd?w.includes(e.cwd):!1}catch{return!1}}).map(b=>b.replace(/\.service$/,"")):[])[0];return{cause:`Nothing is listening on ${l[1]??l[3]??"that address"}${u?`:${u}`:""}. `+(f?`The service that runs this checkout is "${f}" - a restart moves its start timestamp even when it dies a second later, so "a restart really happened" does not mean it stayed up. Either it is crash-looping, or it bound a DIFFERENT port than this check expects.`:"No systemd unit on this machine references this checkout, so nothing here is keeping the app alive between deploys."),commands:f?[`systemctl status ${f} --no-pager -l # active (running), or restarting in a loop?`,`journalctl -u ${f} -n 40 --no-pager # the crash itself`,`systemctl show ${f} -p Environment --value # the PORT it was actually given`,"ss -ltnp | grep -E 'node|next' # what it really bound, if anything"]:["ss -ltnp | grep -E 'node|next' # is anything serving this app at all?"],note:f?"If the port differs, change either the unit's PORT or this check - they must be the same number. If it crash-loops, the journal's last lines are the reason; a wrong ExecStart path shows up as status=203/EXEC.":"Until something supervises this app, a deploy has nothing to restart and nothing survives a reboot."}}if(/could not read (Username|Password) for/i.test(n)||/Authentication failed for .*https/i.test(n)||/fatal: Authentication failed/i.test(n))return{cause:`git needs a GitHub credential for the account this deploy runs as (${r}) and has none. It tried to ask, found no terminal, and gave up. Allwright's own GitHub token is NOT used here: deploy steps are plain shell, so they see only this machine's git config - which is why the same repo can push fine from Allwright and still fail this step.`,commands:[`sudo -u ${r} git${s} ls-remote origin >/dev/null && echo "AUTH OK" || echo "AUTH FAIL"`,`sudo -u ${r} gh auth setup-git # if you signed in with the gh CLI - its login does not reach git by itself`,`sudo -u ${r} git config --global credential.helper store # then one manual 'git fetch' to save the token`],note:`Or switch the checkout to SSH and give ${r} a deploy key: git${s} remote set-url origin git@github.com:OWNER/REPO.git. Never paste a token into a deploy step - it ends up in run logs and screenshots.`};if(/Permission denied \(publickey/i.test(n))return{cause:`SSH could not authenticate to the git host as ${r}. The key either does not exist for that account, or is not the one registered with the repository.`,commands:[`sudo -u ${r} ssh -T git@github.com # expect "successfully authenticated"`,`sudo -u ${r} ls -l ~/.ssh/`],note:"Add that account's public key as a deploy key on the repository (read-only is enough to fetch)."};if(/Host key verification failed/i.test(n))return{cause:`The git host is not in ${r}'s known_hosts, and ssh will not accept it unattended.`,commands:[`sudo -u ${r} ssh-keyscan github.com >> ~/.ssh/known_hosts`],note:"Run it as that user - a known_hosts entry under your own account does nothing for the service."};let c=/(?:^|\n)(?:bash: )?([\w.-]+): command not found/i.exec(n);return c?{cause:`"${c[1]}" is not on the PATH of the account this deploy runs as (${r}). A tool installed through nvm, asdf or a shell profile usually is not: the service starts with a bare environment, not your login shell.`,commands:[`sudo -u ${r} which ${c[1]} || echo "not on this account's PATH"`,`command -v ${c[1]} # where YOUR shell finds it`],note:"Either install it system-wide, or use the absolute path in the step - the path your own shell resolves is not the one the deploy gets."}:/EACCES|Permission denied(?!\s*\(publickey)/i.test(n)?{cause:`A path in this step is not writable by the account the deploy runs as (${r}).`,commands:[`sudo -u ${r} test -w ${e?.cwd??"<the path>"} && echo writable || echo "NOT writable"`],note:"Fix the ownership of that path rather than running the deploy as root - a root-owned build directory breaks the next deploy the other way."}:null}function Dh(t){return t?`
|
|
865
865
|
|
|
866
866
|
What this means: ${t.cause}
|
|
867
867
|
Run these ON THE DEPLOY MACHINE:
|
|
868
868
|
`+t.commands.map(e=>` ${e}`).join(`
|
|
869
869
|
`)+`
|
|
870
|
-
${t.note}`:""}var $r=
|
|
870
|
+
${t.note}`:""}var $r=I(require("node:path"),1),To=require("node:child_process"),Fl=I(require("node:readline"),1),Bl=require("node:crypto"),Pr=I(ke(),1);Xr();Ae();var xo=I(ke(),1);Ct();kt();kr();_o();var Bh="";function Hh(t){Bh=(t??"").trim()}function Kh(){return Bh}Ul();Xt();var Yh=4e3,ev=4e3;function Xh(t,e){t("warn",`${e.length} step(s) still need YOU - Allwright deliberately did not run these:
|
|
871
871
|
`+e.map(n=>` ${n.command}${n.why?` # ${n.why}`:""}`).join(`
|
|
872
|
-
`))}function
|
|
872
|
+
`))}function Hl(t){let e=0;return{emit:(s,i)=>{t.transport.send({type:"run.log",runId:t.runId,seq:e++,ts:new Date().toISOString(),level:s,message:i.slice(0,ev)}),s!=="agent"&&y.info(`[deploy ${t.runId}] ${i}`)},setStatus:(s,i={})=>{t.transport.send({type:"run.status",runId:t.runId,status:s,...i})}}}var tv=/^\s*(?:ALLWRIGHT|TICKETPILOT)[-\s]MANUAL:\s*(.+)$/i;function nv(t){let e=tv.exec(t);if(!e)return null;let[n,...r]=e[1].split(/\s+#\s+/),s=n.trim();return s?{command:s.slice(0,500),why:r.join(" # ").trim().slice(0,300)}:null}async function Ro(t){let{emit:e,setStatus:n}=Hl(t),r=t.environment;try{let s=rv(t);if(s){e("error",s),await dt(t,`**Allwright could not deploy to \`${r.name}\`.**
|
|
873
873
|
|
|
874
|
-
${s}`),n("failed",{error:s});return}if(r.requireApproval){
|
|
874
|
+
${s}`),n("failed",{error:s});return}if(r.requireApproval){mh({runId:t.runId,issueKey:t.issueKey,issueSummary:t.issueSummary,projectId:t.project.id,repoName:t.project.repoName,environmentName:r.name,requestedBy:t.requestedBy,createdAt:new Date().toISOString()}),e("info",`Deploy to "${r.name}" is waiting for approval on the dashboard - no step has run yet`),await dt(t,`**Allwright: deploy to \`${r.name}\` needs approval.**
|
|
875
875
|
|
|
876
|
-
${t.requestedBy?`Requested by ${t.requestedBy}. `:""}Nothing has been executed yet. Approve it on the Allwright dashboard to run the ${r.steps.length} deploy step(s), or reject to cancel. (run \`${t.runId}\`)`),n("awaiting_approval",{resultSummary:`Awaiting approval to deploy ${t.issueKey} to ${r.name}`});return}await
|
|
876
|
+
${t.requestedBy?`Requested by ${t.requestedBy}. `:""}Nothing has been executed yet. Approve it on the Allwright dashboard to run the ${r.steps.length} deploy step(s), or reject to cancel. (run \`${t.runId}\`)`),n("awaiting_approval",{resultSummary:`Awaiting approval to deploy ${t.issueKey} to ${r.name}`});return}await np(t,e,n)}catch(s){let i=s instanceof Error?s.message:String(s);e("error",`Deploy failed: ${i}`),await dt(t,`**Allwright deploy to \`${r.name}\` failed.**
|
|
877
877
|
|
|
878
878
|
${i.slice(0,800)}
|
|
879
879
|
|
|
880
|
-
(run \`${t.runId}\`)`),n("failed",{error:i})}}function
|
|
880
|
+
(run \`${t.runId}\`)`),n("failed",{error:i})}}function rv(t){let e=t.environment;if(!t.cfg.deploy.enabled)return"deployments are turned off on this runner. Deploy steps are shell commands, so they stay disabled until someone with access to this machine runs `allwright deploy enable`.";if(!e.steps.length)return`environment "${e.name}" has no deploy steps configured - add them in the dashboard first`;if(e.promotionMode==="merge_and_deploy"&&!e.branch)return`environment "${e.name}" is set to merge-and-deploy but has no branch configured`;if(e.useDedicatedCheckout&&!e.branch)return`environment "${e.name}" wants a dedicated checkout but has no branch configured`;let n=Gt(t.cfg,t.project.repoName,e.name),r=new Set,s=new Set;for(let l of e.steps){for(let c of l.run.matchAll(/(?:^|[\s;&|(])([A-Za-z_][A-Za-z0-9_]*)=/g))r.add(c[1]);for(let c of l.run.matchAll(/\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/g))s.add(c[1])}let i=e.requiredSecrets.filter(l=>!s.has(l));i.length&&y.warn(`environment "${e.name}" lists ${i.join(", ")} under required secrets, but no step uses ${i.length===1?"it":"them"} - ignoring. Remove ${i.length===1?"it":"them"} from "Needs secrets" on the environment to silence this.`);let o=e.requiredSecrets.filter(l=>s.has(l)&&!r.has(l)&&!n[l]&&!process.env[l]);return o.length?`missing deploy secret(s) on this runner: ${o.join(", ")}. Set them with: allwright env set "${t.project.repoName}" "${e.name}" ${o[0]}=...`:null}async function np(t,e,n){let r=t.environment,s=Gt(t.cfg,t.project.repoName,r.name),i=Kl(Object.values(s)),o=Date.now(),l=[];if(n("running"),e("info",`Deploying ${t.issueKey} to "${r.name}"`+(t.requestedBy?` (requested by ${t.requestedBy})`:"")+` - ${r.steps.length} step(s), ${r.timeoutSeconds}s budget`),r.auditBeforeDeploy){e("info",`Pre-deploy ${r.auditBeforeDeploy} audit starting (advisory - will not block)`);try{let C=Oe(t.cfg,t.project,"assist"),M="error"in C?{ok:!1,error:C.error}:await ys({projectId:t.project.id,repoPath:t.repoPath,role:r.auditBeforeDeploy,scope:{kind:"repo",ref:""},model:"",agent:C,jira:t.jira});if(!M.ok)e("warn",`Pre-deploy audit could not run: ${M.error} - deploying anyway (advisory)`);else if(!M.audit.findings.length)e("info","Pre-deploy audit: no findings \u2713");else{let B={};for(let j of M.audit.findings)B[j.severity]=(B[j.severity]??0)+1;e("warn",`Pre-deploy audit: ${M.audit.findings.length} finding(s) (`+Object.entries(B).map(([j,d])=>`${d} ${j}`).join(", ")+") - full report on the Audits page. Deploying anyway (advisory).");for(let j of M.audit.findings.slice(0,5))e("warn",` [${j.severity}] ${j.title} - ${j.evidence[0]?.file??""}`)}}catch(C){e("warn",`Pre-deploy audit crashed: ${C instanceof Error?C.message:String(C)} - deploying anyway`)}}if(r.requireSyncCheck){if(!r.previousEnvBranch||!r.branch){let M=r.branch?`"${r.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 "${r.name}" moved to the top?), or turn the check off.`:`"${r.name}" requires a branch sync check but has no branch set - set it, or turn the check off`;e("error",M),await dt(t,`**Allwright refused to deploy to \`${r.name}\`.**
|
|
881
881
|
|
|
882
|
-
${
|
|
882
|
+
${M}
|
|
883
883
|
|
|
884
|
-
(run \`${t.runId}\`)`),n("failed",{error:
|
|
884
|
+
(run \`${t.runId}\`)`),n("failed",{error:M,errorKind:"guard"});return}let C=await iv(t,e);if(C){await dt(t,C.comment),n("failed",{error:C.error,...C.guard?{errorKind:"guard"}:{}});return}}let c=t.repoPath;if(r.useDedicatedCheckout||r.promotionMode==="merge_and_deploy"?(e("info",`Preparing ${r.name} checkout at origin/${r.branch}`),c=await Ga({repoPath:t.repoPath,repoName:t.project.repoName,envName:r.name,branch:r.branch,attached:r.promotionMode==="merge_and_deploy"})):e("info",`No dedicated checkout for "${r.name}" - running the steps in the mapped checkout as it is`),r.promotionMode==="merge_and_deploy"){let C=Qt(r.ticketBranchTemplate,{issueKey:t.issueKey});e("info",`Merging "${C}" into "${r.branch}"`);let M=await Za(c,C,`Deploy ${t.issueKey} to ${r.name}
|
|
885
885
|
|
|
886
|
-
Allwright run ${t.runId}`);if(!
|
|
886
|
+
Allwright run ${t.runId}`);if(!M.ok){e("error",M.reason??"merge failed"),await dt(t,`**Allwright deploy to \`${r.name}\` failed before running anything.**
|
|
887
887
|
|
|
888
|
-
${
|
|
888
|
+
${M.reason}`),n("failed",{error:M.reason});return}M.alreadyMerged?e("info",`"${C}" is already in "${r.branch}" - nothing to merge`):(e("info",`Pushing "${r.branch}" to origin`),await Ya(c,r.branch))}let h=await Ze(c).catch(()=>"");h&&e("info",`Deploying commit ${h.slice(0,10)}`);let f=ov(c,r.workdir),b={...process.env,...s,ALLWRIGHT_ENVIRONMENT:r.name,ALLWRIGHT_ISSUE_KEY:t.issueKey,ALLWRIGHT_RUN_ID:t.runId,ALLWRIGHT_DEPLOY_REF:h,ALLWRIGHT_BRANCH:r.branch,TICKETPILOT_ENVIRONMENT:r.name,TICKETPILOT_ISSUE_KEY:t.issueKey,TICKETPILOT_RUN_ID:t.runId,TICKETPILOT_DEPLOY_REF:h,TICKETPILOT_BRANCH:r.branch},w=0,_=r.timeoutSeconds*1e3,S=Th(t.runId),A=()=>S.signal.aborted;try{for(let[C,M]of r.steps.entries()){if(A()){let d=`stopped from the dashboard during step ${C+1} - nothing further ran`;e("error",d),n("failed",{error:d,errorKind:"guard",deployedRef:h});return}let B=_-(Date.now()-o);if(B<=0){let d=`deploy exceeded its ${r.timeoutSeconds}s budget before step ${C+1}`;e("error",d),await dt(t,`**Allwright deploy to \`${r.name}\` timed out.**
|
|
889
889
|
|
|
890
|
-
${d}`),n("timed_out",{error:d,deployedRef:
|
|
890
|
+
${d}`),n("timed_out",{error:d,deployedRef:h});return}e("info",`\u25B6 step ${C+1}/${r.steps.length}: ${M.name}`);let j=await av({command:M.run,cwd:f,env:b,timeoutMs:B,signal:S.signal,onLine:(d,m)=>{w++;let g=nv(m);g&&l.length<20&&l.push(g),w===Yh&&e("warn","(output truncated - deploy log limit reached)"),!(w>=Yh)&&e(d,i(m))}});if(j.timedOut){let d=`step "${M.name}" hit the ${r.timeoutSeconds}s deploy budget and was killed`;e("error",d),await dt(t,`**Allwright deploy to \`${r.name}\` timed out.**
|
|
891
891
|
|
|
892
|
-
${d}`),n("timed_out",{error:d,deployedRef:
|
|
892
|
+
${d}`),n("timed_out",{error:d,deployedRef:h});return}if(j.code!==0){if(M.continueOnError){e("warn",`step "${M.name}" exited ${j.code} - continuing (marked continue-on-error)`);continue}let d="";try{d=i(await Ua(c))}catch{}let m=Dh(Ol(j.tail??"",{cwd:c})),g=`step ${C+1} "${M.name}" failed with exit code ${j.code}`+(j.tail?`: ${i(j.tail)}`:"")+m+(d?`
|
|
893
893
|
|
|
894
894
|
Checkout at failure:
|
|
895
895
|
${d}`:"");e("error",g),await dt(t,`**Allwright deploy to \`${r.name}\` failed.**
|
|
896
896
|
|
|
897
|
-
Step ${
|
|
897
|
+
Step ${C+1} \`${M.name}\` exited ${j.code}.
|
|
898
898
|
|
|
899
|
-
`+(
|
|
900
|
-
${i(
|
|
899
|
+
`+(j.tail?`\`\`\`
|
|
900
|
+
${i(j.tail).slice(0,1200)}
|
|
901
901
|
\`\`\`
|
|
902
902
|
|
|
903
903
|
`:"")+(m?`${m.trim()}
|
|
@@ -911,87 +911,87 @@ ${d.slice(0,800)}
|
|
|
911
911
|
`+l.map(R=>`- \`${R.command}\`${R.why?` - ${R.why}`:""}`).join(`
|
|
912
912
|
`)+`
|
|
913
913
|
|
|
914
|
-
`:"")+`Nothing after it ran. Full log is on the Allwright dashboard. (run \`${t.runId}\`)`),ut(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.name} failed`,detail:`step ${
|
|
915
|
-
${i(
|
|
914
|
+
`:"")+`Nothing after it ran. Full log is on the Allwright dashboard. (run \`${t.runId}\`)`),ut(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.name} failed`,detail:`step ${C+1} "${M.name}" exit ${j.code}`+(j.tail?`
|
|
915
|
+
${i(j.tail).slice(0,500)}`:"")}),l.length&&Xh(e,l),n("failed",{error:g.slice(0,1600),deployedRef:h,...l.length?{manualSteps:l}:{}});return}e("info",`\u2713 step ${C+1}/${r.steps.length}: ${M.name}`)}}finally{xh(t.runId)}if(h=await Ze(c).catch(()=>"")||h,r.servePath?.trim()&&h){let C=r.servePath.trim(),M=await Ze(C).catch(()=>"");if(!M)e("warn",`serving check: cannot read a git HEAD at ${C} - the deploy is done, but whether that checkout serves THIS build could not be verified`);else if(M!==h){let B=`The steps all succeeded, but the live checkout at ${C} is still at ${M.slice(0,10)} - not the ${h.slice(0,10)} this deploy shipped. Users are NOT getting this build. Usually one of: a step pulls a different directory than the one that serves, the pull failed quietly, or the serve path in this environment's settings points at the wrong checkout.`;e("error",`serving check: ${B}`),await dt(t,`**Allwright deployed to \`${r.name}\`, but it did not take.**
|
|
916
916
|
|
|
917
|
-
${
|
|
917
|
+
${B}`),ut(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.name} did not take effect`,detail:`serving ${M.slice(0,10)}, shipped ${h.slice(0,10)} (${C})`}),n("failed",{error:B,deployedRef:h});return}else e("info",`serving check: ${C} is at ${h.slice(0,10)} - users get this build`)}n("posting");let z=Math.round((Date.now()-o)/1e3),q=null;r.publicUrl?.trim()&&(q=await uv(r.publicUrl.trim()),e(q?"warn":"info",q??`${r.publicUrl.trim()} points at this machine - the deploy is live there`)),t.issueKey!==Pr.BRANCH_DEPLOY_ISSUE_KEY&&await dt(t,`**Allwright deployed \`${t.issueKey}\` to \`${r.name}\`.**
|
|
918
918
|
|
|
919
919
|
`+(q?`> **Live where?** ${q}
|
|
920
920
|
|
|
921
921
|
`:"")+(l.length?`**${l.length} step(s) still need a person - Allwright did not run these:**
|
|
922
|
-
`+l.map(
|
|
922
|
+
`+l.map(C=>`- \`${C.command}\`${C.why?` - ${C.why}`:""}`).join(`
|
|
923
923
|
`)+`
|
|
924
924
|
|
|
925
|
-
`:"")+(
|
|
926
|
-
`:"")+`${r.steps.length} step(s) in ${
|
|
925
|
+
`:"")+(h?`Commit: \`${h.slice(0,10)}\`${r.branch?` on \`${r.branch}\``:""}
|
|
926
|
+
`:"")+`${r.steps.length} step(s) in ${z}s.`+(t.requestedBy?` Requested by ${t.requestedBy}.`:"")+`
|
|
927
927
|
|
|
928
|
-
(run \`${t.runId}\`)`);let v=await
|
|
928
|
+
(run \`${t.runId}\`)`);let v=await sv(t,e,h);t.project.goLiveIssueKey&&e("info",`Go-live checklist: this project keeps one on ${t.project.goLiveIssueKey} - review it before shipping to production`),Zs(t.repoPath,t.issueKey)&&ut(t.repoPath,{issueKey:t.issueKey,runId:t.runId,title:`deploy to ${r.name} succeeded after earlier failure`,detail:h?`commit ${h.slice(0,10)}`:void 0}),l.length&&Xh(e,l),n("succeeded",{resultSummary:`Deployed to ${r.name}${h?` at ${h.slice(0,10)}`:""} in ${z}s`+(v!==null?` \xB7 ${v} ticket(s) moved to "${r.deployToColumn}"`:"")+(l.length?` \xB7 ${l.length} manual step(s) left for you`:"")+(q?` \xB7 NOT reachable at ${r.publicUrl} yet`:""),deployedRef:h,...l.length?{manualSteps:l}:{}}),e("info",`Deploy to "${r.name}" succeeded in ${z}s`)}async function sv(t,e,n){let r=t.environment;if(!r.deployFromColumn||!r.deployToColumn)return null;let s=new Date().toISOString().slice(0,10),i;try{i=await t.jira.search(`project = "${t.project.jiraProjectKey}" AND status = "${r.deployFromColumn}" ORDER BY updated ASC`,50)}catch(l){return e("warn",`deploy succeeded, but listing tickets in "${r.deployFromColumn}" failed: ${l instanceof Error?l.message:l} - move them by hand`),null}if(!i.length)return e("info",`No tickets in "${r.deployFromColumn}" to move`),0;e("info",`Moving ${i.length} ticket(s) from "${r.deployFromColumn}" to "${r.deployToColumn}"`);let o=0;for(let l of i)try{if(await t.jira.addComment(l.key,`**Allwright: deployed to \`${r.name}\` on ${s}.**
|
|
929
929
|
|
|
930
930
|
`+(n?`Commit: \`${n.slice(0,10)}\`${r.branch?` on \`${r.branch}\``:""}
|
|
931
|
-
`:"")+(t.requestedBy?`Requested by ${t.requestedBy}. `:"")+`(run \`${t.runId}\`)`),!await t.jira.transitionByName(l.key,r.deployToColumn)){e("warn",`${l.key}: no workflow transition to "${r.deployToColumn}" from its current status - left in place`),await t.jira.addComment(l.key,`**Allwright could not move this ticket to \`${r.deployToColumn}\`** - no such transition from its current status. The deploy itself succeeded; move it by hand. (run \`${t.runId}\`)`).catch(()=>{});continue}o++,e("info",`\u2713 ${l.key} \u2192 "${r.deployToColumn}"`)}catch(c){e("warn",`${l.key}: sweep failed (${c instanceof Error?c.message:c}) - left in "${r.deployFromColumn}"`)}return e("info",`Moved ${o}/${i.length} ticket(s) to "${r.deployToColumn}"`),o}async function
|
|
931
|
+
`:"")+(t.requestedBy?`Requested by ${t.requestedBy}. `:"")+`(run \`${t.runId}\`)`),!await t.jira.transitionByName(l.key,r.deployToColumn)){e("warn",`${l.key}: no workflow transition to "${r.deployToColumn}" from its current status - left in place`),await t.jira.addComment(l.key,`**Allwright could not move this ticket to \`${r.deployToColumn}\`** - no such transition from its current status. The deploy itself succeeded; move it by hand. (run \`${t.runId}\`)`).catch(()=>{});continue}o++,e("info",`\u2713 ${l.key} \u2192 "${r.deployToColumn}"`)}catch(c){e("warn",`${l.key}: sweep failed (${c instanceof Error?c.message:c}) - left in "${r.deployFromColumn}"`)}return e("info",`Moved ${o}/${i.length} ticket(s) to "${r.deployToColumn}"`),o}async function iv(t,e){let n=t.environment,r=n.previousEnvBranch,s=(l,c=!1)=>({error:l,guard:c,comment:`**Allwright could not deploy \`${t.issueKey}\` to \`${n.name}\`.**
|
|
932
932
|
|
|
933
933
|
${l}
|
|
934
934
|
|
|
935
|
-
(run \`${t.runId}\`)`});e("info",`Checking "${n.branch}" is in sync with "${r}" before deploying`);try{await Tn(t.repoPath,r),await Tn(t.repoPath,n.branch)}catch(l){return s(`sync check could not fetch branches: ${l instanceof Error?l.message:String(l)}`)}let i;try{i=await
|
|
935
|
+
(run \`${t.runId}\`)`});e("info",`Checking "${n.branch}" is in sync with "${r}" before deploying`);try{await Tn(t.repoPath,r),await Tn(t.repoPath,n.branch)}catch(l){return s(`sync check could not fetch branches: ${l instanceof Error?l.message:String(l)}`)}let i;try{i=await Xa(t.repoPath,`origin/${r}`,`origin/${n.branch}`)}catch(l){return s(`sync check failed: ${l instanceof Error?l.message:String(l)}`)}if(!i)return e("info",`"${n.branch}" already matches "${r}" - continuing`),null;e("warn",`"${n.branch}" and "${r}" have diverged - opening a PR instead of deploying`);let o=je(ve()??t.cfg,t.project.repoName);if(!o)return s(`"${n.branch}" and "${r}" have diverged, and no GitHub token applies to this repo to open a PR. Run \`allwright github set-token\`, or merge them manually, then retry the deploy.`,!0);try{let l=await vr(t.repoPath),c=wt(l);if(!c)throw new Error(`could not parse a GitHub owner/repo from origin "${l}"`);let h=await new Me(o).createPullRequest(c.owner,c.repo,{title:`Sync ${n.name} (${n.branch}) with ${r}`,head:r,base:n.branch,body:`Allwright opened this automatically while trying to deploy \`${t.issueKey}\` to \`${n.name}\`: \`${n.branch}\` doesn't have everything that's on \`${r}\` yet, so deploying now would ship different code than what was validated there. Merge this PR, then retry the deploy.
|
|
936
936
|
|
|
937
|
-
(run \`${t.runId}\`)`});return s(`"${n.branch}" is not in sync with "${r}" - opened ${
|
|
938
|
-
`)}))},c=setTimeout(()=>{o=!0,
|
|
937
|
+
(run \`${t.runId}\`)`});return s(`"${n.branch}" is not in sync with "${r}" - opened ${h.url} to catch it up. Merge that, then retry the deploy.`,!0)}catch(l){return s(`could not open a sync PR: ${l instanceof Error?l.message:String(l)}`)}}function ov(t,e){if(!e.trim())return t;let n=$r.default.resolve(t,e),r=$r.default.relative(t,n);if(r.startsWith("..")||$r.default.isAbsolute(r))throw new Error(`working directory "${e}" is outside the repository checkout`);return n}function av(t){return new Promise(e=>{let n=(0,To.spawn)("bash",["-lc",t.command],{cwd:t.cwd,env:t.env,detached:!0,stdio:["ignore","pipe","pipe"]}),r=[],s=h=>{r.push(h),r.length>20&&r.shift()},i=!1,o=!1,l=h=>{i||(i=!0,clearTimeout(c),t.signal?.removeEventListener("abort",u),e({code:h,timedOut:o,tail:r.join(`
|
|
938
|
+
`)}))},c=setTimeout(()=>{o=!0,So(n.pid,"SIGTERM"),setTimeout(()=>So(n.pid,"SIGKILL"),1e4).unref()},t.timeoutMs),u=()=>{t.onLine("warn","stop requested - killing this step"),So(n.pid,"SIGTERM"),setTimeout(()=>So(n.pid,"SIGKILL"),5e3).unref()};t.signal&&(t.signal.aborted?u():t.signal.addEventListener("abort",u,{once:!0})),Fl.default.createInterface({input:n.stdout}).on("line",h=>{s(h),t.onLine("info",h)}),Fl.default.createInterface({input:n.stderr}).on("line",h=>{s(h),t.onLine("warn",h)}),n.on("error",h=>{s(`failed to start: ${h.message}`),l(127)}),n.on("close",h=>l(h??1))})}function So(t,e){if(t)try{process.kill(-t,e)}catch{try{process.kill(t,e)}catch{}}}function Kl(t){let e=t.filter(n=>n&&n.length>=6).sort((n,r)=>r.length-n.length);return e.length?n=>{let r=n;for(let s of e)r=r.split(s).join("***");return r}:n=>n}async function dt(t,e){if(t.issueKey!==Pr.BRANCH_DEPLOY_ISSUE_KEY)try{await t.jira.addComment(t.issueKey,e)}catch(n){y.error(`could not post deploy comment to ${t.issueKey}: ${n}`)}}function Gl(t){return fo(t)!==null}async function rp(t,e){let n=fo(e);if(!n)return;let{emit:r,setStatus:s}=Hl({runId:e,transport:t.transport}),i=t.lookup(n.projectId,n.environmentName);if(!i){let l=`approved, but environment "${n.environmentName}" is no longer in this runner's config (deleted or renamed?) - nothing was deployed`;r("error",l),s("failed",{error:l}),mo(e);return}mo(e);let o={runId:e,project:i.project,environment:i.environment,issueKey:n.issueKey,issueSummary:n.issueSummary,repoPath:i.repoPath,cfg:t.cfg,jira:t.jiraFor(i.project.repoName),transport:t.transport,requestedBy:n.requestedBy};r("info",`Approved - running the ${i.environment.steps.length} deploy step(s) now`);try{await np(o,r,s)}catch(l){let c=l instanceof Error?l.message:String(l);r("error",`Deploy failed: ${c}`),await dt(o,`**Allwright deploy failed.**
|
|
939
939
|
|
|
940
|
-
${c.slice(0,800)}`),s("failed",{error:c})}}async function
|
|
940
|
+
${c.slice(0,800)}`),s("failed",{error:c})}}async function sp(t,e){let n=fo(e);if(!n)return;let{emit:r,setStatus:s}=Hl({runId:e,transport:t.transport});mo(e),r("info",`Deploy to "${n.environmentName}" was rejected - nothing ran`);let i=t.lookup(n.projectId,n.environmentName);try{await t.jiraFor(i?.project.repoName??"").addComment(n.issueKey,`**Allwright: deploy to \`${n.environmentName}\` was rejected.**
|
|
941
941
|
|
|
942
|
-
No deploy step was executed. (run \`${e}\`)`)}catch(o){y.error(`could not post rejection comment to ${n.issueKey}: ${o}`)}s("failed",{error:"deploy rejected by a reviewer"})}var
|
|
942
|
+
No deploy step was executed. (run \`${e}\`)`)}catch(o){y.error(`could not post rejection comment to ${n.issueKey}: ${o}`)}s("failed",{error:"deploy rejected by a reviewer"})}var lv=k.object({steps:k.array(Pr.DeployStep).max(50).default([]),requiredSecrets:k.array(k.string()).max(50).default([]),notes:k.string().default("")}),Qh=24e3;function Io(t){for(let e of xo.DEPLOY_DOC_CANDIDATES){let n=$r.default.join(t,e);try{if(!Ss.default.existsSync(n))continue;let r=Ss.default.readFileSync(n,"utf8");if(!r.trim())continue;return{path:e,content:r.length>Qh?r.slice(0,Qh)+`
|
|
943
943
|
|
|
944
|
-
[\u2026document truncated\u2026]`:r}}catch{continue}}return null}var
|
|
944
|
+
[\u2026document truncated\u2026]`:r}}catch{continue}}return null}var ep=["docker","docker-compose","pm2","systemctl","node","pnpm","npm","yarn","make","python3","pip","rsync","ssh","caddy","nginx"];function ip(t){return cv("bash",["-lc",`command -v ${JSON.stringify(t)}`]).trim().length>0}function cv(t,e){try{let n=(0,To.spawnSync)(t,e,{encoding:"utf8",timeout:5e3});return n.status===0?n.stdout??"":""}catch{return""}}async function uv(t){let e;try{e=new URL(t)}catch{return null}let n=[];try{let{resolve4:o,resolve6:l}=await import("node:dns/promises"),[c,u]=await Promise.all([o(e.hostname).catch(()=>[]),l(e.hostname).catch(()=>[])]);n=[...c,...u]}catch{n=[]}if(!n.length)return`${e.hostname} does not resolve yet - this build is on THIS machine, but nothing points at it. Users see whatever your DNS points at today.`;let r=await import("node:os"),s=new Set(Object.values(r.networkInterfaces()).flatMap(o=>o??[]).filter(o=>!o.internal).map(o=>o.address)),i=Kh();return i&&s.add(i),n.some(o=>s.has(o))?null:`${e.hostname} resolves to ${n.slice(0,3).join(", ")}, which is not an address of this machine`+(i?` (this machine is ${i})`:" as far as it can tell - its own public address is not known here, so treat this as a prompt to check rather than a verdict")+". If you front it with a CDN or load balancer that is expected; otherwise this deploy changed nothing for users - they are still being served by the old server until the DNS record moves."}async function dv(t,e){let n;try{n=new URL(t)}catch{e.push({name:"public-url",ok:!1,detail:`not a valid URL: ${t}`});return}try{let{lookup:r}=await import("node:dns/promises"),s=await r(n.hostname);e.push({name:"public-url-dns",ok:!0,detail:`${n.hostname} \u2192 ${s.address}`})}catch{e.push({name:"public-url-dns",ok:!1,detail:`${n.hostname} does not resolve - add an A/CNAME record for it at your DNS provider (changes can take a few minutes to propagate)`});return}if(n.protocol==="https:"){let r=await import("node:tls");await new Promise(s=>{let i=r.connect({host:n.hostname,port:Number(n.port||443),servername:n.hostname,timeout:8e3},()=>{let o=i.getPeerCertificate(),l=o?.valid_to?Math.round((new Date(o.valid_to).getTime()-Date.now())/864e5):NaN;e.push(Number.isFinite(l)&&l>0?{name:"public-url-tls",ok:l>14,detail:`certificate valid, expires in ${l} day(s)${l<=14?" - renew soon":""}`}:{name:"public-url-tls",ok:!1,detail:"certificate expired or unreadable"}),i.end(),s()});i.on("error",o=>{e.push({name:"public-url-tls",ok:!1,detail:`TLS handshake failed: ${o.message} - is a certificate installed for this hostname?`}),s()}),i.on("timeout",()=>{e.push({name:"public-url-tls",ok:!1,detail:"TLS handshake timed out"}),i.destroy(),s()})})}try{let r=await fetch(n.toString(),{method:"GET",redirect:"manual",signal:AbortSignal.timeout(1e4)});e.push({name:"public-url-reachable",ok:r.status<500,detail:`HTTP ${r.status}${r.status>=300&&r.status<400?` \u2192 ${r.headers.get("location")??""}`:""}`})}catch(r){e.push({name:"public-url-reachable",ok:!1,detail:`not reachable from the runner: ${r instanceof Error?r.message:String(r)}`})}}function hv(t){let e=t.match(/\/(?:var|home|opt|srv)\/[\w./-]+/g)??[],n=[...new Set(e.map(s=>s.replace(/[.,;:)\]'"`]+$/,"")))].slice(0,12);return n.length?`
|
|
945
945
|
- absolute paths the document mentions, checked on THIS machine:
|
|
946
946
|
${n.map(s=>` - ${s}: ${Ss.default.existsSync(s)?"EXISTS on this machine":"not found on this machine"}`).join(`
|
|
947
|
-
`)}`:""}function
|
|
947
|
+
`)}`:""}function op(t,e,n,r="",s="."){let i=ep.filter(c=>ip(c)),o=ep.filter(c=>!i.includes(c)),l=Object.keys(Gt(t,e,n));return`About the machine these steps will run on (gathered by the runner, trust it):
|
|
948
948
|
- available tools: ${i.join(", ")||"(none of the common ones)"}
|
|
949
949
|
- NOT installed: ${o.join(", ")||"(none missing)"}
|
|
950
|
-
- secrets already stored for this environment (names only): ${l.join(", ")||"(none yet)"}`+
|
|
951
|
-
${
|
|
952
|
-
`),failedStep:t.failedStep||"(unknown)",errorText:t.errorText||"(no error text recorded)",knownCause:(()=>{let
|
|
950
|
+
- secrets already stored for this environment (names only): ${l.join(", ")||"(none yet)"}`+Ml()+hv(r)+ri(s)}async function ap(t){let e=[];if(t.publicUrl?.trim()&&await dv(t.publicUrl.trim(),e),e.push(Ss.default.existsSync(t.repoPath)?{name:"repo-path",ok:!0,detail:t.repoPath}:{name:"repo-path",ok:!1,detail:`checkout missing: ${t.repoPath}`}),e.push({name:"deploys-enabled",ok:t.cfg.deploy.enabled,detail:t.cfg.deploy.enabled?"enabled on this runner":"disabled - run: allwright deploy enable (then restart the runner)"}),t.workdir){let l=$r.default.isAbsolute(t.workdir)?t.workdir:$r.default.join(t.repoPath,t.workdir);e.push(Ss.default.existsSync(l)?{name:"workdir",ok:!0,detail:l}:{name:"workdir",ok:!1,detail:`does not exist: ${l}`})}if(t.branch){let l=ko(t.repoPath);l.ok?e.push(l.branches.includes(t.branch)?{name:"branch",ok:!0,detail:`origin/${t.branch} exists`}:{name:"branch",ok:!1,detail:`origin has no branch "${t.branch}" - it really was asked, and answered with: ${l.branches.join(", ")||"(no branches at all)"}`}):e.push({name:"branch",ok:!1,detail:`${l.detail} Fix: ${l.fix}`})}let n=Gt(t.cfg,t.repoName,t.environmentName),r=new Set(t.requiredSecrets);for(let l of t.steps)for(let c of l.run.matchAll(/\$\{?([A-Z][A-Z0-9_]{2,})\}?/g))r.add(c[1]);let s=[...r].filter(l=>!n[l]&&!process.env[l]);e.push({name:"secrets",ok:s.length===0,detail:s.length?`missing: ${s.join(", ")} - set with: allwright env set "${t.repoName}" "${t.environmentName}" ${s[0]}=...`:`${r.size} present`});let i=new Set;for(let l of t.steps)for(let c of l.run.split(/&&|\|\||;|\|/)){let u=c.trim().split(/\s+/),h=u.shift();for(;h&&(/^[A-Za-z_][A-Za-z0-9_]*=/.test(h)||h==="sudo"||h==="env"||h==="nohup");)h=u.shift();!h||h.startsWith("$")||h.startsWith("#")||h.startsWith("(")||i.add(h)}let o=[...i].filter(l=>!ip(l));return e.push({name:"binaries",ok:o.length===0,detail:o.length?`not found on this machine: ${o.join(", ")}`:`${i.size} found: ${[...i].slice(0,12).join(", ")}`}),{ok:e.every(l=>l.ok),checks:e}}async function lp(t){let e=op(t.cfg,t.repoName,t.environmentName,"",t.repoPath),n=Qt(xo.DEPLOY_FIX_PROMPT_TEMPLATE,{envName:t.environmentName,steps:t.steps.map((h,f)=>`${f+1}. [${h.name}]${h.continueOnError?" (continues on error)":""}
|
|
951
|
+
${h.run}`).join(`
|
|
952
|
+
`),failedStep:t.failedStep||"(unknown)",errorText:t.errorText||"(no error text recorded)",knownCause:(()=>{let h=Ol(t.errorText,{cwd:t.repoPath});return h?`
|
|
953
953
|
|
|
954
954
|
THE RUNNER ALREADY RECOGNISES THIS FAILURE, and told the operator so:
|
|
955
|
-
- what it means: ${
|
|
956
|
-
- what closes it: ${
|
|
957
|
-
- ${
|
|
958
|
-
Start from this. If your own reading of the evidence agrees, say so in one line and turn it into steps; if it does NOT, say which evidence contradicts it - do not quietly produce a second, different answer to the same failure.`:""})(),evidence:
|
|
959
|
-
`+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
|
|
960
|
-
`)[0].trim()||`Step ${e+1}`).slice(0,120)}Ct();kt();kr();function Ao(t,e){if(!t.componentRoutes.length)return{project:t};let n=e.filter(Boolean);if(!n.length)return{error:`no Jira component set - project "${t.name}" routes by component (${t.componentRoutes.map(i=>i.component).join(", ")}); set one on the ticket`};let r=t.componentRoutes.filter(i=>n.includes(i.component));if(!r.length)return{error:`component(s) [${n.join(", ")}] not mapped - known: `+t.componentRoutes.map(i=>`${i.component}\u2192${i.repoName}`).join(", ")};let s=new Set(r.map(i=>i.repoName));return s.size>1?{error:`components map to DIFFERENT repos (${[...s].join(", ")}) - ambiguous, refusing`}:{project:{...t,repoName:r[0].repoName}}}Xt();
|
|
955
|
+
- what it means: ${h.cause}
|
|
956
|
+
- what closes it: ${h.commands.join(" ; ")}
|
|
957
|
+
- ${h.note}
|
|
958
|
+
Start from this. If your own reading of the evidence agrees, say so in one line and turn it into steps; if it does NOT, say which evidence contradicts it - do not quietly produce a second, different answer to the same failure.`:""})(),evidence:Jh(Vh({errorText:t.errorText,repoPath:t.repoPath})),machineContext:e}),r=await t.agent.adapter.run({repoPath:t.repoPath,prompt:n,timeoutSeconds:240,bin:t.agent.bin,mode:"read_only",maxTurns:40,sessionId:(0,Bl.randomUUID)(),onLog:()=>{}});if(!r.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:r.error??"the agent produced no output"};let s=up(r.resultText),i=(r.resultText.split(/```/)[0]??"").replace(/^\s*CAUSE TYPE:.*$/im,"").trim(),l=/```(?:markdown|md)\s*\n([\s\S]*?)```/i.exec(r.resultText)?.[1]?.trim()??"",c=l?Io(t.repoPath):null;if(!s)return{ok:!1,steps:[],requiredSecrets:[],notes:i,error:i?"the agent diagnosed the failure (see its notes) but did not produce an applicable step list - the cause may live outside the steps":`the agent's answer was not in the expected shape. It started: "${r.resultText.trim().slice(0,200).replace(/\s+/g," ")}\u2026"`};let u=/^\s*CAUSE TYPE:\s*(CODE|MACHINE)\b/im.exec(r.resultText)?.[1]?.toUpperCase();return u?{ok:!1,steps:[],requiredSecrets:[],notes:i,error:u==="MACHINE"?'this is not a steps problem - the steps are right, but something on this machine is missing or misconfigured. The commands to fix it are under "WHAT A HUMAN MUST RUN" above; run them on that server, then retry the deploy. Allwright will not paste a credential into a deploy recipe to work around it.':"this is not a steps problem - the deploy failed because the code or the database is not ready (a build error, a failing test, or a migration that was never applied). Changing deploy steps cannot fix it; the diagnosis above says what a person has to change."}:{ok:!0,...s,notes:i||s.notes,docPath:c?.path??(l?"DEPLOY.md":""),docContent:l}}async function cp(t){let e=Io(t.repoPath);if(!e)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:'this repo has no deploy document. Create DEPLOY.md at the repo root (or .ticketpilot/deploy.md) describing how this project actually deploys - the same commands you run by hand. "Ask Claude for steps" translates that document; it does not guess.'};let n=op(t.cfg,t.repoName,t.environmentName,e.content,t.repoPath),r=Qt(Pr.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE,{envName:t.environmentName,docPath:e.path,docContent:e.content,notes:t.notes.trim()||"(nothing specified)",machineContext:n}),s=await t.agent.adapter.run({repoPath:t.repoPath,prompt:r,timeoutSeconds:t.timeoutSeconds,bin:t.agent.bin,mode:"read_only",maxTurns:30,sessionId:(0,Bl.randomUUID)(),onLog:()=>{}});if(!s.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:s.error??"Claude Code produced no output"};let i=up(s.resultText);return i?{ok:!0,...i}:(y.warn(`deploy step suggestion could not be parsed. Claude's raw answer follows:
|
|
959
|
+
`+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 up(t){for(let e of pv(t)){let n;try{n=JSON.parse(e)}catch{continue}let r=lv.safeParse(fv(n));if(r.success&&r.data.steps.length||r.success&&r.data.notes.trim())return r.data}return null}function pv(t){let e=[];for(let s of t.matchAll(/```[a-zA-Z0-9_-]*[ \t]*\r?\n([\s\S]*?)```/g))s[1].trim()&&e.push(s[1]);let n=t.indexOf("{"),r=t.lastIndexOf("}");return n>=0&&r>n&&e.push(t.slice(n,r+1)),e}function fv(t){if(!t||typeof t!="object")return t;let e=t,r=(Array.isArray(t)?t:Array.isArray(e.steps)?e.steps:Array.isArray(e.deploy_steps)?e.deploy_steps:Array.isArray(e.deploySteps)?e.deploySteps:[]).map((o,l)=>{if(typeof o=="string")return o.trim()?{name:tp(o,l),run:o.trim()}:null;if(!o||typeof o!="object")return null;let c=o,u=ql(c.run,c.command,c.cmd,c.script,c.shell);return u?{name:(ql(c.name,c.title,c.description)??tp(u,l)).slice(0,120),run:u,continueOnError:c.continueOnError===!0||c.continue_on_error===!0}:null}).filter(Boolean),s=e.requiredSecrets??e.required_secrets??e.secrets,i=Array.isArray(s)?s.filter(o=>typeof o=="string"):s&&typeof s=="object"?Object.keys(s):[];return{steps:r.slice(0,50),requiredSecrets:i.slice(0,50),notes:ql(e.notes,e.note,e.explanation)??""}}function ql(...t){for(let e of t)if(typeof e=="string"&&e.trim())return e.trim()}function tp(t,e){return(t.split(`
|
|
960
|
+
`)[0].trim()||`Step ${e+1}`).slice(0,120)}Ct();kt();kr();function Ao(t,e){if(!t.componentRoutes.length)return{project:t};let n=e.filter(Boolean);if(!n.length)return{error:`no Jira component set - project "${t.name}" routes by component (${t.componentRoutes.map(i=>i.component).join(", ")}); set one on the ticket`};let r=t.componentRoutes.filter(i=>n.includes(i.component));if(!r.length)return{error:`component(s) [${n.join(", ")}] not mapped - known: `+t.componentRoutes.map(i=>`${i.component}\u2192${i.repoName}`).join(", ")};let s=new Set(r.map(i=>i.repoName));return s.size>1?{error:`components map to DIFFERENT repos (${[...s].join(", ")}) - ambiguous, refusing`}:{project:{...t,repoName:r[0].repoName}}}Xt();jo();var pp=24*3600*1e3,No=14,gv=No*24*3600*1e3,yv=new Set(["to","on","this","the","a","an","env","environment","please","now","it"]),Oo=class{constructor(e,n,r){this.cfg=e;this.jiraFor=n;this.transport=r}cfg;jiraFor;transport;projects=[];rules=[];environments=[];inFlight=new Set;autopilotPausedUntil=0;externalBusy=()=>0;setExternalBusy(e){this.externalBusy=e}get busyCount(){return Math.max(this.inFlight.size,this.activeWork)+this.externalBusy()}activeWork=0;get idle(){return!this.ticking&&this.inFlight.size===0&&this.activeWork===0&&this.externalBusy()===0}repoQueues=new Map;envQueues=new Map;timer=null;ticking=!1;paused=!1;jiraOf(e){return this.jiraFor(e.repoName)}hasJira(e){return!!$i(this.cfg,e)}get jiraless(){return Pi(this.cfg)}jiralessLogged=!1;noteJiraless(){this.jiralessLogged||(this.jiralessLogged=!0,y.info("no Jira credentials on this runner - Jira polling is off. That is the deploy-only setup; add them with `allwright jira set-default` and polling starts without a restart."))}jiraWarned=new Set;warnNoJiraForRepo(e){this.jiraWarned.has(e)||(this.jiraWarned.add(e),y.warn(`no Jira credential for repo "${e}" - its rules are not being polled. Add a runner-wide one with \`allwright jira set-default\`, or one for this repo with \`allwright jira set "${e}"\`.`))}routingWarned=new Set;warnRoutingOnce(e,n){this.routingWarned.has(e)||(this.routingWarned.add(e),y.warn(`Component routing refused - ${n}`))}resolveClaudeProfile(e,n){if(!n)return;let r=this.cfg.claudeProfiles[n]?.configDir;return!r&&e&&(this.transport.send({type:"run.log",runId:e,seq:99e3,ts:new Date().toISOString(),level:"warn",message:`Claude profile "${n}" is not set up on this runner (allwright claude login "${n}") - using the runner's own login instead.`}),y.warn(`run ${e}: claude profile "${n}" missing locally - using default login`)),r}setConfig(e,n,r=!1,s=[]){this.projects=e,this.rules=n,this.environments=s;let i=n.filter(o=>o.enabled).length;y.info(`config synced: ${e.length} project(s), ${n.length} rule(s) (${i} enabled), ${s.length} environment(s)`),r!==this.paused&&(y.info(r?"polling paused from the dashboard":"polling resumed from the dashboard"),this.paused=r)}start(){let e=this.cfg.pollIntervalSeconds*1e3;this.timer=setInterval(()=>{this.tick()},e),this.tick(),this.jiraless?this.noteJiraless():y.info(`polling Jira every ${this.cfg.pollIntervalSeconds}s`)}stop(){this.timer&&clearInterval(this.timer)}lastScheduleCheck=0;auditInFlight=!1;async runScheduledAudits(){if(!(!this.cfg.auditSchedules.length||this.auditInFlight)&&!(Date.now()-this.lastScheduleCheck<15*6e4)){this.lastScheduleCheck=Date.now();for(let e of this.cfg.auditSchedules){let n=this.projects.find(s=>s.repoName===e.repoName);if(!n)continue;let r=Pd(n.id,e.role);if(!(r&&Date.now()-new Date(r).getTime()<e.intervalHours*36e5)){this.auditInFlight=!0;try{y.info(`Scheduled ${e.role} audit of ${e.repoName} starting (every ${e.intervalHours}h)`);let s=Oe(this.cfg,n,"assist");if("error"in s){y.warn(`Scheduled audit skipped: ${s.error}`);continue}let i=await ys({projectId:n.id,repoPath:this.cfg.repos[e.repoName]?.path??"",role:e.role,scope:{kind:"repo",ref:""},model:"",agent:s,jira:this.jiraFor(e.repoName)});if(i.ok){let o=i.audit.findings.length;y.info(`Scheduled audit done: ${o} finding(s) - drift visible on the Audits page`)}else y.warn(`Scheduled audit failed: ${i.error}`)}catch(s){y.warn(`Scheduled audit crashed: ${s instanceof Error?s.message:String(s)}`)}finally{this.auditInFlight=!1}break}}}}async tick(){if(!(this.ticking||this.paused||!this.transport.connected)){if(this.jiraless){this.noteJiraless();return}this.jiralessLogged=!1,this.ticking=!0;try{await this.runScheduledAudits(),await this.sweepMergedPRs(),await this.sweepGitHubApprovals();let e=new Set;for(let n of this.rules){if(!n.enabled)continue;let r=this.projects.find(i=>i.id===n.projectId);if(!r)continue;let s=this.cfg.repos[r.repoName];if(!s){y.warn(`rule "${n.name}": no local path for repo "${r.repoName}" - run: allwright repo add "${r.repoName}" /path/to/checkout`);continue}if(!this.hasJira(r.repoName)){this.warnNoJiraForRepo(r.repoName);continue}n.action.type==="deploy"?await this.pollDeployRule(n,r,s.path):n.action.type==="respond"?await this.pollRespondRule(n,r,s.path):(e.has(r.id)||(e.add(r.id),await this.sweepNeedsInput(r)),n.trigger.type==="comment_keyword"&&await this.sweepRevisions(n,r),await this.pollRule(n,r,s.path))}await this.pullAutopilotWork()}catch(e){y.warn(`poll tick failed: ${e instanceof Error?e.message:e}`)}finally{this.ticking=!1}}}async pullAutopilotWork(){if(this.inFlight.size>0||this.autopilotPausedUntil>Date.now())return;let e=await this.transport.requestAutopilotNext();if(!e?.ok)return;if(e.pausedUntil){let q=Date.parse(e.pausedUntil);Number.isFinite(q)&&(this.autopilotPausedUntil=q);return}let n=e.item;if(!n)return;let r=this.rules.find(q=>q.id===n.ruleId&&q.enabled),s=this.projects.find(q=>q.id===n.projectId);if(!r||!s){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:"the rule or project this item was queued against no longer exists"});return}let i=Ao(s,[]),o="project"in i?i.project:s,l=this.cfg.repos[o.repoName];if(!l){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:`no local checkout mapped for "${o.repoName}" on this machine`});return}if(!this.hasJira(o.repoName)){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:`no Jira credential for "${o.repoName}" on this machine - run \`allwright jira set-default\` there (or \`allwright jira set "${o.repoName}"\`)`});return}let c=n.baseOverride||n.branchOverride||n.autoMerge?{...r,action:r.action.type==="implement"?{...r.action,...n.baseOverride?{baseBranch:n.baseOverride}:{},...n.branchOverride?{branchTemplate:n.branchOverride}:{},...n.autoMerge?{requireApproval:!1,autoMerge:!0}:{}}:r.action}:r;y.info(`autopilot: taking ${n.issueKey} (${r.name})`+(n.branchOverride?` -> shared branch ${n.branchOverride}`:"")+(n.baseOverride?` -> stacked on ${n.baseOverride}`:""));let u=this.jiraOf(o),h="";try{h=(await u.getIssue(n.issueKey))?.summary??""}catch(q){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:`could not read ${n.issueKey} from Jira: ${q instanceof Error?q.message:String(q)}`});return}let f=await this.transport.claimRun({ruleId:r.id,issueKey:n.issueKey,issueSummary:h,triggerFingerprint:`autopilot:${n.id}`,dedupKey:`autopilot:${n.id}`});if(!f.accepted||!f.runId){this.transport.sendAutopilotReport({itemId:n.id,outcome:"failed",error:f.reason??"the control plane refused the run"});return}this.transport.sendAutopilotReport({itemId:n.id,outcome:"claimed",runId:f.runId});let b=`${r.id}:${n.issueKey}`;this.inFlight.add(b);let w=this.resolveClaudeProfile(f.runId,f.claudeProfile),_=n.batchId?Wl(n.batchId):null,S=n.continueBranch?null:Vl(_,n.issueKey),A=S?Po(n.batchId,S,n.issueKey):null,z=Xl(S,n.issueKey);this.enqueueForRepo(l.path,async()=>{try{await bo({runId:f.runId,rule:c,project:o,issueKey:n.issueKey,repoPath:l.path,cfg:this.cfg,jira:u,transport:this.transport,claudeConfigDir:w,actorEmail:f.actorEmail,continueBranch:n.continueBranch,...A?{chain:{sessionId:A.sessionId,worktreePath:A.worktreePath}}:{},keepWorktree:z,onChainSession:S?q=>Jl(n.batchId,S,n.issueKey,q):void 0}),S&&!Po(n.batchId,S,S[S.indexOf(n.issueKey)+1]??"")&&S.indexOf(n.issueKey)<S.length-1&&Yl(n.batchId,S)}finally{this.inFlight.delete(b)}})}async sweepGitHubApprovals(){let e=Object.values(Js());if(!e.length)return;let n=ve()??this.cfg,r=new Map,s=i=>{let o=je(n,i);if(!o)return null;let l=r.get(o);return l||r.set(o,l=new Me(o)),l};for(let i of e.slice(0,10)){let o=s(i.repoName);if(!o)continue;if(!this.hasJira(i.repoName)){this.warnNoJiraForRepo(i.repoName);continue}let l=`gh-approve:${i.runId}`;if(this.inFlight.has(l))continue;let c,u;try{[c,u]=await Promise.all([o.getReviews(i.owner,i.repo,i.prNumber),o.getPullRequest(i.owner,i.repo,i.prNumber)])}catch(w){y.warn(`review check failed for ${i.owner}/${i.repo}#${i.prNumber}: ${w instanceof Error?w.message:w}`);continue}if(!u)continue;let h={cfg:this.cfg,jiraFor:this.jiraFor,transport:this.transport};if(u.merged){y.info(`PR #${i.prNumber} for ${i.issueKey} was merged on GitHub - completing the run`),this.inFlight.add(l);try{await Qs(h,i.runId,u.headSha)}finally{this.inFlight.delete(l)}continue}if(u.state==="closed"){y.info(`PR #${i.prNumber} for ${i.issueKey} was closed unmerged on GitHub - failing the run`);let w=this.jiraFor(i.repoName),_=`PR #${i.prNumber} was closed on GitHub without merging`;await w.addComment(i.issueKey,`**Allwright: the pull request for this ticket was closed on GitHub without merging.**
|
|
961
961
|
|
|
962
962
|
PR: ${i.prUrl}
|
|
963
963
|
|
|
964
|
-
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 w.editLabels(i.issueKey,{add:[i.failedLabel]}).catch(()=>{}),this.transport.send({type:"run.status",runId:i.runId,status:"failed",error:
|
|
964
|
+
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 w.editLabels(i.issueKey,{add:[i.failedLabel]}).catch(()=>{}),this.transport.send({type:"run.status",runId:i.runId,status:"failed",error:_}),xr(i.runId);continue}u.mergeableState==="dirty"?(this.transport.send({type:"run.pr.conflict",runId:i.runId,conflicted:!0}),i.conflictNotified||(await this.jiraFor(i.repoName).addComment(i.issueKey,`**Allwright: the pull request for this ticket has merge conflicts.** The base branch moved after this change was built, so GitHub cannot merge it as-is.
|
|
965
965
|
|
|
966
966
|
PR: ${i.prUrl}
|
|
967
967
|
|
|
968
|
-
To fix: Reject this run on the Allwright dashboard (that closes the conflicted PR), then post the implement trigger comment again - a fresh run rebuilds the change on the current base. Or resolve the conflicts manually on branch \`${i.branch}\`; approval works normally once the PR is conflict-free. (run \`${i.runId}\`)`).catch(()=>{}),i.conflictNotified=!0,_t(i),y.info(`merge conflicts on PR #${i.prNumber} for ${i.issueKey} - ticket notified`))):u.mergeableState!==null&&u.mergeableState!=="unknown"&&(this.transport.send({type:"run.pr.conflict",runId:i.runId,conflicted:!1}),i.conflictNotified&&(i.conflictNotified=!1,_t(i)));let f=c.filter(w=>w.state==="APPROVED"||w.state==="CHANGES_REQUESTED").sort((w,
|
|
968
|
+
To fix: Reject this run on the Allwright dashboard (that closes the conflicted PR), then post the implement trigger comment again - a fresh run rebuilds the change on the current base. Or resolve the conflicts manually on branch \`${i.branch}\`; approval works normally once the PR is conflict-free. (run \`${i.runId}\`)`).catch(()=>{}),i.conflictNotified=!0,_t(i),y.info(`merge conflicts on PR #${i.prNumber} for ${i.issueKey} - ticket notified`))):u.mergeableState!==null&&u.mergeableState!=="unknown"&&(this.transport.send({type:"run.pr.conflict",runId:i.runId,conflicted:!1}),i.conflictNotified&&(i.conflictNotified=!1,_t(i)));let f=c.filter(w=>w.state==="APPROVED"||w.state==="CHANGES_REQUESTED").sort((w,_)=>w.submittedAt.localeCompare(_.submittedAt)),b=f[f.length-1];if(b){if(b.state==="CHANGES_REQUESTED"){i.changesRequestedNotified||(await this.jiraFor(i.repoName).addComment(i.issueKey,`**Allwright: changes were requested on the pull request** (by ${b.user}).
|
|
969
969
|
|
|
970
970
|
PR: ${i.prUrl}
|
|
971
971
|
|
|
972
|
-
Reply to the review on GitHub, or reject the run on the Allwright dashboard and re-trigger with new instructions. (run \`${i.runId}\`)`).catch(()=>{}),_t({...i,changesRequestedNotified:!0}),y.info(`changes requested on PR #${i.prNumber} for ${i.issueKey} - ticket notified`));continue}if(b.commitId===u.headSha){y.info(`PR #${i.prNumber} for ${i.issueKey} approved on GitHub by ${b.user} - completing the run`),this.inFlight.add(l);try{await
|
|
972
|
+
Reply to the review on GitHub, or reject the run on the Allwright dashboard and re-trigger with new instructions. (run \`${i.runId}\`)`).catch(()=>{}),_t({...i,changesRequestedNotified:!0}),y.info(`changes requested on PR #${i.prNumber} for ${i.issueKey} - ticket notified`));continue}if(b.commitId===u.headSha){y.info(`PR #${i.prNumber} for ${i.issueKey} approved on GitHub by ${b.user} - completing the run`),this.inFlight.add(l);try{await Qs(h,i.runId,b.commitId)}catch(w){y.warn(`github-approval completion failed for ${i.runId}: ${w instanceof Error?w.message:w}`)}finally{this.inFlight.delete(l)}}}}}async sweepMergedPRs(){let e=Object.values(po());if(!e.length)return;let n=ve()??this.cfg,r=new Map,s=l=>{let c=je(n,l);if(!c)return null;let u=r.get(c);return u||r.set(c,u=new Me(c)),u},i=20,o=720*3600*1e3;for(let l of e.slice(0,i)){let c=s(l.repoName);if(!c)continue;if(!this.hasJira(l.repoName)){this.warnNoJiraForRepo(l.repoName);continue}if(Date.now()-new Date(l.createdAt).getTime()>o){y.warn(`merge watch for ${l.issueKey} PR #${l.prNumber} is over 30 days old - dropping`),Vs(l.runId);continue}let u;try{u=await c.getPullRequest(l.owner,l.repo,l.prNumber)}catch(b){y.warn(`merge check failed for ${l.owner}/${l.repo}#${l.prNumber}: ${b instanceof Error?b.message:b}`);continue}if(!u){Vs(l.runId);continue}if(u.state==="open")continue;if(!u.merged){Vs(l.runId);continue}let h=this.jiraFor(l.repoName),f="";if(l.jiraTransitionOnMerge)try{f=await h.transitionByName(l.issueKey,l.jiraTransitionOnMerge)?`
|
|
973
973
|
|
|
974
974
|
Ticket moved to **${l.jiraTransitionOnMerge}**.`:`
|
|
975
975
|
|
|
976
976
|
Note: no transition named "${l.jiraTransitionOnMerge}" is available from this ticket's current status - move it manually.`}catch(b){f=`
|
|
977
977
|
|
|
978
|
-
Note: the "${l.jiraTransitionOnMerge}" transition failed: ${b instanceof Error?b.message:b}`}try{await
|
|
978
|
+
Note: the "${l.jiraTransitionOnMerge}" transition failed: ${b instanceof Error?b.message:b}`}try{await h.addComment(l.issueKey,`**Allwright: the pull request for this ticket was merged.**
|
|
979
979
|
|
|
980
980
|
PR: ${l.prUrl} (merged at \`${u.headSha.slice(0,10)}\`)${f}
|
|
981
981
|
|
|
982
|
-
(run \`${l.runId}\`)`)}catch(b){y.warn(`could not post merge comment to ${l.issueKey}: ${b instanceof Error?b.message:b}`);continue}y.info(`PR #${l.prNumber} for ${l.issueKey} merged - ticket updated`),
|
|
982
|
+
(run \`${l.runId}\`)`)}catch(b){y.warn(`could not post merge comment to ${l.issueKey}: ${b instanceof Error?b.message:b}`);continue}y.info(`PR #${l.prNumber} for ${l.issueKey} merged - ticket updated`),Vs(l.runId)}}async sweepNeedsInput(e){let n;try{n=await this.jiraOf(e).search(`project = "${e.jiraProjectKey}" AND labels = "${Cn.NEEDS_INPUT_LABEL}"`,10)}catch(s){y.warn(`needs-input sweep failed for ${e.jiraProjectKey}: ${s instanceof Error?s.message:s}`);return}if(!n.length)return;let r=Rr();for(let s of n){let i=Object.values(r).filter(l=>l.issueKey===s.key);if(!i.length){await this.jiraOf(e).editLabels(s.key,{remove:[Cn.NEEDS_INPUT_LABEL]}).catch(()=>{}),y.warn(`${s.key}: needs-input label with no local pending record - removed`);continue}let o=null;for(let l of i){let c=`resume:${l.runId}`;if(this.inFlight.has(c))continue;if(Date.now()-new Date(l.createdAt).getTime()>gv){this.inFlight.add(c),this.abandonStaleInput(l,e).finally(()=>this.inFlight.delete(c));continue}try{o=o??await this.jiraOf(e).getIssue(s.key)}catch(_){y.warn(`needs-input check failed for ${s.key}: ${_ instanceof Error?_.message:_}`);continue}let u=new Date(l.questionsPostedAt).getTime(),h=o.comments.filter(_=>!$t(_.body)&&new Date(_.created).getTime()>u);if(!h.length)continue;let f=ei(h),b=o.attachments;this.inFlight.add(c),y.info(`reply received on ${s.key} - resuming run ${l.runId}`),await this.jiraOf(e).editLabels(s.key,{remove:[Cn.NEEDS_INPUT_LABEL]}).catch(_=>{y.warn(`could not remove needs-input label on ${s.key}: ${_}`)});let w={jiraFor:this.jiraFor,transport:this.transport,cfg:this.cfg};l.kind==="implement"?this.enqueueForRepo(l.baseRepoPath??l.repoPath,async()=>{try{await jl(l,f,b,w)}finally{this.inFlight.delete(c)}}):this.enqueueForRepo(l.repoPath,async()=>{try{await Pl(l,f,b,w)}finally{this.inFlight.delete(c)}})}}}async answerPendingInput(e,n,r){let s=yh(e);if(!s)return{ok:!1,note:"",error:"this run is not waiting for an answer on this server - it may have been answered already, or abandoned after 14 days without a reply"};let i=`resume:${e}`;if(this.inFlight.has(i))return{ok:!1,note:"",error:"an answer for this run is already being applied"};this.inFlight.add(i);let o=this.jiraFor(s.repoName??""),l=[];try{l=(await o.getIssue(s.issueKey)).attachments,await o.addComment(s.issueKey,`**Answered on the Allwright dashboard${r?` by ${r}`:""}.**
|
|
983
983
|
|
|
984
984
|
${n}
|
|
985
985
|
|
|
986
|
-
This run is continuing from where it left off. (run \`${e}\`)`),await o.editLabels(s.issueKey,{remove:[Cn.NEEDS_INPUT_LABEL]})}catch(f){this.inFlight.delete(i);let b=f instanceof Error?f.message:String(f);return{ok:!1,note:"",error:`could not write the answer to ${s.issueKey}: ${b}`}}y.info(`answer received from the dashboard for ${s.issueKey} - resuming run ${e}`);let c=r?`${r}: ${n}`:n,u={jiraFor:this.jiraFor,transport:this.transport,cfg:this.cfg},
|
|
986
|
+
This run is continuing from where it left off. (run \`${e}\`)`),await o.editLabels(s.issueKey,{remove:[Cn.NEEDS_INPUT_LABEL]})}catch(f){this.inFlight.delete(i);let b=f instanceof Error?f.message:String(f);return{ok:!1,note:"",error:`could not write the answer to ${s.issueKey}: ${b}`}}y.info(`answer received from the dashboard for ${s.issueKey} - resuming run ${e}`);let c=r?`${r}: ${n}`:n,u={jiraFor:this.jiraFor,transport:this.transport,cfg:this.cfg},h=s.kind==="implement"?s.baseRepoPath??s.repoPath:s.repoPath;return this.enqueueForRepo(h,async()=>{try{s.kind==="implement"?await jl(s,c,l,u):await Pl(s,c,l,u)}finally{this.inFlight.delete(i)}}),{ok:!0,note:`Answer sent - the run is continuing, and it was posted to ${s.issueKey} too.`}}async abandonStaleInput(e,n){y.warn(`${e.issueKey}: needs-input unanswered for over ${No}d - abandoning run ${e.runId}`);try{await this.jiraOf(n).addComment(e.issueKey,`**Allwright gave up waiting for an answer.**
|
|
987
987
|
|
|
988
|
-
No reply arrived within ${
|
|
988
|
+
No reply arrived within ${No} days of the question above. This ticket has been labeled \`${e.failedLabel}\`; remove it and re-trigger to try again. (run \`${e.runId}\`)`),await this.jiraOf(n).editLabels(e.issueKey,{add:[e.failedLabel],remove:[Cn.NEEDS_INPUT_LABEL]})}catch(r){y.warn(`could not post staleness notice for ${e.issueKey}: ${r}`)}e.kind==="implement"&&await Et(e.baseRepoPath??e.repoPath,e.repoPath).catch(()=>{}),jt(e.runId),this.transport.send({type:"run.status",runId:e.runId,status:"failed",error:`no reply within ${No} days`})}async pollRule(e,n,r){let s=e.trigger.type==="label_added"?await this.matchLabelTrigger(e,n):await this.matchCommentTrigger(e,n);for(let i of s){let o=`${e.id}:${i.issueKey}`;if(this.inFlight.has(o))continue;let l=Ao(n,i.components??[]);if("error"in l){this.warnRoutingOnce(`${e.id}:${i.issueKey}`,`${i.issueKey}: ${l.error}`);continue}let c=l.project,u=c.repoName===n.repoName?r:this.cfg.repos[c.repoName]?.path;if(!u){this.warnRoutingOnce(`${e.id}:${i.issueKey}:path`,`${i.issueKey}: routed to repo "${c.repoName}" but it has no local checkout - run: allwright repo add "${c.repoName}" /path/to/checkout`);continue}let h=await this.transport.claimRun({ruleId:e.id,issueKey:i.issueKey,issueSummary:i.summary,triggerFingerprint:i.fingerprint,triggeredByAccountId:i.triggeredByAccountId});if(!h.accepted||!h.runId){h.reason!=="duplicate"&&y.warn(`claim rejected for ${i.issueKey}: ${h.reason??"unknown"}`);continue}this.inFlight.add(o),y.info(`claimed run ${h.runId} for ${i.issueKey}`+(c.repoName!==n.repoName?` (routed \u2192 ${c.repoName})`:"")+(h.claudeProfile?` (claude profile "${h.claudeProfile}")`:""));let f=this.resolveClaudeProfile(h.runId,h.claudeProfile);this.enqueueForRepo(u,async()=>{try{await bo({runId:h.runId,rule:e,project:c,issueKey:i.issueKey,repoPath:u,cfg:this.cfg,jira:this.jiraOf(c),transport:this.transport,claudeConfigDir:f,actorEmail:h.actorEmail})}finally{this.inFlight.delete(o)}})}}async pollRespondRule(e,n,r){let s=e.trigger;if(s.type!=="comment_keyword"||e.action.type!=="respond")return;let i=await this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=s.keyword.toLowerCase(),l=Date.now()-pp;for(let c of i){let u=await this.jiraOf(n).getIssue(c.key);for(let h of u.comments){if(!h.body.toLowerCase().includes(o)||$t(h.body)||new Date(h.created).getTime()<l||!h.id)continue;let f=`respond:${h.id}`;if(this.inFlight.has(f))continue;let b=Ao(n,c.components??[]);if("error"in b){this.warnRoutingOnce(`${e.id}:${c.key}`,`${c.key}: ${b.error}`);continue}let w=b.project,_=w.repoName===n.repoName?r:this.cfg.repos[w.repoName]?.path;if(!_){this.warnRoutingOnce(`${e.id}:${c.key}:path`,`${c.key}: routed to repo "${w.repoName}" but it has no local checkout - run: allwright repo add "${w.repoName}" /path/to/checkout`);continue}let S=await this.transport.claimRun({ruleId:e.id,issueKey:c.key,issueSummary:c.summary,triggerFingerprint:`question by ${h.author} at ${h.created}`,dedupKey:`respond:comment:${h.id}`,triggeredByAccountId:h.authorAccountId??void 0});if(!S.accepted||!S.runId){S.reason!=="duplicate"&&y.warn(`respond claim rejected for ${c.key}: ${S.reason??"unknown"}`);continue}this.inFlight.add(f),y.info(`claimed respond run ${S.runId}: ${c.key} (comment ${h.id})`+(w.repoName!==n.repoName?` (routed \u2192 ${w.repoName})`:"")+(S.claudeProfile?` (claude profile "${S.claudeProfile}")`:""));let A={author:h.author,body:h.body},z=this.resolveClaudeProfile(S.runId,S.claudeProfile);this.enqueueForRepo(_,async()=>{try{await bo({runId:S.runId,rule:e,project:w,issueKey:c.key,repoPath:_,cfg:this.cfg,jira:this.jiraOf(w),transport:this.transport,question:A,claudeConfigDir:z,actorEmail:S.actorEmail})}finally{this.inFlight.delete(f)}})}}}async sweepRevisions(e,n){let r=e.trigger;if(r.type!=="comment_keyword")return;let s;try{s=await this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND labels = "${r.doneLabel}" AND updated >= "-2d"`,10)}catch(o){y.warn(`revision sweep failed for ${n.jiraProjectKey}: ${o instanceof Error?o.message:o}`);return}let i=r.keyword.toLowerCase();for(let o of s)try{let l=await this.jiraOf(n).getIssue(o.key),c=null;for(let h of l.comments)$t(h.body)&&(c=Math.max(c??0,new Date(h.created).getTime()));if(c===null||!l.comments.some(h=>!$t(h.body)&&h.body.toLowerCase().includes(i)&&new Date(h.created).getTime()>c))continue;await this.jiraOf(n).editLabels(o.key,{remove:[r.doneLabel]}),y.info(`revision requested on ${o.key} (new "${r.keyword}" after completion) - done label removed, rule will re-fire`)}catch(l){y.warn(`revision check failed for ${o.key}: ${l instanceof Error?l.message:l}`)}}async pollDeployRule(e,n,r){if(e.action.type!=="deploy")return;let s=e.trigger.type==="status_changed"?await this.matchStatusDeploys(e,n):await this.matchCommentDeploys(e,n);for(let i of s){let o=`deploy:${i.dedupKey}`;if(this.inFlight.has(o))continue;let l=await this.transport.claimDeploy({projectId:n.id,ruleId:e.id,issueKey:i.issueKey,issueSummary:i.summary,environmentName:i.environmentName,requestedByAccountId:i.requestedByAccountId,requestedByDisplayName:i.requestedByDisplayName,dedupKey:i.dedupKey,triggerFingerprint:i.fingerprint});if(!l.accepted||!l.runId||!l.environment){if(l.code==="duplicate")continue;l.reason&&l.runId?(await this.jiraOf(n).addComment(i.issueKey,`**Allwright did not deploy this ticket.**
|
|
989
989
|
|
|
990
990
|
${l.reason}`+(i.requestedByAccountId?`
|
|
991
991
|
|
|
992
992
|
Jira account id: \`${i.requestedByAccountId}\``:"")+`
|
|
993
993
|
|
|
994
|
-
(run \`${l.runId}\`)`).catch(u=>y.warn(`could not post refusal to ${i.issueKey}: ${u}`)),y.warn(`deploy refused for ${i.issueKey}: ${l.reason}`)):l.reason&&y.warn(`deploy claim rejected for ${i.issueKey}: ${l.reason}`);continue}let c=l.environment;this.inFlight.add(o),y.info(`claimed deploy ${l.runId}: ${i.issueKey} \u2192 ${c.name}`),this.enqueue(this.envQueues,c.id,async()=>{try{await
|
|
994
|
+
(run \`${l.runId}\`)`).catch(u=>y.warn(`could not post refusal to ${i.issueKey}: ${u}`)),y.warn(`deploy refused for ${i.issueKey}: ${l.reason}`)):l.reason&&y.warn(`deploy claim rejected for ${i.issueKey}: ${l.reason}`);continue}let c=l.environment;this.inFlight.add(o),y.info(`claimed deploy ${l.runId}: ${i.issueKey} \u2192 ${c.name}`),this.enqueue(this.envQueues,c.id,async()=>{try{await Ro({runId:l.runId,project:n,environment:c,issueKey:i.issueKey,issueSummary:i.summary,repoPath:r,cfg:this.cfg,jira:this.jiraOf(n),transport:this.transport,requestedBy:i.requestedByDisplayName})}finally{this.inFlight.delete(o)}})}}async matchCommentDeploys(e,n){let r=e.trigger,s=e.action;if(r.type!=="comment_keyword"||s.type!=="deploy")return[];let i=await this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=r.keyword.toLowerCase(),l=Date.now()-pp,c=this.environments.filter(f=>f.projectId===n.id).map(f=>f.name),u=this.fixedEnvironmentName(s.environmentId),h=[];for(let f of i){let b=await this.jiraOf(n).getIssue(f.key);if(!(s.requireStatus&&b.status.toLowerCase()!==s.requireStatus.toLowerCase()))for(let w of b.comments){if(!w.body.toLowerCase().includes(o)||$t(w.body)||new Date(w.created).getTime()<l||!w.id)continue;let _=s.envSelection==="fixed"?u:bv(w.body,r.keyword,c);h.push({issueKey:f.key,summary:f.summary,environmentName:_,requestedByAccountId:w.authorAccountId??void 0,requestedByDisplayName:w.author,dedupKey:`deploy:comment:${w.id}`,fingerprint:`comment "${r.keyword}" by ${w.author} at ${w.created}`+(_?` \u2192 ${_}`:"")})}}return h}async matchStatusDeploys(e,n){let r=e.trigger,s=e.action;if(r.type!=="status_changed"||s.type!=="deploy")return[];let i=await this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND status = "${r.status}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=this.fixedEnvironmentName(s.environmentId),l=[];for(let c of i){let u=await this.jiraOf(n).lastEnteredStatus(c.key,r.status);u&&l.push({issueKey:c.key,summary:c.summary,environmentName:o,requestedByAccountId:u.authorAccountId??void 0,requestedByDisplayName:u.author,dedupKey:`deploy:status:${e.id}:${c.key}:${u.at}`,fingerprint:`moved to "${r.status}" by ${u.author} at ${u.at}`})}return l}fixedEnvironmentName(e){return e?this.environments.find(n=>n.id===e)?.name??"":""}async matchLabelTrigger(e,n){let r=e.trigger;if(r.type!=="label_added")return[];let s=`project = "${n.jiraProjectKey}" AND labels = "${r.label}" AND labels not in ("${r.doneLabel}", "${r.failedLabel}", "${Cn.NEEDS_INPUT_LABEL}") ORDER BY updated ASC`;return(await this.jiraOf(n).search(s,10)).map(o=>({issueKey:o.key,summary:o.summary,components:o.components,fingerprint:`label "${r.label}" matched at ${new Date().toISOString()}`}))}async matchCommentTrigger(e,n){let r=e.trigger;if(r.type!=="comment_keyword")return[];let s=`project = "${n.jiraProjectKey}" AND updated >= "-2d" AND (labels IS EMPTY OR labels not in ("${r.doneLabel}", "${r.failedLabel}", "${Cn.NEEDS_INPUT_LABEL}")) ORDER BY updated DESC`,i=await this.jiraOf(n).search(s,10),o=r.keyword.toLowerCase(),l=[];for(let c of i){let h=[...(await this.jiraOf(n).getIssue(c.key)).comments].reverse().find(f=>f.body.toLowerCase().includes(o)&&!$t(f.body));h&&l.push({issueKey:c.key,components:c.components,summary:c.summary,fingerprint:`comment keyword "${r.keyword}" by ${h.author} at ${h.created}`,triggeredByAccountId:h.authorAccountId??void 0})}return l}async diagnoseRule(e,n){let r=e.trigger;if(e.action.type==="deploy"){let c=r.type==="status_changed"?await this.matchStatusDeploys(e,n):await this.matchCommentDeploys(e,n),u=c.filter(h=>h.environmentName);return{matchedCount:u.length,excludedCount:c.length-u.length,excludedSample:c.filter(h=>!h.environmentName).slice(0,5).map(h=>h.issueKey)}}if(r.type==="status_changed")return{matchedCount:(await this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND status = "${r.status}"`,50)).length,excludedCount:0,excludedSample:[]};if(r.type==="label_added"){let[c,u]=await Promise.all([this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND labels = "${r.label}" AND labels not in ("${r.doneLabel}", "${r.failedLabel}")`,50),this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND labels = "${r.label}" AND labels in ("${r.doneLabel}", "${r.failedLabel}")`,50)]);return{matchedCount:c.length,excludedCount:u.length,excludedSample:u.slice(0,5).map(h=>h.key)}}let s=r.keyword.toLowerCase(),[i,o]=await Promise.all([this.matchCommentTrigger(e,n),this.jiraOf(n).search(`project = "${n.jiraProjectKey}" AND updated >= "-2d" AND labels in ("${r.doneLabel}", "${r.failedLabel}")`,50)]),l=[];for(let c of o)(await this.jiraOf(n).getIssue(c.key)).comments.some(h=>h.body.toLowerCase().includes(s))&&l.push(c.key);return{matchedCount:i.length,excludedCount:l.length,excludedSample:l.slice(0,5)}}enqueueForRepo(e,n){this.enqueue(this.repoQueues,e,n)}runOnRepoQueue(e,n){this.enqueue(this.repoQueues,e,n)}runOnEnvironmentQueue(e,n){this.enqueue(this.envQueues,e,n)}enqueue(e,n,r){let i=(e.get(n)??Promise.resolve()).then(async()=>{this.activeWork++;try{await r()}finally{this.activeWork--}}).catch(o=>{y.error(`run crashed: ${o instanceof Error?o.stack:o}`)});e.set(n,i)}};function bv(t,e,n){let r=t.toLowerCase().indexOf(e.toLowerCase());if(r<0)return"";let i=t.slice(r+e.length).split(/[^\w.-]+/).filter(Boolean);for(let o of i){let l=n.find(c=>c.toLowerCase()===o.toLowerCase());if(l)return l}for(let o of i)if(!yv.has(o.toLowerCase()))return o;return""}var fp=I(require("node:fs"),1),mp=I(require("node:path"),1),ec=require("node:crypto");Ct();var wv=`This repository is in the middle of a git merge: the base branch moved and some files conflict with the change on this branch. Your ONLY job is to resolve those conflicts.
|
|
995
995
|
|
|
996
996
|
Rules:
|
|
997
997
|
- Edit ONLY the conflicted files listed below. Do not touch anything else, do not refactor, do not "improve" surrounding code.
|
|
@@ -1000,10 +1000,10 @@ Rules:
|
|
|
1000
1000
|
- When you are done, every listed file must contain no conflict markers and must be syntactically valid.
|
|
1001
1001
|
|
|
1002
1002
|
Conflicted files:
|
|
1003
|
-
`;async function
|
|
1004
|
-
`),timeoutSeconds:t.timeoutSeconds,bin:
|
|
1003
|
+
`;async function gp(t){let{cfg:e,repoPath:n,branch:r,baseBranch:s,issueKey:i,onLog:o}=t,l=mp.default.join(Yt(),`conflict-${(0,ec.randomUUID)().slice(0,8)}`),c=!1;try{o("info",`Preparing a worktree for ${r} to merge ${s} into it`),await Ks(n,l,r),c=!0;let u=await Wa(l,s);if(u.ok&&u.alreadyUpToDate)return o("info",`${r} already contains ${s} - nothing to merge`),{ok:!0,freeOfCharge:!0,note:`This branch already contains ${s}, so there was nothing to merge - GitHub's conflict flag was out of date. Refresh the PR.`};if(!u.ok&&u.conflicts===null)return{ok:!1,note:`The merge could not even be started: ${u.reason}`};let h={},f=!1;if(!u.ok){let _=u.conflicts;o("info",`git merged everything except ${_.length} file(s): ${_.slice(0,20).join(", ")}`+(_.length>20?", \u2026":""));let S=We(t.agentId);if(!S)return await Rn(l),{ok:!1,note:`no adapter for agent "${t.agentId}" on this runner`};let A=En(t.agentId,"edit_no_shell");if(A)return await Rn(l),{ok:!1,note:`${A} Resolve the conflicts yourself on branch ${r}, or use Rebuild on current base.`};o("info",`Asking ${S.displayName} to resolve only those files`);let z=-1,q=setInterval(()=>{Ja(l,_).then(M=>{let B=_.filter(j=>!M.includes(j));B.length!==z&&(z=B.length,o("info",`Conflict progress: ${B.length}/${_.length} resolved`+(B.length?` \xB7 clean: ${B.join(", ")}`:"")+(M.length?` \xB7 still conflicted: ${M.join(", ")}`:"")))}).catch(()=>{})},12e3),v=await Xs(S,{repoPath:l,prompt:wv+_.map(M=>`- ${M}`).join(`
|
|
1004
|
+
`),timeoutSeconds:t.timeoutSeconds,bin:Ve(e,t.agentId),configDir:t.configDir,mode:"edit_no_shell",sessionId:(0,ec.randomUUID)(),onLog:(M,B)=>o(M,B)},(M,B)=>o(M==="warn"?"warn":M,B));if(clearInterval(q),h={costUsd:v.costUsd,inputTokens:v.inputTokens,outputTokens:v.outputTokens},!v.ok)return await Rn(l),{ok:!1,...h,note:`The agent could not do the resolution: ${v.error??"it produced no output"}. Nothing was changed - the merge was rolled back. Fix that first, then Resolve again.`};f=!0;let C=await Xi(l);if(C.length)return await Rn(l),{ok:!1,...h,note:`The agent left conflict markers in ${C.slice(0,5).join(", ")}, so nothing was pushed and the merge was rolled back. Resolve it by hand on ${r}, or use Rebuild on current base to redo the ticket against today's base.`};await Va(l,`${i}: merge ${s}, conflicts resolved by the agent
|
|
1005
1005
|
|
|
1006
|
-
Resolved via Allwright`)}let b=await xn(l,s);if(!b.ok){let
|
|
1006
|
+
Resolved via Allwright`)}let b=await xn(l,s);if(!b.ok){let _=b.forbidden.length?`the merged result touches protected paths (${b.forbidden.slice(0,5).join(", ")})`:`the merged result is too large (${b.files} files, ${b.insertions+b.deletions} lines; limits ${_n}/${Sn})`;return await Rn(l),{ok:!1,...h,note:`Nothing was pushed: ${_}. The merge was rolled back.`}}await wr(l,r);let w=await Ze(l);return o("info",`Pushed the merge to ${r} (${w.slice(0,7)})`),{ok:!0,...h,freeOfCharge:!f,headSha:w,note:f?`Merged ${s} into ${r}; the agent resolved the overlapping files. The PR is the same one - review the merge commit, then approve.`:`Merged ${s} into ${r} cleanly - no agent was needed, so this cost nothing. The PR is the same one; review and approve.`}}catch(u){return await Rn(l).catch(()=>{}),{ok:!1,note:`Could not resolve the conflict: ${u instanceof Error?u.message.slice(0,300):String(u)}`}}finally{c&&(await Et(n,l).catch(()=>{}),fp.default.rmSync(l,{recursive:!0,force:!0}))}}var tc=I(require("node:fs"),1),yp=I(require("node:path"),1),nc=require("node:crypto");Ct();function vv(t,e){let n=e.map(r=>`$ ${r.command} (exit ${r.exitCode})
|
|
1007
1007
|
${r.tail.slice(-2e3)}`).join(`
|
|
1008
1008
|
|
|
1009
1009
|
`);return`You are on the pull-request branch for ticket ${t}. The work itself is done and under review - do NOT redo or extend it. The repository's documented TEST.md commands were executed by the runner and ${e.length} failed:
|
|
@@ -1016,17 +1016,17 @@ Your ONLY job is to make these commands pass, with the smallest change possible.
|
|
|
1016
1016
|
- If a failure is clearly pre-existing on the base branch and unrelated to this PR's change, leave the code alone and say so in one sentence.
|
|
1017
1017
|
- Do not ask questions; if you cannot fix something safely, say what you found and stop.
|
|
1018
1018
|
- You have no shell; the runner re-runs every documented command after you finish.
|
|
1019
|
-
End with one short paragraph stating exactly what you changed, or why you changed nothing.`}async function
|
|
1019
|
+
End with one short paragraph stating exactly what you changed, or why you changed nothing.`}async function bp(t){let{cfg:e,repoPath:n,branch:r,baseBranch:s,issueKey:i,failedTests:o,onLog:l}=t,c=yp.default.join(Yt(),`testfix-${(0,nc.randomUUID)().slice(0,8)}`),u=!1;try{let h=We(t.agentId);if(!h)return{ok:!1,note:`no adapter for agent "${t.agentId}" on this runner`};let f=En(t.agentId,"edit_no_shell");if(f)return{ok:!1,note:f};l("info",`Preparing a worktree on ${r} for the test fix`),await Tn(n,r),await Ks(n,c,r),u=!0,await ds(c,`origin/${r}`);let b=await Ze(c);l("info",`Asking ${h.displayName} to fix ${o.length} failing test command(s) - narrow prompt, failure output included, no re-exploration`);let w=await Xs(h,{repoPath:c,prompt:vv(i,o),timeoutSeconds:t.timeoutSeconds,bin:Ve(e,t.agentId),configDir:t.configDir,mode:"edit_no_shell",maxTurns:60,sessionId:(0,nc.randomUUID)(),onLog:(j,d)=>l(j,d)},(j,d)=>l(j==="warn"?"warn":j,d)),_={costUsd:w.costUsd,inputTokens:w.inputTokens,outputTokens:w.outputTokens};if(!w.ok)return{ok:!1,..._,note:`The fix agent could not run: ${w.error??"it produced no output"}. Nothing was changed or pushed.`};let S=await us(c);for(let j of S.refused)l("warn",`${Jt} entry refused: ${j}`);let A=!0;try{await br(c,`${i}: fix failing TEST.md commands
|
|
1020
1020
|
|
|
1021
|
-
Allwright test-fix run`)}catch{
|
|
1022
|
-
${m.tail.slice(-1500)}`));q=d.filter(m=>m.exitCode!==0).slice(0,20).map(m=>({command:m.command.slice(0,500),exitCode:m.exitCode,tail:m.tail.slice(-4e3)})),
|
|
1023
|
-
`,{mode:384}),jr.default.renameSync(n,e),jr.default.chmodSync(e,384)}function
|
|
1021
|
+
Allwright test-fix run`)}catch{A=!1}if(!A){let j=`The agent changed nothing - its own conclusion: ${w.resultText.trim().slice(0,400)||"(no explanation given)"}`;return l("info",j),{ok:!0,..._,remaining:o,note:j}}let z=await xn(c,s);if(!z.ok){await ds(c,b);let j=z.forbidden.length?`the fixed result touches protected paths (${z.forbidden.slice(0,5).join(", ")})`:`the fixed result is too large (${z.files} files, ${z.insertions+z.deletions} lines; limits ${_n}/${Sn})`;return{ok:!1,..._,note:`Nothing was pushed: ${j}. The fix commit was discarded; the PR is unchanged.`}}let q=o,v,C,M=ms(c);if(M){let j=gs(tc.default.readFileSync(M,"utf8"));if(j.length){l("info",`Re-running ${j.length} documented test command(s)`);let d=await _r(c,j,{perCommandTimeoutMs:15*6e4});for(let m of d)l(m.exitCode===0?"info":"warn",`${m.exitCode===0?"PASS":"FAIL"} ${m.command} (exit ${m.exitCode})`+(m.exitCode===0?"":`
|
|
1022
|
+
${m.tail.slice(-1500)}`));q=d.filter(m=>m.exitCode!==0).slice(0,20).map(m=>({command:m.command.slice(0,500),exitCode:m.exitCode,tail:m.tail.slice(-4e3)})),C=d.length,v=d.length-q.length}}await wr(c,r);let B=await Ze(c);return l("info",`Pushed the fix to ${r} (${B.slice(0,7)})`),{ok:!0,..._,headSha:B,remaining:q,testsPassed:v,testsTotal:C,note:q.length?`The fix was pushed, but ${q.length} command(s) still fail - output is in the run log. The PR is the same one; review the new commit.`:"All documented test commands pass now. The PR is the same one - review the fix commit, then approve."}}catch(h){return{ok:!1,note:`Could not fix the tests: ${h instanceof Error?h.message.slice(0,300):String(h)}`}}finally{u&&(await Et(n,c).catch(()=>{}),tc.default.rmSync(c,{recursive:!0,force:!0}))}}kt();var jr=I(require("node:fs"),1),vp=I(require("node:path"),1);Xr();Ae();var kv=k.object({role:k.enum(["user","agent"]),text:k.string(),steps:k.array(k.string()).default([]),files:k.array(k.string()).default([]),at:k.string().default(""),ms:k.number().int().nonnegative().default(0)}),_v=k.object({sessionId:k.string(),projectId:k.string(),title:k.string().default(""),updatedAt:k.string(),messages:k.array(kv).default([])}),Sv=k.record(_v),Tv=10,xv=200,wp=2e4,Rv=30,Iv=2e3,Av=8,Ev=255;function kp(){return vp.default.join(ie(),"chat-sessions.json")}function rc(){let t=kp();if(!jr.default.existsSync(t))return{};try{return Sv.parse(JSON.parse(jr.default.readFileSync(t,"utf8")))}catch{return{}}}function Cv(t){jr.default.mkdirSync(ie(),{recursive:!0,mode:448});let e=kp(),n=e+".tmp";jr.default.writeFileSync(n,JSON.stringify(t,null,2)+`
|
|
1023
|
+
`,{mode:384}),jr.default.renameSync(n,e),jr.default.chmodSync(e,384)}function _p(t,e,n,r,s=[],i=[],o={}){let l=rc(),u=l[e]??{sessionId:e,projectId:t,title:n.slice(0,80),updatedAt:new Date().toISOString(),messages:[]};u.messages.push({role:"user",text:n.slice(0,wp),steps:[],files:i.slice(0,Av).map(f=>f.slice(0,Ev)),at:o.askedAt||new Date().toISOString(),ms:0},{role:"agent",text:r.slice(0,wp),steps:s.slice(0,Rv).map(f=>f.slice(0,Iv)),files:[],at:new Date().toISOString(),ms:Math.max(0,Math.round(o.ms??0))}),u.messages=u.messages.slice(-xv),u.updatedAt=new Date().toISOString(),l[e]=u;let h=Object.values(l).filter(f=>f.projectId===u.projectId).sort((f,b)=>b.updatedAt.localeCompare(f.updatedAt));for(let f of h.slice(Tv))delete l[f.sessionId];Cv(l)}function Sp(t){return Object.values(rc()).filter(e=>e.projectId===t).sort((e,n)=>n.updatedAt.localeCompare(e.updatedAt)).map(e=>({sessionId:e.sessionId,title:e.title,updatedAt:e.updatedAt,messageCount:e.messages.length}))}function ii(t){return rc()[t]??null}Xt();var Tp=36,xp=60;function Rp(t){let e=t.toLowerCase();return e?e.includes("[1m]")||e.includes("-1m")?1e6:e.includes("haiku")||e.includes("sonnet")||e.includes("opus")||e.includes("fable")?2e5:0:0}var $v=`This conversation is being COMPACTED: it continues in a fresh window that will only have your summary, so anything you leave out is gone. Summarize it now under these headings, in under 500 words total:
|
|
1024
1024
|
Goal: what the user is trying to achieve.
|
|
1025
1025
|
Decided: choices already made, including ones you talked them out of - each as one line.
|
|
1026
1026
|
Constraints: rules, preferences and corrections the user gave you.
|
|
1027
1027
|
Repo facts: what you learned about this codebase that is worth not re-reading.
|
|
1028
1028
|
Open: what is still unresolved right now.
|
|
1029
|
-
Write plain statements, no preamble, no closing offer of help. Do NOT emit a ticket block.`;async function
|
|
1029
|
+
Write plain statements, no preamble, no closing offer of help. Do NOT emit a ticket block.`;async function Ip(t,e,n){if(!ii(e))return null;let s=Oe(n,t.project,"chat");if("error"in s)return null;try{let i=await s.adapter.run({repoPath:t.repoPath,prompt:$v,timeoutSeconds:60,bin:s.bin,mode:"read_only",maxTurns:3,model:s.adapter.fastModel,sessionId:e,resume:!0,onLog:()=>{}}),o=i.ok?i.resultText.trim():"";return o?o.slice(0,6e3):null}catch(i){return y.warn(`chat compaction failed: ${i instanceof Error?i.message:i}`),null}}var Ap=`
|
|
1030
1030
|
|
|
1031
1031
|
TWO OPTIONAL BLOCKS, for the dashboard's benefit. Never mention them in your prose.
|
|
1032
1032
|
1. When you ASK the user something and the sensible answers are countable, end with:
|
|
@@ -1039,12 +1039,12 @@ TWO OPTIONAL BLOCKS, for the dashboard's benefit. Never mention them in your pro
|
|
|
1039
1039
|
["\u2026", "\u2026"]
|
|
1040
1040
|
\`\`\`
|
|
1041
1041
|
1 to 3 short suggestions, written AS THE USER (first person, imperative) - they are typed into the user's box, not yours. Skip the block entirely when nothing obvious follows; a wrong guess costs the user more than no guess.
|
|
1042
|
-
Never emit both blocks in one reply, and never let either replace the actual answer.`;var Nr=
|
|
1043
|
-
`).trim();if(!s)return r({code:0,output:l});let c=typeof s.code=="number"?s.code:1;r({code:c||1,output:l||s.message})})})}var Yk=A(xf(),1),Xk=A(Ho(),1),Qk=A(Rs(),1),e_=A(mc(),1),t_=A(bc(),1),n_=A(Tc(),1),Nf=A(Wo(),1),r_=A(jf(),1);var Rc=Nf.default;var hi=A(require("node:crypto"),1),zt=A(ke(),1);Xt();function s_(t){let e=t&&typeof t=="object"&&"name"in t?String(t.name):null;return e?`"${e}"`:"(unnamed)"}function Ac(t,e,n,r){t.push(`dropped ${e} ${n} - this runner is out of date and does not understand it yet (${r}). Update the runner (npm install -g @ticketpilot/runner) to pick it up.`)}function i_(t){if(!t||typeof t!="object"||t.type!=="config")return null;let e=t,n=[],r=[];for(let l of Array.isArray(e.projects)?e.projects:[]){let c=zt.ProjectConfig.safeParse(l);c.success?r.push(c.data):Ac(n,"project","",c.error.issues[0]?.message??"invalid shape")}let s=[];for(let l of Array.isArray(e.rules)?e.rules:[]){let c=zt.RuleConfig.safeParse(l);c.success?s.push(c.data):Ac(n,"rule",s_(l),c.error.issues[0]?.message??"invalid shape")}let i=[];for(let l of Array.isArray(e.environments)?e.environments:[]){let c=zt.EnvironmentConfig.safeParse(l);c.success?i.push(c.data):Ac(n,"environment","",c.error.issues[0]?.message??"invalid shape")}return{msg:{type:"config",projects:r,rules:s,environments:i,pollingPaused:typeof e.pollingPaused=="boolean"?e.pollingPaused:!1,publicIp:typeof e.publicIp=="string"?e.publicIp:""},warnings:n}}var o_=2e4,a_=6e4,l_=5e3,Jo=class{constructor(e,n,r,s){this.wsUrl=e;this.runnerToken=n;this.meta=r;this.events=s}wsUrl;runnerToken;meta;events;ws=null;queue=[];pending=new Map;backoffMs=1e3;heartbeat=null;closed=!1;bootAnnounced=!1;start(){this.closed=!1,this.connect()}stop(){this.closed=!0,this.heartbeat&&clearInterval(this.heartbeat),this.ws?.close()}get connected(){return this.ws?.readyState===Rc.OPEN}connect(){if(this.closed)return;y.info(`connecting to control plane at ${this.wsUrl}`);let e=new Rc(this.wsUrl,{headers:{authorization:`Bearer ${this.runnerToken}`}});this.ws=e,e.on("open",()=>{this.backoffMs=1e3,this.sendNow({type:"hello",protocolVersion:zt.PROTOCOL_VERSION,runnerVersion:this.meta.runnerVersion,platform:`${process.platform}/${process.arch} node${process.versions.node}`,justBooted:!this.bootAnnounced});let n=this.queue.splice(0,this.queue.length);for(let r of n)this.sendNow(r);this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=setInterval(()=>{this.send({type:"heartbeat",ts:new Date().toISOString()})},o_)}),e.on("message",n=>{let r;try{r=JSON.parse(n.toString())}catch(i){y.warn(`ignoring malformed server message (bad JSON): ${i}`);return}let s;try{s=(0,zt.parseServerMsg)(r)}catch(i){let o=i_(r);if(!o){y.warn(`ignoring malformed server message: ${i}`);return}for(let l of o.warnings)y.warn(l);y.warn(`config push had ${o.warnings.length} ${o.warnings.length===1?"entry":"entries"} this runner doesn't understand - applied everything else instead of dropping the whole config`),s=o.msg}this.handle(s)}),e.on("close",n=>{if(this.heartbeat&&clearInterval(this.heartbeat),n===4001)y.error("control plane rejected this runner version (protocol mismatch). Update with: npm install -g @ticketpilot/runner");else if(n===4003){y.error("this runner has been revoked from the control plane UI. Re-enroll with a fresh token if this was not intended."),this.closed=!0;return}if(this.closed)return;let r=Math.random()*.3+.85,s=Math.round(this.backoffMs*r);y.warn(`disconnected (code ${n}); reconnecting in ${Math.round(s/1e3)}s`),setTimeout(()=>this.connect(),s),this.backoffMs=Math.min(this.backoffMs*2,a_)}),e.on("error",n=>{y.warn(`websocket error: ${n.message}`)})}handle(e){if(e.type==="hello.ack"){this.bootAnnounced=!0,y.info(`connected as runner "${e.runnerName}" (${e.runnerId})`);return}if(e.type==="run.claim.result"||e.type==="deploy.claim.result"||e.type==="autopilot.next.result"){let n=this.pending.get(e.requestId);n&&(clearTimeout(n.timer),this.pending.delete(e.requestId),n.resolve(e));return}if(e.type==="config")return this.events.onConfig(e);if(e.type==="project.test")return this.events.onProjectTest(e);if(e.type==="rule.diagnose")return this.events.onRuleDiagnose(e);if(e.type==="run.cancel")return this.events.onCancel(e.runId);if(e.type==="run.approved")return this.events.onApproved(e.runId,e.headSha);if(e.type==="run.rejected")return this.events.onRejected(e.runId);if(e.type==="run.retryPush")return this.events.onRetryPush(e.runId);if(e.type==="deploy.start")return this.events.onDeployStart(e);if(e.type==="deploy.suggest")return this.events.onDeploySuggest(e);if(e.type==="deploy.fix")return this.events.onDeployFix(e);if(e.type==="env.preflight")return this.events.onEnvPreflight(e);if(e.type==="selfmigration.apply")return this.events.onSelfMigrationApply(e);if(e.type==="chat.turn")return this.events.onChatTurn(e);if(e.type==="chat.create.ticket")return this.events.onChatCreateTicket(e);if(e.type==="chat.list")return this.events.onChatList(e);if(e.type==="repo.docs")return this.events.onRepoDocs(e);if(e.type==="repo.doc.read")return this.events.onRepoDocRead(e);if(e.type==="chat.load")return this.events.onChatLoad(e);if(e.type==="board.fetch")return this.events.onBoardFetch(e);if(e.type==="board.trigger")return this.events.onBoardTrigger(e);if(e.type==="audit.start")return this.events.onAuditStart(e);if(e.type==="audit.list")return this.events.onAuditList(e);if(e.type==="audit.get")return this.events.onAuditGet(e);if(e.type==="audit.explain")return this.events.onAuditExplain(e);if(e.type==="chat.cancel")return this.events.onChatCancel(e);if(e.type==="chat.diagnostic")return this.events.onChatDiagnostic(e);if(e.type==="autopilot.plan")return this.events.onAutopilotPlan(e);if(e.type==="audit.review")return this.events.onAuditReview(e);if(e.type==="knowledge.list")return this.events.onKnowledgeList(e);if(e.type==="knowledge.save")return this.events.onKnowledgeSave(e);if(e.type==="epic.list")return this.events.onEpicList(e);if(e.type==="epic.suggest")return this.events.onEpicSuggest(e);if(e.type==="team.creds")return this.events.onTeamCreds(e);if(e.type==="jira.users")return this.events.onJiraUsers(e);if(e.type==="setup.status")return this.events.onSetupStatus(e);if(e.type==="setup.claudemd.generate")return this.events.onSetupClaudeMdGenerate(e);if(e.type==="setup.ask")return this.events.onSetupAsk(e);if(e.type==="setup.recheck")return this.events.onSetupRecheck(e);if(e.type==="repo.unmap")return this.events.onRepoUnmap(e);if(e.type==="setup.claudemd.save")return this.events.onSetupClaudeMdSave(e);if(e.type==="repo.doc.save")return this.events.onRepoDocSave(e);if(e.type==="runner.update")return this.events.onRunnerUpdate(e);if(e.type==="runner.uninstall")return this.events.onRunnerUninstall(e);if(e.type==="agent.profiles")return this.events.onAgentProfiles(e);if(e.type==="run.resolve.conflict")return this.events.onResolveConflict(e);if(e.type==="run.testfix")return this.events.onTestFix(e);if(e.type==="run.answer")return this.events.onRunAnswer(e);if(e.type==="audit.stats")return this.events.onAuditStats(e)}sendNow(e){this.ws?.send(JSON.stringify(e))}send(e){if(this.connected){this.sendNow(e);return}if(this.queue.length>=l_){let n=this.queue.findIndex(r=>r.type==="run.log");n>=0?this.queue.splice(n,1):this.queue.shift()}this.queue.push(e)}async claimRun(e){if(!this.connected)return{accepted:!1,reason:"control plane offline"};let n=hi.default.randomUUID(),r=await new Promise(s=>{let i=setTimeout(()=>{this.pending.delete(n),s(null)},15e3);this.pending.set(n,{resolve:s,timer:i}),this.sendNow({type:"run.claim",requestId:n,...e})});return!r||r.type!=="run.claim.result"?{accepted:!1,reason:"claim timed out"}:{accepted:r.accepted,runId:r.runId,reason:r.reason,claudeProfile:r.claudeProfile,actorEmail:r.actorEmail}}async requestAutopilotNext(){if(!this.connected)return null;let e=hi.default.randomUUID(),n=await new Promise(r=>{let s=setTimeout(()=>{this.pending.delete(e),r(null)},15e3);this.pending.set(e,{resolve:r,timer:s}),this.sendNow({type:"autopilot.next",requestId:e})});return!n||n.type!=="autopilot.next.result"?null:{ok:n.ok,item:n.item,pausedUntil:n.pausedUntil}}sendAutopilotReport(e){this.send({type:"autopilot.report",requestId:hi.default.randomUUID(),itemId:e.itemId,outcome:e.outcome,runId:e.runId??"",error:e.error??""})}async claimDeploy(e){if(!this.connected)return{accepted:!1,reason:"control plane offline"};let n=hi.default.randomUUID(),r=await new Promise(s=>{let i=setTimeout(()=>{this.pending.delete(n),s(null)},15e3);this.pending.set(n,{resolve:s,timer:i}),this.sendNow({type:"deploy.claim",requestId:n,...e})});return!r||r.type!=="deploy.claim.result"?{accepted:!1,reason:"deploy authorization timed out"}:{accepted:r.accepted,runId:r.runId,environment:r.environment,reason:r.reason,code:r.code}}sendDeploySuggestResult(e,n){this.send({type:"deploy.suggest.result",requestId:e,...n,docPath:n.docPath??"",docContent:n.docContent??""})}sendChatTurnResult(e,n){this.send({type:"chat.turn.result",requestId:e,...n,inputTokens:n.inputTokens??0,outputTokens:n.outputTokens??0,cacheReadTokens:n.cacheReadTokens??0,costUsd:n.costUsd??0,model:n.model??"",contextTokens:n.contextTokens??0,contextLimit:n.contextLimit??0,compacted:n.compacted??!1,compactedMessages:n.compactedMessages??0})}sendChatCreateTicketResult(e,n){this.send({type:"chat.create.ticket.result",requestId:e,...n,childKeys:n.childKeys??[]})}sendChatListResult(e,n){this.send({type:"chat.list.result",requestId:e,sessions:n})}sendRepoDocsResult(e,n){this.send({type:"repo.docs.result",requestId:e,...n})}sendRepoDocReadResult(e,n){this.send({type:"repo.doc.read.result",requestId:e,...n})}sendChatLoadResult(e,n){this.send({type:"chat.load.result",requestId:e,...n,messages:n.messages.map(r=>({...r,steps:r.steps??[],files:r.files??[],at:r.at??"",ms:r.ms??0}))})}sendBoardFetchResult(e,n){this.send({type:"board.fetch.result",requestId:e,...n,browseBaseUrl:n.browseBaseUrl??""})}sendAuditStartResult(e,n){this.send({type:"audit.start.result",requestId:e,...n})}sendAuditListResult(e,n){this.send({type:"audit.list.result",requestId:e,ok:n.ok,error:n.error,audits:(n.audits??[]).map(r=>({...r,detailLevel:r.detailLevel??"technical"}))})}sendChatDiagnosticResult(e,n){this.send({type:"chat.diagnostic.result",requestId:e,ok:n.ok,commandLine:n.commandLine??"",output:n.output??""})}sendAutopilotPlanResult(e,n){this.send({type:"autopilot.plan.result",requestId:e,ok:n.ok,error:n.error??"",order:n.order??[],chains:n.chains??[],dependencies:n.dependencies??[],reasoning:n.reasoning??""})}sendAuditExplainResult(e,n){this.send({type:"audit.explain.result",requestId:e,ok:n.ok,error:n.error??"",explanation:n.explanation??""})}sendAuditGetResult(e,n){this.send({type:"audit.get.result",requestId:e,...n})}sendAuditReviewResult(e,n){this.send({type:"audit.review.result",requestId:e,...n})}sendKnowledgeListResult(e,n){this.send({type:"knowledge.list.result",requestId:e,ok:n.ok,error:n.error,files:n.files??[]})}sendKnowledgeSaveResult(e,n){this.send({type:"knowledge.save.result",requestId:e,...n})}sendEpicListResult(e,n){this.send({type:"epic.list.result",requestId:e,ok:n.ok,error:n.error,epics:n.epics??[],children:n.children??[]})}sendEpicSuggestResult(e,n){this.send({type:"epic.suggest.result",requestId:e,ok:n.ok,error:n.error,issueKey:n.issueKey??"",reason:n.reason??"",considered:n.considered??0})}sendTeamCredsResult(e,n){this.send({type:"team.creds.result",requestId:e,ok:n.ok,error:n.error,githubShared:n.githubShared??!1,sharedGithubLogin:n.sharedGithubLogin??"",entries:n.entries??[]})}sendBoardTriggerResult(e,n){this.send({type:"board.trigger.result",requestId:e,...n})}sendAuditStatsResult(e,n){this.send({type:"audit.stats.result",requestId:e,ok:n.ok,error:n.error,byProject:n.byProject??{}})}sendRunnerUpdateResult(e,n){this.send({type:"runner.update.result",requestId:e,ok:n.ok,error:n.error,note:n.note??"",scheduled:n.scheduled??!1})}sendRunnerUninstallResult(e,n){this.send({type:"runner.uninstall.result",requestId:e,ok:n.ok,error:n.error,note:n.note??"",serviceRemoved:n.serviceRemoved??!1,configRemoved:n.configRemoved??!1})}sendSetupClaudeMdGenerateResult(e,n){this.send({type:"setup.claudemd.generate.result",requestId:e,ok:n.ok,error:n.error,content:n.content??"",truncated:n.truncated??!1})}sendSetupAskResult(e,n){this.send({type:"setup.ask.result",requestId:e,ok:n.ok,error:n.error,answer:n.answer??""})}sendRepoUnmapResult(e,n){this.send({type:"repo.unmap.result",requestId:e,ok:n.ok,error:n.error??"",removedPath:n.removedPath??""})}sendSetupRecheckResult(e,n){this.send({type:"setup.recheck.result",requestId:e,ok:n.ok,error:n.error??"",checks:(n.checks??[]).map(r=>({environment:r.environment??"",question:r.question,ok:r.ok,detail:r.detail??"",blocking:r.blocking??!0}))})}sendSetupClaudeMdSaveResult(e,n){this.send({type:"setup.claudemd.save.result",requestId:e,ok:n.ok,error:n.error,note:n.note??""})}sendResolveConflictResult(e,n){this.send({type:"run.resolve.conflict.result",requestId:e,ok:n.ok,note:n.note??"",freeOfCharge:n.freeOfCharge??!1,headSha:n.headSha??"",costUsd:n.costUsd,inputTokens:n.inputTokens,outputTokens:n.outputTokens})}sendTestFixResult(e,n){this.send({type:"run.testfix.result",requestId:e,ok:n.ok,note:n.note??"",headSha:n.headSha??"",remaining:n.remaining??[],costUsd:n.costUsd,inputTokens:n.inputTokens,outputTokens:n.outputTokens})}sendRunAnswerResult(e,n){this.send({type:"run.answer.result",requestId:e,ok:n.ok,note:n.note??"",error:n.error})}sendAgentProfilesResult(e,n){this.send({type:"agent.profiles.result",requestId:e,ok:n.ok,error:n.error,profiles:n.profiles??[],defaultLoggedIn:n.defaultLoggedIn??!1,agentsWithoutProfiles:n.agentsWithoutProfiles??[]})}sendRepoDocSaveResult(e,n){this.send({type:"repo.doc.save.result",requestId:e,ok:n.ok,error:n.error,note:n.note??""})}sendSetupStatusResult(e,n){this.send({type:"setup.status.result",requestId:e,ok:n.ok,error:n.error,jiraConfigured:n.jiraConfigured??!1,jiraEmail:n.jiraEmail??"",claude:n.claude,githubTokenSet:n.githubTokenSet??!1,githubLogin:n.githubLogin??"",deploysEnabled:n.deploysEnabled??!1,jiraUserCount:n.jiraUserCount??0,repos:n.repos??[]})}sendEnvPreflightResult(e,n){this.send({type:"env.preflight.result",requestId:e,...n,checks:this.withFixDefaults(n.checks)})}sendSelfMigrationApplyResult(e,n){this.send({type:"selfmigration.apply.result",requestId:e,...n})}sendJiraUsersResult(e,n){this.send({type:"jira.users.result",requestId:e,...n})}withFixDefaults(e){return e.map(n=>({...n,kind:n.kind??"connection",fix:n.fix??[],fixNote:n.fixNote??""}))}sendProjectTestResult(e,n,r){this.send({type:"project.test.result",requestId:e,ok:n,checks:this.withFixDefaults(r)})}sendRuleDiagnoseResult(e,n){this.send({type:"rule.diagnose.result",requestId:e,...n,checks:this.withFixDefaults(n.checks)})}};var Yo=A(require("node:fs"),1),Ps=A(require("node:path"),1),Ic=require("node:child_process"),c_=/\.mdx?$/i,Of=6,u_=/^[\w.\- ()]+$/;function d_(t,e){let n=e.trim().replace(/\\/g,"/").replace(/^\.\//,"");if(!n)return{ok:!1,error:"empty path"};if(Ps.default.isAbsolute(n))return{ok:!1,error:"path must be repo-relative"};if(!c_.test(n))return{ok:!1,error:"only markdown files (.md) can be saved"};let r=n.split("/");if(r.length>Of)return{ok:!1,error:`path deeper than ${Of} levels`};for(let o of r)if(o==="."||o===".."||!u_.test(o))return{ok:!1,error:`invalid path segment "${o}"`};if(r[0]===".git")return{ok:!1,error:"cannot write under .git"};let s=Ps.default.resolve(t),i=Ps.default.resolve(s,n);return i!==s&&!i.startsWith(s+Ps.default.sep)?{ok:!1,error:"path escapes the checkout"}:{ok:!0,abs:i,rel:n}}async function Ec(t){let e=d_(t.repoPath,t.relPath);if(!e.ok)return{ok:!1,error:e.error};if(Yo.default.existsSync(e.abs)&&!t.overwrite)return{ok:!1,error:`${e.rel} already exists in this checkout`};Yo.default.mkdirSync(Ps.default.dirname(e.abs),{recursive:!0}),Yo.default.writeFileSync(e.abs,t.content.endsWith(`
|
|
1042
|
+
Never emit both blocks in one reply, and never let either replace the actual answer.`;var Nr=I(require("node:fs"),1),ht=I(require("node:path"),1),sc=300,Pv=4,Ep=512*1024,jv=new Set([".git","node_modules","dist","build","out",".next","vendor","coverage",".venv","venv","__pycache__",".turbo",".cache"]),Cp=/\.mdx?$/i;function $p(t){let e=ht.default.resolve(t),n=[],r=(s,i)=>{if(i>Pv||n.length>=sc)return;let o;try{o=Nr.default.readdirSync(s,{withFileTypes:!0})}catch{return}for(let l of o){if(n.length>=sc)return;if(!l.isFile()||!Cp.test(l.name))continue;let c=ht.default.join(s,l.name);try{let u=Nr.default.statSync(c);n.push({path:ht.default.relative(e,c).split(ht.default.sep).join("/"),sizeBytes:u.size,updatedAt:u.mtime.toISOString()})}catch{}}for(let l of o){if(n.length>=sc)return;!l.isDirectory()||l.isSymbolicLink()||jv.has(l.name)||l.name.startsWith(".")||r(ht.default.join(s,l.name),i+1)}};return r(e,0),n}function Pp(t,e){let n=ht.default.resolve(t);if(!Cp.test(e))return{ok:!1,error:"only markdown files can be opened here"};let r=ht.default.resolve(n,e);if(r!==n&&!r.startsWith(n+ht.default.sep))return{ok:!1,error:"that path is outside the project checkout"};let s;try{s=Nr.default.realpathSync(r)}catch{return{ok:!1,error:"file not found in this checkout"}}let i=(()=>{try{return Nr.default.realpathSync(n)}catch{return n}})();if(s!==i&&!s.startsWith(i+ht.default.sep))return{ok:!1,error:"that path links outside the project checkout"};let o;try{o=Nr.default.statSync(s)}catch{return{ok:!1,error:"file not found in this checkout"}}if(!o.isFile())return{ok:!1,error:"that path is not a file"};try{let l=Nr.default.readFileSync(s,"utf8"),c=Buffer.byteLength(l,"utf8")>Ep;return{ok:!0,path:ht.default.relative(i,s).split(ht.default.sep).join("/"),content:c?l.slice(0,Ep):l,truncated:c}}catch(l){return{ok:!1,error:l instanceof Error?l.message:"could not read the file"}}}var Le=I(ke(),1);var Mo=I(require("node:fs"),1),jp=I(require("node:path"),1);Xr();Ae();var Nv=k.object({id:k.string(),name:k.string().default(""),jiraProjectKey:k.string().default(""),repoName:k.string().default(""),jiraSiteUrl:k.string().default("")}),Ov=k.array(Nv);function Np(){return jp.default.join(ie(),"synced-projects.json")}function Op(t){try{let e=t.map(n=>({id:n.id,name:n.name,jiraProjectKey:n.jiraProjectKey,repoName:n.repoName,jiraSiteUrl:n.jiraSiteUrl??""}));Mo.default.mkdirSync(ie(),{recursive:!0}),Mo.default.writeFileSync(Np(),JSON.stringify(e,null,2),{mode:384})}catch{}}function Mv(){try{let t=Ov.safeParse(JSON.parse(Mo.default.readFileSync(Np(),"utf8")));return t.success?t.data:[]}catch{return[]}}function Mp(t){return Mv().find(e=>e.repoName===t)??null}var oc=I(require("node:fs"),1),Or=I(require("node:path"),1),zp=require("node:child_process"),Mr=I(ke(),1);Ae();var zv=15e4,ic=(t,e,n,r="")=>({ok:!1,file:t,checks:[e],output:r,error:n});function Dv(t){let e=Or.default.join(t,"node_modules",".bin","prisma");return oc.default.existsSync(e)?{bin:e,prefix:[]}:{bin:"npx",prefix:["--yes","prisma"]}}function Lv(t,e){if(!(0,Mr.isSelfMigrationFilename)(e))return null;let n=Or.default.join(t,Mr.SELF_MIGRATION_DIR),r=Or.default.resolve(n,e),s=Or.default.relative(n,r);return s!==e||s.startsWith("..")||Or.default.isAbsolute(s)?null:r}async function Dp(t){let{file:e}=t,n=Lv(t.repoPath,e);if(!n)return ic(e,{name:"file",ok:!1,detail:`"${e}" is not a migration filename`,fix:[]},`"${e}" is not a migration filename`);if(!oc.default.existsSync(n))return ic(e,{name:"file",ok:!1,detail:`${Mr.SELF_MIGRATION_DIR}/${e} does not exist in this checkout`,fix:[`cd ${t.repoPath} && git pull`]},`${Mr.SELF_MIGRATION_DIR}/${e} is not in this checkout - it may be newer than the code here`);let s=Gt(t.cfg,t.repoName,t.environmentName)[t.urlSecret]?.trim();if(!s)return ic(e,{name:"database url",ok:!1,detail:`no ${t.urlSecret} in this runner's secret store for "${t.repoName}:${t.environmentName}" - the value stays on this machine`,fix:[`allwright env set ${t.repoName} ${t.environmentName} "${t.urlSecret}=postgresql://\u2026"`]},`this runner has no ${t.urlSecret} for "${t.environmentName}"`);let i=Or.default.join(t.repoPath,"apps","api"),{bin:o,prefix:l}=Dv(i),c=Kl([s]),u=await Uv(o,[...l,"db","execute","--url",s,"--file",n],i),h=c(u.output).slice(-8e3);return u.code!==0?{ok:!1,file:e,checks:[{name:"apply",ok:!1,detail:`prisma db execute exited ${u.code}`,fix:[`cd apps/api && npx prisma db execute --url "$DATABASE_URL" --file prisma/manual/${e}`]}],output:h,error:`applying ${e} failed (exit ${u.code})`}:{ok:!0,file:e,checks:[{name:"apply",ok:!0,detail:`${Mr.SELF_MIGRATION_DIR}/${e} applied`,fix:[]}],output:h,error:""}}function Uv(t,e,n){return new Promise(r=>{(0,zp.execFile)(t,e,{cwd:n,timeout:zv,maxBuffer:4*1024*1024,encoding:"utf8"},(s,i,o)=>{let l=[i,o].filter(Boolean).join(`
|
|
1043
|
+
`).trim();if(!s)return r({code:0,output:l});let c=typeof s.code=="number"?s.code:1;r({code:c||1,output:l||s.message})})})}var a_=I(Nf(),1),l_=I(Ko(),1),c_=I(Rs(),1),u_=I(yc(),1),d_=I(vc(),1),h_=I(Rc(),1),Bf=I(Vo(),1),p_=I(Ff(),1);var Ac=Bf.default;var pi=I(require("node:crypto"),1),zt=I(ke(),1);Xt();function f_(t){let e=t&&typeof t=="object"&&"name"in t?String(t.name):null;return e?`"${e}"`:"(unnamed)"}function Ec(t,e,n,r){t.push(`dropped ${e} ${n} - this runner is out of date and does not understand it yet (${r}). Update the runner (npm install -g @ticketpilot/runner) to pick it up.`)}function m_(t){if(!t||typeof t!="object"||t.type!=="config")return null;let e=t,n=[],r=[];for(let l of Array.isArray(e.projects)?e.projects:[]){let c=zt.ProjectConfig.safeParse(l);c.success?r.push(c.data):Ec(n,"project","",c.error.issues[0]?.message??"invalid shape")}let s=[];for(let l of Array.isArray(e.rules)?e.rules:[]){let c=zt.RuleConfig.safeParse(l);c.success?s.push(c.data):Ec(n,"rule",f_(l),c.error.issues[0]?.message??"invalid shape")}let i=[];for(let l of Array.isArray(e.environments)?e.environments:[]){let c=zt.EnvironmentConfig.safeParse(l);c.success?i.push(c.data):Ec(n,"environment","",c.error.issues[0]?.message??"invalid shape")}return{msg:{type:"config",projects:r,rules:s,environments:i,pollingPaused:typeof e.pollingPaused=="boolean"?e.pollingPaused:!1,publicIp:typeof e.publicIp=="string"?e.publicIp:""},warnings:n}}var g_=2e4,y_=6e4,b_=5e3,Yo=class{constructor(e,n,r,s){this.wsUrl=e;this.runnerToken=n;this.meta=r;this.events=s}wsUrl;runnerToken;meta;events;ws=null;queue=[];pending=new Map;backoffMs=1e3;heartbeat=null;closed=!1;bootAnnounced=!1;start(){this.closed=!1,this.connect()}stop(){this.closed=!0,this.heartbeat&&clearInterval(this.heartbeat),this.ws?.close()}get connected(){return this.ws?.readyState===Ac.OPEN}connect(){if(this.closed)return;y.info(`connecting to control plane at ${this.wsUrl}`);let e=new Ac(this.wsUrl,{headers:{authorization:`Bearer ${this.runnerToken}`}});this.ws=e,e.on("open",()=>{this.backoffMs=1e3,this.sendNow({type:"hello",protocolVersion:zt.PROTOCOL_VERSION,runnerVersion:this.meta.runnerVersion,platform:`${process.platform}/${process.arch} node${process.versions.node}`,justBooted:!this.bootAnnounced});let n=this.queue.splice(0,this.queue.length);for(let r of n)this.sendNow(r);this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=setInterval(()=>{this.send({type:"heartbeat",ts:new Date().toISOString()})},g_)}),e.on("message",n=>{let r;try{r=JSON.parse(n.toString())}catch(i){y.warn(`ignoring malformed server message (bad JSON): ${i}`);return}let s;try{s=(0,zt.parseServerMsg)(r)}catch(i){let o=m_(r);if(!o){y.warn(`ignoring malformed server message: ${i}`);return}for(let l of o.warnings)y.warn(l);y.warn(`config push had ${o.warnings.length} ${o.warnings.length===1?"entry":"entries"} this runner doesn't understand - applied everything else instead of dropping the whole config`),s=o.msg}this.handle(s)}),e.on("close",n=>{if(this.heartbeat&&clearInterval(this.heartbeat),n===4001)y.error("control plane rejected this runner version (protocol mismatch). Update with: npm install -g @ticketpilot/runner");else if(n===4003){y.error("this runner has been revoked from the control plane UI. Re-enroll with a fresh token if this was not intended."),this.closed=!0;return}if(this.closed)return;let r=Math.random()*.3+.85,s=Math.round(this.backoffMs*r);y.warn(`disconnected (code ${n}); reconnecting in ${Math.round(s/1e3)}s`),setTimeout(()=>this.connect(),s),this.backoffMs=Math.min(this.backoffMs*2,y_)}),e.on("error",n=>{y.warn(`websocket error: ${n.message}`)})}handle(e){if(e.type==="hello.ack"){this.bootAnnounced=!0,y.info(`connected as runner "${e.runnerName}" (${e.runnerId})`);return}if(e.type==="run.claim.result"||e.type==="deploy.claim.result"||e.type==="autopilot.next.result"){let n=this.pending.get(e.requestId);n&&(clearTimeout(n.timer),this.pending.delete(e.requestId),n.resolve(e));return}if(e.type==="config")return this.events.onConfig(e);if(e.type==="project.test")return this.events.onProjectTest(e);if(e.type==="rule.diagnose")return this.events.onRuleDiagnose(e);if(e.type==="run.cancel")return this.events.onCancel(e.runId);if(e.type==="run.approved")return this.events.onApproved(e.runId,e.headSha);if(e.type==="run.rejected")return this.events.onRejected(e.runId);if(e.type==="run.retryPush")return this.events.onRetryPush(e.runId);if(e.type==="deploy.start")return this.events.onDeployStart(e);if(e.type==="deploy.suggest")return this.events.onDeploySuggest(e);if(e.type==="deploy.fix")return this.events.onDeployFix(e);if(e.type==="env.preflight")return this.events.onEnvPreflight(e);if(e.type==="selfmigration.apply")return this.events.onSelfMigrationApply(e);if(e.type==="chat.turn")return this.events.onChatTurn(e);if(e.type==="chat.create.ticket")return this.events.onChatCreateTicket(e);if(e.type==="chat.list")return this.events.onChatList(e);if(e.type==="repo.docs")return this.events.onRepoDocs(e);if(e.type==="repo.doc.read")return this.events.onRepoDocRead(e);if(e.type==="chat.load")return this.events.onChatLoad(e);if(e.type==="board.fetch")return this.events.onBoardFetch(e);if(e.type==="board.trigger")return this.events.onBoardTrigger(e);if(e.type==="audit.start")return this.events.onAuditStart(e);if(e.type==="audit.list")return this.events.onAuditList(e);if(e.type==="audit.get")return this.events.onAuditGet(e);if(e.type==="audit.explain")return this.events.onAuditExplain(e);if(e.type==="chat.cancel")return this.events.onChatCancel(e);if(e.type==="chat.diagnostic")return this.events.onChatDiagnostic(e);if(e.type==="autopilot.plan")return this.events.onAutopilotPlan(e);if(e.type==="audit.review")return this.events.onAuditReview(e);if(e.type==="knowledge.list")return this.events.onKnowledgeList(e);if(e.type==="knowledge.save")return this.events.onKnowledgeSave(e);if(e.type==="epic.list")return this.events.onEpicList(e);if(e.type==="epic.suggest")return this.events.onEpicSuggest(e);if(e.type==="team.creds")return this.events.onTeamCreds(e);if(e.type==="jira.users")return this.events.onJiraUsers(e);if(e.type==="setup.status")return this.events.onSetupStatus(e);if(e.type==="setup.claudemd.generate")return this.events.onSetupClaudeMdGenerate(e);if(e.type==="setup.ask")return this.events.onSetupAsk(e);if(e.type==="setup.recheck")return this.events.onSetupRecheck(e);if(e.type==="repo.unmap")return this.events.onRepoUnmap(e);if(e.type==="setup.claudemd.save")return this.events.onSetupClaudeMdSave(e);if(e.type==="repo.doc.save")return this.events.onRepoDocSave(e);if(e.type==="runner.update")return this.events.onRunnerUpdate(e);if(e.type==="runner.uninstall")return this.events.onRunnerUninstall(e);if(e.type==="agent.profiles")return this.events.onAgentProfiles(e);if(e.type==="run.resolve.conflict")return this.events.onResolveConflict(e);if(e.type==="run.testfix")return this.events.onTestFix(e);if(e.type==="run.answer")return this.events.onRunAnswer(e);if(e.type==="audit.stats")return this.events.onAuditStats(e)}sendNow(e){this.ws?.send(JSON.stringify(e))}send(e){if(this.connected){this.sendNow(e);return}if(this.queue.length>=b_){let n=this.queue.findIndex(r=>r.type==="run.log");n>=0?this.queue.splice(n,1):this.queue.shift()}this.queue.push(e)}async claimRun(e){if(!this.connected)return{accepted:!1,reason:"control plane offline"};let n=pi.default.randomUUID(),r=await new Promise(s=>{let i=setTimeout(()=>{this.pending.delete(n),s(null)},15e3);this.pending.set(n,{resolve:s,timer:i}),this.sendNow({type:"run.claim",requestId:n,...e})});return!r||r.type!=="run.claim.result"?{accepted:!1,reason:"claim timed out"}:{accepted:r.accepted,runId:r.runId,reason:r.reason,claudeProfile:r.claudeProfile,actorEmail:r.actorEmail}}async requestAutopilotNext(){if(!this.connected)return null;let e=pi.default.randomUUID(),n=await new Promise(r=>{let s=setTimeout(()=>{this.pending.delete(e),r(null)},15e3);this.pending.set(e,{resolve:r,timer:s}),this.sendNow({type:"autopilot.next",requestId:e})});return!n||n.type!=="autopilot.next.result"?null:{ok:n.ok,item:n.item,pausedUntil:n.pausedUntil}}sendAutopilotReport(e){this.send({type:"autopilot.report",requestId:pi.default.randomUUID(),itemId:e.itemId,outcome:e.outcome,runId:e.runId??"",error:e.error??""})}async claimDeploy(e){if(!this.connected)return{accepted:!1,reason:"control plane offline"};let n=pi.default.randomUUID(),r=await new Promise(s=>{let i=setTimeout(()=>{this.pending.delete(n),s(null)},15e3);this.pending.set(n,{resolve:s,timer:i}),this.sendNow({type:"deploy.claim",requestId:n,...e})});return!r||r.type!=="deploy.claim.result"?{accepted:!1,reason:"deploy authorization timed out"}:{accepted:r.accepted,runId:r.runId,environment:r.environment,reason:r.reason,code:r.code}}sendDeploySuggestResult(e,n){this.send({type:"deploy.suggest.result",requestId:e,...n,docPath:n.docPath??"",docContent:n.docContent??""})}sendChatTurnResult(e,n){this.send({type:"chat.turn.result",requestId:e,...n,inputTokens:n.inputTokens??0,outputTokens:n.outputTokens??0,cacheReadTokens:n.cacheReadTokens??0,costUsd:n.costUsd??0,model:n.model??"",contextTokens:n.contextTokens??0,contextLimit:n.contextLimit??0,compacted:n.compacted??!1,compactedMessages:n.compactedMessages??0})}sendChatCreateTicketResult(e,n){this.send({type:"chat.create.ticket.result",requestId:e,...n,childKeys:n.childKeys??[]})}sendChatListResult(e,n){this.send({type:"chat.list.result",requestId:e,sessions:n})}sendRepoDocsResult(e,n){this.send({type:"repo.docs.result",requestId:e,...n})}sendRepoDocReadResult(e,n){this.send({type:"repo.doc.read.result",requestId:e,...n})}sendChatLoadResult(e,n){this.send({type:"chat.load.result",requestId:e,...n,messages:n.messages.map(r=>({...r,steps:r.steps??[],files:r.files??[],at:r.at??"",ms:r.ms??0}))})}sendBoardFetchResult(e,n){this.send({type:"board.fetch.result",requestId:e,...n,browseBaseUrl:n.browseBaseUrl??""})}sendAuditStartResult(e,n){this.send({type:"audit.start.result",requestId:e,...n})}sendAuditListResult(e,n){this.send({type:"audit.list.result",requestId:e,ok:n.ok,error:n.error,audits:(n.audits??[]).map(r=>({...r,detailLevel:r.detailLevel??"technical"}))})}sendChatDiagnosticResult(e,n){this.send({type:"chat.diagnostic.result",requestId:e,ok:n.ok,commandLine:n.commandLine??"",output:n.output??""})}sendAutopilotPlanResult(e,n){this.send({type:"autopilot.plan.result",requestId:e,ok:n.ok,error:n.error??"",order:n.order??[],chains:n.chains??[],dependencies:n.dependencies??[],reasoning:n.reasoning??""})}sendAuditExplainResult(e,n){this.send({type:"audit.explain.result",requestId:e,ok:n.ok,error:n.error??"",explanation:n.explanation??""})}sendAuditGetResult(e,n){this.send({type:"audit.get.result",requestId:e,...n})}sendAuditReviewResult(e,n){this.send({type:"audit.review.result",requestId:e,...n})}sendKnowledgeListResult(e,n){this.send({type:"knowledge.list.result",requestId:e,ok:n.ok,error:n.error,files:n.files??[]})}sendKnowledgeSaveResult(e,n){this.send({type:"knowledge.save.result",requestId:e,...n})}sendEpicListResult(e,n){this.send({type:"epic.list.result",requestId:e,ok:n.ok,error:n.error,epics:n.epics??[],children:n.children??[]})}sendEpicSuggestResult(e,n){this.send({type:"epic.suggest.result",requestId:e,ok:n.ok,error:n.error,issueKey:n.issueKey??"",reason:n.reason??"",considered:n.considered??0})}sendTeamCredsResult(e,n){this.send({type:"team.creds.result",requestId:e,ok:n.ok,error:n.error,githubShared:n.githubShared??!1,sharedGithubLogin:n.sharedGithubLogin??"",entries:n.entries??[]})}sendBoardTriggerResult(e,n){this.send({type:"board.trigger.result",requestId:e,...n})}sendAuditStatsResult(e,n){this.send({type:"audit.stats.result",requestId:e,ok:n.ok,error:n.error,byProject:n.byProject??{}})}sendRunnerUpdateResult(e,n){this.send({type:"runner.update.result",requestId:e,ok:n.ok,error:n.error,note:n.note??"",scheduled:n.scheduled??!1})}sendRunnerUninstallResult(e,n){this.send({type:"runner.uninstall.result",requestId:e,ok:n.ok,error:n.error,note:n.note??"",serviceRemoved:n.serviceRemoved??!1,configRemoved:n.configRemoved??!1})}sendSetupClaudeMdGenerateResult(e,n){this.send({type:"setup.claudemd.generate.result",requestId:e,ok:n.ok,error:n.error,content:n.content??"",truncated:n.truncated??!1})}sendSetupAskResult(e,n){this.send({type:"setup.ask.result",requestId:e,ok:n.ok,error:n.error,answer:n.answer??""})}sendRepoUnmapResult(e,n){this.send({type:"repo.unmap.result",requestId:e,ok:n.ok,error:n.error??"",removedPath:n.removedPath??""})}sendSetupRecheckResult(e,n){this.send({type:"setup.recheck.result",requestId:e,ok:n.ok,error:n.error??"",checks:(n.checks??[]).map(r=>({environment:r.environment??"",question:r.question,ok:r.ok,detail:r.detail??"",blocking:r.blocking??!0}))})}sendSetupClaudeMdSaveResult(e,n){this.send({type:"setup.claudemd.save.result",requestId:e,ok:n.ok,error:n.error,note:n.note??""})}sendResolveConflictResult(e,n){this.send({type:"run.resolve.conflict.result",requestId:e,ok:n.ok,note:n.note??"",freeOfCharge:n.freeOfCharge??!1,headSha:n.headSha??"",costUsd:n.costUsd,inputTokens:n.inputTokens,outputTokens:n.outputTokens})}sendTestFixResult(e,n){this.send({type:"run.testfix.result",requestId:e,ok:n.ok,note:n.note??"",headSha:n.headSha??"",remaining:n.remaining??[],costUsd:n.costUsd,inputTokens:n.inputTokens,outputTokens:n.outputTokens})}sendRunAnswerResult(e,n){this.send({type:"run.answer.result",requestId:e,ok:n.ok,note:n.note??"",error:n.error})}sendAgentProfilesResult(e,n){this.send({type:"agent.profiles.result",requestId:e,ok:n.ok,error:n.error,profiles:n.profiles??[],defaultLoggedIn:n.defaultLoggedIn??!1,agentsWithoutProfiles:n.agentsWithoutProfiles??[]})}sendRepoDocSaveResult(e,n){this.send({type:"repo.doc.save.result",requestId:e,ok:n.ok,error:n.error,note:n.note??""})}sendSetupStatusResult(e,n){this.send({type:"setup.status.result",requestId:e,ok:n.ok,error:n.error,jiraConfigured:n.jiraConfigured??!1,jiraEmail:n.jiraEmail??"",claude:n.claude,githubTokenSet:n.githubTokenSet??!1,githubLogin:n.githubLogin??"",deploysEnabled:n.deploysEnabled??!1,jiraUserCount:n.jiraUserCount??0,repos:n.repos??[]})}sendEnvPreflightResult(e,n){this.send({type:"env.preflight.result",requestId:e,...n,checks:this.withFixDefaults(n.checks)})}sendSelfMigrationApplyResult(e,n){this.send({type:"selfmigration.apply.result",requestId:e,...n})}sendJiraUsersResult(e,n){this.send({type:"jira.users.result",requestId:e,...n})}withFixDefaults(e){return e.map(n=>({...n,kind:n.kind??"connection",fix:n.fix??[],fixNote:n.fixNote??""}))}sendProjectTestResult(e,n,r){this.send({type:"project.test.result",requestId:e,ok:n,checks:this.withFixDefaults(r)})}sendRuleDiagnoseResult(e,n){this.send({type:"rule.diagnose.result",requestId:e,...n,checks:this.withFixDefaults(n.checks)})}};var Xo=I(require("node:fs"),1),Ps=I(require("node:path"),1),Cc=require("node:child_process"),w_=/\.mdx?$/i,Hf=6,v_=/^[\w.\- ()]+$/;function k_(t,e){let n=e.trim().replace(/\\/g,"/").replace(/^\.\//,"");if(!n)return{ok:!1,error:"empty path"};if(Ps.default.isAbsolute(n))return{ok:!1,error:"path must be repo-relative"};if(!w_.test(n))return{ok:!1,error:"only markdown files (.md) can be saved"};let r=n.split("/");if(r.length>Hf)return{ok:!1,error:`path deeper than ${Hf} levels`};for(let o of r)if(o==="."||o===".."||!v_.test(o))return{ok:!1,error:`invalid path segment "${o}"`};if(r[0]===".git")return{ok:!1,error:"cannot write under .git"};let s=Ps.default.resolve(t),i=Ps.default.resolve(s,n);return i!==s&&!i.startsWith(s+Ps.default.sep)?{ok:!1,error:"path escapes the checkout"}:{ok:!0,abs:i,rel:n}}async function $c(t){let e=k_(t.repoPath,t.relPath);if(!e.ok)return{ok:!1,error:e.error};if(Xo.default.existsSync(e.abs)&&!t.overwrite)return{ok:!1,error:`${e.rel} already exists in this checkout`};Xo.default.mkdirSync(Ps.default.dirname(e.abs),{recursive:!0}),Xo.default.writeFileSync(e.abs,t.content.endsWith(`
|
|
1044
1044
|
`)?t.content:t.content+`
|
|
1045
|
-
`);let n=i=>new Promise((o,l)=>{(0,Ic.execFile)("git",["-C",t.repoPath,...i],{timeout:12e4},(c,u,p)=>c?l(new Error(p||c.message)):o())}),r="";try{r=await new Promise((i,o)=>(0,Ic.execFile)("git",["-C",t.repoPath,"rev-parse","--abbrev-ref","HEAD"],{timeout:2e4},(l,c,u)=>l?o(new Error(u||l.message)):i(c.trim())))}catch{}let s="";try{await n(["add",e.rel]),await n(["-c","user.name=Allwright","-c","user.email=runner@allwright.local","commit","-m",t.commitMessage]);try{await n(["push"]),s=`committed and pushed to ${r||"the current branch"}`}catch(i){s=`committed locally to ${r||"the current branch"}, but push failed: `+(i instanceof Error?i.message.slice(0,200):"unknown")+" - push it from the server when convenient"}}catch(i){s="file written, but commit failed: "+(i instanceof Error?i.message.slice(0,200):"unknown")+" - commit it from the server when convenient"}return{ok:!0,note:s}}var Fr=A(require("node:fs"),1),Cc=A(require("node:path"),1),Xo=require("node:child_process"),zf=require("node:util");Ce();kr();Ct();var Df=A(ke(),1),Mf=(0,zf.promisify)(Xo.execFile);function h_(t){try{return new URL(t).host}catch{return t}}function p_(t){try{return(0,Xo.execFileSync)("git",["-C",t,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim()}catch{return null}}async function Qo(t,e,n=[],r){let s=[],i=t.repos[e.repoName]?.jira,o=i??t.jira,l=(e.jiraSiteUrl??"").trim().toLowerCase();if(!o)s.push({name:"jira-credentials",ok:!1,detail:"no Jira credentials configured on this runner",fix:["allwright jira set-default"],fixNote:"A server set up with `allwright init --no-jira` has none on purpose - that is fine for a machine that only deploys, but this project polls a board, so it needs one. The command asks for the Jira base URL, an account email and an API token (id.atlassian.com -> Security -> API tokens), and applies live."});else if(!l)s.push({name:"jira-site",ok:!1,detail:"this project has not said which Atlassian site it is on, so nothing here can be verified - a credential that authenticates somewhere else would look like a pass.",fixNote:"This one is fixed in the dashboard, not on the server: open the project and fill in its Atlassian site (for example yourcompany.atlassian.net), then run this test again."});else{let f=h_(o.baseUrl),b=i?"this repo's own Jira credential":"the runner-wide Jira credential";if(f!==l)s.push({name:"jira-site",ok:!1,detail:`this project is on ${l}, but ${b} is for ${f}.`,fix:[`allwright jira set "${e.repoName}"`],fixNote:`"${e.repoName}" in that command is this project's REPO NAME - the label that ties the project here to a checkout on the server (the same one used with allwright repo add). Not the Jira key, not a folder path. The command asks for three things for ${l}: the base URL (https://${l}), your Jira account email, and an API token from id.atlassian.com/manage-profile/security/api-tokens. They are stored on this server only. Restart afterwards: allwright stop && allwright start`});else{let w=new Pe(o);try{let k=await w.myself();s.push({name:"jira-auth",ok:!0,detail:`authenticated as ${k.displayName} on ${f} (${b})`});try{await w.search(`project = "${e.jiraProjectKey}" ORDER BY created DESC`,1),s.push({name:"jira-project",ok:!0,detail:`project ${e.jiraProjectKey} is readable on ${f}`})}catch(T){s.push({name:"jira-project",ok:!1,detail:`cannot read project ${e.jiraProjectKey} on ${f}: ${pi(T)}`})}}catch(k){s.push({name:"jira-auth",ok:!1,detail:`Jira auth failed on ${f}: ${pi(k)}`})}}}let c=t.repos[e.repoName];if(c&&Fr.default.existsSync(c.path)){let f=Cc.default.join(c.path,"CLAUDE.md"),b=Fr.default.existsSync(f)&&Fr.default.readFileSync(f,"utf8").trim().length>0;s.push({name:"memory-file",kind:"content",ok:b,detail:b?"CLAUDE.md present - the agent has project memory":"MISSING: CLAUDE.md at the repo root. Rules can't be enabled until the project has a memory file - it is what makes every run smarter than the last.",...b?{}:{fixNote:"No command needed: the setup step below this one drafts CLAUDE.md by reading the repo, shows it to you, and commits it when you approve. Writing it by hand works too - any honest description of what the project is and how it is built beats an empty file."}});let w=Ro(c.path);s.push({name:"deploy-doc",kind:"content",ok:w!==null,detail:w?`${w.path} present - deploy suggestions will follow it`:"MISSING: DEPLOY.md (or .ticketpilot/deploy.md). Environments can't be created until the repo documents how it deploys.",...w?{}:{fixNote:"Only needed if this project will deploy from Allwright. The setup wizard can draft DEPLOY.md the same way it drafts CLAUDE.md - describe how you deploy today (the commands you actually run), and the agent proposes steps a human saves. Skip it if you only want tickets to become pull requests."}})}if(!c)s.push({name:"repo-path",ok:!1,detail:`no local path mapped for repo "${e.repoName}" - run: allwright repo add "${e.repoName}" /path/to/checkout`});else if(!Fr.default.existsSync(c.path))s.push({name:"repo-path",ok:!1,detail:`path does not exist: ${c.path}`});else{let f=Fr.default.existsSync(Cc.default.join(c.path,".git"));s.push({name:"repo-path",ok:!0,detail:`${c.path}${f?" (git checkout)":" (warning: not a git checkout)"}`})}let u=[...new Set([e.defaultAgent||"claude-code",...r??[]])];for(let f of u){let b=Ze(t,f),w=f==="claude-code"?"claude-code":`agent:${f}`;try{let{stdout:k}=await Mf(b,["--version"],{timeout:15e3});s.push({name:w,ok:!0,detail:k.trim().slice(0,100)})}catch(k){s.push({name:w,ok:!1,detail:`cannot run "${b}" for agent "${f}": ${pi(k)}`,fixNote:f==="claude-code"?"Install Claude Code on this server (npm install -g @anthropic-ai/claude-code) and log it in.":`Install the "${f}" CLI on this server, or point the runner at its binary in the config's agents section.`})}}try{let{stdout:f}=await Mf("git",["--version"],{timeout:15e3});s.push({name:"git",ok:!0,detail:f.trim().slice(0,100)})}catch(f){s.push({name:"git",ok:!1,detail:`cannot run git: ${pi(f)}`})}let p=je(t,e.repoName);if(!p)s.push({name:"github-token",ok:!1,detail:`no GitHub token applies to "${e.repoName}" - implement rules cannot push.`,fix:[`allwright github set "${e.repoName}"`,"allwright github set-token"],fixNote:`"${e.repoName}" is this project's REPO NAME - the same label used with allwright repo add, not a folder path. The first command stores a token for this repo alone (separately revocable); the second stores one shared by every repo on this server. Both print the exact permission checklist before asking. In short: create it at ${Df.GITHUB_TOKEN_PERMISSIONS.where}, with the RESOURCE OWNER set to the org that owns the repo (the usual mistake), Contents and Pull requests both Read and write.`});else try{let{GitHubClient:f}=await Promise.resolve().then(()=>(kt(),Tr)),b=new f(p),w=await b.whoami(),k=c&&Fr.default.existsSync(c.path)?p_(c.path):null,T=k?wt(k):null;if(!T)s.push({name:"github-token",ok:!0,detail:`authenticated as ${w} - repo access not checked (no local checkout yet)`});else{let C=await b.repoAccess(T.owner,T.repo);s.push({name:"github-token",ok:C.ok&&C.canPush,detail:C.ok?C.canPush?`${w} has push access to ${T.owner}/${T.repo}`:`${w} can read ${T.owner}/${T.repo} but NOT push to it - implement rules will fail at the push`:`${w} cannot see ${T.owner}/${T.repo}: ${C.error}`,...C.ok&&C.canPush?{}:{fix:[`allwright github set "${e.repoName}"`],fixNote:`Two ways: edit the existing PAT on GitHub and add ${T.owner}/${T.repo} to it with contents:write and pull_requests:write - or give this repo its own token with the command above. A fine-grained PAT only ever covers ONE organisation, so a repo in a different org than your other projects always needs its own.`}})}}catch(f){s.push({name:"github-token",ok:!1,detail:pi(f)})}if(n.length){t.deploy.enabled?s.push({name:"deploy",ok:!0,detail:"deployments enabled on this runner"}):s.push({name:"deploy",ok:!1,detail:"deployments are disabled on this runner - run `allwright deploy enable` to allow it to execute your saved deploy steps"});for(let f of n){let b=Gt(t,e.repoName,f.name),w=f.requiredSecrets.filter(k=>!b[k]&&!process.env[k]);s.push({name:`env:${f.name}`,ok:w.length===0,detail:w.length?`missing secret(s): ${w.join(", ")} - allwright env set "${e.repoName}" "${f.name}" ${w[0]}=...`:`${f.steps.length} step(s), ${f.requiredSecrets.length} secret(s) present`+(f.branch?`, deploys origin/${f.branch}`:"")})}}return s}function pi(t){return(t instanceof Error?t.message:String(t)).slice(0,300)}Xt();ko();Po();Oc();var Re=new eu;Re.name("allwright").description("Allwright runner - runs on YOUR machine, holds YOUR credentials locally, connects outbound-only to the control plane. Your Jira token, Anthropic key and source code never leave this host.").version(Ki);function lm(t){y.info(`Create the token at ${Le.GITHUB_TOKEN_PERMISSIONS.where}`);for(let e of Le.GITHUB_TOKEN_PERMISSIONS.steps)y.info(` - ${e}`);y.info(Le.GITHUB_TOKEN_PERMISSIONS.note),y.info(`Then paste it below for ${t}.`)}Re.command("init").description("Interactive setup: enroll this runner and store credentials locally. Jira is optional - skip it here (or pass --no-jira) on a server that only deploys.").option("--cp-url <url>","control plane URL").option("--enroll-token <token>","enrolment token from the Allwright UI").option("--name <name>","runner name",yi.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)").option("--no-jira","set this machine up WITHOUT Jira - a deploy-only server that never reads a board (add them later with `allwright jira set-default`)").action(async t=>{let e=Mn.default.createInterface({input:process.stdin,output:process.stdout}),n=async(r,s,i=!1)=>{if(s)return s;let o=await e.question(`${r}: `);if(!o.trim())throw new Error(`${r} is required`);return o.trim()};try{let r=await n("Control plane URL",t.cpUrl),s=await n("Enrolment token (from the web UI)",t.enrollToken),i=cd(t),o=i==="skip";i==="offer-skip"&&(y.info("Jira: the credential below is what this machine polls your board with, and comments back under. A server that only DEPLOYS never reads a board and does not need one."),o=ud(await e.question('Connect Jira now? [Enter = yes, or type "skip" for a deploy-only server]: ')));let l=o?void 0:{baseUrl:await n("Jira base URL (https://yourorg.atlassian.net)",t.jiraUrl),email:await n("Jira account email",t.jiraEmail),apiToken:await n("Jira API token (create at id.atlassian.com/manage-profile/security/api-tokens)",t.jiraToken,!0)},c=Ra.parse({controlPlaneUrl:r,runnerName:t.name,jira:l});if(c.jira){let u=await new Pe(c.jira).myself();y.info(`Jira credential OK - authenticated as ${u.displayName}`)}c=await Yu(c,s),y.info(`Enrolled as runner "${c.runnerName}" (${c.runnerId})`),y.info(`Credentials saved to ${Kt()} (mode 600, this machine only)`),c.jira||y.info("No Jira credentials stored - this machine polls no board. That is the deploy-only setup; add them whenever you need with `allwright jira set-default` (applies live, no reinstall)."),y.info("Next: map your repo with `allwright repo add <repoName> <localPath>`, then `allwright start`")}finally{e.close()}});var zc=Re.command("repo").description("Map control-plane repo names to local checkouts");zc.command("add <repoName> <localPath>").description("Map a repo name (as configured in the web UI) to a local checkout path").option("--force","map it even though there is no git checkout there yet").action(async(t,e,n)=>{let r=le(),s=an.default.resolve(e.replace(/^~(?=\/|$)/,yi.default.homedir()));if(!n.force){if(!tt.default.existsSync(s))throw new Error(`${s} does not exist - nothing was mapped. The clone before this command probably failed; scroll up and read its error. Map it anyway with --force if you are going to clone it in a moment.`);if(!tt.default.existsSync(an.default.join(s,".git")))throw new Error(`${s} exists but is not a git checkout (no .git) - nothing was mapped. If the clone landed one level deeper, the path you want probably ends in the repo name. Map it anyway with --force if you know what you are doing.`)}r.repos[t]={path:s},ye(r),y.info(`mapped repo "${t}" -> ${s}`);try{let{originUrl:i}=await Promise.resolve().then(()=>(Ct(),id));y.info(` origin remote: ${await i(s)} - make sure this is the repo you meant`)}catch{y.warn(` could not read an origin remote at ${s} - is it a git checkout?`)}ln()||y.warn(`"${t}" is saved but NOT live yet - the running runner still does not know about it, and runs will keep saying it is not mapped until it reloads.`)});zc.command("list").description("Show configured repo mappings").action(()=>{let t=le(),e=Object.entries(t.repos);if(!e.length)return y.info("no repos mapped yet");for(let[n,r]of e)y.info(`${n} -> ${r.path}`)});var cm=Re.command("claude").description("Per-user Claude login profiles - each teammate's runs bill their OWN Claude account");cm.command("login <profileName>").description("Create (or re-login) a named Claude profile. Opens Claude Code interactively with its own config directory - have the PERSON WHOSE ACCOUNT IT IS complete the /login flow with their credentials, then exit. Assign the profile to their user on the dashboard's Team page.").action(async t=>{if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new Error("profile name: letters, digits, dots, dashes and underscores only");let e=le(),n=e.claudeProfiles[t]?.configDir??`${Kt().replace(/runner\.json$/,"")}claude-profiles/${t}`;tt.default.mkdirSync(n,{recursive:!0,mode:448}),e.claudeProfiles[t]={configDir:n},ye(e),y.info(`profile "${t}" -> ${n}`),y.info("Opening Claude Code with this profile. In it: run /login, complete the browser flow"),y.info("with the account this profile belongs to, then exit Claude (ctrl+c twice or /exit).");let r=(0,cn.spawn)(e.claudeBin,[],{env:{...process.env,CLAUDE_CONFIG_DIR:n},stdio:"inherit"});await new Promise(s=>r.on("exit",()=>s())),y.info(`Done. Assign it on the dashboard: Team -> the user -> Claude profile = "${t}".`),ln()});cm.command("list").description("Show configured Claude profiles and whether each looks logged in").action(()=>{let t=le(),e=Object.entries(t.claudeProfiles);if(y.info("default: this OS user's own Claude login (no profile)"),!e.length)return y.info("no named profiles yet - allwright claude login <name>");for(let[n,r]of e){let s=tt.default.existsSync(r.configDir)&&tt.default.readdirSync(r.configDir).length>0;y.info(`${n} -> ${r.configDir} ${s?"(logged in)":"(NOT logged in yet)"}`)}});zc.command("remove <repoName>").description("Unmap a repo from this runner: removes the mapping plus its per-repo Jira/GitHub overrides and env secrets from the config. Does NOT touch the checkout on disk or anything in the control plane - delete the project on the dashboard separately.").action(t=>{let e=le();if(!e.repos[t]){let i=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${t}" - mapped repos: ${i}`)}let n=e.repos[t].path;delete e.repos[t];let r=Object.keys(e.environments).filter(i=>i.startsWith(`${t}:`));for(let i of r)delete e.environments[i];let s=e.auditSchedules.length;e.auditSchedules=e.auditSchedules.filter(i=>i.repoName!==t),ye(e),y.info(`Removed "${t}" (was ${n})`),r.length&&y.info(`Also removed ${r.length} environment secret set(s): ${r.join(", ")}`),e.auditSchedules.length!==s&&y.info("Also removed its audit schedule(s)"),y.info("The checkout on disk was NOT touched - remove it yourself if you want it gone."),y.info("Restart the runner to apply. Dashboard project (if any) is deleted separately there.")});var Dc=Re.command("service").description("Run the runner as a system service (starts on boot, restarts on crash)");Dc.command("install").description("Install + start the systemd service - detects node, this script, your user and home; no hand-written unit files. Run with sudo. (--print shows the unit without installing.)").option("--print","print the generated unit file and exit").action(t=>{if(t.print){y.info(`
|
|
1046
|
-
`+nl(tl()));return}fd(y)});Dc.command("uninstall").description("Remove Allwright from this machine: stop and delete the systemd service, then delete the runner config - the file holding the Jira and GitHub tokens. Your checkouts are never touched. Run with sudo.").action(()=>md(y));Dc.command("status").description("systemctl status for the runner service").action(()=>{(0,cn.spawn)("systemctl",["status","allwright","--no-pager"],{stdio:"inherit"}).on("exit",e=>process.exit(e??0))});Re.command("update").description("Update the runner to the latest published version (npm install -g allwright@latest). Restart the runner afterwards - and only when no runs are active.").action(async()=>{y.info("Updating: npm install -g allwright@latest");let t=(0,cn.spawn)("npm",["install","-g","allwright@latest"],{stdio:"inherit"});await new Promise((e,n)=>{t.on("exit",r=>r===0?e():n(new Error(`npm exited with code ${r}`))),t.on("error",n)}),y.info("Updated. Restart the runner service to load the new version (check active runs first).")});var js=Re.command("jira").description("Per-repo Jira site overrides - for projects living on a different Atlassian site");js.command("set <repoName>").description("Store Jira credentials for ONE repo's project (e.g. a project on a different *.atlassian.net site than the runner's main credential). Prompts on stdin; stored locally only, like every other credential.").action(async t=>{let e=le();if(!e.repos[t]){let l=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${t}" - mapped repos: ${l}. Run \`allwright repo add\` first.`)}let n=Ap(t),r=(n?.jiraSiteUrl??"").trim(),s=r?`https://${r}`:"",i=e.jira?.email??"";if(s&&i&&e.jira?.apiToken){let l={baseUrl:s,email:i,apiToken:e.jira.apiToken};try{let c=await new Pe(l).myself();if(e.repos[t].jira=l,ye(e),y.info(`The token already on this server works on ${r} - authenticated as ${c.displayName}. Saved it for "${t}"; nothing to type.`),n?.jiraProjectKey)try{await new Pe(l).search(`project = "${n.jiraProjectKey}"`,1),y.info(`Project ${n.jiraProjectKey} is readable with it.`)}catch{y.warn(`Authenticated, but project ${n.jiraProjectKey} is not readable with this account. Ask a Jira admin for access, or re-run this command to enter a different account's token.`)}ln();return}catch{y.info(`The token already on this server does not work on ${r} - asking for one that does.`)}}let o=Mn.default.createInterface({input:process.stdin,output:process.stdout});try{let c=(await o.question(s?`Jira base URL [${s}]: `:"Jira base URL for this repo (https://yourorg.atlassian.net): ")).trim()||s,p=(await o.question(i?`Jira account email [${i}]: `:"Jira account email: ")).trim()||i,f=(await o.question("Jira API token (id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!c||!p||!f)throw new Error("all three values are required");let b={baseUrl:c,email:p,apiToken:f},w=await new Pe(b).myself();y.info(`Jira credential OK - authenticated as ${w.displayName} on ${c}`),e.repos[t].jira=b,ye(e),y.info(`Saved: repo "${t}" now polls ${c} (other repos keep the runner-wide credential)`),ln()}finally{o.close()}});js.command("set-token").alias("set-default").description("Set or replace the RUNNER-WIDE Jira credential (the one every repo without an override uses) - including on a machine that was set up with `init --no-jira`. Atlassian API tokens also expire, which surfaces as boards quietly going empty. Prompts on stdin; validated before saving; applies live, no restart.").action(async()=>{let t=le(),e=Mn.default.createInterface({input:process.stdin,output:process.stdout});try{let n=t.jira?.baseUrl??"",r=t.jira?.email??"",s=(await e.question(n?`Jira base URL [${n}]: `:"Jira base URL (https://yourorg.atlassian.net): ")).trim()||n,i=(await e.question(r?`Jira account email [${r}]: `:"Jira account email: ")).trim()||r,o=(await e.question("Jira API token (id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!s||!i||!o)throw new Error("all three values are required");let l={baseUrl:s,email:i,apiToken:o},c=await new Pe(l).myself();t.jira=l,ye(t),y.info(`Jira credential OK - authenticated as ${c.displayName} on ${s}`),y.info(`Saved to ${Kt()} (mode 600, this machine only). Repo overrides are untouched.`),ln()}finally{e.close()}});js.command("show").description("Show which Jira site each repo uses (never prints tokens)").action(()=>{let t=le();y.info(`runner-wide: ${t.jira?`${t.jira.baseUrl} (${t.jira.email})`:"(not configured)"}`);for(let[e,n]of Object.entries(t.repos))y.info(`${e} -> ${n.jira?`${n.jira.baseUrl} (${n.jira.email})`:"(runner-wide credential)"}`)});js.command("user-add <ticketpilotEmail>").description("Store a PERSON's own Jira credential, so board buttons and Compose tickets they click post to Jira under THEIR Atlassian identity instead of the runner's account. Keyed by their Allwright login email. Prompts on stdin; stored locally only. Picked up on the next click - no restart needed.").action(async t=>{let e=le(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=Mn.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await r.question(`Their ATLASSIAN account email [${n}]: `)).trim()||n,i=(await r.question("Their Jira API token (they create it at id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!i)throw new Error("API token is required");let o=[e.jira,...Object.values(e.repos).map(u=>u.jira)].filter(u=>!!u),l=new Set,c=!1;for(let u of o)if(!l.has(u.baseUrl)){l.add(u.baseUrl);try{let p=await new Pe({baseUrl:u.baseUrl,email:s,apiToken:i}).myself();y.info(`${u.baseUrl}: OK - authenticated as ${p.displayName}`),c=!0}catch{y.warn(`${u.baseUrl}: this credential does NOT work there (fine if they don't use that site)`)}}if(!c)throw new Error("credential failed on every configured Jira site - nothing saved");e.jiraUsers[n]={email:s,apiToken:i},ye(e),y.info(`Saved. Dashboard actions by ${n} now post to Jira as ${s}. No restart needed.`)}finally{r.close()}});js.command("user-list").description("Show which Allwright users have their own Jira credential here (never prints tokens)").action(()=>{let t=le(),e=Object.entries(t.jiraUsers);if(!e.length)return y.info("none yet - everyone's dashboard clicks require one: allwright jira user-add <their-ticketpilot-email>");for(let[n,r]of e)y.info(`${n} -> posts to Jira as ${r.email}`)});js.command("user-remove <ticketpilotEmail>").description("Delete a person's stored Jira credential").action(t=>{let e=le(),n=t.trim().toLowerCase();if(!e.jiraUsers[n])throw new Error(`no credential stored for ${n}`);delete e.jiraUsers[n],ye(e),y.info(`Removed. Dashboard actions by ${n} will now be refused until a new credential is added.`)});var Ns=Re.command("github").description("GitHub credential for implement-mode rules");Ns.command("set-token").description("Store a GitHub token for opening pull requests (implement rules). Stored locally only, like your Jira token. Recommended: a fine-grained PAT scoped to the repo with contents:write + pull_requests:write.").option("--token <token>","GitHub token (omit to be prompted)").action(async t=>{let e=Mn.default.createInterface({input:process.stdin,output:process.stdout});try{let n=t.token??void lm("every repo on this server")??(await e.question("GitHub token: ")).trim();if(!n)throw new Error("token is required");let{GitHubClient:r}=await Promise.resolve().then(()=>(kt(),Tr)),s=await new r(n).whoami(),i=le();i.github={token:n,login:s},ye(i),y.info(`GitHub token OK - authenticated as ${s}`),y.info(`Saved to ${Kt()} (mode 600, this machine only)`)}finally{e.close()}});Ns.command("set <repoName>").description("Store a GitHub token for ONE repo only - overrides the runner-wide token for that repo's PRs and PR-watching. Useful when projects need separately revocable access. Prompts on stdin; stored locally only.").action(async t=>{let e=le();if(!e.repos[t]){let i=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${t}" - mapped repos: ${i}. Run \`allwright repo add\` first.`)}let n=e.github?.token,r=e.repos[t]?.path;if(n&&r&&tt.default.existsSync(r))try{let i=(0,cn.execFileSync)("git",["-C",r,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim(),o=wt(i);if(o){let{GitHubClient:l}=await Promise.resolve().then(()=>(kt(),Tr)),c=new l(n),u=await c.repoAccess(o.owner,o.repo);if(u.ok&&u.canPush){let p=await c.whoami();y.info(`The shared token on this server already has push access to ${o.owner}/${o.repo} as ${p} - "${t}" needs nothing of its own. Storing a second token here would only give you two to rotate.`),y.info("Want a separately revocable one anyway? Paste it at the prompt below; press Enter to leave things as they are.")}}}catch{}let s=Mn.default.createInterface({input:process.stdin,output:process.stdout});try{lm(`"${t}"`);let i=(await s.question(`GitHub token for "${t}": `)).trim();if(!i&&n){y.info(`Nothing changed - "${t}" keeps using the shared token.`);return}if(!i)throw new Error("token is required");let{GitHubClient:o}=await Promise.resolve().then(()=>(kt(),Tr)),l=await new o(i).whoami();e.repos[t].github={token:i,login:l},ye(e),y.info(`GitHub token OK - authenticated as ${l}`),y.info(`Saved: repo "${t}" now uses its own token (other repos keep the runner-wide one)`)}finally{s.close()}});Ns.command("user-add <ticketpilotEmail>").description("Store a PERSON's own GitHub token, so PRs from implement runs THEY trigger are authored by their GitHub account. Keyed by their Allwright login email. Optional - without it their runs fall back to the repo/runner-wide token. Needs contents:write + pull_requests:write on the repos they'll touch.").action(async t=>{let e=le(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=Mn.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await r.question(`GitHub token for ${n}: `)).trim();if(!s)throw new Error("token is required");let{GitHubClient:i}=await Promise.resolve().then(()=>(kt(),Tr)),o=await new i(s).whoami();e.githubUsers[n]={token:s,login:o},ye(e),y.info(`GitHub token OK - authenticated as ${o}`),y.info(`Saved. Implement runs triggered by ${n} now open PRs as ${o}. No restart needed.`)}finally{r.close()}});Ns.command("user-list").description("Show which Allwright users have their own GitHub token here (never prints tokens)").action(()=>{let t=le(),e=Object.entries(t.githubUsers);if(!e.length)return y.info("no per-user GitHub tokens - everyone's PRs use the repo/runner-wide token");for(let[n]of e)y.info(`${n} -> own GitHub token stored`)});Ns.command("user-remove <ticketpilotEmail>").description("Delete a person's stored GitHub token (their runs fall back to the shared token)").action(t=>{let e=le(),n=t.trim().toLowerCase();if(!e.githubUsers[n])throw new Error(`no GitHub token stored for ${n}`);delete e.githubUsers[n],ye(e),y.info(`Removed. ${n}'s runs use the repo/runner-wide token again.`)});Ns.command("show").description("Show which GitHub token each repo and person would use (never prints tokens)").action(()=>{let t=le();y.info(`runner-wide: ${t.github?.token?"token set":"(not configured)"}`);for(let[n,r]of Object.entries(t.repos))y.info(`${n} -> ${r.github?.token?"own repo token":"runner-wide token"}`);let e=Object.keys(t.githubUsers);y.info(e.length?`per-user tokens: ${e.join(", ")}`:"per-user tokens: (none)")});var Lc=Re.command("audit").description("Recurring specialist audits on this runner");Lc.command("schedule <repoName> <role> <intervalHours>").description("Audit this repo's project on a cadence (role: security|testing; interval in hours, min 6). Runs on the runner's own clock; reports land in the Audits page history, where the diff-vs-previous view shows drift. Advisory only - nothing blocks.").action((t,e,n)=>{let r=le();if(!r.repos[t]){let i=Object.keys(r.repos).join(", ")||"(none)";throw new Error(`unknown repo "${t}" - mapped repos: ${i}`)}if(e!=="security"&&e!=="testing")throw new Error('role must be "security" or "testing"');let s=parseInt(n,10);if(!Number.isInteger(s)||s<6||s>720)throw new Error("intervalHours must be 6-720");r.auditSchedules=[...r.auditSchedules.filter(i=>!(i.repoName===t&&i.role===e)),{repoName:t,role:e,intervalHours:s}],ye(r),y.info(`Scheduled: ${e} audit of "${t}" every ${s}h. Restart the runner to apply.`)});Lc.command("schedules").description("List scheduled audits").action(()=>{let t=le();if(!t.auditSchedules.length)return y.info("no scheduled audits - allwright audit schedule <repo> <role> <hours>");for(let e of t.auditSchedules)y.info(`${e.repoName} \xB7 ${e.role} \xB7 every ${e.intervalHours}h`)});Lc.command("unschedule <repoName> <role>").description("Remove a scheduled audit").action((t,e)=>{let n=le(),r=n.auditSchedules.length;if(n.auditSchedules=n.auditSchedules.filter(s=>!(s.repoName===t&&s.role===e)),n.auditSchedules.length===r)throw new Error("no such schedule");ye(n),y.info("Removed. Restart the runner to apply.")});var Uc=Re.command("deploy").description("Deployment settings for this machine");Uc.command("enable").description("Allow this runner to execute the deploy steps saved in the dashboard. Those steps are shell commands that run here, as this user - so this switch lives on the machine, not in the web UI, and only someone with shell access can flip it.").action(()=>{let t=le();t.deploy={enabled:!0},ye(t),y.info("deployments ENABLED on this runner"),y.info("This runner will now execute the deploy steps configured for your environments. Review them in the dashboard before shipping to production."),ln()});Uc.command("disable").description("Stop this runner from executing any deploy steps").action(()=>{let t=le();t.deploy={enabled:!1},ye(t),y.info("deployments DISABLED on this runner"),ln()});Uc.command("status").description("Show whether deployments are enabled here, and which env secrets are stored").action(()=>{let t=le();y.info(`deployments: ${t.deploy.enabled?"enabled":"disabled"}`);let e=Object.entries(t.environments);if(!e.length)return y.info("no environment secrets stored");for(let[n,r]of e){let s=Object.keys(r.secrets);y.info(`${n}: ${s.length?s.join(", "):"(no secrets)"}`)}});var ra=Re.command("env").description("Per-environment deploy secrets. Values stay on this machine, like your Jira token.");ra.command("set <repoName> <envName> <assignments...>").description('Store secrets for one environment, e.g. env set acme/api production "SSH_HOST=1.2.3.4" "SSH_USER=deploy". Your deploy steps reference these as $SSH_HOST. The control plane only ever learns the NAMES.').action((t,e,n)=>{let r=le(),s=Ei(t,e),i=r.environments[s]??{secrets:{}},o=[];for(let l of n){let c=l.indexOf("=");if(c<=0)throw new Error(`expected KEY=VALUE, got "${l}"`);let u=l.slice(0,c).trim();i.secrets[u]=l.slice(c+1),o.push(u)}r.environments[s]=i,ye(r),y.info(`stored ${o.length} secret(s) for ${s}: ${o.join(", ")}`),y.info(`Saved to ${Kt()} (mode 600, this machine only)`),ln()});ra.command("prepare <repoName> <envName>").description("Stand the environment up: systemd unit (nvm-aware PATH, crash-loop limit), scoped passwordless restart for deploys, and a Caddy site block when --url is given. Fixed templates, no AI anywhere; runs with YOUR sudo, in YOUR terminal, and only ever overwrites files it wrote itself. --dry-run prints everything without touching anything.").option("--port <n>","port the app should bind (default: first free from 3000)").option("--url <publicUrl>","public URL this environment serves - wires the running Caddy").option("--workdir <dir>","checkout to run from (default: the mapped repo path)").option("--dry-run","print every file this would write, write nothing").action(async(t,e,n)=>{let s=le().repos[t]?.path,i=n.workdir??s;if(!i)throw new Error(`"${t}" is not mapped on this runner and no --workdir was given. Map it first: allwright repo add "${t}" <path>`);let{envPrepare:o}=await Promise.resolve().then(()=>(em(),Qf));await o({repoName:t,envName:e,dir:an.default.resolve(i.replace(/^~(?=\/|$)/,yi.default.homedir())),port:n.port?Number(n.port):void 0,publicUrl:n.url,dryRun:!!n.dryRun})});ra.command("unset <repoName> <envName> <names...>").description("Remove stored secrets for an environment").action((t,e,n)=>{let r=le(),s=Ei(t,e),i=r.environments[s];if(!i)return y.info(`nothing stored for ${s}`);for(let o of n)delete i.secrets[o];r.environments[s]=i,ye(r),y.info(`removed ${n.join(", ")} from ${s}`)});ra.command("list").description("Show which environments have secrets stored here (names only, never values)").action(()=>{let t=le(),e=Object.entries(t.environments);if(!e.length)return y.info("no environment secrets stored");for(let[n,r]of e)y.info(`${n}: ${Object.keys(r.secrets).join(", ")||"(none)"}`)});Re.command("export [file]").description("Back up ALL runner state (config+secrets, knowledge, audits, chats) to one tarball").action(t=>{try{let e=gu(t);y.info(`Backup written: ${e.file} (${e.entries.length} entries, mode 600)`),y.warn("This file CONTAINS YOUR SECRETS (Jira/GitHub tokens). Keep it private - anyone holding it can act as this runner."),y.info(`Restore on any machine with: allwright import ${an.default.basename(e.file)}`)}catch(e){y.error(e instanceof Error?e.message:String(e)),process.exitCode=1}});Re.command("import <file>").description("Restore runner state from an `export` tarball (existing config is kept as a .bak dir)").action(t=>{let e=Qn();if(e&&er(e)){y.error("the runner is running - stop it first (systemctl stop allwright, or `allwright stop` for a pid-file daemon), then import."),process.exitCode=1;return}try{let n=yu(t);y.info(`Restored ${n.restored.length} entries into ${ie()}`),n.previousDir&&y.info(`Previous config kept at ${n.previousDir}`),y.info("Start the runner and it will reconnect with the restored identity.")}catch(n){y.error(n instanceof Error?n.message:String(n)),process.exitCode=1}});Re.command("test").alias("doctor").description("Check local setup: Jira auth, repo mappings, Claude Code binary").action(async()=>{let t=le(),e=Object.keys(t.repos),n=$i(t);n&&y.warn("no Jira credentials on this runner - it polls no board. Expected on a deploy-only server; add them any time with `allwright jira set-default`.");let r=e.length?e.map(i=>({jiraProjectKey:"*",repoName:i})):[{jiraProjectKey:"*",repoName:"(none mapped)"}],s=!0;for(let i of r){let o=await Qo(t,i),l=!Ci(t,i.repoName);for(let c of o){if(i.jiraProjectKey==="*"&&c.name==="jira-project")continue;if(l&&c.name==="jira-credentials"){n||y.warn(`[WARN] jira-credentials: nothing covers "${i.repoName}" - add a runner-wide credential with \`allwright jira set-default\`, or one for this repo with \`allwright jira set "${i.repoName}"\`.`);continue}let u=c.ok?"PASS":"FAIL";(c.ok?y.info:y.error)(`[${u}] ${c.name}: ${c.detail}`),s&&=c.ok}}s||(process.exitCode=1)});function ln(){let t=Qn()??ns();if(t&&er(t)&&process.platform!=="win32")try{return process.kill(t,"SIGHUP"),y.info("running runner reloaded its config live - no restart needed"),!0}catch{}let e=t?xu(t):null;return y.info(e?`No background runner found to reload, but a service named "${e}" exists here: sudo systemctl kill -s HUP ${e} - otherwise it applies on the next start.`:"Could not signal the running runner - it may run as another user (the service usually runs as root, and `sudo` is what lets you signal it). Under systemd: sudo systemctl kill -s HUP <your allwright service> (allwright service install names it 'allwright'; installs predating the rename use 'ticketpilot-runner') - otherwise it applies on the next allwright start."),!1}function R_(t){if(!t.runnerToken)throw new Error("runner not enrolled - run `allwright init`");let e=Tu();e.ok||(y.warn(`another runner is already running on this machine (pid ${e.pid}). Two runner processes with one identity kick each other off the control plane every second. Stop the other one first: \`allwright stop\` (background runner) or \`sudo systemctl stop allwright\` (service).`),process.exit(1)),process.on("exit",Ea);let n=t.jira?new Pe(t.jira):Qa(),r=new Map,s=d=>{let m=t.repos[d]?.jira;if(!m)return n;let g=r.get(d);return g||(g=new Pe(m),r.set(d,g)),g},i=new Map,o=(d,m)=>{let g=ld(ve()??t,d,m);switch(g.kind){case"legacy":return{jira:s(d),authored:!1};case"self":return{jira:s(d),authored:!0};case"missing":return{error:g.error};case"user":{let R=`${g.creds.baseUrl}:${g.creds.email}:${g.creds.apiToken.slice(-6)}`,N=i.get(R);return N||(N=new Pe(g.creds),i.set(R,N)),{jira:N,authored:!0}}}},l=new URL("/api/runner/ws",t.controlPlaneUrl);l.protocol=l.protocol==="https:"?"wss:":"ws:";let c=[],u=[],p=[],f,b=null,w={cfg:t,jiraFor:s,transport:null},k=new Set,T=d=>{let m=c.find(R=>R.id===d),g=m&&t.repos[m.repoName];return m&&g?{project:m,repoPath:g.path}:null},C=d=>{let m=c.find(N=>N.id===d),g=t.runnerName?`This runner ("${t.runnerName}")`:"This runner";if(!m)return`${g} does not know that project at all - it may have been deleted, or this runner has not synced yet.`;let R=Object.keys(t.repos).join(", ")||"(none)";return`${g} has no local checkout for "${m.name}" (repo "${m.repoName}"). Repos mapped here: ${R}. Either pin the project to the runner that HAS that repo (Dashboard \u2192 the project \u2192 Edit \u2192 Runner) - do this when several runners are online and the project is unpinned, because then the request goes to whichever one answers first - or map the repo on this machine: allwright repo add ${m.repoName} /path/to/checkout`},P={cfg:t,jiraFor:s,get transport(){return w.transport},lookup:(d,m)=>{let g=T(d),R=p.find(N=>N.projectId===d&&N.name===m);return g&&R?{...g,environment:R}:null}},q=new Map,v=new Jo(l.toString(),t.runnerToken,{runnerVersion:Ki},{onConfig:d=>{c=d.projects,Rp(d.projects),u=d.rules,p=d.environments,Oh(d.publicIp),f.setConfig(d.projects,d.rules,d.pollingPaused,d.environments)},onDeployFix:async d=>{let m=T(d.projectId);if(!m){v.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:C(d.projectId)});return}let g=Oe(t,m.project,"assist");if("error"in g){v.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:g.error});return}y.info(`investigating failed deploy of "${d.environmentName}" (step: ${d.failedStep||"?"})`);let R=await Qh({agent:g,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,steps:d.steps,failedStep:d.failedStep,errorText:d.errorText,cfg:t});v.sendDeploySuggestResult(d.requestId,R)},onProjectTest:async d=>{let m=c.find(R=>R.id===d.projectId);if(!m){v.sendProjectTestResult(d.requestId,!1,[{name:"config",ok:!1,detail:"project not in this runner's synced config yet"}]);return}y.info(`running connection test for project "${m.name}"`);let g=await Qo(ve()??t,m,p.filter(R=>R.projectId===m.id),u.filter(R=>R.projectId===m.id).map(R=>"agent"in R.action?R.action.agent:"").filter(Boolean));v.sendProjectTestResult(d.requestId,g.every(R=>R.ok),g)},onRuleDiagnose:async d=>{let m=u.find(B=>B.id===d.ruleId),g=m&&c.find(B=>B.id===m.projectId);if(!m||!g){v.sendRuleDiagnoseResult(d.requestId,{checks:[{name:"config",ok:!1,detail:"rule not in this runner's synced config yet"}],matchedCount:0,excludedCount:0,excludedSample:[]});return}y.info(`diagnosing rule "${m.name}"`);let R=await Qo(ve()??t,g,m.action.type==="deploy"?p.filter(B=>B.projectId===g.id):[]),N=m.action.type==="implement"?R:R.filter(B=>B.name!=="github-token"),{matchedCount:K,excludedCount:X,excludedSample:U}=await f.diagnoseRule(m,g);v.sendRuleDiagnoseResult(d.requestId,{checks:N,matchedCount:K,excludedCount:X,excludedSample:U})},onCancel:d=>{fh(d)?y.info(`run ${d} stopped from the dashboard`):y.warn(`cancel requested for run ${d}, but nothing is running under that id here - it likely finished already`)},onApproved:(d,m)=>{if(Hl(d)){Wh(P,d).catch(g=>y.error(`deploy approval crashed for ${d}: ${g instanceof Error?g.stack:g}`));return}Xs(w,d,m).catch(g=>y.error(`approval handling crashed for ${d}: ${g instanceof Error?g.stack:g}`))},onRetryPush:d=>{let m=uo(d),g=()=>Th(w,d).catch(R=>y.error(`retry push crashed for ${d}: ${R instanceof Error?R.stack:R}`));m?f.runOnRepoQueue(m.baseRepoPath,g):g()},onRejected:d=>{if(Hl(d)){Vh(P,d).catch(m=>y.error(`deploy rejection crashed for ${d}: ${m instanceof Error?m.stack:m}`));return}Sh(w,d).catch(m=>y.error(`rejection handling crashed for ${d}: ${m instanceof Error?m.stack:m}`))},onDeployStart:d=>{let m=`${d.runId}#${d.attempt}`;if(k.has(m))return;k.add(m);let g=T(d.projectId);if(!g){let R=C(d.projectId);y.error(`deploy ${d.runId}: ${R}`),v.send({type:"run.status",runId:d.runId,status:"failed",error:R});return}y.info(`deploy ${d.runId} requested from the dashboard: ${d.issueKey} \u2192 ${d.environment.name}`),f.runOnEnvironmentQueue(d.environment.id,()=>xo({runId:d.runId,project:g.project,environment:d.environment,issueKey:d.issueKey,issueSummary:d.issueSummary,repoPath:g.repoPath,cfg:t,jira:s(g.project.repoName),transport:v,requestedBy:d.requestedBy}).catch(R=>y.error(`deploy crashed for ${d.runId}: ${R instanceof Error?R.stack:R}`)))},onDeploySuggest:async d=>{let m=T(d.projectId);if(!m){v.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:C(d.projectId)});return}let g=Oe(t,m.project,"assist");if("error"in g){v.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:g.error});return}y.info(`asking ${g.adapter.displayName} for "${d.environmentName}" deploy steps in ${m.repoPath}`);let R=await ep({agent:g,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,notes:d.notes,timeoutSeconds:d.timeoutSeconds,cfg:t});v.sendDeploySuggestResult(d.requestId,R)},onEnvPreflight:async d=>{let m=T(d.projectId);if(!m){v.sendEnvPreflightResult(d.requestId,{ok:!1,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project"}]});return}let g=await Xh({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,steps:d.steps,requiredSecrets:d.requiredSecrets,workdir:d.workdir,branch:d.branch,publicUrl:d.publicUrl,cfg:t});v.sendEnvPreflightResult(d.requestId,g)},onSelfMigrationApply:async d=>{let m=T(d.projectId);if(!m){v.sendSelfMigrationApplyResult(d.requestId,{ok:!1,file:d.file,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project",fix:[]}],output:"",error:C(d.projectId)});return}y.info(`applying migration ${d.file} for "${d.environmentName}"`);let g=await Ep({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,file:d.file,urlSecret:d.urlSecret,cfg:t});y.info(g.ok?`migration ${d.file} applied`:`migration ${d.file} failed: ${g.error}`),v.sendSelfMigrationApplyResult(d.requestId,g)},onAutopilotPlan:async d=>{try{let m=T(d.projectId);if(!m){v.sendAutopilotPlanResult(d.requestId,{ok:!1,error:C(d.projectId)});return}let g=s(m.project.repoName),R=[];for(let L of d.issueKeys)try{let ne=await g.getIssue(L);R.push(`${L}: ${ne.summary}
|
|
1047
|
-
${(ne.description||"").slice(0,500)}`)}catch{R.push(`${L}: (could not read from Jira)`)}let N=Oe(t,m.project,"assist");if("error"in N){v.sendAutopilotPlanResult(d.requestId,{ok:!1,error:N.error});return}let
|
|
1045
|
+
`);let n=i=>new Promise((o,l)=>{(0,Cc.execFile)("git",["-C",t.repoPath,...i],{timeout:12e4},(c,u,h)=>c?l(new Error(h||c.message)):o())}),r="";try{r=await new Promise((i,o)=>(0,Cc.execFile)("git",["-C",t.repoPath,"rev-parse","--abbrev-ref","HEAD"],{timeout:2e4},(l,c,u)=>l?o(new Error(u||l.message)):i(c.trim())))}catch{}let s="";try{await n(["add",e.rel]),await n(["-c","user.name=Allwright","-c","user.email=runner@allwright.local","commit","-m",t.commitMessage]);try{await n(["push"]),s=`committed and pushed to ${r||"the current branch"}`}catch(i){s=`committed locally to ${r||"the current branch"}, but push failed: `+(i instanceof Error?i.message.slice(0,200):"unknown")+" - push it from the server when convenient"}}catch(i){s="file written, but commit failed: "+(i instanceof Error?i.message.slice(0,200):"unknown")+" - commit it from the server when convenient"}return{ok:!0,note:s}}var Fr=I(require("node:fs"),1),Pc=I(require("node:path"),1),Qo=require("node:child_process"),Gf=require("node:util");Ae();kr();Ct();var Zf=I(ke(),1),Kf=(0,Gf.promisify)(Qo.execFile);function __(t){try{return new URL(t).host}catch{return t}}function S_(t){try{return(0,Qo.execFileSync)("git",["-C",t,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim()}catch{return null}}async function ea(t,e,n=[],r){let s=[],i=t.repos[e.repoName]?.jira,o=i??t.jira,l=(e.jiraSiteUrl??"").trim().toLowerCase();if(!o)s.push({name:"jira-credentials",ok:!1,detail:"no Jira credentials configured on this runner",fix:["allwright jira set-default"],fixNote:"A server set up with `allwright init --no-jira` has none on purpose - that is fine for a machine that only deploys, but this project polls a board, so it needs one. The command asks for the Jira base URL, an account email and an API token (id.atlassian.com -> Security -> API tokens), and applies live."});else if(!l)s.push({name:"jira-site",ok:!1,detail:"this project has not said which Atlassian site it is on, so nothing here can be verified - a credential that authenticates somewhere else would look like a pass.",fixNote:"This one is fixed in the dashboard, not on the server: open the project and fill in its Atlassian site (for example yourcompany.atlassian.net), then run this test again."});else{let f=__(o.baseUrl),b=i?"this repo's own Jira credential":"the runner-wide Jira credential";if(f!==l)s.push({name:"jira-site",ok:!1,detail:`this project is on ${l}, but ${b} is for ${f}.`,fix:[`allwright jira set "${e.repoName}"`],fixNote:`"${e.repoName}" in that command is this project's REPO NAME - the label that ties the project here to a checkout on the server (the same one used with allwright repo add). Not the Jira key, not a folder path. The command asks for three things for ${l}: the base URL (https://${l}), your Jira account email, and an API token from id.atlassian.com/manage-profile/security/api-tokens. They are stored on this server only. Restart afterwards: allwright stop && allwright start`});else{let w=new Pe(o);try{let _=await w.myself();s.push({name:"jira-auth",ok:!0,detail:`authenticated as ${_.displayName} on ${f} (${b})`});try{await w.search(`project = "${e.jiraProjectKey}" ORDER BY created DESC`,1),s.push({name:"jira-project",ok:!0,detail:`project ${e.jiraProjectKey} is readable on ${f}`})}catch(S){s.push({name:"jira-project",ok:!1,detail:`cannot read project ${e.jiraProjectKey} on ${f}: ${fi(S)}`})}}catch(_){s.push({name:"jira-auth",ok:!1,detail:`Jira auth failed on ${f}: ${fi(_)}`})}}}let c=t.repos[e.repoName];if(c&&Fr.default.existsSync(c.path)){let f=Pc.default.join(c.path,"CLAUDE.md"),b=Fr.default.existsSync(f)&&Fr.default.readFileSync(f,"utf8").trim().length>0;s.push({name:"memory-file",kind:"content",ok:b,detail:b?"CLAUDE.md present - the agent has project memory":"MISSING: CLAUDE.md at the repo root. Rules can't be enabled until the project has a memory file - it is what makes every run smarter than the last.",...b?{}:{fixNote:"No command needed: the setup step below this one drafts CLAUDE.md by reading the repo, shows it to you, and commits it when you approve. Writing it by hand works too - any honest description of what the project is and how it is built beats an empty file."}});let w=Io(c.path);s.push({name:"deploy-doc",kind:"content",ok:w!==null,detail:w?`${w.path} present - deploy suggestions will follow it`:"MISSING: DEPLOY.md (or .ticketpilot/deploy.md). Environments can't be created until the repo documents how it deploys.",...w?{}:{fixNote:"Only needed if this project will deploy from Allwright. The setup wizard can draft DEPLOY.md the same way it drafts CLAUDE.md - describe how you deploy today (the commands you actually run), and the agent proposes steps a human saves. Skip it if you only want tickets to become pull requests."}})}if(!c)s.push({name:"repo-path",ok:!1,detail:`no local path mapped for repo "${e.repoName}" - run: allwright repo add "${e.repoName}" /path/to/checkout`});else if(!Fr.default.existsSync(c.path))s.push({name:"repo-path",ok:!1,detail:`path does not exist: ${c.path}`});else{let f=Fr.default.existsSync(Pc.default.join(c.path,".git"));s.push({name:"repo-path",ok:!0,detail:`${c.path}${f?" (git checkout)":" (warning: not a git checkout)"}`})}let u=[...new Set([e.defaultAgent||"claude-code",...r??[]])];for(let f of u){let b=Ve(t,f),w=f==="claude-code"?"claude-code":`agent:${f}`;try{let{stdout:_}=await Kf(b,["--version"],{timeout:15e3});s.push({name:w,ok:!0,detail:_.trim().slice(0,100)})}catch(_){s.push({name:w,ok:!1,detail:`cannot run "${b}" for agent "${f}": ${fi(_)}`,fixNote:f==="claude-code"?"Install Claude Code on this server (npm install -g @anthropic-ai/claude-code) and log it in.":`Install the "${f}" CLI on this server, or point the runner at its binary in the config's agents section.`})}}try{let{stdout:f}=await Kf("git",["--version"],{timeout:15e3});s.push({name:"git",ok:!0,detail:f.trim().slice(0,100)})}catch(f){s.push({name:"git",ok:!1,detail:`cannot run git: ${fi(f)}`})}let h=je(t,e.repoName);if(!h)s.push({name:"github-token",ok:!1,detail:`no GitHub token applies to "${e.repoName}" - implement rules cannot push.`,fix:[`allwright github set "${e.repoName}"`,"allwright github set-token"],fixNote:`"${e.repoName}" is this project's REPO NAME - the same label used with allwright repo add, not a folder path. The first command stores a token for this repo alone (separately revocable); the second stores one shared by every repo on this server. Both print the exact permission checklist before asking. In short: create it at ${Zf.GITHUB_TOKEN_PERMISSIONS.where}, with the RESOURCE OWNER set to the org that owns the repo (the usual mistake), Contents and Pull requests both Read and write.`});else try{let{GitHubClient:f}=await Promise.resolve().then(()=>(kt(),Tr)),b=new f(h),w=await b.whoami(),_=c&&Fr.default.existsSync(c.path)?S_(c.path):null,S=_?wt(_):null;if(!S)s.push({name:"github-token",ok:!0,detail:`authenticated as ${w} - repo access not checked (no local checkout yet)`});else{let A=await b.repoAccess(S.owner,S.repo);s.push({name:"github-token",ok:A.ok&&A.canPush,detail:A.ok?A.canPush?`${w} has push access to ${S.owner}/${S.repo}`:`${w} can read ${S.owner}/${S.repo} but NOT push to it - implement rules will fail at the push`:`${w} cannot see ${S.owner}/${S.repo}: ${A.error}`,...A.ok&&A.canPush?{}:{fix:[`allwright github set "${e.repoName}"`],fixNote:`Two ways: edit the existing PAT on GitHub and add ${S.owner}/${S.repo} to it with contents:write and pull_requests:write - or give this repo its own token with the command above. A fine-grained PAT only ever covers ONE organisation, so a repo in a different org than your other projects always needs its own.`}})}}catch(f){s.push({name:"github-token",ok:!1,detail:fi(f)})}if(n.length){t.deploy.enabled?s.push({name:"deploy",ok:!0,detail:"deployments enabled on this runner"}):s.push({name:"deploy",ok:!1,detail:"deployments are disabled on this runner - run `allwright deploy enable` to allow it to execute your saved deploy steps"});for(let f of n){let b=Gt(t,e.repoName,f.name),w=f.requiredSecrets.filter(_=>!b[_]&&!process.env[_]);s.push({name:`env:${f.name}`,ok:w.length===0,detail:w.length?`missing secret(s): ${w.join(", ")} - allwright env set "${e.repoName}" "${f.name}" ${w[0]}=...`:`${f.steps.length} step(s), ${f.requiredSecrets.length} secret(s) present`+(f.branch?`, deploys origin/${f.branch}`:"")})}}return s}function fi(t){return(t instanceof Error?t.message:String(t)).slice(0,300)}Xt();_o();jo();zc();var Re=new nu;Re.name("allwright").description("Allwright runner - runs on YOUR machine, holds YOUR credentials locally, connects outbound-only to the control plane. Your Jira token, Anthropic key and source code never leave this host.").version(Gi);function ym(t){y.info(`Create the token at ${Le.GITHUB_TOKEN_PERMISSIONS.where}`);for(let e of Le.GITHUB_TOKEN_PERMISSIONS.steps)y.info(` - ${e}`);y.info(Le.GITHUB_TOKEN_PERMISSIONS.note),y.info(`Then paste it below for ${t}.`)}Re.command("init").description("Interactive setup: enroll this runner and store credentials locally. Jira is optional - skip it here (or pass --no-jira) on a server that only deploys.").option("--cp-url <url>","control plane URL").option("--enroll-token <token>","enrolment token from the Allwright UI").option("--name <name>","runner name",bi.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)").option("--no-jira","set this machine up WITHOUT Jira - a deploy-only server that never reads a board (add them later with `allwright jira set-default`)").action(async t=>{let e=Mn.default.createInterface({input:process.stdin,output:process.stdout}),n=async(r,s,i=!1)=>{if(s)return s;let o=await e.question(`${r}: `);if(!o.trim())throw new Error(`${r} is required`);return o.trim()};try{let r=await n("Control plane URL",t.cpUrl),s=await n("Enrolment token (from the web UI)",t.enrollToken),i=dd(t),o=i==="skip";i==="offer-skip"&&(y.info("Jira: the credential below is what this machine polls your board with, and comments back under. A server that only DEPLOYS never reads a board and does not need one."),o=hd(await e.question('Connect Jira now? [Enter = yes, or type "skip" for a deploy-only server]: ')));let l=o?void 0:{baseUrl:await n("Jira base URL (https://yourorg.atlassian.net)",t.jiraUrl),email:await n("Jira account email",t.jiraEmail),apiToken:await n("Jira API token (create at id.atlassian.com/manage-profile/security/api-tokens)",t.jiraToken,!0)},c=Ia.parse({controlPlaneUrl:r,runnerName:t.name,jira:l});if(c.jira){let u=await new Pe(c.jira).myself();y.info(`Jira credential OK - authenticated as ${u.displayName}`)}c=await Qu(c,s),y.info(`Enrolled as runner "${c.runnerName}" (${c.runnerId})`),y.info(`Credentials saved to ${Kt()} (mode 600, this machine only)`),c.jira||y.info("No Jira credentials stored - this machine polls no board. That is the deploy-only setup; add them whenever you need with `allwright jira set-default` (applies live, no reinstall)."),y.info("Next: map your repo with `allwright repo add <repoName> <localPath>`, then `allwright start`")}finally{e.close()}});var Lc=Re.command("repo").description("Map control-plane repo names to local checkouts");Lc.command("add <repoName> <localPath>").description("Map a repo name (as configured in the web UI) to a local checkout path").option("--force","map it even though there is no git checkout there yet").action(async(t,e,n)=>{let r=ce(),s=an.default.resolve(e.replace(/^~(?=\/|$)/,bi.default.homedir()));if(!n.force){if(!tt.default.existsSync(s))throw new Error(`${s} does not exist - nothing was mapped. The clone before this command probably failed; scroll up and read its error. Map it anyway with --force if you are going to clone it in a moment.`);if(!tt.default.existsSync(an.default.join(s,".git")))throw new Error(`${s} exists but is not a git checkout (no .git) - nothing was mapped. If the clone landed one level deeper, the path you want probably ends in the repo name. Map it anyway with --force if you know what you are doing.`)}r.repos[t]={path:s},ye(r),y.info(`mapped repo "${t}" -> ${s}`);try{let{originUrl:i}=await Promise.resolve().then(()=>(Ct(),ad));y.info(` origin remote: ${await i(s)} - make sure this is the repo you meant`)}catch{y.warn(` could not read an origin remote at ${s} - is it a git checkout?`)}ln()||y.warn(`"${t}" is saved but NOT live yet - the running runner still does not know about it, and runs will keep saying it is not mapped until it reloads.`)});Lc.command("list").description("Show configured repo mappings").action(()=>{let t=ce(),e=Object.entries(t.repos);if(!e.length)return y.info("no repos mapped yet");for(let[n,r]of e)y.info(`${n} -> ${r.path}`)});var bm=Re.command("claude").description("Per-user Claude login profiles - each teammate's runs bill their OWN Claude account");bm.command("login <profileName>").description("Create (or re-login) a named Claude profile. Opens Claude Code interactively with its own config directory - have the PERSON WHOSE ACCOUNT IT IS complete the /login flow with their credentials, then exit. Assign the profile to their user on the dashboard's Team page.").action(async t=>{if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new Error("profile name: letters, digits, dots, dashes and underscores only");let e=ce(),n=e.claudeProfiles[t]?.configDir??`${Kt().replace(/runner\.json$/,"")}claude-profiles/${t}`;tt.default.mkdirSync(n,{recursive:!0,mode:448}),e.claudeProfiles[t]={configDir:n},ye(e),y.info(`profile "${t}" -> ${n}`),y.info("Opening Claude Code with this profile. In it: run /login, complete the browser flow"),y.info("with the account this profile belongs to, then exit Claude (ctrl+c twice or /exit).");let r=(0,cn.spawn)(e.claudeBin,[],{env:{...process.env,CLAUDE_CONFIG_DIR:n},stdio:"inherit"});await new Promise(s=>r.on("exit",()=>s())),y.info(`Done. Assign it on the dashboard: Team -> the user -> Claude profile = "${t}".`),ln()});bm.command("list").description("Show configured Claude profiles and whether each looks logged in").action(()=>{let t=ce(),e=Object.entries(t.claudeProfiles);if(y.info("default: this OS user's own Claude login (no profile)"),!e.length)return y.info("no named profiles yet - allwright claude login <name>");for(let[n,r]of e){let s=tt.default.existsSync(r.configDir)&&tt.default.readdirSync(r.configDir).length>0;y.info(`${n} -> ${r.configDir} ${s?"(logged in)":"(NOT logged in yet)"}`)}});Lc.command("remove <repoName>").description("Unmap a repo from this runner: removes the mapping plus its per-repo Jira/GitHub overrides and env secrets from the config. Does NOT touch the checkout on disk or anything in the control plane - delete the project on the dashboard separately.").action(t=>{let e=ce();if(!e.repos[t]){let i=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${t}" - mapped repos: ${i}`)}let n=e.repos[t].path;delete e.repos[t];let r=Object.keys(e.environments).filter(i=>i.startsWith(`${t}:`));for(let i of r)delete e.environments[i];let s=e.auditSchedules.length;e.auditSchedules=e.auditSchedules.filter(i=>i.repoName!==t),ye(e),y.info(`Removed "${t}" (was ${n})`),r.length&&y.info(`Also removed ${r.length} environment secret set(s): ${r.join(", ")}`),e.auditSchedules.length!==s&&y.info("Also removed its audit schedule(s)"),y.info("The checkout on disk was NOT touched - remove it yourself if you want it gone."),y.info("Restart the runner to apply. Dashboard project (if any) is deleted separately there.")});var Uc=Re.command("service").description("Run the runner as a system service (starts on boot, restarts on crash)");Uc.command("install").description("Install + start the systemd service - detects node, this script, your user and home; no hand-written unit files. Run with sudo. (--print shows the unit without installing.)").option("--print","print the generated unit file and exit").action(t=>{if(t.print){y.info(`
|
|
1046
|
+
`+rl(nl()));return}gd(y)});Uc.command("uninstall").description("Remove Allwright from this machine: stop and delete the systemd service, then delete the runner config - the file holding the Jira and GitHub tokens. Your checkouts are never touched. Run with sudo.").action(()=>yd(y));Uc.command("status").description("systemctl status for the runner service").action(()=>{(0,cn.spawn)("systemctl",["status","allwright","--no-pager"],{stdio:"inherit"}).on("exit",e=>process.exit(e??0))});Re.command("update").description("Update the runner to the latest published version (npm install -g allwright@latest). Restart the runner afterwards - and only when no runs are active.").action(async()=>{y.info("Updating: npm install -g allwright@latest");let t=(0,cn.spawn)("npm",["install","-g","allwright@latest"],{stdio:"inherit"});await new Promise((e,n)=>{t.on("exit",r=>r===0?e():n(new Error(`npm exited with code ${r}`))),t.on("error",n)}),y.info("Updated. Restart the runner service to load the new version (check active runs first).")});var js=Re.command("jira").description("Per-repo Jira site overrides - for projects living on a different Atlassian site");js.command("set <repoName>").description("Store Jira credentials for ONE repo's project (e.g. a project on a different *.atlassian.net site than the runner's main credential). Prompts on stdin; stored locally only, like every other credential.").action(async t=>{let e=ce();if(!e.repos[t]){let l=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${t}" - mapped repos: ${l}. Run \`allwright repo add\` first.`)}let n=Mp(t),r=(n?.jiraSiteUrl??"").trim(),s=r?`https://${r}`:"",i=e.jira?.email??"";if(s&&i&&e.jira?.apiToken){let l={baseUrl:s,email:i,apiToken:e.jira.apiToken};try{let c=await new Pe(l).myself();if(e.repos[t].jira=l,ye(e),y.info(`The token already on this server works on ${r} - authenticated as ${c.displayName}. Saved it for "${t}"; nothing to type.`),n?.jiraProjectKey)try{await new Pe(l).search(`project = "${n.jiraProjectKey}"`,1),y.info(`Project ${n.jiraProjectKey} is readable with it.`)}catch{y.warn(`Authenticated, but project ${n.jiraProjectKey} is not readable with this account. Ask a Jira admin for access, or re-run this command to enter a different account's token.`)}ln();return}catch{y.info(`The token already on this server does not work on ${r} - asking for one that does.`)}}let o=Mn.default.createInterface({input:process.stdin,output:process.stdout});try{let c=(await o.question(s?`Jira base URL [${s}]: `:"Jira base URL for this repo (https://yourorg.atlassian.net): ")).trim()||s,h=(await o.question(i?`Jira account email [${i}]: `:"Jira account email: ")).trim()||i,f=(await o.question("Jira API token (id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!c||!h||!f)throw new Error("all three values are required");let b={baseUrl:c,email:h,apiToken:f},w=await new Pe(b).myself();y.info(`Jira credential OK - authenticated as ${w.displayName} on ${c}`),e.repos[t].jira=b,ye(e),y.info(`Saved: repo "${t}" now polls ${c} (other repos keep the runner-wide credential)`),ln()}finally{o.close()}});js.command("set-token").alias("set-default").description("Set or replace the RUNNER-WIDE Jira credential (the one every repo without an override uses) - including on a machine that was set up with `init --no-jira`. Atlassian API tokens also expire, which surfaces as boards quietly going empty. Prompts on stdin; validated before saving; applies live, no restart.").action(async()=>{let t=ce(),e=Mn.default.createInterface({input:process.stdin,output:process.stdout});try{let n=t.jira?.baseUrl??"",r=t.jira?.email??"",s=(await e.question(n?`Jira base URL [${n}]: `:"Jira base URL (https://yourorg.atlassian.net): ")).trim()||n,i=(await e.question(r?`Jira account email [${r}]: `:"Jira account email: ")).trim()||r,o=(await e.question("Jira API token (id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!s||!i||!o)throw new Error("all three values are required");let l={baseUrl:s,email:i,apiToken:o},c=await new Pe(l).myself();t.jira=l,ye(t),y.info(`Jira credential OK - authenticated as ${c.displayName} on ${s}`),y.info(`Saved to ${Kt()} (mode 600, this machine only). Repo overrides are untouched.`),ln()}finally{e.close()}});js.command("show").description("Show which Jira site each repo uses (never prints tokens)").action(()=>{let t=ce();y.info(`runner-wide: ${t.jira?`${t.jira.baseUrl} (${t.jira.email})`:"(not configured)"}`);for(let[e,n]of Object.entries(t.repos))y.info(`${e} -> ${n.jira?`${n.jira.baseUrl} (${n.jira.email})`:"(runner-wide credential)"}`)});js.command("user-add <ticketpilotEmail>").description("Store a PERSON's own Jira credential, so board buttons and Compose tickets they click post to Jira under THEIR Atlassian identity instead of the runner's account. Keyed by their Allwright login email. Prompts on stdin; stored locally only. Picked up on the next click - no restart needed.").action(async t=>{let e=ce(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=Mn.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await r.question(`Their ATLASSIAN account email [${n}]: `)).trim()||n,i=(await r.question("Their Jira API token (they create it at id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!i)throw new Error("API token is required");let o=[e.jira,...Object.values(e.repos).map(u=>u.jira)].filter(u=>!!u),l=new Set,c=!1;for(let u of o)if(!l.has(u.baseUrl)){l.add(u.baseUrl);try{let h=await new Pe({baseUrl:u.baseUrl,email:s,apiToken:i}).myself();y.info(`${u.baseUrl}: OK - authenticated as ${h.displayName}`),c=!0}catch{y.warn(`${u.baseUrl}: this credential does NOT work there (fine if they don't use that site)`)}}if(!c)throw new Error("credential failed on every configured Jira site - nothing saved");e.jiraUsers[n]={email:s,apiToken:i},ye(e),y.info(`Saved. Dashboard actions by ${n} now post to Jira as ${s}. No restart needed.`)}finally{r.close()}});js.command("user-list").description("Show which Allwright users have their own Jira credential here (never prints tokens)").action(()=>{let t=ce(),e=Object.entries(t.jiraUsers);if(!e.length)return y.info("none yet - everyone's dashboard clicks require one: allwright jira user-add <their-ticketpilot-email>");for(let[n,r]of e)y.info(`${n} -> posts to Jira as ${r.email}`)});js.command("user-remove <ticketpilotEmail>").description("Delete a person's stored Jira credential").action(t=>{let e=ce(),n=t.trim().toLowerCase();if(!e.jiraUsers[n])throw new Error(`no credential stored for ${n}`);delete e.jiraUsers[n],ye(e),y.info(`Removed. Dashboard actions by ${n} will now be refused until a new credential is added.`)});var Ns=Re.command("github").description("GitHub credential for implement-mode rules");Ns.command("set-token").description("Store a GitHub token for opening pull requests (implement rules). Stored locally only, like your Jira token. Recommended: a fine-grained PAT scoped to the repo with contents:write + pull_requests:write.").option("--token <token>","GitHub token (omit to be prompted)").action(async t=>{let e=Mn.default.createInterface({input:process.stdin,output:process.stdout});try{let n=t.token??void ym("every repo on this server")??(await e.question("GitHub token: ")).trim();if(!n)throw new Error("token is required");let{GitHubClient:r}=await Promise.resolve().then(()=>(kt(),Tr)),s=await new r(n).whoami(),i=ce();i.github={token:n,login:s},ye(i),y.info(`GitHub token OK - authenticated as ${s}`),y.info(`Saved to ${Kt()} (mode 600, this machine only)`)}finally{e.close()}});Ns.command("set <repoName>").description("Store a GitHub token for ONE repo only - overrides the runner-wide token for that repo's PRs and PR-watching. Useful when projects need separately revocable access. Prompts on stdin; stored locally only.").action(async t=>{let e=ce();if(!e.repos[t]){let i=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${t}" - mapped repos: ${i}. Run \`allwright repo add\` first.`)}let n=e.github?.token,r=e.repos[t]?.path;if(n&&r&&tt.default.existsSync(r))try{let i=(0,cn.execFileSync)("git",["-C",r,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim(),o=wt(i);if(o){let{GitHubClient:l}=await Promise.resolve().then(()=>(kt(),Tr)),c=new l(n),u=await c.repoAccess(o.owner,o.repo);if(u.ok&&u.canPush){let h=await c.whoami();y.info(`The shared token on this server already has push access to ${o.owner}/${o.repo} as ${h} - "${t}" needs nothing of its own. Storing a second token here would only give you two to rotate.`),y.info("Want a separately revocable one anyway? Paste it at the prompt below; press Enter to leave things as they are.")}}}catch{}let s=Mn.default.createInterface({input:process.stdin,output:process.stdout});try{ym(`"${t}"`);let i=(await s.question(`GitHub token for "${t}": `)).trim();if(!i&&n){y.info(`Nothing changed - "${t}" keeps using the shared token.`);return}if(!i)throw new Error("token is required");let{GitHubClient:o}=await Promise.resolve().then(()=>(kt(),Tr)),l=await new o(i).whoami();e.repos[t].github={token:i,login:l},ye(e),y.info(`GitHub token OK - authenticated as ${l}`),y.info(`Saved: repo "${t}" now uses its own token (other repos keep the runner-wide one)`)}finally{s.close()}});Ns.command("user-add <ticketpilotEmail>").description("Store a PERSON's own GitHub token, so PRs from implement runs THEY trigger are authored by their GitHub account. Keyed by their Allwright login email. Optional - without it their runs fall back to the repo/runner-wide token. Needs contents:write + pull_requests:write on the repos they'll touch.").action(async t=>{let e=ce(),n=t.trim().toLowerCase();if(!n.includes("@"))throw new Error(`"${t}" doesn't look like an email`);let r=Mn.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await r.question(`GitHub token for ${n}: `)).trim();if(!s)throw new Error("token is required");let{GitHubClient:i}=await Promise.resolve().then(()=>(kt(),Tr)),o=await new i(s).whoami();e.githubUsers[n]={token:s,login:o},ye(e),y.info(`GitHub token OK - authenticated as ${o}`),y.info(`Saved. Implement runs triggered by ${n} now open PRs as ${o}. No restart needed.`)}finally{r.close()}});Ns.command("user-list").description("Show which Allwright users have their own GitHub token here (never prints tokens)").action(()=>{let t=ce(),e=Object.entries(t.githubUsers);if(!e.length)return y.info("no per-user GitHub tokens - everyone's PRs use the repo/runner-wide token");for(let[n]of e)y.info(`${n} -> own GitHub token stored`)});Ns.command("user-remove <ticketpilotEmail>").description("Delete a person's stored GitHub token (their runs fall back to the shared token)").action(t=>{let e=ce(),n=t.trim().toLowerCase();if(!e.githubUsers[n])throw new Error(`no GitHub token stored for ${n}`);delete e.githubUsers[n],ye(e),y.info(`Removed. ${n}'s runs use the repo/runner-wide token again.`)});Ns.command("show").description("Show which GitHub token each repo and person would use (never prints tokens)").action(()=>{let t=ce();y.info(`runner-wide: ${t.github?.token?"token set":"(not configured)"}`);for(let[n,r]of Object.entries(t.repos))y.info(`${n} -> ${r.github?.token?"own repo token":"runner-wide token"}`);let e=Object.keys(t.githubUsers);y.info(e.length?`per-user tokens: ${e.join(", ")}`:"per-user tokens: (none)")});var qc=Re.command("audit").description("Recurring specialist audits on this runner");qc.command("schedule <repoName> <role> <intervalHours>").description("Audit this repo's project on a cadence (role: security|testing; interval in hours, min 6). Runs on the runner's own clock; reports land in the Audits page history, where the diff-vs-previous view shows drift. Advisory only - nothing blocks.").action((t,e,n)=>{let r=ce();if(!r.repos[t]){let i=Object.keys(r.repos).join(", ")||"(none)";throw new Error(`unknown repo "${t}" - mapped repos: ${i}`)}if(e!=="security"&&e!=="testing")throw new Error('role must be "security" or "testing"');let s=parseInt(n,10);if(!Number.isInteger(s)||s<6||s>720)throw new Error("intervalHours must be 6-720");r.auditSchedules=[...r.auditSchedules.filter(i=>!(i.repoName===t&&i.role===e)),{repoName:t,role:e,intervalHours:s}],ye(r),y.info(`Scheduled: ${e} audit of "${t}" every ${s}h. Restart the runner to apply.`)});qc.command("schedules").description("List scheduled audits").action(()=>{let t=ce();if(!t.auditSchedules.length)return y.info("no scheduled audits - allwright audit schedule <repo> <role> <hours>");for(let e of t.auditSchedules)y.info(`${e.repoName} \xB7 ${e.role} \xB7 every ${e.intervalHours}h`)});qc.command("unschedule <repoName> <role>").description("Remove a scheduled audit").action((t,e)=>{let n=ce(),r=n.auditSchedules.length;if(n.auditSchedules=n.auditSchedules.filter(s=>!(s.repoName===t&&s.role===e)),n.auditSchedules.length===r)throw new Error("no such schedule");ye(n),y.info("Removed. Restart the runner to apply.")});var Fc=Re.command("deploy").description("Deployment settings for this machine");Fc.command("enable").description("Allow this runner to execute the deploy steps saved in the dashboard. Those steps are shell commands that run here, as this user - so this switch lives on the machine, not in the web UI, and only someone with shell access can flip it.").action(()=>{let t=ce();t.deploy={enabled:!0},ye(t),y.info("deployments ENABLED on this runner"),y.info("This runner will now execute the deploy steps configured for your environments. Review them in the dashboard before shipping to production."),ln()});Fc.command("disable").description("Stop this runner from executing any deploy steps").action(()=>{let t=ce();t.deploy={enabled:!1},ye(t),y.info("deployments DISABLED on this runner"),ln()});Fc.command("status").description("Show whether deployments are enabled here, and which env secrets are stored").action(()=>{let t=ce();y.info(`deployments: ${t.deploy.enabled?"enabled":"disabled"}`);let e=Object.entries(t.environments);if(!e.length)return y.info("no environment secrets stored");for(let[n,r]of e){let s=Object.keys(r.secrets);y.info(`${n}: ${s.length?s.join(", "):"(no secrets)"}`)}});var sa=Re.command("env").description("Per-environment deploy secrets. Values stay on this machine, like your Jira token.");sa.command("set <repoName> <envName> <assignments...>").description('Store secrets for one environment, e.g. env set acme/api production "SSH_HOST=1.2.3.4" "SSH_USER=deploy". Your deploy steps reference these as $SSH_HOST. The control plane only ever learns the NAMES.').action((t,e,n)=>{let r=ce(),s=Ci(t,e),i=r.environments[s]??{secrets:{}},o=[];for(let l of n){let c=l.indexOf("=");if(c<=0)throw new Error(`expected KEY=VALUE, got "${l}"`);let u=l.slice(0,c).trim();i.secrets[u]=l.slice(c+1),o.push(u)}r.environments[s]=i,ye(r),y.info(`stored ${o.length} secret(s) for ${s}: ${o.join(", ")}`),y.info(`Saved to ${Kt()} (mode 600, this machine only)`),ln()});sa.command("prepare <repoName> <envName>").description("Stand the environment up: systemd unit (nvm-aware PATH, crash-loop limit), scoped passwordless restart for deploys, and a Caddy site block when --url is given. Fixed templates, no AI anywhere; runs with YOUR sudo, in YOUR terminal, and only ever overwrites files it wrote itself. --dry-run prints everything without touching anything.").option("--port <n>","port the app should bind (default: first free from 3000)").option("--url <publicUrl>","public URL this environment serves - wires the running Caddy").option("--workdir <dir>","checkout to run from (default: the mapped repo path)").option("--dry-run","print every file this would write, write nothing").action(async(t,e,n)=>{let s=ce().repos[t]?.path,i=n.workdir??s;if(!i)throw new Error(`"${t}" is not mapped on this runner and no --workdir was given. Map it first: allwright repo add "${t}" <path>`);let{envPrepare:o}=await Promise.resolve().then(()=>(cm(),lm));await o({repoName:t,envName:e,dir:an.default.resolve(i.replace(/^~(?=\/|$)/,bi.default.homedir())),port:n.port?Number(n.port):void 0,publicUrl:n.url,dryRun:!!n.dryRun})});sa.command("unset <repoName> <envName> <names...>").description("Remove stored secrets for an environment").action((t,e,n)=>{let r=ce(),s=Ci(t,e),i=r.environments[s];if(!i)return y.info(`nothing stored for ${s}`);for(let o of n)delete i.secrets[o];r.environments[s]=i,ye(r),y.info(`removed ${n.join(", ")} from ${s}`)});sa.command("list").description("Show which environments have secrets stored here (names only, never values)").action(()=>{let t=ce(),e=Object.entries(t.environments);if(!e.length)return y.info("no environment secrets stored");for(let[n,r]of e)y.info(`${n}: ${Object.keys(r.secrets).join(", ")||"(none)"}`)});Re.command("export [file]").description("Back up ALL runner state (config+secrets, knowledge, audits, chats) to one tarball").action(t=>{try{let e=bu(t);y.info(`Backup written: ${e.file} (${e.entries.length} entries, mode 600)`),y.warn("This file CONTAINS YOUR SECRETS (Jira/GitHub tokens). Keep it private - anyone holding it can act as this runner."),y.info(`Restore on any machine with: allwright import ${an.default.basename(e.file)}`)}catch(e){y.error(e instanceof Error?e.message:String(e)),process.exitCode=1}});Re.command("import <file>").description("Restore runner state from an `export` tarball (existing config is kept as a .bak dir)").action(t=>{let e=Qn();if(e&&er(e)){y.error("the runner is running - stop it first (systemctl stop allwright, or `allwright stop` for a pid-file daemon), then import."),process.exitCode=1;return}try{let n=wu(t);y.info(`Restored ${n.restored.length} entries into ${ie()}`),n.previousDir&&y.info(`Previous config kept at ${n.previousDir}`),y.info("Start the runner and it will reconnect with the restored identity.")}catch(n){y.error(n instanceof Error?n.message:String(n)),process.exitCode=1}});Re.command("test").alias("doctor").description("Check local setup: Jira auth, repo mappings, Claude Code binary").action(async()=>{let t=ce(),e=Object.keys(t.repos),n=Pi(t);n&&y.warn("no Jira credentials on this runner - it polls no board. Expected on a deploy-only server; add them any time with `allwright jira set-default`.");let r=e.length?e.map(i=>({jiraProjectKey:"*",repoName:i})):[{jiraProjectKey:"*",repoName:"(none mapped)"}],s=!0;for(let i of r){let o=await ea(t,i),l=!$i(t,i.repoName);for(let c of o){if(i.jiraProjectKey==="*"&&c.name==="jira-project")continue;if(l&&c.name==="jira-credentials"){n||y.warn(`[WARN] jira-credentials: nothing covers "${i.repoName}" - add a runner-wide credential with \`allwright jira set-default\`, or one for this repo with \`allwright jira set "${i.repoName}"\`.`);continue}let u=c.ok?"PASS":"FAIL";(c.ok?y.info:y.error)(`[${u}] ${c.name}: ${c.detail}`),s&&=c.ok}}s||(process.exitCode=1)});function ln(){let t=Qn()??ns();if(t&&er(t)&&process.platform!=="win32")try{return process.kill(t,"SIGHUP"),y.info("running runner reloaded its config live - no restart needed"),!0}catch{}let e=t?Iu(t):null;return y.info(e?`No background runner found to reload, but a service named "${e}" exists here: sudo systemctl kill -s HUP ${e} - otherwise it applies on the next start.`:"Could not signal the running runner - it may run as another user (the service usually runs as root, and `sudo` is what lets you signal it). Under systemd: sudo systemctl kill -s HUP <your allwright service> (allwright service install names it 'allwright'; installs predating the rename use 'ticketpilot-runner') - otherwise it applies on the next allwright start."),!1}function M_(t){if(!t.runnerToken)throw new Error("runner not enrolled - run `allwright init`");let e=Ru();e.ok||(y.warn(`another runner is already running on this machine (pid ${e.pid}). Two runner processes with one identity kick each other off the control plane every second. Stop the other one first: \`allwright stop\` (background runner) or \`sudo systemctl stop allwright\` (service).`),process.exit(1)),process.on("exit",Ca);let n=t.jira?new Pe(t.jira):el(),r=new Map,s=d=>{let m=t.repos[d]?.jira;if(!m)return n;let g=r.get(d);return g||(g=new Pe(m),r.set(d,g)),g},i=new Map,o=(d,m)=>{let g=ud(ve()??t,d,m);switch(g.kind){case"legacy":return{jira:s(d),authored:!1};case"self":return{jira:s(d),authored:!0};case"missing":return{error:g.error};case"user":{let R=`${g.creds.baseUrl}:${g.creds.email}:${g.creds.apiToken.slice(-6)}`,N=i.get(R);return N||(N=new Pe(g.creds),i.set(R,N)),{jira:N,authored:!0}}}},l=new URL("/api/runner/ws",t.controlPlaneUrl);l.protocol=l.protocol==="https:"?"wss:":"ws:";let c=[],u=[],h=[],f,b=null,w={cfg:t,jiraFor:s,transport:null},_=new Set,S=d=>{let m=c.find(R=>R.id===d),g=m&&t.repos[m.repoName];return m&&g?{project:m,repoPath:g.path}:null},A=d=>{let m=c.find(N=>N.id===d),g=t.runnerName?`This runner ("${t.runnerName}")`:"This runner";if(!m)return`${g} does not know that project at all - it may have been deleted, or this runner has not synced yet.`;let R=Object.keys(t.repos).join(", ")||"(none)";return`${g} has no local checkout for "${m.name}" (repo "${m.repoName}"). Repos mapped here: ${R}. Either pin the project to the runner that HAS that repo (Dashboard \u2192 the project \u2192 Edit \u2192 Runner) - do this when several runners are online and the project is unpinned, because then the request goes to whichever one answers first - or map the repo on this machine: allwright repo add ${m.repoName} /path/to/checkout`},z={cfg:t,jiraFor:s,get transport(){return w.transport},lookup:(d,m)=>{let g=S(d),R=h.find(N=>N.projectId===d&&N.name===m);return g&&R?{...g,environment:R}:null}},q=new Map,v=new Yo(l.toString(),t.runnerToken,{runnerVersion:Gi},{onConfig:d=>{c=d.projects,Op(d.projects),u=d.rules,h=d.environments,Hh(d.publicIp),f.setConfig(d.projects,d.rules,d.pollingPaused,d.environments)},onDeployFix:async d=>{let m=S(d.projectId);if(!m){v.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:A(d.projectId)});return}let g=Oe(t,m.project,"assist");if("error"in g){v.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:g.error});return}y.info(`investigating failed deploy of "${d.environmentName}" (step: ${d.failedStep||"?"})`);let R=await lp({agent:g,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,steps:d.steps,failedStep:d.failedStep,errorText:d.errorText,cfg:t});v.sendDeploySuggestResult(d.requestId,R)},onProjectTest:async d=>{let m=c.find(R=>R.id===d.projectId);if(!m){v.sendProjectTestResult(d.requestId,!1,[{name:"config",ok:!1,detail:"project not in this runner's synced config yet"}]);return}y.info(`running connection test for project "${m.name}"`);let g=await ea(ve()??t,m,h.filter(R=>R.projectId===m.id),u.filter(R=>R.projectId===m.id).map(R=>"agent"in R.action?R.action.agent:"").filter(Boolean));v.sendProjectTestResult(d.requestId,g.every(R=>R.ok),g)},onRuleDiagnose:async d=>{let m=u.find(H=>H.id===d.ruleId),g=m&&c.find(H=>H.id===m.projectId);if(!m||!g){v.sendRuleDiagnoseResult(d.requestId,{checks:[{name:"config",ok:!1,detail:"rule not in this runner's synced config yet"}],matchedCount:0,excludedCount:0,excludedSample:[]});return}y.info(`diagnosing rule "${m.name}"`);let R=await ea(ve()??t,g,m.action.type==="deploy"?h.filter(H=>H.projectId===g.id):[]),N=m.action.type==="implement"?R:R.filter(H=>H.name!=="github-token"),{matchedCount:G,excludedCount:X,excludedSample:U}=await f.diagnoseRule(m,g);v.sendRuleDiagnoseResult(d.requestId,{checks:N,matchedCount:G,excludedCount:X,excludedSample:U})},onCancel:d=>{Sh(d)?y.info(`run ${d} stopped from the dashboard`):y.warn(`cancel requested for run ${d}, but nothing is running under that id here - it likely finished already`)},onApproved:(d,m)=>{if(Gl(d)){rp(z,d).catch(g=>y.error(`deploy approval crashed for ${d}: ${g instanceof Error?g.stack:g}`));return}Qs(w,d,m).catch(g=>y.error(`approval handling crashed for ${d}: ${g instanceof Error?g.stack:g}`))},onRetryPush:d=>{let m=ho(d),g=()=>jh(w,d).catch(R=>y.error(`retry push crashed for ${d}: ${R instanceof Error?R.stack:R}`));m?f.runOnRepoQueue(m.baseRepoPath,g):g()},onRejected:d=>{if(Gl(d)){sp(z,d).catch(m=>y.error(`deploy rejection crashed for ${d}: ${m instanceof Error?m.stack:m}`));return}Ph(w,d).catch(m=>y.error(`rejection handling crashed for ${d}: ${m instanceof Error?m.stack:m}`))},onDeployStart:d=>{let m=`${d.runId}#${d.attempt}`;if(_.has(m))return;_.add(m);let g=S(d.projectId);if(!g){let R=A(d.projectId);y.error(`deploy ${d.runId}: ${R}`),v.send({type:"run.status",runId:d.runId,status:"failed",error:R});return}y.info(`deploy ${d.runId} requested from the dashboard: ${d.issueKey} \u2192 ${d.environment.name}`),f.runOnEnvironmentQueue(d.environment.id,()=>Ro({runId:d.runId,project:g.project,environment:d.environment,issueKey:d.issueKey,issueSummary:d.issueSummary,repoPath:g.repoPath,cfg:t,jira:s(g.project.repoName),transport:v,requestedBy:d.requestedBy}).catch(R=>y.error(`deploy crashed for ${d.runId}: ${R instanceof Error?R.stack:R}`)))},onDeploySuggest:async d=>{let m=S(d.projectId);if(!m){v.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:A(d.projectId)});return}let g=Oe(t,m.project,"assist");if("error"in g){v.sendDeploySuggestResult(d.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:g.error});return}y.info(`asking ${g.adapter.displayName} for "${d.environmentName}" deploy steps in ${m.repoPath}`);let R=await cp({agent:g,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,notes:d.notes,timeoutSeconds:d.timeoutSeconds,cfg:t});v.sendDeploySuggestResult(d.requestId,R)},onEnvPreflight:async d=>{let m=S(d.projectId);if(!m){v.sendEnvPreflightResult(d.requestId,{ok:!1,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project"}]});return}let g=await ap({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,steps:d.steps,requiredSecrets:d.requiredSecrets,workdir:d.workdir,branch:d.branch,publicUrl:d.publicUrl,cfg:t});v.sendEnvPreflightResult(d.requestId,g)},onSelfMigrationApply:async d=>{let m=S(d.projectId);if(!m){v.sendSelfMigrationApplyResult(d.requestId,{ok:!1,file:d.file,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project",fix:[]}],output:"",error:A(d.projectId)});return}y.info(`applying migration ${d.file} for "${d.environmentName}"`);let g=await Dp({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:d.environmentName,file:d.file,urlSecret:d.urlSecret,cfg:t});y.info(g.ok?`migration ${d.file} applied`:`migration ${d.file} failed: ${g.error}`),v.sendSelfMigrationApplyResult(d.requestId,g)},onAutopilotPlan:async d=>{try{let m=S(d.projectId);if(!m){v.sendAutopilotPlanResult(d.requestId,{ok:!1,error:A(d.projectId)});return}let g=s(m.project.repoName),R=[];for(let L of d.issueKeys)try{let ne=await g.getIssue(L);R.push(`${L}: ${ne.summary}
|
|
1047
|
+
${(ne.description||"").slice(0,500)}`)}catch{R.push(`${L}: (could not read from Jira)`)}let N=Oe(t,m.project,"assist");if("error"in N){v.sendAutopilotPlanResult(d.requestId,{ok:!1,error:N.error});return}let G=`You are planning a work queue. Below are tickets about ONE repository. Do not open any files - the summaries are your whole input, and speed matters.
|
|
1048
1048
|
|
|
1049
1049
|
`+R.join(`
|
|
1050
1050
|
|
|
@@ -1057,7 +1057,7 @@ Rules:
|
|
|
1057
1057
|
- "order": every key exactly once. Prerequisites before the work that needs them.
|
|
1058
1058
|
- "chains": tickets one engineer would do in one sitting, in the same part of the code, ADJACENT in your order. Chained tickets share a warm agent session, so group real neighbours - and leave a ticket out of every chain when unsure. Solo tickets appear in no chain.
|
|
1059
1059
|
- "dependencies": ONLY hard prerequisites, where the blocked ticket CANNOT pass if the other failed. An empty list is the normal answer.
|
|
1060
|
-
- "reasoning": 2-3 short lines a person can check your plan against.`,X=await N.adapter.run({repoPath:m.repoPath,prompt:
|
|
1060
|
+
- "reasoning": 2-3 short lines a person can check your plan against.`,X=await N.adapter.run({repoPath:m.repoPath,prompt:G,timeoutSeconds:90,bin:N.bin,mode:"read_only",maxTurns:3,model:N.adapter.fastModel,sessionId:(0,On.randomUUID)(),onLog:()=>{}}),U=Ql(X.resultText,d.issueKeys);if(!U){v.sendAutopilotPlanResult(d.requestId,{ok:!1,error:"the planner's answer could not be parsed - the queue keeps its given order"});return}let{saveBatchPlan:H}=await Promise.resolve().then(()=>(jo(),hp));H({batchId:d.batchId,projectId:d.projectId,order:U.order,chains:U.chains,dependencies:U.dependencies,reasoning:U.reasoning}),v.sendAutopilotPlanResult(d.requestId,{ok:!0,...U})}catch(m){v.sendAutopilotPlanResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onChatDiagnostic:async d=>{try{let{runDiagnostic:m}=await Promise.resolve().then(()=>(zc(),Yf)),g=await m({command:d.command,args:d.args});y.info(`chat diagnostic (user-approved): ${g.commandLine}`),v.sendChatDiagnosticResult(d.requestId,g)}catch(m){v.sendChatDiagnosticResult(d.requestId,{ok:!1,output:m instanceof Error?m.message:String(m)})}},onChatCancel:d=>{let m=q.get(d.turnId);m&&(m.abort(),y.info(`chat turn ${d.turnId} stopped from the dashboard`))},onChatTurn:async d=>{let m=S(d.projectId);if(!m){v.sendChatTurnResult(d.requestId,{ok:!1,sessionId:d.sessionId??"",reply:"",error:A(d.projectId)});return}let g=d.sessionId||(0,On.randomUUID)(),R=!d.sessionId,N=R?0:ii(g)?.messages.length??0,G=!1,X=0,U="";if(!R&&N>=Tp){let fe=await Ip(m,g,t);if(fe)G=!0,X=N,U=fe,g=(0,On.randomUUID)(),R=!0,y.info(`chat compacted: ${N} message(s) summarized into a fresh session`);else if(N>=xp){v.sendChatTurnResult(d.requestId,{ok:!1,sessionId:g,reply:"",error:"this chat is very long and could not be compacted automatically - start a new chat (it keeps the repo knowledge; only the conversation resets)."});return}}let H=d.files.length?_u(m.repoPath,d.requestId,d.files):null,L=(0,Le.replyPreferenceAppendix)({language:d.replyLanguage,languageInstruction:d.replyLanguageInstruction,style:d.replyStyle})+(0,Le.pendingMigrationsAppendix)(d.pendingMigrations)+(0,Le.deployTargetsAppendix)(d.environments),ne="```",W=R?`You are the project assistant for "${m.project.name}" - this working directory is its repository, and you have read-only access.
|
|
1061
1061
|
|
|
1062
1062
|
DEFAULT MODE IS DISCUSSION. Answer questions, explain code, weigh approaches, review ideas - like a teammate who knows this repo. Most conversations never produce a ticket, and that is fine. Do NOT propose a Jira ticket unless the user explicitly asks for one in this conversation ("create a ticket", "make this a ticket", "draft the ticket" or similar). Never end a normal answer with a ticket proposal.
|
|
1063
1063
|
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.
|
|
@@ -1067,7 +1067,7 @@ ${ne}diagnose
|
|
|
1067
1067
|
{"command": "<id>", "args": {...}, "why": "one line the user reads before approving"}
|
|
1068
1068
|
${ne}
|
|
1069
1069
|
Catalogue (nothing else exists):
|
|
1070
|
-
${
|
|
1070
|
+
${Mc()}
|
|
1071
1071
|
The user approves or denies each request - never assume the answer; wait for the output, which arrives as the next message. Ask only when reading the repo cannot answer, and ask for the single most informative command first.
|
|
1072
1072
|
|
|
1073
1073
|
ONLY when the user explicitly asks for a ticket, propose it by ending your reply with EXACTLY one fenced block in this shape:
|
|
@@ -1090,23 +1090,23 @@ EXCEPTION - big requirements: when the user asks for an epic with sub-tickets, o
|
|
|
1090
1090
|
RE-EMIT, never refer back: when the user asks for the ticket again, says it did not appear, or a quick action repeats the request, emit the COMPLETE ${ne}ticket block again in that reply. The dashboard only acts on a block in the NEWEST reply, and a long earlier reply can be cut off in transport without you ever knowing - so "I already sent it" is never a valid answer, and explaining your capabilities instead of re-emitting the block is never what was asked.
|
|
1091
1091
|
SIZE: a reply that outgrows the transport is cut off mid-block and creates NOTHING. A payload that lives in the repo is referenced by exact path, never inlined - the implementing agent has the checkout. A pasted payload too large to inline safely (more than ~200 lines) is distilled into the description sections instead; say plainly that you distilled it and ask the user to attach the original file to the ticket so nothing is lost.
|
|
1092
1092
|
|
|
1093
|
-
`+
|
|
1093
|
+
`+Ap+(U?`
|
|
1094
1094
|
|
|
1095
1095
|
This conversation was already running and has been compacted. Everything agreed so far, in summary form - treat it as established, do not re-ask:
|
|
1096
1096
|
${U}
|
|
1097
1097
|
`:"")+L+`
|
|
1098
|
-
${d.userName||"The user"} says: ${d.message}`+(
|
|
1098
|
+
${d.userName||"The user"} says: ${d.message}`+(H?.section??""):L+`${d.userName||"The user"} says: ${d.message}`+(H?.section??""),he=0,Ue=new Date,ge=[],oe;try{let fe=Oe(t,m.project,"chat");if("error"in fe){v.sendChatTurnResult(d.requestId,{ok:!1,sessionId:g,reply:"",error:fe.error});return}let gt=new AbortController;q.set(d.requestId,gt),oe=await fe.adapter.run({repoPath:m.repoPath,prompt:W,signal:gt.signal,timeoutSeconds:180,bin:fe.bin,mode:"read_only",maxTurns:25,model:d.model||fe.adapter.fastModel,sessionId:g,resume:!R,onLog:(Fe,ae)=>{Fe==="agent"&&(ge.push(ae.slice(0,4e3)),v.send({type:"chat.stream",requestId:d.requestId,seq:he++,text:ae.slice(0,8e3)}))},onUsage:Fe=>{v.send({type:"chat.usage",requestId:d.requestId,inputTokens:Math.round(Fe.inputTokens),outputTokens:Math.round(Fe.outputTokens),cacheReadTokens:Fe.cacheReadTokens===void 0?void 0:Math.round(Fe.cacheReadTokens),turns:Fe.turns})}})}finally{q.delete(d.requestId),H&&tt.default.rmSync(H.dir,{recursive:!0,force:!0})}if(oe.cancelled){v.sendChatTurnResult(d.requestId,{ok:!1,sessionId:g,reply:"",error:"stopped by you - the reply was cut off and nothing was saved to this chat",inputTokens:oe.inputTokens,outputTokens:oe.outputTokens,cacheReadTokens:oe.cacheReadTokens});return}if(!oe.ok&&oe.timedOut&&(oe.error="this question needs more room than a chat turn has - ask something narrower, or make it a ticket so a full run (with more time and the ability to execute) can take it"),oe.ok){let fe=ge.filter(gt=>gt.trim()&&!oe.resultText.trim().startsWith(gt.trim()));_p(d.projectId,g,d.message,oe.resultText,fe,d.files.map(gt=>gt.name),{askedAt:Ue.toISOString(),ms:Date.now()-Ue.getTime()})}let qe=(oe.inputTokens??0)+(oe.cacheReadTokens??0);v.sendChatTurnResult(d.requestId,{contextTokens:qe,contextLimit:Rp(oe.model||d.model||""),compacted:G,compactedMessages:X,ok:oe.ok,sessionId:g,reply:oe.resultText,error:oe.ok?void 0:oe.error??"the agent produced no reply",inputTokens:oe.inputTokens,outputTokens:oe.outputTokens,cacheReadTokens:oe.cacheReadTokens,costUsd:oe.costUsd,model:oe.model??""})},onChatList:d=>{v.sendChatListResult(d.requestId,Sp(d.projectId))},onRepoDocs:d=>{let m=S(d.projectId);if(!m){v.sendRepoDocsResult(d.requestId,{ok:!1,docs:[],error:A(d.projectId)});return}v.sendRepoDocsResult(d.requestId,{ok:!0,docs:$p(m.repoPath)})},onRepoDocRead:d=>{let m=S(d.projectId);if(!m){v.sendRepoDocReadResult(d.requestId,{ok:!1,path:d.path,content:"",truncated:!1,error:A(d.projectId)});return}let g=Pp(m.repoPath,d.path);v.sendRepoDocReadResult(d.requestId,{ok:g.ok,path:g.ok?g.path:d.path,content:g.ok?g.content:"",truncated:g.ok?g.truncated:!1,error:g.ok?void 0:g.error})},onChatLoad:d=>{let m=ii(d.sessionId);v.sendChatLoadResult(d.requestId,{ok:m!==null,projectId:m?.projectId??"",messages:m?.messages??[],error:m?void 0:"chat not found on this runner (pruned or never existed)"})},onBoardFetch:async d=>{let m=S(d.projectId);if(!m){v.sendBoardFetchResult(d.requestId,{ok:!1,columns:[],error:A(d.projectId)});return}try{let g=s(m.project.repoName),R;try{R=await g.searchBoard(`project = "${m.project.jiraProjectKey}" ORDER BY Rank ASC`,100)}catch{R=await g.searchBoard(`project = "${m.project.jiraProjectKey}" ORDER BY updated DESC`,100)}let N=await g.boardColumns(m.project.jiraProjectKey),G;if(N){G=N.map(H=>({name:H.name,issues:[]}));let U=new Map;for(let H of R){let L=N.findIndex(W=>W.statusIds.includes(H.statusId)),ne={key:H.key,summary:H.summary,labels:H.labels};if(L>=0)G[L].issues.push(ne);else{let W=U.get(H.status)??[];W.push(ne),U.set(H.status,W)}}for(let[H,L]of U)G.push({name:H,issues:L})}else{let U=he=>he.trim().toLowerCase(),H=new Map,L=new Map;for(let he of R){let Ue=U(he.status);H.has(Ue)||H.set(Ue,he.status.trim());let ge=L.get(Ue)??[];ge.push({key:he.key,summary:he.summary,labels:he.labels}),L.set(Ue,ge)}let ne=[];try{ne=await g.projectStatuses(m.project.jiraProjectKey)}catch{}let W=[];for(let he of ne){let Ue=U(he);!W.includes(Ue)&&L.has(Ue)&&W.push(Ue)}for(let he of L.keys())W.includes(he)||W.push(he);G=W.map(he=>({name:H.get(he)??he,issues:L.get(he)??[]}))}let X=t.repos[m.project.repoName]?.jira??t.jira;v.sendBoardFetchResult(d.requestId,{ok:!0,browseBaseUrl:(X?.baseUrl??"").replace(/\/+$/,""),columns:G})}catch(g){v.sendBoardFetchResult(d.requestId,{ok:!1,columns:[],error:g instanceof Error?g.message:String(g)})}},onBoardTrigger:async d=>{let m=S(d.projectId);if(!m){v.sendBoardTriggerResult(d.requestId,{ok:!1,error:A(d.projectId)});return}try{let g=s(m.project.repoName),R=d.comment.trim()?o(m.project.repoName,d.requestedByEmail):{jira:g,authored:!1};if(R.error!==void 0){v.sendBoardTriggerResult(d.requestId,{ok:!1,error:R.error});return}if(d.reimplement){let N=await g.getIssue(d.issueKey),G=N.comments.filter(H=>$t(H.body)),X=G.length?Math.max(...G.map(H=>new Date(H.created).getTime())):0;if(!N.comments.some(H=>!$t(H.body)&&new Date(H.created).getTime()>X)){v.sendBoardTriggerResult(d.requestId,{ok:!1,error:`${d.issueKey} has nothing new since the last implementation - add a comment describing what should change, then hit Implement again. Re-running with the same ticket would just rebuild the same thing.`});return}await g.editLabels(d.issueKey,{remove:["agent-implemented"]})}d.removeLabel.trim()&&await g.editLabels(d.issueKey,{remove:[d.removeLabel.trim()]}),d.comment.trim()&&await R.jira.addTriggerComment(d.issueKey,`${d.comment.trim()}`+(!R.authored&&d.requestedBy?`
|
|
1099
1099
|
|
|
1100
|
-
_(requested by ${d.requestedBy} via Allwright)_`:"")),y.info(`Board action on ${d.issueKey}`+(d.comment?` comment "${d.comment.trim()}"`:"")+(d.removeLabel?` -label ${d.removeLabel}`:"")+(d.requestedBy?` by ${d.requestedBy}`:"")),v.sendBoardTriggerResult(d.requestId,{ok:!0})}catch(g){v.sendBoardTriggerResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onChatCreateTicket:async d=>{let m=
|
|
1100
|
+
_(requested by ${d.requestedBy} via Allwright)_`:"")),y.info(`Board action on ${d.issueKey}`+(d.comment?` comment "${d.comment.trim()}"`:"")+(d.removeLabel?` -label ${d.removeLabel}`:"")+(d.requestedBy?` by ${d.requestedBy}`:"")),v.sendBoardTriggerResult(d.requestId,{ok:!0})}catch(g){v.sendBoardTriggerResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onChatCreateTicket:async d=>{let m=S(d.projectId);if(!m){v.sendChatCreateTicketResult(d.requestId,{ok:!1,issueKey:"",error:A(d.projectId)});return}try{let g=o(m.project.repoName,d.requestedByEmail);if(g.error!==void 0){v.sendChatCreateTicketResult(d.requestId,{ok:!1,issueKey:"",error:g.error});return}let R=`
|
|
1101
1101
|
|
|
1102
1102
|
---
|
|
1103
|
-
_Created via Allwright Compose`+(!g.authored&&d.requestedBy?` by ${d.requestedBy}`:"")+", drafted with the project agent._";if(d.asEpic&&d.createAs!=="epic_with_children"&&d.children.length){let X=d.createAs==="separate_epics"?"Epic":"Task",U=[];for(let
|
|
1103
|
+
_Created via Allwright Compose`+(!g.authored&&d.requestedBy?` by ${d.requestedBy}`:"")+", drafted with the project agent._";if(d.asEpic&&d.createAs!=="epic_with_children"&&d.children.length){let X=d.createAs==="separate_epics"?"Epic":"Task",U=[];for(let H of d.children){let L=await g.jira.createIssue(m.project.jiraProjectKey,H.summary,(H.description||"(no description)")+R,X);U.push(L.key)}y.info(`Compose created ${U.length} standalone ${X.toLowerCase()}(s)`),v.sendChatCreateTicketResult(d.requestId,{ok:!0,issueKey:U[0]??"",childKeys:U});return}let{key:N}=await g.jira.createIssue(m.project.jiraProjectKey,d.summary,(d.description||"(no description)")+R,d.asEpic?"Epic":"Task");d.files.length&&await g.jira.addAttachments(N,d.files.map(X=>({name:X.name,content:Buffer.from(X.contentBase64,"base64")}))).then(()=>y.info(`Compose attached ${d.files.length} file(s) to ${N}`)).catch(X=>y.warn(`Compose could not attach files to ${N}: ${X instanceof Error?X.message:X}`));let G=[];if(d.asEpic){for(let X of d.children){let U=await g.jira.createIssue(m.project.jiraProjectKey,X.summary,X.description||"(no description)","Task",N);G.push(U.key)}y.info(`Compose created epic ${N} with ${G.length} child ticket(s)`),v.sendChatCreateTicketResult(d.requestId,{ok:!0,issueKey:N,childKeys:G});return}d.triggerComment.trim()&&await g.jira.addTriggerComment(N,`${d.triggerComment.trim()}`+(!g.authored&&d.requestedBy?`
|
|
1104
1104
|
|
|
1105
|
-
_(requested by ${d.requestedBy} via Allwright)_`:"")),y.info(`Compose created ${N}`+(d.requestedBy?` for ${d.requestedBy}`:"")+(d.triggerComment?` with trigger "${d.triggerComment.trim()}"`:"")),v.sendChatCreateTicketResult(d.requestId,{ok:!0,issueKey:N})}catch(g){v.sendChatCreateTicketResult(d.requestId,{ok:!1,issueKey:"",error:g instanceof Error?g.message:String(g)})}},onAuditStart:async d=>{let m=
|
|
1105
|
+
_(requested by ${d.requestedBy} via Allwright)_`:"")),y.info(`Compose created ${N}`+(d.requestedBy?` for ${d.requestedBy}`:"")+(d.triggerComment?` with trigger "${d.triggerComment.trim()}"`:"")),v.sendChatCreateTicketResult(d.requestId,{ok:!0,issueKey:N})}catch(g){v.sendChatCreateTicketResult(d.requestId,{ok:!1,issueKey:"",error:g instanceof Error?g.message:String(g)})}},onAuditStart:async d=>{let m=S(d.projectId);if(!m){v.sendAuditStartResult(d.requestId,{ok:!1,error:A(d.projectId)});return}try{y.info(`Audit (${d.role}) starting on ${m.project.repoName}`+(d.scope.kind!=="repo"?` scoped to ${d.scope.kind}:${d.scope.ref}`:""));let g=Oe(t,m.project,"assist");if("error"in g){v.sendAuditStartResult(d.requestId,{ok:!1,error:g.error});return}let R=await ys({projectId:d.projectId,repoPath:m.repoPath,role:d.role,scope:d.scope,detailLevel:d.detailLevel,model:d.model,agent:g,jira:s(m.project.repoName),baseUrl:d.baseUrl});if(!R.ok){v.sendAuditStartResult(d.requestId,{ok:!1,error:R.error});return}v.sendAuditStartResult(d.requestId,{ok:!0,audit:R.audit})}catch(g){v.sendAuditStartResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onAuditList:async d=>{try{v.sendAuditListResult(d.requestId,{ok:!0,audits:Cd(d.projectId)})}catch(m){v.sendAuditListResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditExplain:async d=>{try{let m=dl(d.projectId,d.auditId),g=m?.findings.find(H=>H.id===d.findingId);if(!m||!g){v.sendAuditExplainResult(d.requestId,{ok:!1,error:"that finding is not on this runner any more"});return}let R=S(d.projectId);if(!R){v.sendAuditExplainResult(d.requestId,{ok:!1,error:A(d.projectId)});return}let N=Oe(t,R.project,"assist");if("error"in N){v.sendAuditExplainResult(d.requestId,{ok:!1,error:N.error});return}let G=`Explain ONE audit finding to a smart person who is not a programmer - they have to decide whether to fix it now, later, or accept the risk, and the finding below was written for engineers.
|
|
1106
1106
|
|
|
1107
1107
|
FINDING (${g.severity}${g.ruleId?`, rule ${g.ruleId}`:""}):
|
|
1108
1108
|
${g.title}
|
|
1109
|
-
`+g.evidence.map(
|
|
1109
|
+
`+g.evidence.map(H=>`- ${H.file}${H.line?`:${H.line}`:""} ${H.note}`.trim()).join(`
|
|
1110
1110
|
`)+(g.fix?`
|
|
1111
1111
|
Proposed fix: ${g.fix}`:"")+`
|
|
1112
1112
|
|
|
@@ -1117,7 +1117,7 @@ Answer in EXACTLY these four short sections, plain words, no jargon without an i
|
|
|
1117
1117
|
**What can happen if ignored:** a concrete story, not a category ("someone could..." with the actual consequence), and how LIKELY that is for this project.
|
|
1118
1118
|
**How urgent:** now / before the next release / when convenient - and why.
|
|
1119
1119
|
**What fixing it takes:** rough size (an hour, a day, a project) and whether anything visible to users changes.
|
|
1120
|
-
Nothing else - no preamble, no code.`,X=await N.adapter.run({repoPath:R.repoPath,prompt:
|
|
1120
|
+
Nothing else - no preamble, no code.`,X=await N.adapter.run({repoPath:R.repoPath,prompt:G,timeoutSeconds:120,bin:N.bin,mode:"read_only",maxTurns:8,sessionId:(0,On.randomUUID)(),onLog:()=>{}}),U=X.resultText.trim();if(!X.ok||!U){v.sendAuditExplainResult(d.requestId,{ok:!1,error:X.error??"the agent returned nothing - try again"});return}v.sendAuditExplainResult(d.requestId,{ok:!0,explanation:U})}catch(m){v.sendAuditExplainResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditGet:async d=>{try{let m=dl(d.projectId,d.auditId);if(!m){v.sendAuditGetResult(d.requestId,{ok:!1,error:"audit not found on this runner"});return}v.sendAuditGetResult(d.requestId,{ok:!0,audit:m})}catch(m){v.sendAuditGetResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditReview:async d=>{try{let m=ul(d.projectId,d.auditId,{selected:d.selected,ticketed:d.ticketed,verdicts:d.verdicts,verdictBy:d.verdictBy});if(!m){v.sendAuditReviewResult(d.requestId,{ok:!1,error:"audit not found on this runner"});return}let g=S(d.projectId);if(g&&d.verdicts.length){let R=[];for(let N of d.verdicts){if(N.verdict==="valid"||m.lessonsWritten.includes(N.findingId))continue;let G=m.findings.find(X=>X.id===N.findingId);G&&(ml(g.repoPath,m.role,Ud(G,N.verdict,N.note,d.verdictBy)),R.push(N.findingId),y.info(`Lesson written (${m.role}): ${N.verdict} - ${G.title.slice(0,60)}`))}R.length&&(m=ul(d.projectId,d.auditId,{markLessonsWritten:R})??m)}v.sendAuditReviewResult(d.requestId,{ok:!0,audit:m})}catch(m){v.sendAuditReviewResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onKnowledgeList:async d=>{let m=S(d.projectId);if(!m){v.sendKnowledgeListResult(d.requestId,{ok:!1,error:A(d.projectId)});return}try{v.sendKnowledgeListResult(d.requestId,{ok:!0,files:Fd(m.repoPath)})}catch(g){v.sendKnowledgeListResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onKnowledgeSave:async d=>{let m=S(d.projectId);if(!m){v.sendKnowledgeSaveResult(d.requestId,{ok:!1,error:A(d.projectId)});return}try{d.append?ml(m.repoPath,d.role,qd(d.content,d.by),d.level):Bd(m.repoPath,d.role,d.level,d.source,d.name,d.content),y.info(`Knowledge ${d.append?"taught":"saved"}: ${d.role}/${d.level}/${d.name}`),v.sendKnowledgeSaveResult(d.requestId,{ok:!0})}catch(g){v.sendKnowledgeSaveResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onEpicList:async d=>{let m=S(d.projectId);if(!m){v.sendEpicListResult(d.requestId,{ok:!1,error:A(d.projectId)});return}try{let g=s(m.project.repoName);if(d.epicKey){let R=await g.epicChildren(d.epicKey);v.sendEpicListResult(d.requestId,{ok:!0,children:R})}else{let R=await g.searchEpics(m.project.jiraProjectKey);v.sendEpicListResult(d.requestId,{ok:!0,epics:R})}}catch(g){v.sendEpicListResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onEpicSuggest:async d=>{let m=S(d.projectId);if(!m){v.sendEpicSuggestResult(d.requestId,{ok:!1,error:A(d.projectId)});return}try{let g=s(m.project.repoName),R=await g.epicChildren(d.epicKey),N=wd(R);if(!N.length){v.sendEpicSuggestResult(d.requestId,{ok:!1,error:`every child of ${d.epicKey} is already done or in an agent's hands - nothing to sequence`});return}if(N.length===1){v.sendEpicSuggestResult(d.requestId,{ok:!0,issueKey:N[0].key,reason:"It's the only pending ticket left in this epic.",considered:1});return}let G=await Promise.all(N.slice(0,12).map(async ne=>{try{let W=await g.getIssue(ne.key);return{...ne,description:W.description}}catch{return{...ne,description:""}}})),X=(await g.getIssue(d.epicKey).catch(()=>null))?.summary??"";y.info(`Epic suggest: weighing ${G.length} pending children of ${d.epicKey}`);let U=Oe(t,m.project,"assist");if("error"in U){v.sendEpicSuggestResult(d.requestId,{ok:!1,error:U.error});return}let H=await U.adapter.run({repoPath:m.repoPath,prompt:vd(d.epicKey,X,G),timeoutSeconds:150,bin:U.bin,mode:"read_only",maxTurns:20,sessionId:(0,On.randomUUID)(),model:d.model||"claude-sonnet-5",onLog:()=>{}}),L=kd(H.resultText,G.map(ne=>ne.key));if("error"in L){v.sendEpicSuggestResult(d.requestId,{ok:!1,error:L.error});return}y.info(`Epic suggest: ${d.epicKey} -> do ${L.issueKey} first`),v.sendEpicSuggestResult(d.requestId,{ok:!0,issueKey:L.issueKey,reason:L.reason,considered:G.length})}catch(g){v.sendEpicSuggestResult(d.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onTeamCreds:async d=>{try{let m=ve()??t;if(m.github?.token&&!m.github.login)try{let{GitHubClient:R}=await Promise.resolve().then(()=>(kt(),Tr));m.github.login=await new R(m.github.token).whoami(),ye(m)}catch{}let g=pd(m,d.emails);v.sendTeamCredsResult(d.requestId,{ok:!0,...g})}catch(m){v.sendTeamCredsResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRepoUnmap:d=>{try{let m=ve();if(!m){v.sendRepoUnmapResult(d.requestId,{ok:!1,error:"this runner has no config file"});return}let g=m.repos[d.repoName];if(!g){v.sendRepoUnmapResult(d.requestId,{ok:!0,removedPath:""});return}let R=g.path;delete m.repos[d.repoName];for(let N of Object.keys(m.environments).filter(G=>G.startsWith(`${d.repoName}:`)))delete m.environments[N];m.auditSchedules=m.auditSchedules.filter(N=>N.repoName!==d.repoName),ye(m),ln(),y.info(`Unmapped "${d.repoName}" (was ${R}) - its project was deleted on the dashboard. The checkout on disk was NOT touched.`),v.sendRepoUnmapResult(d.requestId,{ok:!0,removedPath:R})}catch(m){v.sendRepoUnmapResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupRecheck:d=>{try{let m=S(d.projectId);if(!m){v.sendSetupRecheckResult(d.requestId,{ok:!1,error:A(d.projectId)});return}v.sendSetupRecheckResult(d.requestId,{ok:!0,checks:Fh({repoPath:m.repoPath,environments:d.environments})})}catch(m){v.sendSetupRecheckResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupStatus:async d=>{try{let m=ve()??t,{buildSetupReport:g}=await Promise.resolve().then(()=>(gm(),mm)),R=await g(m,d.repoNames,t);v.sendSetupStatusResult(d.requestId,{ok:!0,...R})}catch(m){v.sendSetupStatusResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdGenerate:async d=>{try{let m=S(d.projectId);if(!m){v.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=d.kind==="deploy"?"DEPLOY.md":d.kind==="design"?"DESIGN.md":"CLAUDE.md";y.info(`Setup: drafting ${g} for ${m.project.repoName}`);let R="Explore this repository and draft the content of a CLAUDE.md file for its repo root - the memory file AI agents read before working on tickets here. Cover: what the product does (one paragraph), the tech stack, how the code is organized (key directories and what lives in them), exact commands to install dependencies / build / run tests, code conventions worth following, and gotchas a newcomer would trip over. Under 150 lines, factual, no marketing language, nothing you cannot verify from the code. Reply with ONLY the file content - no preamble, no fences around the whole thing.",N=`Inspect this repository (deploy scripts, CI files, server configs, package scripts) and draft the content of a DEPLOY.md deploy contract for its repo root. An automation tool will follow it LITERALLY, so only write what you can verify from the repo. IMPORTANT: you are running ON the machine where deploys will execute - commands are plain local commands, no ssh wrapper, unless the repo clearly documents a different target machine. For each environment that VERIFIABLY exists: name, branch, exact deploy commands, secrets as $NAMES only (never values), pre/post checks (post-restart checks must wait and retry - services report active before their port binds). Where you cannot verify something (hosts, service names, ports), write it with a clear "VERIFY:" marker so the human fills it in during review, instead of guessing. State explicitly which environments do NOT exist.
|
|
1121
1121
|
|
|
1122
1122
|
Ten things decide whether this document can actually be run:
|
|
1123
1123
|
1. Open with TWO sections, and put every finding in the right one. "## Blockers" is only for things that make the deploy IMPOSSIBLE or produce a broken release: no restart mechanism, an install command that exits non-zero, a build that cannot run. "## Warnings" is for everything that leaves a WORKING release with something degraded - one feature returning an error, a check that is weaker than it should be, a reproducibility risk. Apply this test to each one and state the answer: if the deploy still produces a site that serves its pages, it is a WARNING, never a blocker. A secret that only one route needs is the standard example - the site deploys and works, one endpoint errors, so it is a warning. Blockers are also different from VERIFY: markers, which are questions. Every entry in BOTH sections MUST end with a sentence starting "Fix:" naming the smallest concrete action that closes it and who can do it - someone with shell on that machine, or a code change that can become a ticket. A blocker without a fix is just bad news, and it is read by someone who cannot open the document to go looking for the answer. Write "None" under either heading that has nothing - do not pad it, and do not promote a warning to a blocker to make the list look thorough.
|
|
@@ -1134,16 +1134,16 @@ Ten things decide whether this document can actually be run:
|
|
|
1134
1134
|
Reply with ONLY the file content - no preamble, no fences around the whole thing.`+(d.environments.length?`
|
|
1135
1135
|
|
|
1136
1136
|
THESE ENVIRONMENTS ARE ALREADY DECLARED for this project - write a section for EACH one, no more and no fewer, and target each one's own health checks at its own URL:
|
|
1137
|
-
`+d.environments.map(
|
|
1137
|
+
`+d.environments.map(W=>`- ${W.name}`+(W.branch?` (branch ${W.branch})`:"")+(W.publicUrl?` serves ${W.publicUrl}`:" - no URL given")+(W.onThisRunner?", its deploy commands run ON THIS MACHINE, in "+(W.workdir?`${W.workdir}`:W.dedicatedCheckout?"a checkout of its own, managed by the runner":"THE MAPPED CHECKOUT - the same directory as every other environment"):", deployed by a DIFFERENT machine - this runner cannot see it")).join(`
|
|
1138
1138
|
`)+`
|
|
1139
|
-
If the repo shows no evidence of how one of them deploys, still write its section with VERIFY: markers rather than dropping it.`:"")+(d.kind==="deploy"?
|
|
1139
|
+
If the repo shows no evidence of how one of them deploys, still write its section with VERIFY: markers rather than dropping it.`:"")+(d.kind==="deploy"?zl({repoPath:m.repoPath,urls:d.environments.map(W=>W.publicUrl).filter(Boolean)})+ri(m.repoPath):""),G=`Explore this repository's UI code and draft the content of a DESIGN.md file for its repo root - the design guidelines AI agents will follow for anything user-facing here. This is a SEED DRAFT: extract only what the code proves, and leave taste to the humans. Cover, from real evidence (tailwind/theme configs, design tokens, CSS, component libraries, existing screens): the color palette actually in use (names + hex), typography (families, the size scale), spacing and layout conventions, the component idiom (which library, how buttons/forms/cards are built, naming), dark mode, responsive breakpoints, and accessibility patterns already present. For everything code cannot prove - brand intent, tone of voice, look-and-feel references, what to never do - write a line starting with "VERIFY:" phrased as a question for the human to answer during review, instead of guessing. If the project has no UI at all, say exactly that in one line and stop. Under 120 lines, factual, no marketing language. Reply with ONLY the file content - no preamble, no fences around the whole thing.`,X=`A deploy contract was drafted for this repository and it reported the blockers below - things that stop an automated deploy from running at all. Your job is to tell ONE person, sitting at a terminal on this machine, exactly how to close them.
|
|
1140
1140
|
|
|
1141
1141
|
BLOCKERS AS REPORTED:
|
|
1142
|
-
`+d.blockers.map((
|
|
1142
|
+
`+d.blockers.map((W,he)=>`${he+1}. ${W}`).join(`
|
|
1143
1143
|
`)+(d.machineState.length?`
|
|
1144
1144
|
|
|
1145
1145
|
WHAT THE MACHINE SAYS RIGHT NOW - checked seconds ago, and NEWER than the list above, which came from a document written earlier:
|
|
1146
|
-
`+d.machineState.map(
|
|
1146
|
+
`+d.machineState.map(W=>`- ${W}`).join(`
|
|
1147
1147
|
`)+`
|
|
1148
1148
|
Anything the list asks for that is ALREADY TRUE here gets one line - "already done, nothing to do" and what proves it - and no commands at all. Re-explaining a fix somebody has already carried out is how a tool tells them it was not paying attention. If the two disagree, the machine is right.`:"")+`
|
|
1149
1149
|
|
|
@@ -1175,8 +1175,8 @@ Rules, and they matter more than completeness:
|
|
|
1175
1175
|
Reply with ONLY the guide - no preamble.`+(d.environments.length?`
|
|
1176
1176
|
|
|
1177
1177
|
THE ENVIRONMENTS AS ALLWRIGHT HAS THEM TODAY - your instructions have to end with these matching reality:
|
|
1178
|
-
`+d.environments.map(
|
|
1179
|
-
`):"")+
|
|
1178
|
+
`+d.environments.map(W=>`- ${W.name}`+(W.branch?` (branch ${W.branch})`:"")+(W.publicUrl?` serves ${W.publicUrl}`:"")+(W.onThisRunner?", deploy commands run ON THIS MACHINE, in "+(W.workdir?W.workdir:W.dedicatedCheckout?"a checkout of its own":"the MAPPED CHECKOUT, shared with every other environment"):", deployed by a DIFFERENT machine - none of the commands below can set it up, and the facts below say nothing about it")).join(`
|
|
1179
|
+
`):"")+zl({repoPath:m.repoPath,urls:d.environments.map(W=>W.publicUrl).filter(Boolean)})+ri(m.repoPath),U=Oe(t,m.project,"assist");if("error"in U){v.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,content:"",error:U.error});return}let H=0,L=await U.adapter.run({repoPath:m.repoPath,prompt:d.kind==="deploy"?N:d.kind==="design"?G:d.kind==="unblock"?X:R,timeoutSeconds:600,bin:U.bin,mode:"read_only",maxTurns:40,sessionId:(0,On.randomUUID)(),onLog:(W,he)=>{W==="agent"&&d.streamId&&v.send({type:"chat.stream",requestId:d.streamId,seq:H++,text:he.slice(0,8e3)})}}),ne=L.resultText.trim();if(!ne){v.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:"the agent returned no content - try again"});return}L.outputTruncated&&y.warn(`Setup: the ${g} draft was cut off at the agent's output limit - ${ne.length} chars, incomplete`),v.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!0,content:ne,truncated:!!L.outputTruncated})}catch(m){v.sendSetupClaudeMdGenerateResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupAsk:async d=>{try{let m=S(d.projectId);if(!m){v.sendSetupAskResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=Oe(t,m.project,"assist");if("error"in g){v.sendSetupAskResult(d.requestId,{ok:!1,error:g.error});return}y.info(`Setup: question about "${d.subject.slice(0,60)}" (${m.project.repoName})`);let R="Someone is at a terminal on THIS machine, part-way through fixing one setup problem in Allwright, and has a question about it. Answer that question and stop."+(d.subject?`
|
|
1180
1180
|
|
|
1181
1181
|
WHAT THEY ARE WORKING ON:
|
|
1182
1182
|
${d.subject}`:"")+(d.command?`
|
|
@@ -1198,4 +1198,4 @@ ${d.question}
|
|
|
1198
1198
|
|
|
1199
1199
|
HOW TO ANSWER. You have READ-ONLY access to this repository and no shell: you cannot run anything, so never claim to have checked something you could only have run. Give the cause in one or two sentences, then the exact command or file edit that moves them forward, in a fenced block. Under 150 words unless the question genuinely needs more. No preamble, no summary of what they asked, no encouragement.
|
|
1200
1200
|
|
|
1201
|
-
Stay on the ONE problem above. If their error is actually a different problem, say which in a single line and stop - do not start fixing it. If the honest answer is that you cannot tell from here, say that and name the one command whose output would settle it. A confident guess about someone's production server is the worst thing you can hand them.`,K=(await g.adapter.run({repoPath:m.repoPath,prompt:R,timeoutSeconds:120,bin:g.bin,mode:"read_only",maxTurns:6,sessionId:(0,On.randomUUID)(),onLog:()=>{}})).resultText.trim();v.sendSetupAskResult(d.requestId,K?{ok:!0,answer:K}:{ok:!1,error:"the agent returned nothing - ask again, or rephrase"})}catch(m){v.sendSetupAskResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdSave:async d=>{try{let m=T(d.projectId);if(!m){v.sendSetupClaudeMdSaveResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=d.kind==="deploy"?"DEPLOY.md":d.kind==="design"?"DESIGN.md":"CLAUDE.md",R=await Ec({repoPath:m.repoPath,relPath:g,content:d.content,overwrite:d.overwrite,commitMessage:`Add ${g} (agent-drafted, human-approved via Allwright)`});R.ok&&y.info(`Setup: wrote human-approved ${g} to ${m.repoPath} - ${R.note}`),v.sendSetupClaudeMdSaveResult(d.requestId,R)}catch(m){v.sendSetupClaudeMdSaveResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRepoDocSave:async d=>{try{let m=T(d.projectId);if(!m){v.sendRepoDocSaveResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=await Ec({repoPath:m.repoPath,relPath:d.relPath,content:d.content,overwrite:d.overwrite,commitMessage:`Add ${d.relPath.trim()} (written in Allwright Compose, human-approved)`});g.ok&&y.info(`Saved approved doc ${d.relPath} into ${m.repoPath}`),v.sendRepoDocSaveResult(d.requestId,g)}catch(m){v.sendRepoDocSaveResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditStats:d=>{try{v.sendAuditStatsResult(d.requestId,{ok:!0,byProject:Ed(d.projectIds,d.since)})}catch(m){v.sendAuditStatsResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRunnerUpdate:async d=>{if(!process.env.INVOCATION_ID){v.sendRunnerUpdateResult(d.requestId,{ok:!1,error:"this runner is not running as a systemd service, so it cannot restart itself after updating. On the machine run: allwright update && allwright stop && allwright start"});return}let m=()=>{y.info("Installing allwright@latest");let R=an.default.dirname(process.execPath),N=tt.default.existsSync(an.default.join(R,"npm"))?an.default.join(R,"npm"):"npm";(0,cn.execFile)(N,["install","-g","allwright@latest"],{timeout:18e4,env:{...process.env,PATH:`${R}:${process.env.PATH??""}`}},(K,X,U)=>{if(K){v.sendRunnerUpdateResult(d.requestId,{ok:!1,error:`npm install failed: ${(U||K.message).slice(0,300)} - on the machine run: allwright update && sudo systemctl restart allwright`});return}v.sendRunnerUpdateResult(d.requestId,{ok:!0,note:"updated - restarting now, back in a few seconds"}),y.info("Update installed; exiting so systemd restarts on the new version"),setTimeout(()=>process.exit(0),1500)})};if(f.idle){m();return}if(b){v.sendRunnerUpdateResult(d.requestId,{ok:!0,scheduled:!0,note:"an update is already scheduled and will install once the current work finishes"});return}let g=f.busyCount;v.sendRunnerUpdateResult(d.requestId,{ok:!0,scheduled:!0,note:`scheduled - ${g} run(s)/deploy(s) active right now. Nothing is refused meanwhile; the install runs automatically as soon as this machine goes idle.`}),y.info(`Update scheduled: waiting for ${g} active run(s)/deploy(s)/chat turn(s) to finish`),b=setInterval(()=>{f.idle&&(clearInterval(b),b=null,m())},5e3)},onRunnerUninstall:d=>{if(!f.idle){v.sendRunnerUninstallResult(d.requestId,{ok:!1,error:`${f.busyCount} run(s)/deploy(s)/chat turn(s) are executing on this machine right now - nothing was uninstalled.`});return}let m;try{m=ol()}catch(R){v.sendRunnerUninstallResult(d.requestId,{ok:!1,error:R instanceof Error?R.message:String(R)});return}let g=m.problems.length===0;if(v.sendRunnerUninstallResult(d.requestId,{ok:g,error:g?void 0:m.problems.join("; "),note:g?[m.serviceRemoved?"service stopped and removed":"no systemd service was installed here",m.configRemoved?`config deleted (${m.removedPaths.join(", ")}) - the Jira and GitHub tokens went with it`:"no runner config was left to delete","checkouts untouched"].join("; "):"",serviceRemoved:m.serviceRemoved||m.serviceAbsent,configRemoved:m.configRemoved}),!g){y.info("Uninstall requested from the dashboard, but it could not complete here");return}y.info("Uninstalled from the dashboard - stopping now. Checkouts were not touched."),setTimeout(()=>{il(),process.exit(0)},1500)},onTestFix:async d=>{let m=g=>v.sendTestFixResult(d.requestId,{ok:!1,note:g});try{let g=ws(d.runId);if(!g){m("this runner no longer has that PR on file - it may have been decided already");return}let R=t.repos[g.repoName];if(!R){m(`no local checkout mapped for "${g.repoName}" on this machine`);return}let N=je(t,g.repoName);if(!N){m("no GitHub token on this runner for that repo");return}let K=await new Me(N).getPullRequest(g.owner,g.repo,g.prNumber);if(!K){m("that pull request no longer exists on GitHub");return}if(K.merged||K.state==="closed"){m("that pull request is already merged or closed - there is nothing left to fix");return}let X=c.find(ne=>ne.repoName===g.repoName),U=g.nextDecisionSeq??1e5,B=(ne,Z)=>{v.send({type:"run.log",runId:d.runId,seq:U++,ts:new Date().toISOString(),level:ne,message:Z}),g.nextDecisionSeq=U,_t(g)},L=await cp({cfg:t,repoPath:R.path,branch:g.branch,baseBranch:K.baseRef||"main",issueKey:g.issueKey,agentId:X?.defaultAgent||Le.DEFAULT_AGENT_ID,configDir:g.agentConfigDir,failedTests:d.failedTests,timeoutSeconds:900,onLog:B});L.ok&&L.headSha&&(g.headSha=L.headSha,_t(g),v.send({type:"run.status",runId:d.runId,status:"awaiting_approval",headSha:L.headSha,failedTests:L.remaining??[],...L.testsPassed!==void 0?{testsPassed:L.testsPassed}:{},...L.testsTotal!==void 0?{testsTotal:L.testsTotal}:{},...L.costUsd!==void 0?{costUsd:L.costUsd}:{},...L.inputTokens!==void 0?{inputTokens:L.inputTokens}:{},...L.outputTokens!==void 0?{outputTokens:L.outputTokens}:{}})),ut(R.path,{issueKey:g.issueKey,runId:d.runId,title:L.ok?L.headSha?(L.remaining??[]).length?"dashboard test fix pushed, some commands still failing":"tests fixed from the dashboard":"dashboard test fix: agent changed nothing":"dashboard test fix failed",detail:L.note.slice(0,500)}),v.sendTestFixResult(d.requestId,L)}catch(g){m(g instanceof Error?g.message.slice(0,300):String(g))}},onRunAnswer:async d=>{try{let m=await f.answerPendingInput(d.runId,d.text,d.answeredBy);v.sendRunAnswerResult(d.requestId,m)}catch(m){v.sendRunAnswerResult(d.requestId,{ok:!1,error:m instanceof Error?m.message.slice(0,300):String(m)})}},onResolveConflict:async d=>{let m=g=>v.sendResolveConflictResult(d.requestId,{ok:!1,note:g});try{let g=ws(d.runId);if(!g){m("this runner no longer has that PR on file - it may have been decided already");return}let R=t.repos[g.repoName];if(!R){m(`no local checkout mapped for "${g.repoName}" on this machine`);return}let N=je(t,g.repoName);if(!N){m("no GitHub token on this runner for that repo");return}let K=await new Me(N).getPullRequest(g.owner,g.repo,g.prNumber);if(!K){m("that pull request no longer exists on GitHub");return}if(!K.baseRef){m("GitHub did not report the PR's base branch, so there is nothing to merge in");return}let X=c.find(ne=>ne.repoName===g.repoName),U=g.nextDecisionSeq??1e5,B=(ne,Z)=>{v.send({type:"run.log",runId:d.runId,seq:U++,ts:new Date().toISOString(),level:ne,message:Z}),g.nextDecisionSeq=U,_t(g)},L=await ap({cfg:t,repoPath:R.path,branch:g.branch,baseBranch:K.baseRef,issueKey:g.issueKey,agentId:X?.defaultAgent||Le.DEFAULT_AGENT_ID,configDir:g.agentConfigDir,timeoutSeconds:900,onLog:B});L.ok&&L.headSha&&(g.headSha=L.headSha,g.conflictNotified=!1,_t(g),v.send({type:"run.pr.conflict",runId:d.runId,conflicted:!1}),v.send({type:"run.status",runId:d.runId,status:"awaiting_approval",headSha:L.headSha,...L.costUsd!==void 0?{costUsd:L.costUsd}:{},...L.inputTokens!==void 0?{inputTokens:L.inputTokens}:{},...L.outputTokens!==void 0?{outputTokens:L.outputTokens}:{}})),v.sendResolveConflictResult(d.requestId,L)}catch(g){m(g instanceof Error?g.message.slice(0,300):String(g))}},onAgentProfiles:d=>{try{let m=R=>{try{return tt.default.existsSync(R)&&tt.default.readdirSync(R).length>0}catch{return!1}},g=Object.entries(t.claudeProfiles).map(([R,N])=>({agent:"claude-code",name:R,loggedIn:m(N.configDir)}));v.sendAgentProfilesResult(d.requestId,{ok:!0,profiles:g,defaultLoggedIn:m(an.default.join(yi.default.homedir(),".claude")),agentsWithoutProfiles:Le.REGISTERED_AGENTS.filter(R=>!R.capabilities.loginProfiles).map(R=>R.id)})}catch(m){v.sendAgentProfilesResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onJiraUsers:async d=>{try{let m=await n.searchUsers(d.query);v.sendJiraUsersResult(d.requestId,{ok:!0,users:m})}catch(m){v.sendJiraUsersResult(d.requestId,{ok:!1,users:[],error:m instanceof Error?m.message:String(m)})}}});w.transport=v,f=new No(t,s,v),f.setExternalBusy(()=>q.size);let E=Object.values(Rr()).filter(d=>d.kind==="implement").map(d=>d.repoPath);Fa(Object.values(t.repos).map(d=>d.path),E).catch(()=>{}),v.start(),f.start();let O=()=>{y.info("shutting down"),b&&clearInterval(b),v.stop(),Su(process.pid),Ea(),process.exit(0)},W=!1,z=()=>{if(W){y.warn("second stop signal - exiting NOW; the interrupted run will be marked failed"),O();return}if(W=!0,f.stop(),f.idle){O();return}y.info(`stop requested - no new work will start; waiting for ${f.busyCount} active run(s)/deploy(s)/chat turn(s) to finish. Send the signal again to kill them immediately.`);let d=setInterval(()=>{f.idle&&(clearInterval(d),O())},3e3)};process.on("SIGINT",z),process.on("SIGTERM",z),process.on("SIGHUP",()=>{try{let d=le();for(let m of Object.keys(t))delete t[m];Object.assign(t,d),n=d.jira?new Pe(d.jira):Qa(),r.clear(),y.info("config reloaded live - new Jira tokens/repos/rules apply from the next poll. (Poll interval and control-plane URL still need a restart.)")}catch(d){y.error(`config reload failed - keeping the running config: ${d instanceof Error?d.message:String(d)}`)}})}Re.command("start").description("Start watching Jira. Runs in the background by default - close this terminal and it keeps going until you run `allwright stop`. Use --foreground to keep it attached (e.g. under systemd).").option("--foreground","run in this terminal instead of detaching to the background").action(async t=>{let e=le();if(t.foreground){R_(e);return}let n=Qn();if(n&&er(n)){y.info(`already running in the background (pid ${n}). Use \`allwright status\` or \`stop\`.`);return}let r=ns();if(r){y.info(`a runner is already running on this machine (pid ${r}) - most likely the systemd service. One machine runs ONE runner; nothing to do. (Service controls: sudo systemctl status|stop|restart allwright)`);return}let s=ku(),i=(0,cn.spawn)(process.execPath,[process.argv[1],"start","--foreground"],{detached:!0,stdio:["ignore",s,s]});i.unref(),_u(i.pid),y.info(`Runner started in the background (pid ${i.pid}).`),y.info(`Logs: ${Oi()}`),y.info("It will keep polling Jira until you run `allwright stop` - closing this terminal is fine.")});Re.command("stop").description("Stop the background runner started by `start`. Graceful by default: it stops taking new work and exits once active runs and deploys finish - safe to use while customers' tickets are running.").option("--force","kill immediately - anything executing is interrupted and marked failed").action(t=>{let e=Qn();if(!e||!er(e)){y.info("no background runner is running"),e&&tt.default.rmSync(ts(),{force:!0});return}if(t.force){process.kill(e,"SIGKILL"),tt.default.rmSync(ts(),{force:!0}),y.info(`killed (pid ${e}) - any interrupted run will show as failed on the dashboard`);return}process.kill(e,"SIGTERM"),y.info(`stop signal sent (pid ${e}) - it stops polling now and exits once active work finishes (watch \`allwright status\`). Use --force to kill immediately.`)});Re.command("status").description("Check whether the background runner is running").action(()=>{let t=Qn();t&&er(t)?y.info(`running in the background (pid ${t})`):y.info("not running")});Re.parseAsync().catch(t=>{y.error(t instanceof Error?t.message:String(t)),process.exit(1)});
|
|
1201
|
+
Stay on the ONE problem above. If their error is actually a different problem, say which in a single line and stop - do not start fixing it. If the honest answer is that you cannot tell from here, say that and name the one command whose output would settle it. A confident guess about someone's production server is the worst thing you can hand them.`,G=(await g.adapter.run({repoPath:m.repoPath,prompt:R,timeoutSeconds:120,bin:g.bin,mode:"read_only",maxTurns:6,sessionId:(0,On.randomUUID)(),onLog:()=>{}})).resultText.trim();v.sendSetupAskResult(d.requestId,G?{ok:!0,answer:G}:{ok:!1,error:"the agent returned nothing - ask again, or rephrase"})}catch(m){v.sendSetupAskResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdSave:async d=>{try{let m=S(d.projectId);if(!m){v.sendSetupClaudeMdSaveResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=d.kind==="deploy"?"DEPLOY.md":d.kind==="design"?"DESIGN.md":"CLAUDE.md",R=await $c({repoPath:m.repoPath,relPath:g,content:d.content,overwrite:d.overwrite,commitMessage:`Add ${g} (agent-drafted, human-approved via Allwright)`});R.ok&&y.info(`Setup: wrote human-approved ${g} to ${m.repoPath} - ${R.note}`),v.sendSetupClaudeMdSaveResult(d.requestId,R)}catch(m){v.sendSetupClaudeMdSaveResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRepoDocSave:async d=>{try{let m=S(d.projectId);if(!m){v.sendRepoDocSaveResult(d.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=await $c({repoPath:m.repoPath,relPath:d.relPath,content:d.content,overwrite:d.overwrite,commitMessage:`Add ${d.relPath.trim()} (written in Allwright Compose, human-approved)`});g.ok&&y.info(`Saved approved doc ${d.relPath} into ${m.repoPath}`),v.sendRepoDocSaveResult(d.requestId,g)}catch(m){v.sendRepoDocSaveResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditStats:d=>{try{v.sendAuditStatsResult(d.requestId,{ok:!0,byProject:$d(d.projectIds,d.since)})}catch(m){v.sendAuditStatsResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRunnerUpdate:async d=>{if(!process.env.INVOCATION_ID){v.sendRunnerUpdateResult(d.requestId,{ok:!1,error:"this runner is not running as a systemd service, so it cannot restart itself after updating. On the machine run: allwright update && allwright stop && allwright start"});return}let m=()=>{y.info("Installing allwright@latest");let R=an.default.dirname(process.execPath),N=tt.default.existsSync(an.default.join(R,"npm"))?an.default.join(R,"npm"):"npm";(0,cn.execFile)(N,["install","-g","allwright@latest"],{timeout:18e4,env:{...process.env,PATH:`${R}:${process.env.PATH??""}`}},(G,X,U)=>{if(G){v.sendRunnerUpdateResult(d.requestId,{ok:!1,error:`npm install failed: ${(U||G.message).slice(0,300)} - on the machine run: allwright update && sudo systemctl restart allwright`});return}v.sendRunnerUpdateResult(d.requestId,{ok:!0,note:"updated - restarting now, back in a few seconds"}),y.info("Update installed; exiting so systemd restarts on the new version"),setTimeout(()=>process.exit(0),1500)})};if(f.idle){m();return}if(b){v.sendRunnerUpdateResult(d.requestId,{ok:!0,scheduled:!0,note:"an update is already scheduled and will install once the current work finishes"});return}let g=f.busyCount;v.sendRunnerUpdateResult(d.requestId,{ok:!0,scheduled:!0,note:`scheduled - ${g} run(s)/deploy(s) active right now. Nothing is refused meanwhile; the install runs automatically as soon as this machine goes idle.`}),y.info(`Update scheduled: waiting for ${g} active run(s)/deploy(s)/chat turn(s) to finish`),b=setInterval(()=>{f.idle&&(clearInterval(b),b=null,m())},5e3)},onRunnerUninstall:d=>{if(!f.idle){v.sendRunnerUninstallResult(d.requestId,{ok:!1,error:`${f.busyCount} run(s)/deploy(s)/chat turn(s) are executing on this machine right now - nothing was uninstalled.`});return}let m;try{m=al()}catch(R){v.sendRunnerUninstallResult(d.requestId,{ok:!1,error:R instanceof Error?R.message:String(R)});return}let g=m.problems.length===0;if(v.sendRunnerUninstallResult(d.requestId,{ok:g,error:g?void 0:m.problems.join("; "),note:g?[m.serviceRemoved?"service stopped and removed":"no systemd service was installed here",m.configRemoved?`config deleted (${m.removedPaths.join(", ")}) - the Jira and GitHub tokens went with it`:"no runner config was left to delete","checkouts untouched"].join("; "):"",serviceRemoved:m.serviceRemoved||m.serviceAbsent,configRemoved:m.configRemoved}),!g){y.info("Uninstall requested from the dashboard, but it could not complete here");return}y.info("Uninstalled from the dashboard - stopping now. Checkouts were not touched."),setTimeout(()=>{ol(),process.exit(0)},1500)},onTestFix:async d=>{let m=g=>v.sendTestFixResult(d.requestId,{ok:!1,note:g});try{let g=ws(d.runId);if(!g){m("this runner no longer has that PR on file - it may have been decided already");return}let R=t.repos[g.repoName];if(!R){m(`no local checkout mapped for "${g.repoName}" on this machine`);return}let N=je(t,g.repoName);if(!N){m("no GitHub token on this runner for that repo");return}let G=await new Me(N).getPullRequest(g.owner,g.repo,g.prNumber);if(!G){m("that pull request no longer exists on GitHub");return}if(G.merged||G.state==="closed"){m("that pull request is already merged or closed - there is nothing left to fix");return}let X=c.find(ne=>ne.repoName===g.repoName),U=g.nextDecisionSeq??1e5,H=(ne,W)=>{v.send({type:"run.log",runId:d.runId,seq:U++,ts:new Date().toISOString(),level:ne,message:W}),g.nextDecisionSeq=U,_t(g)},L=await bp({cfg:t,repoPath:R.path,branch:g.branch,baseBranch:G.baseRef||"main",issueKey:g.issueKey,agentId:X?.defaultAgent||Le.DEFAULT_AGENT_ID,configDir:g.agentConfigDir,failedTests:d.failedTests,timeoutSeconds:900,onLog:H});L.ok&&L.headSha&&(g.headSha=L.headSha,_t(g),v.send({type:"run.status",runId:d.runId,status:"awaiting_approval",headSha:L.headSha,failedTests:L.remaining??[],...L.testsPassed!==void 0?{testsPassed:L.testsPassed}:{},...L.testsTotal!==void 0?{testsTotal:L.testsTotal}:{},...L.costUsd!==void 0?{costUsd:L.costUsd}:{},...L.inputTokens!==void 0?{inputTokens:L.inputTokens}:{},...L.outputTokens!==void 0?{outputTokens:L.outputTokens}:{}})),ut(R.path,{issueKey:g.issueKey,runId:d.runId,title:L.ok?L.headSha?(L.remaining??[]).length?"dashboard test fix pushed, some commands still failing":"tests fixed from the dashboard":"dashboard test fix: agent changed nothing":"dashboard test fix failed",detail:L.note.slice(0,500)}),v.sendTestFixResult(d.requestId,L)}catch(g){m(g instanceof Error?g.message.slice(0,300):String(g))}},onRunAnswer:async d=>{try{let m=await f.answerPendingInput(d.runId,d.text,d.answeredBy);v.sendRunAnswerResult(d.requestId,m)}catch(m){v.sendRunAnswerResult(d.requestId,{ok:!1,error:m instanceof Error?m.message.slice(0,300):String(m)})}},onResolveConflict:async d=>{let m=g=>v.sendResolveConflictResult(d.requestId,{ok:!1,note:g});try{let g=ws(d.runId);if(!g){m("this runner no longer has that PR on file - it may have been decided already");return}let R=t.repos[g.repoName];if(!R){m(`no local checkout mapped for "${g.repoName}" on this machine`);return}let N=je(t,g.repoName);if(!N){m("no GitHub token on this runner for that repo");return}let G=await new Me(N).getPullRequest(g.owner,g.repo,g.prNumber);if(!G){m("that pull request no longer exists on GitHub");return}if(!G.baseRef){m("GitHub did not report the PR's base branch, so there is nothing to merge in");return}let X=c.find(ne=>ne.repoName===g.repoName),U=g.nextDecisionSeq??1e5,H=(ne,W)=>{v.send({type:"run.log",runId:d.runId,seq:U++,ts:new Date().toISOString(),level:ne,message:W}),g.nextDecisionSeq=U,_t(g)},L=await gp({cfg:t,repoPath:R.path,branch:g.branch,baseBranch:G.baseRef,issueKey:g.issueKey,agentId:X?.defaultAgent||Le.DEFAULT_AGENT_ID,configDir:g.agentConfigDir,timeoutSeconds:900,onLog:H});L.ok&&L.headSha&&(g.headSha=L.headSha,g.conflictNotified=!1,_t(g),v.send({type:"run.pr.conflict",runId:d.runId,conflicted:!1}),v.send({type:"run.status",runId:d.runId,status:"awaiting_approval",headSha:L.headSha,...L.costUsd!==void 0?{costUsd:L.costUsd}:{},...L.inputTokens!==void 0?{inputTokens:L.inputTokens}:{},...L.outputTokens!==void 0?{outputTokens:L.outputTokens}:{}})),v.sendResolveConflictResult(d.requestId,L)}catch(g){m(g instanceof Error?g.message.slice(0,300):String(g))}},onAgentProfiles:d=>{try{let m=R=>{try{return tt.default.existsSync(R)&&tt.default.readdirSync(R).length>0}catch{return!1}},g=Object.entries(t.claudeProfiles).map(([R,N])=>({agent:"claude-code",name:R,loggedIn:m(N.configDir)}));v.sendAgentProfilesResult(d.requestId,{ok:!0,profiles:g,defaultLoggedIn:m(an.default.join(bi.default.homedir(),".claude")),agentsWithoutProfiles:Le.REGISTERED_AGENTS.filter(R=>!R.capabilities.loginProfiles).map(R=>R.id)})}catch(m){v.sendAgentProfilesResult(d.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onJiraUsers:async d=>{try{let m=await n.searchUsers(d.query);v.sendJiraUsersResult(d.requestId,{ok:!0,users:m})}catch(m){v.sendJiraUsersResult(d.requestId,{ok:!1,users:[],error:m instanceof Error?m.message:String(m)})}}});w.transport=v,f=new Oo(t,s,v),f.setExternalBusy(()=>q.size);let C=Object.values(Rr()).filter(d=>d.kind==="implement").map(d=>d.repoPath);Ba(Object.values(t.repos).map(d=>d.path),C).catch(()=>{}),v.start(),f.start();let M=()=>{y.info("shutting down"),b&&clearInterval(b),v.stop(),xu(process.pid),Ca(),process.exit(0)},B=!1,j=()=>{if(B){y.warn("second stop signal - exiting NOW; the interrupted run will be marked failed"),M();return}if(B=!0,f.stop(),f.idle){M();return}y.info(`stop requested - no new work will start; waiting for ${f.busyCount} active run(s)/deploy(s)/chat turn(s) to finish. Send the signal again to kill them immediately.`);let d=setInterval(()=>{f.idle&&(clearInterval(d),M())},3e3)};process.on("SIGINT",j),process.on("SIGTERM",j),process.on("SIGHUP",()=>{try{let d=ce();for(let m of Object.keys(t))delete t[m];Object.assign(t,d),n=d.jira?new Pe(d.jira):el(),r.clear(),y.info("config reloaded live - new Jira tokens/repos/rules apply from the next poll. (Poll interval and control-plane URL still need a restart.)")}catch(d){y.error(`config reload failed - keeping the running config: ${d instanceof Error?d.message:String(d)}`)}})}Re.command("start").description("Start watching Jira. Runs in the background by default - close this terminal and it keeps going until you run `allwright stop`. Use --foreground to keep it attached (e.g. under systemd).").option("--foreground","run in this terminal instead of detaching to the background").action(async t=>{let e=ce();if(t.foreground){M_(e);return}let n=Qn();if(n&&er(n)){y.info(`already running in the background (pid ${n}). Use \`allwright status\` or \`stop\`.`);return}let r=ns();if(r){y.info(`a runner is already running on this machine (pid ${r}) - most likely the systemd service. One machine runs ONE runner; nothing to do. (Service controls: sudo systemctl status|stop|restart allwright)`);return}let s=Su(),i=(0,cn.spawn)(process.execPath,[process.argv[1],"start","--foreground"],{detached:!0,stdio:["ignore",s,s]});i.unref(),Tu(i.pid),y.info(`Runner started in the background (pid ${i.pid}).`),y.info(`Logs: ${Mi()}`),y.info("It will keep polling Jira until you run `allwright stop` - closing this terminal is fine.")});Re.command("stop").description("Stop the background runner started by `start`. Graceful by default: it stops taking new work and exits once active runs and deploys finish - safe to use while customers' tickets are running.").option("--force","kill immediately - anything executing is interrupted and marked failed").action(t=>{let e=Qn();if(!e||!er(e)){y.info("no background runner is running"),e&&tt.default.rmSync(ts(),{force:!0});return}if(t.force){process.kill(e,"SIGKILL"),tt.default.rmSync(ts(),{force:!0}),y.info(`killed (pid ${e}) - any interrupted run will show as failed on the dashboard`);return}process.kill(e,"SIGTERM"),y.info(`stop signal sent (pid ${e}) - it stops polling now and exits once active work finishes (watch \`allwright status\`). Use --force to kill immediately.`)});Re.command("status").description("Check whether the background runner is running").action(()=>{let t=Qn();t&&er(t)?y.info(`running in the background (pid ${t})`):y.info("not running")});Re.parseAsync().catch(t=>{y.error(t instanceof Error?t.message:String(t)),process.exit(1)});
|